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
pam revamp backend updates
x032205d036352d356c
diff --git a/backend/src/db/migrations/20260603030053_pam-revamp.ts b/backend/src/db/migrations/20260603030053_pam-revamp.tsindex 0f755b6d87..7d24a8886f 100644--- a/backend/src/db/migrations/20260603030053_pam-revamp.ts+++ b/backend/src/db/migrations/20260603030053_pam-revamp.ts@@ -45,7 +45,7 @@ const createPamProjectForOrg = async (knex: Knex, orgId: string) => {const [{ id: projectId }] = (await knex(TableName.Project).insert({- name: "Access Management",+ name: "Privileged Access Manager",slug,type: ProjectType.PAM,orgId,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 9e85da4b8f..dbf373008e 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@@ -3,7 +3,11 @@ import z from "zod";import { PamAccountsSchema } from "@app/db/schemas";import { EventType } from "@app/ee/services/audit-log/audit-log-types";import { PamAccountType } from "@app/ee/services/pam/pam-enums";-import { ACCOUNT_TYPE_CONFIGS } from "@app/ee/services/pam-account/pam-account-schemas";+import {+ ACCOUNT_TYPE_CONFIGS,+ buildPamAccountTypeMetadata,+ PamAccountTypeMetadataSchema+} from "@app/ee/services/pam-account/pam-account-schemas";import {PamTemplateAccessPolicySchema,PamTemplateSettingsSchema@@ -40,21 +44,20 @@ const SanitizedAccountListItemSchema = BaseAccountFields.extend({accountType: z.string()});-type TConnectionDetailsSchema = (typeof ACCOUNT_TYPE_CONFIGS)[keyof typeof ACCOUNT_TYPE_CONFIGS]["connectionDetails"];--const ConnectionDetailsSchema = z.union(- Object.values(ACCOUNT_TYPE_CONFIGS).map((c) => c.connectionDetails) as [- TConnectionDetailsSchema,- TConnectionDetailsSchema,- ...TConnectionDetailsSchema[]- ]+const accountDetailVariants = Object.entries(ACCOUNT_TYPE_CONFIGS).map(([accountType, config]) =>+ SanitizedAccountListItemSchema.extend({+ accountType: z.literal(accountType as TSupportedAccountType),+ connectionDetails: config.connectionDetails,+ templateAccessPolicy: PamTemplateAccessPolicySchema.nullable().optional(),+ templateSettings: PamTemplateSettingsSchema.nullable().optional(),+ credentials: config.sanitizedCredentials+ }));-const SanitizedAccountDetailSchema = SanitizedAccountListItemSchema.extend({- templateAccessPolicy: PamTemplateAccessPolicySchema.nullable().optional(),- templateSettings: PamTemplateSettingsSchema.nullable().optional(),- connectionDetails: ConnectionDetailsSchema-});+const SanitizedAccountDetailSchema = z.discriminatedUnion(+ "accountType",+ accountDetailVariants as [(typeof accountDetailVariants)[number], ...(typeof accountDetailVariants)[number][]]+);const toPascalCase = (s: string) =>s@@ -264,6 +267,26 @@ const registerPerTypeEndpoints = (};export const registerPamAccountRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/types",+ schema: {+ operationId: "listPamAccountTypes",+ description: "List supported PAM account types and their form field metadata",+ tags: [ApiDocsTags.PamAccounts],+ response: {+ 200: z.object({+ accountTypes: z.array(PamAccountTypeMetadataSchema)+ })+ }+ },+ config: { rateLimit: readLimit },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async () => {+ return { accountTypes: buildPamAccountTypeMetadata() };+ }+ });+server.route({method: "GET",url: "/",@@ -325,6 +348,8 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {folderName: true,templateName: true,accountType: true+ }).extend({+ canLaunch: z.boolean().describe("Whether the caller can launch a session for this account")})),totalCount: z.number()diff --git a/backend/src/ee/routes/v1/pam-routers/pam-membership-router.ts b/backend/src/ee/routes/v1/pam-routers/pam-membership-router.tsindex f194e83085..8f96d7dbb1 100644--- a/backend/src/ee/routes/v1/pam-routers/pam-membership-router.ts+++ b/backend/src/ee/routes/v1/pam-routers/pam-membership-router.ts@@ -17,6 +17,7 @@ const MemberSchema = z.object({groupId: z.string().uuid().nullable().optional(),role: z.string(),isActive: z.boolean(),+ expiresAt: z.date().nullable().optional(),createdAt: z.date()});@@ -59,17 +60,39 @@ const emitAuditLog = async (const emitTelemetry = (server: FastifyZodProvider,req: FastifyRequest & { permission: { orgId: string } },- event: PostHogEventTypes+ event: PostHogEventTypes,+ properties: Record<string, unknown> = {}) => {void server.services.telemetry.sendPostHogEvents({event,distinctId: getTelemetryDistinctId(req),organizationId: req.permission.orgId,- properties: { orgId: req.permission.orgId }+ properties: { orgId: req.permission.orgId, ...properties }} as Parameters<typeof server.services.telemetry.sendPostHogEvents>[0]);};export const registerPamProductMembershipRouter = async (server: FastifyZodProvider) => {+ server.route({+ method: "GET",+ url: "/capabilities",+ schema: {+ operationId: "getPamAccessCapabilities",+ description: "Get the current user's PAM management capabilities",+ tags: [ApiDocsTags.PamMemberships],+ response: {+ 200: z.object({+ isProductAdmin: z.boolean(),+ isResourceAdmin: z.boolean()+ })+ }+ },+ config: { rateLimit: readLimit },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ return server.services.pamMembership.getAccessCapabilities(actorCtx(req));+ }+ });+server.route({method: "GET",url: "/users",@@ -352,7 +375,14 @@ export const registerPamFolderMembershipRouter = async (server: FastifyZodProviddescription: "Add a user to a folder",tags: [ApiDocsTags.PamMemberships],params: folderParam.extend({ userId: z.string().uuid().describe("The ID of the user") }),- body: z.object({ role: z.nativeEnum(PamResourceRole).describe("The role to assign") }),+ body: z.object({+ role: z.nativeEnum(PamResourceRole).describe("The role to assign"),+ expiry: z+ .string()+ .nullable()+ .optional()+ .describe("Relative duration for temporary access (e.g. '1h', '7d'). Null for permanent.")+ }),response: { 200: FolderMemberResultSchema }},config: { rateLimit: writeLimit },@@ -362,14 +392,16 @@ export const registerPamFolderMembershipRouter = async (server: FastifyZodProvid...actorCtx(req),folderId: req.params.folderId,userId: req.params.userId,- role: req.body.role+ role: req.body.role,+ expiry: req.body.expiry});await emitAuditLog(server, req, EventType.PAM_FOLDER_MEMBER_ADD, {folderId: req.params.folderId,userId: req.params.userId,- role: req.body.role+ role: req.body.role,+ expiry: req.body.expiry});- emitTelemetry(server, req, PostHogEventTypes.PamFolderMemberAdded);+ emitTelemetry(server, req, PostHogEventTypes.PamFolderMemberAdded, { expiry: req.body.expiry });return { ...membership, folderId: req.params.folderId };}});@@ -439,7 +471,14 @@ export const registerPamFolderMembershipRouter = async (server: FastifyZodProviddescription: "Add a group to a folder",tags: [ApiDocsTags.PamMemberships],params: folderParam.extend({ groupId: z.string().uuid().describe("The ID of the group") }),- body: z.object({ role: z.nativeEnum(PamResourceRole).describe("The role to assign") }),+ body: z.object({+ role: z.nativeEnum(PamResourceRole).describe("The role to assign"),+ expiry: z+ .string()+ .nullable()+ .optional()+ .describe("Relative duration for temporary access (e.g. '1h', '7d'). Null for permanent.")+ }),response: { 200: FolderMemberResultSchema }},config: { rateLimit: writeLimit },@@ -449,14 +488,16 @@ export const registerPamFolderMembershipRouter = async (server: FastifyZodProvid...actorCtx(req),folderId: req.params.folderId,groupId: req.params.groupId,- role: req.body.role+ role: req.body.role,+ expiry: req.body.expiry});await emitAuditLog(server, req, EventType.PAM_FOLDER_MEMBER_ADD, {folderId: req.params.folderId,groupId: req.params.groupId,- role: req.body.role+ role: req.body.role,+ expiry: req.body.expiry});- emitTelemetry(server, req, PostHogEventTypes.PamFolderMemberAdded);+ emitTelemetry(server, req, PostHogEventTypes.PamFolderMemberAdded, { expiry: req.body.expiry });return { ...membership, folderId: req.params.folderId };}});@@ -573,7 +614,14 @@ export const registerPamAccountMembershipRouter = async (server: FastifyZodProvidescription: "Add a user to an account",tags: [ApiDocsTags.PamMemberships],params: accountParam.extend({ userId: z.string().uuid().describe("The ID of the user") }),- body: z.object({ role: z.nativeEnum(PamResourceRole).describe("The role to assign") }),+ body: z.object({+ role: z.nativeEnum(PamResourceRole).describe("The role to assign"),+ expiry: z+ .string()+ .nullable()+ .optional()+ .describe("Relative duration for temporary access (e.g. '1h', '7d'). Null for permanent.")+ }),response: { 200: AccountMemberResultSchema }},config: { rateLimit: writeLimit },@@ -583,14 +631,16 @@ export const registerPamAccountMembershipRouter = async (server: FastifyZodProvi...actorCtx(req),accountId: req.params.accountId,userId: req.params.userId,- role: req.body.role+ role: req.body.role,+ expiry: req.body.expiry});await emitAuditLog(server, req, EventType.PAM_ACCOUNT_MEMBER_ADD, {accountId: req.params.accountId,userId: req.params.userId,- role: req.body.role+ role: req.body.role,+ expiry: req.body.expiry});- emitTelemetry(server, req, PostHogEventTypes.PamAccountMemberAdded);+ emitTelemetry(server, req, PostHogEventTypes.PamAccountMemberAdded, { expiry: req.body.expiry });return { ...membership, accountId: req.params.accountId };}});@@ -660,7 +710,14 @@ export const registerPamAccountMembershipRouter = async (server: FastifyZodProvidescription: "Add a group to an account",tags: [ApiDocsTags.PamMemberships],params: accountParam.extend({ groupId: z.string().uuid().describe("The ID of the group") }),- body: z.object({ role: z.nativeEnum(PamResourceRole).describe("The role to assign") }),+ body: z.object({+ role: z.nativeEnum(PamResourceRole).describe("The role to assign"),+ expiry: z+ .string()+ .nullable()+ .optional()+ .describe("Relative duration for temporary access (e.g. '1h', '7d'). Null for permanent.")+ }),response: { 200: AccountMemberResultSchema }},config: { rateLimit: writeLimit },@@ -670,14 +727,16 @@ export const registerPamAccountMembershipRouter = async (server: FastifyZodProvi...actorCtx(req),accountId: req.params.accountId,groupId: req.params.groupId,+ expiry: req.body.expiry,role: req.body.role});await emitAuditLog(server, req, EventType.PAM_ACCOUNT_MEMBER_ADD, {accountId: req.params.accountId,groupId: req.params.groupId,- role: req.body.role+ role: req.body.role,+ expiry: req.body.expiry});- emitTelemetry(server, req, PostHogEventTypes.PamAccountMemberAdded);+ emitTelemetry(server, req, PostHogEventTypes.PamAccountMemberAdded, { expiry: req.body.expiry });return { ...membership, accountId: req.params.accountId };}});diff --git a/backend/src/ee/services/pam-account-template/pam-account-template-schemas.ts b/backend/src/ee/services/pam-account-template/pam-account-template-schemas.tsindex 6f077bc15a..7e4dc4253f 100644--- a/backend/src/ee/services/pam-account-template/pam-account-template-schemas.ts+++ b/backend/src/ee/services/pam-account-template/pam-account-template-schemas.ts@@ -26,7 +26,7 @@ export const PamTemplateSettingsSchema = z.object({});export const PamTemplateAccessPolicySchema = z.object({- maxSessionDurationSeconds: z.number().int().min(60).max(86400),+ maxSessionDurationSeconds: z.number().int().min(60).max(86400).optional(),requireReason: z.boolean().default(false),requireMfa: z.boolean().default(false)});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 1ba735b1d6..18cd169145 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@@ -5,6 +5,7 @@ import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError }import { PamProductRole } from "../pam/pam-enums";import { TActorContext, verifyProductMembership } from "../pam/pam-permission";import { TPamValidatorDeps, validateGatewayAttachment, validateRecordingConnection } from "../pam/pam-validators";+import { ACCOUNT_TYPE_CONFIGS } from "../pam-account/pam-account-schemas";import { TPamAccountTemplateDALFactory } from "./pam-account-template-dal";import {TCreatePamAccountTemplateDTO,@@ -14,6 +15,8 @@ import {TUpdatePamAccountTemplateDTO} from "./pam-account-template-types";+const SUPPORTED_ACCOUNT_TYPES = new Set<string>(Object.keys(ACCOUNT_TYPE_CONFIGS));+type TPamAccountTemplateServiceFactoryDep = TPamValidatorDeps & {pamAccountTemplateDAL: TPamAccountTemplateDALFactory;permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "getOrgPermission">;@@ -36,7 +39,8 @@ export const pamAccountTemplateServiceFactory = (deps: TPamAccountTemplateServicconst list = async ({ projectId, search, type, ...ctx }: TListPamAccountTemplatesDTO & TActorContext) => {await verifyMembership(projectId, ctx);- return pamAccountTemplateDAL.findByProjectId(projectId, { search, type });+ const templates = await pamAccountTemplateDAL.findByProjectId(projectId, { search, type });+ return templates.filter((template) => SUPPORTED_ACCOUNT_TYPES.has(template.type));};const getById = async ({ templateId, projectId, ...ctx }: TGetPamAccountTemplateDTO & TActorContext) => {diff --git a/backend/src/ee/services/pam-account/pam-account-schemas.ts b/backend/src/ee/services/pam-account/pam-account-schemas.tsindex e9bab7759e..b772b3796d 100644--- a/backend/src/ee/services/pam-account/pam-account-schemas.ts+++ b/backend/src/ee/services/pam-account/pam-account-schemas.ts@@ -1,9 +1,22 @@+/* eslint-disable no-underscore-dangle */import { z } from "zod";import { PamAccountType } from "../pam/pam-enums";-const ACCOUNT_TYPE_CONFIGS = {+enum PamFieldWidget {+ Text = "text",+ Number = "number",+ Boolean = "boolean",+ Select = "select",+ Textarea = "textarea",+ Password = "password"+}++// Source of truth for account types: per-type schemas + sparse UI hints+export const ACCOUNT_TYPE_CONFIGS = {[PamAccountType.Postgres]: {+ name: "PostgreSQL",+ icon: "Postgres.png",connectionDetails: z.object({host: z.string().trim().min(1).max(255),port: z.coerce.number(),@@ -18,11 +31,25 @@ const ACCOUNT_TYPE_CONFIGS = {}),credentials: z.object({username: z.string().trim().min(1).max(63),- password: z.string().trim().min(1).max(256)- })+ password: z+ .string()+ .trim()+ .max(256)+ .transform((v) => v || undefined)+ .optional()+ }),+ sanitizedCredentials: z.object({ username: z.string().optional() }),+ ui: {+ sslEnabled: { label: "SSL Enabled" },+ sslRejectUnauthorized: { label: "Reject Unauthorized" },+ sslCertificate: { label: "SSL Certificate", widget: PamFieldWidget.Textarea },+ password: { widget: PamFieldWidget.Password, secret: true }+ }},[PamAccountType.SSH]: {+ name: "SSH",+ icon: "SSH.png",connectionDetails: z.object({host: z.string().trim().min(1).max(255),port: z.coerce.number()@@ -31,15 +58,33 @@ const ACCOUNT_TYPE_CONFIGS = {z.object({authMethod: z.literal("password"),username: z.string().trim().min(1),- password: z.string().trim().min(1)+ password: z+ .string()+ .trim()+ .transform((v) => v || undefined)+ .optional()}),z.object({authMethod: z.literal("public-key"),username: z.string().trim().min(1),- privateKey: z.string().trim().min(1).max(5000)+ privateKey: z+ .string()+ .trim()+ .max(5000)+ .transform((v) => v || undefined)+ .optional()}),z.object({ authMethod: z.literal("certificate"), username: z.string().trim().min(1) })]),+ sanitizedCredentials: z.object({+ authMethod: z.string().optional(),+ username: z.string().optional()+ }),+ ui: {+ authMethod: { label: "Auth Method" },+ password: { widget: PamFieldWidget.Password, secret: true },+ privateKey: { label: "Private Key", widget: PamFieldWidget.Textarea, secret: true }+ },internalMetadata: z.object({caPrivateKey: z.string(),caPublicKey: z.string(),@@ -49,7 +94,15 @@ const ACCOUNT_TYPE_CONFIGS = {} as const satisfies Partial<Record<PamAccountType,- { connectionDetails: z.ZodTypeAny; credentials: z.ZodTypeAny; internalMetadata?: z.ZodTypeAny }+ {+ name: string;+ icon: string;+ connectionDetails: z.ZodTypeAny;+ credentials: z.ZodTypeAny;+ sanitizedCredentials: z.ZodTypeAny;+ ui?: Record<string, { label?: string; widget?: PamFieldWidget; secret?: boolean }>;+ internalMetadata?: z.ZodTypeAny;+ }>>;@@ -75,7 +128,11 @@ export const validateCredentials = (accountType: PamAccountType, data: unknown)>;};-export { ACCOUNT_TYPE_CONFIGS };+export const sanitizeCredentials = (accountType: PamAccountType, data: unknown) => {+ return getAccountTypeConfig(accountType).sanitizedCredentials.parse(data) as z.output<+ (typeof ACCOUNT_TYPE_CONFIGS)[TSupportedAccountType]["sanitizedCredentials"]+ >;+};export type TGatewayTarget = { host: string; port?: number };@@ -106,3 +163,161 @@ export const parseInternalMetadata = (accountType: PamAccountType, data: unknown}return null;};++// -- Frontend field metadata derived from the schemas above++export const PamFieldDescriptorSchema = z.object({+ key: z.string(),+ label: z.string(),+ widget: z.nativeEnum(PamFieldWidget),+ required: z.boolean(),+ secret: z.boolean(),+ options: z.array(z.object({ label: z.string(), value: z.string() })).optional(),++ // Only render when the discriminator field equals this value+ showWhen: z.object({ field: z.string(), equals: z.string() }).optional()+});++type PamFieldDescriptor = z.infer<typeof PamFieldDescriptorSchema>;++export const PamAccountTypeMetadataSchema = z.object({+ type: z.nativeEnum(PamAccountType),+ name: z.string(),+ icon: z.string(),+ connectionFields: z.array(PamFieldDescriptorSchema),+ credentialFields: z.array(PamFieldDescriptorSchema)+});++type PamAccountTypeMetadata = z.infer<typeof PamAccountTypeMetadataSchema>;++type TFieldUiHint = { label?: string; widget?: PamFieldWidget; secret?: boolean };++const humanizeKey = (key: string) =>+ key+ .replace(/([A-Z])/g, " $1")+ .replace(/^./, (c) => c.toUpperCase())+ .trim();++const unwrapField = (schema: z.ZodTypeAny): { base: z.ZodTypeAny; required: boolean } => {+ let current = schema;+ let required = true;+ for (let depth = 0; depth < 20; depth += 1) {+ const { typeName } = current._def as { typeName?: string };+ if (typeName === "ZodOptional" || typeName === "ZodDefault") {+ required = false;+ current = (current._def as { innerType: z.ZodTypeAny }).innerType;+ } else if (typeName === "ZodNullable") {+ current = (current._def as { innerType: z.ZodTypeAny }).innerType;+ } else if (typeName === "ZodEffects") {+ current = (current._def as { schema: z.ZodTypeAny }).schema;+ } else {+ break;+ }+ }+ return { base: current, required };+};++const widgetForBase = (base: z.ZodTypeAny): PamFieldWidget => {+ const { typeName } = base._def as { typeName?: string };+ if (typeName === "ZodNumber") return PamFieldWidget.Number;+ if (typeName === "ZodBoolean") return PamFieldWidget.Boolean;+ if (typeName === "ZodEnum") return PamFieldWidget.Select;+ return PamFieldWidget.Text;+};++const describeField = (+ key: string,+ schema: z.ZodTypeAny,+ ui: Record<string, TFieldUiHint>,+ showWhen?: PamFieldDescriptor["showWhen"]+): PamFieldDescriptor => {+ const { base, required } = unwrapField(schema);+ const hint = ui[key] ?? {};+ const widget = hint.widget ?? widgetForBase(base);+ const enumValues = (base._def as { values?: string[] }).values;++ return {+ key,+ label: hint.label ?? humanizeKey(key),+ widget,+ required,+ secret: hint.secret ?? widget === PamFieldWidget.Password,+ ...(widget === PamFieldWidget.Select && enumValues+ ? { options: enumValues.map((v) => ({ label: humanizeKey(v), value: v })) }+ : {}),+ ...(showWhen ? { showWhen } : {})+ };+};++const fieldsFromSchema = (schema: z.ZodTypeAny, ui: Record<string, TFieldUiHint> = {}): PamFieldDescriptor[] => {+ const { typeName } = schema._def as { typeName?: string };++ if (typeName === "ZodObject") {+ const { shape } = schema as z.ZodObject<z.ZodRawShape>;+ return Object.entries(shape).map(([key, fieldSchema]) => describeField(key, fieldSchema, ui));+ }++ // Discriminated union (e.g. SSH authMethod)+ if (typeName === "ZodDiscriminatedUnion") {+ const def = schema._def as {+ discriminator: string;+ options: z.ZodObject<z.ZodRawShape>[];+ };+ const variants = [...def.options];+ const { discriminator } = def;++ const occurrences = new Map<string, number>();+ variants.forEach((variant) => {+ Object.keys(variant.shape).forEach((key) => {+ if (key !== discriminator) occurrences.set(key, (occurrences.get(key) ?? 0) + 1);+ });+ });++ const discriminatorValues = variants.map(+ (variant) => (variant.shape[discriminator]._def as { value: string }).value+ );+ const fields: PamFieldDescriptor[] = [+ {+ key: discriminator,+ label: ui[discriminator]?.label ?? humanizeKey(discriminator),+ widget: PamFieldWidget.Select,+ required: true,+ secret: false,+ options: discriminatorValues.map((v) => ({ label: humanizeKey(v), value: v }))+ }+ ];++ const added = new Set<string>([discriminator]);+ variants.forEach((variant) => {+ const variantValue = (variant.shape[discriminator]._def as { value: string }).value;+ Object.entries(variant.shape).forEach(([key, fieldSchema]) => {+ if (key === discriminator) return;+ const isShared = occurrences.get(key) === variants.length;+ if (isShared) {+ if (added.has(key)) return;+ added.add(key);+ fields.push(describeField(key, fieldSchema, ui));+ } else {+ fields.push(describeField(key, fieldSchema, ui, { field: discriminator, equals: variantValue }));+ }+ });+ });+ return fields;+ }++ return [];+};++export const buildPamAccountTypeMetadata = (): PamAccountTypeMetadata[] =>+ (+ Object.entries(ACCOUNT_TYPE_CONFIGS) as [+ TSupportedAccountType,+ (typeof ACCOUNT_TYPE_CONFIGS)[TSupportedAccountType]+ ][]+ ).map(([type, config]) => ({+ type,+ name: config.name,+ icon: config.icon,+ connectionFields: fieldsFromSchema(config.connectionDetails, config.ui),+ credentialFields: fieldsFromSchema(config.credentials, config.ui)+ }));diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex 8017e60c02..4ebd5768ad 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -35,6 +35,7 @@ import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";import { TPamAccountDALFactory } from "./pam-account-dal";import {parseInternalMetadata,+ sanitizeCredentials,type TSshInternalMetadata,validateConnectionDetails,validateCredentials@@ -149,6 +150,10 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>await checkAccount(accountId, account.folderId, projectId, ResourcePermissionPamResourceActions.ReadAccounts, ctx);const connectionDetails = await decrypt(projectId, account.encryptedConnectionDetails);+ const credentials = sanitizeCredentials(+ account.accountType as PamAccountType,+ await decrypt(projectId, account.encryptedCredentials)+ );return {id: account.id,@@ -166,6 +171,7 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>gatewayPoolId: account.gatewayPoolId,recordingConnectionId: account.recordingConnectionId,connectionDetails,+ credentials,createdAt: account.createdAt,updatedAt: account.updatedAt};@@ -327,7 +333,8 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>}if (credentials) {- const validated = validateCredentials(accountType, credentials);+ const existingCredentials = await decrypt(projectId, existing.encryptedCredentials);+ const validated = validateCredentials(accountType, { ...existingCredentials, ...credentials });updateData.encryptedCredentials = await encrypt(projectId, validated);}@@ -403,6 +410,16 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>);if (folderIds.length === 0 && accountIds.length === 0) return { accounts: [], totalCount: 0 };+ const launchScopes = await getResourceIdsWithActions(+ membershipDAL,+ membershipRoleDAL,+ projectId,+ { allOf: [ResourcePermissionPamResourceActions.LaunchSessions] },+ ctx+ );+ const launchFolderIds = new Set(launchScopes.folderIds);+ const launchAccountIds = new Set(launchScopes.accountIds);+const { accounts, totalCount } = await pamAccountDAL.findAccessible(projectId, folderIds, accountIds, {offset,limit,@@ -422,6 +439,7 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>templateName: a.templateName,accountType: a.accountType,projectId: a.projectId,+ canLaunch: launchAccountIds.has(a.id) || (!!a.folderId && launchFolderIds.has(a.folderId)),createdAt: a.createdAt,updatedAt: a.updatedAt})),diff --git a/backend/src/ee/services/pam-membership/pam-membership-service.ts b/backend/src/ee/services/pam-membership/pam-membership-service.tsindex 001a25a753..c9a7315cee 100644--- a/backend/src/ee/services/pam-membership/pam-membership-service.ts+++ b/backend/src/ee/services/pam-membership/pam-membership-service.ts@@ -1,7 +1,7 @@import { ForbiddenError } from "@casl/ability";import { Knex } from "knex";-import { AccessScope, ActionProjectType, RESOURCE_SCOPE, ResourceType } from "@app/db/schemas";+import { AccessScope, ActionProjectType, RESOURCE_SCOPE, ResourceType, TemporaryPermissionMode } from "@app/db/schemas";import { TGroupDALFactory } from "@app/ee/services/group/group-dal";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";import {@@ -9,12 +9,13 @@ import {ResourcePermissionSub} from "@app/ee/services/permission/resource-permission";import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { ms } from "@app/lib/ms";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";import { PamProductRole, PamResourceRole } from "../pam/pam-enums";-import { TActorContext } from "../pam/pam-permission";+import { getResourceIdsWithActions, TActorContext } from "../pam/pam-permission";import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";import { TPamFolderDALFactory } from "../pam-folder/pam-folder-dal";import {@@ -195,6 +196,7 @@ export const pamMembershipServiceFactory = ({groupId: m.actorGroupId,role: roles[0]?.role ?? defaultRole,isActive: m.isActive,+ expiresAt: roles[0]?.isTemporary ? (roles[0]?.temporaryAccessEndTime ?? null) : null,createdAt: m.createdAt};})@@ -476,6 +478,7 @@ export const pamMembershipServiceFactory = ({resourceId: string,resourceKey: string,role: string,+ expiry: string | null | undefined,dto: { userId?: string; groupId?: string } & TActorContext) => {if (!VALID_RESOURCE_ROLES.includes(role as PamResourceRole)) {@@ -484,6 +487,11 @@ export const pamMembershipServiceFactory = ({});}+ const relativeMs = expiry ? ms(expiry) : null;+ if (expiry && (!relativeMs || relativeMs <= 0)) {+ throw new BadRequestError({ message: `Invalid expiry duration '${expiry}'` });+ }+const { column, id, kind } = await validateActorExists(dto, dto.actorOrgId);await validateProductMember(projectId, dto);@@ -493,9 +501,19 @@ export const pamMembershipServiceFactory = ({{ tx });if (existing.length > 0) {- throw new BadRequestError({- message: `${kind === "user" ? "User" : "Group"} is already a member of this ${resourceKey}`- });+ // Expired memberships can be replaced+ const now = new Date();+ const existingRoles = await membershipRoleDAL.find({ membershipId: existing[0].id }, { tx });+ const isStillActive = existingRoles.some(+ (r) => !r.isTemporary || (r.temporaryAccessEndTime && now < new Date(r.temporaryAccessEndTime))+ );+ if (isStillActive) {+ throw new BadRequestError({+ message: `${kind === "user" ? "User" : "Group"} is already a member of this ${resourceKey}`+ });+ }+ await membershipRoleDAL.delete({ membershipId: existing[0].id }, tx);+ await membershipDAL.deleteById(existing[0].id, tx);}const membership = await membershipDAL.create(@@ -508,7 +526,23 @@ export const pamMembershipServiceFactory = ({tx);- const membershipRole = await membershipRoleDAL.create({ membershipId: membership.id, role }, tx);+ const now = new Date();+ const membershipRole = await membershipRoleDAL.create(+ {+ membershipId: membership.id,+ role,+ ...(relativeMs+ ? {+ isTemporary: true,+ temporaryMode: TemporaryPermissionMode.Relative,+ temporaryRange: expiry,+ temporaryAccessStartTime: now,+ temporaryAccessEndTime: new Date(now.getTime() + relativeMs)+ }+ : {})+ },+ tx+ );return {membershipId: membership.id,@@ -516,6 +550,7 @@ export const pamMembershipServiceFactory = ({userId: kind === "user" ? id : undefined,groupId: kind === "group" ? id : undefined,role: membershipRole.role,+ expiresAt: membershipRole.temporaryAccessEndTime ?? null,createdAt: membership.createdAt};});@@ -527,7 +562,7 @@ export const pamMembershipServiceFactory = ({resourceId: string,resourceKey: string,role: string,- dto: { userId?: string; groupId?: string }+ dto: { userId?: string; groupId?: string } & TActorContext) => {if (!VALID_RESOURCE_ROLES.includes(role as PamResourceRole)) {throw new BadRequestError({@@ -535,6 +570,10 @@ export const pamMembershipServiceFactory = ({});}+ if (dto.userId && dto.userId === dto.actorId) {+ throw new ForbiddenRequestError({ message: "You cannot modify your own membership" });+ }+const { column, id, kind } = resolveActorColumn(dto);return membershipDAL.transaction(async (tx) => {@@ -565,8 +604,12 @@ export const pamMembershipServiceFactory = ({resourceType: ResourceType,resourceId: string,resourceKey: string,- dto: { userId?: string; groupId?: string }+ dto: { userId?: string; groupId?: string } & TActorContext) => {+ if (dto.userId && dto.userId === dto.actorId) {+ throw new ForbiddenRequestError({ message: "You cannot modify your own membership" });+ }+const { column, id, kind } = resolveActorColumn(dto);const [membership] = await membershipDAL.find({@@ -605,7 +648,13 @@ export const pamMembershipServiceFactory = ({return listResourceMembers(projectId, ResourceType.PamFolder, folderId);};- const addFolderMember = async ({ projectId, folderId, role, ...dto }: TAddPamFolderMemberDTO & TActorContext) => {+ const addFolderMember = async ({+ projectId,+ folderId,+ role,+ expiry,+ ...dto+ }: TAddPamFolderMemberDTO & TActorContext) => {await checkManageMembers(projectId, { type: ResourceType.PamFolder, id: folderId }, dto);const folder = await pamFolderDAL.findById(folderId);@@ -613,7 +662,7 @@ export const pamMembershipServiceFactory = ({throw new NotFoundError({ message: `Folder with ID '${folderId}' not found` });}- return addResourceMember(projectId, ResourceType.PamFolder, folderId, "folderId", role, dto);+ return addResourceMember(projectId, ResourceType.PamFolder, folderId, "folderId", role, expiry, dto);};const updateFolderMemberRole = async ({@@ -648,9 +697,15 @@ export const pamMembershipServiceFactory = ({return listResourceMembers(projectId, ResourceType.PamAccount, accountId);};- const addAccountMember = async ({ projectId, accountId, role, ...dto }: TAddPamAccountMemberDTO & TActorContext) => {+ const addAccountMember = async ({+ projectId,+ accountId,+ role,+ expiry,+ ...dto+ }: TAddPamAccountMemberDTO & TActorContext) => {await checkAccountManagePermission(projectId, accountId, dto);- return addResourceMember(projectId, ResourceType.PamAccount, accountId, "accountId", role, dto);+ return addResourceMember(projectId, ResourceType.PamAccount, accountId, "accountId", role, expiry, dto);};const updateAccountMemberRole = async ({@@ -668,6 +723,29 @@ export const pamMembershipServiceFactory = ({return removeResourceMember(projectId, ResourceType.PamAccount, accountId, "accountId", dto);};+ const getAccessCapabilities = async ({ projectId, ...ctx }: { projectId: string } & TActorContext) => {+ const { hasRole } = await permissionService.getProjectPermission({+ actor: ctx.actor,+ actorId: ctx.actorId,+ projectId,+ actorAuthMethod: ctx.actorAuthMethod,+ actorOrgId: ctx.actorOrgId,+ actionProjectType: ActionProjectType.PAM+ });+ const isProductAdmin = hasRole(PamProductRole.Admin);++ const { folderIds, accountIds } = await getResourceIdsWithActions(+ membershipDAL,+ membershipRoleDAL,+ projectId,+ { allOf: [ResourcePermissionPamResourceActions.ManageMembers] },+ ctx+ );+ const isResourceAdmin = folderIds.length > 0 || accountIds.length > 0;++ return { isProductAdmin, isResourceAdmin };+ };+return {listProductMembers,addProductMember,@@ -681,6 +759,7 @@ export const pamMembershipServiceFactory = ({listAccountMembers,addAccountMember,updateAccountMemberRole,- removeAccountMember+ removeAccountMember,+ getAccessCapabilities};};diff --git a/backend/src/ee/services/pam-membership/pam-membership-types.ts b/backend/src/ee/services/pam-membership/pam-membership-types.tsindex 19a1641720..432b6a793a 100644--- a/backend/src/ee/services/pam-membership/pam-membership-types.ts+++ b/backend/src/ee/services/pam-membership/pam-membership-types.ts@@ -42,6 +42,7 @@ export type TAddPamFolderMemberDTO = {userId?: string;groupId?: string;role: PamResourceRole;+ expiry?: string | null;};export type TUpdatePamFolderMemberDTO = {@@ -70,6 +71,7 @@ export type TAddPamAccountMemberDTO = {userId?: string;groupId?: string;role: PamResourceRole;+ expiry?: string | null;};export type TUpdatePamAccountMemberDTO = {diff --git a/backend/src/ee/services/pam-project/pam-project-bootstrap.ts b/backend/src/ee/services/pam-project/pam-project-bootstrap.tsindex e68f3f2078..dc0460e230 100644--- a/backend/src/ee/services/pam-project/pam-project-bootstrap.ts+++ b/backend/src/ee/services/pam-project/pam-project-bootstrap.ts@@ -215,7 +215,7 @@ export const bootstrapPamProject = async (const project = await projectDAL.create({- name: "Access Management",+ name: "Privileged Access Manager",slug,type: ProjectType.PAM,orgId,diff --git a/backend/src/ee/services/pam-project/pam-project-resolver.ts b/backend/src/ee/services/pam-project/pam-project-resolver.tsindex eb9bb88802..d6bee9cac7 100644--- a/backend/src/ee/services/pam-project/pam-project-resolver.ts+++ b/backend/src/ee/services/pam-project/pam-project-resolver.ts@@ -24,7 +24,7 @@ export const pamProjectResolverFactory = ({ projectDAL, keyStore }: TResolverDep);if (projects.length === 0) {throw new BadRequestError({- message: "This organization has no Access Management project. Contact your administrator."+ message: "This organization has no Privileged Access Manager project. Contact your administrator."});}return projects[0].id;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.tsdeleted file mode 100644index 3fc32a3002..0000000000--- a/backend/src/ee/services/pam-web-access/pam-session-handler-registry.ts+++ /dev/null@@ -1,27 +0,0 @@-import { PamAccountType } from "@app/ee/services/pam/pam-enums";--import { TSessionContext, TSessionHandlerResult } from "./pam-web-access-types";--export type TWebAccessHandler = (- ctx: TSessionContext,- params: { connectionDetails: Record<string, unknown>; credentials: Record<string, unknown> }-) => Promise<TSessionHandlerResult>;--type TSessionHandlerEntry = {- gatewayAccountType: PamAccountType;- handler: TWebAccessHandler;-};--const registry = new Map<PamAccountType, TSessionHandlerEntry>();--export const registerSessionHandler = (accountType: PamAccountType, entry: TSessionHandlerEntry) => {- registry.set(accountType, entry);-};--export const getSessionHandler = (accountType: PamAccountType): TSessionHandlerEntry | undefined => {- return registry.get(accountType);-};--export const isWebAccessSupported = (accountType: PamAccountType): boolean => {- return registry.has(accountType);-};diff --git a/backend/src/ee/services/pam-web-access/pam-session-handlers.ts b/backend/src/ee/services/pam-web-access/pam-session-handlers.tsnew file mode 100644index 0000000000..005f459f90--- /dev/null+++ b/backend/src/ee/services/pam-web-access/pam-session-handlers.ts@@ -0,0 +1,26 @@+import { PamAccountType } from "@app/ee/services/pam/pam-enums";++import { TSessionContext, TSessionHandlerResult } from "./pam-web-access-types";+import { handlePostgresSession } from "./postgres/pam-postgres-session-handler";+import { handleSSHSession } from "./ssh/pam-ssh-session-handler";++export type TWebAccessHandler = (+ ctx: TSessionContext,+ params: { connectionDetails: Record<string, unknown>; credentials: Record<string, unknown> }+) => Promise<TSessionHandlerResult>;++type TSessionHandlerEntry = {+ gatewayAccountType: PamAccountType;+ handler: TWebAccessHandler;+};++export const SESSION_HANDLERS: Partial<Record<PamAccountType, TSessionHandlerEntry>> = {+ [PamAccountType.Postgres]: {+ gatewayAccountType: PamAccountType.Postgres,+ handler: handlePostgresSession+ },+ [PamAccountType.SSH]: {+ gatewayAccountType: 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 632624af65..6eea09d671 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@@ -1,27 +1,19 @@-import "./postgres/pam-postgres-session-handler";-import "./ssh/pam-ssh-session-handler";-import net from "node:net";-import { ForbiddenError } from "@casl/ability";import type WebSocket from "ws";-import { ResourceType } from "@app/db/schemas";import { AuditLogInfo, EventType, TAuditLogServiceFactory } from "@app/ee/services/audit-log/audit-log-types";import { 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-account-template-schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";-import {- ResourcePermissionPamResourceActions,- ResourcePermissionSub-} from "@app/ee/services/permission/resource-permission";+import { ResourcePermissionPamResourceActions } from "@app/ee/services/permission/resource-permission";import { BadRequestError, NotFoundError } from "@app/lib/errors";import { GatewayProxyProtocol } from "@app/lib/gateway/types";import { createGatewayConnection, createRelayConnection, setupRelayServer } from "@app/lib/gateway-v2/gateway-v2";import { logger } from "@app/lib/logger";-import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";+import { ActorType } from "@app/services/auth/auth-type";import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-service";import { TokenType } from "@app/services/auth-token/auth-token-types";import { TKmsServiceFactory } from "@app/services/kms/kms-service";@@ -29,10 +21,11 @@ import { KmsDataKey } from "@app/services/kms/kms-types";import { TUserDALFactory } from "@app/services/user/user-dal";import { PamAccessMethod, PamSessionStatus } from "../pam/pam-enums";+import { checkAccountAccess } from "../pam/pam-permission";import { TPamAccountDALFactory } from "../pam-account/pam-account-dal";import { extractGatewayTarget } from "../pam-account/pam-account-schemas";import { TPamSessionDALFactory } from "../pam-session/pam-session-dal";-import { getSessionHandler, isWebAccessSupported } from "./pam-session-handler-registry";+import { SESSION_HANDLERS } from "./pam-session-handlers";import {DEFAULT_WEB_SESSION_DURATION_MS,MAX_WEB_SESSIONS_PER_USER,@@ -125,48 +118,6 @@ export const pamWebAccessServiceFactory = ({socket.close();};- const checkLaunchPermission = async (- projectId: string,- accountId: string,- folderId: string | null | undefined,- ctx: { actorId: string; actor: ActorType; actorOrgId: string; actorAuthMethod: ActorAuthMethod }- ) => {- if (folderId) {- try {- const { permission } = await permissionService.getResourcePermission({- actor: ctx.actor,- actorId: ctx.actorId,- projectId,- resourceType: ResourceType.PamFolder,- resourceId: folderId,- actorAuthMethod: ctx.actorAuthMethod,- actorOrgId: ctx.actorOrgId- });- ForbiddenError.from(permission).throwUnlessCan(- ResourcePermissionPamResourceActions.LaunchSessions,- 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(- ResourcePermissionPamResourceActions.LaunchSessions,- ResourcePermissionSub.PamResource- );- };-const issueWebSocketTicket = async ({accountId,projectId,@@ -182,7 +133,7 @@ export const pamWebAccessServiceFactory = ({throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });}- if (!isWebAccessSupported(account.accountType as PamAccountType)) {+ if (!SESSION_HANDLERS[account.accountType as PamAccountType]) {throw new BadRequestError({ message: "Web access is not supported for this account type" });}@@ -205,12 +156,19 @@ export const pamWebAccessServiceFactory = ({? policy.maxSessionDurationSeconds * 1000: DEFAULT_WEB_SESSION_DURATION_MS;- await checkLaunchPermission(projectId, accountId, account.folderId, {- actorId: actor.id,- actor: actor.type,- actorOrgId: actor.orgId,- actorAuthMethod: actor.authMethod- });+ await checkAccountAccess(+ permissionService,+ accountId,+ account.folderId,+ projectId,+ ResourcePermissionPamResourceActions.LaunchSessions,+ {+ actorId: actor.id,+ actor: actor.type,+ actorOrgId: actor.orgId,+ actorAuthMethod: actor.authMethod+ }+ );await pamSessionDAL.endExpiredWebSessions(actor.id, projectId);const activeCount = await pamSessionDAL.countActiveWebSessions(actor.id, projectId);@@ -380,7 +338,7 @@ export const pamWebAccessServiceFactory = ({throw new BadRequestError({ message: "Invalid account or project" });}- const handlerEntry = getSessionHandler(account.accountType as PamAccountType);+ const handlerEntry = SESSION_HANDLERS[account.accountType as PamAccountType];if (!handlerEntry) {throw new BadRequestError({ message: "Web access is not supported for this account type" });}diff --git a/backend/src/ee/services/pam-web-access/postgres/pam-postgres-session-handler.ts b/backend/src/ee/services/pam-web-access/postgres/pam-postgres-session-handler.tsindex c0696366cc..62b481bf5b 100644--- a/backend/src/ee/services/pam-web-access/postgres/pam-postgres-session-handler.ts+++ b/backend/src/ee/services/pam-web-access/postgres/pam-postgres-session-handler.ts@@ -1,9 +1,7 @@import crypto from "crypto";-import { PamAccountType } from "@app/ee/services/pam/pam-enums";import { logger } from "@app/lib/logger";-import { registerSessionHandler } from "../pam-session-handler-registry";import { parseClientMessage } from "../pam-web-access-fns";import {SessionEndReason,@@ -30,7 +28,7 @@ const toPgErrorFields = (err: unknown) => {return { message: pgErr.message, detail: pgErr.detail, hint: pgErr.hint };};-const handlePostgresSession = async (+export const handlePostgresSession = async (ctx: TSessionContext,params: { connectionDetails: Record<string, unknown>; credentials: Record<string, unknown> }): Promise<TSessionHandlerResult> => {@@ -244,8 +242,3 @@ const handlePostgresSession = async (}};};--registerSessionHandler(PamAccountType.Postgres, {- gatewayAccountType: PamAccountType.Postgres,- handler: handlePostgresSession-});diff --git a/backend/src/ee/services/pam-web-access/ssh/pam-ssh-session-handler.ts b/backend/src/ee/services/pam-web-access/ssh/pam-ssh-session-handler.tsindex c59842dab4..2f2da65362 100644--- a/backend/src/ee/services/pam-web-access/ssh/pam-ssh-session-handler.ts+++ b/backend/src/ee/services/pam-web-access/ssh/pam-ssh-session-handler.ts@@ -1,9 +1,7 @@import { Client, type ClientChannel, type ConnectConfig } from "ssh2";-import { PamAccountType } from "@app/ee/services/pam/pam-enums";import { logger } from "@app/lib/logger";-import { registerSessionHandler } from "../pam-session-handler-registry";import { parseClientMessage, resolveEndReason } from "../pam-web-access-fns";import {SessionEndReason,@@ -13,7 +11,7 @@ import {} from "../pam-web-access-types";import { SshClientMessageSchema, SshClientMessageType } from "./pam-ssh-ws-types";-const handleSSHSession = async (+export const handleSSHSession = async (ctx: TSessionContext,params: { connectionDetails: Record<string, unknown>; credentials: Record<string, unknown> }): Promise<TSessionHandlerResult> => {@@ -128,8 +126,3 @@ const handleSSHSession = async (client.connect(connectConfig);});};--registerSessionHandler(PamAccountType.SSH, {- gatewayAccountType: PamAccountType.SSH,- handler: handleSSHSession-});diff --git a/backend/src/ee/services/pam/CLAUDE.md b/backend/src/ee/services/pam/CLAUDE.mdindex 60b4630ee7..67856ccbc2 100644--- a/backend/src/ee/services/pam/CLAUDE.md+++ b/backend/src/ee/services/pam/CLAUDE.md@@ -46,6 +46,7 @@ Every list/mutation endpoint checks action-level permissions, not just membershi| Endpoint | Required Permission ||---|---|+| Get access capabilities | Product membership (returns `isProductAdmin` / `isResourceAdmin` flags for sidebar gating) || List folders | `ReadFolder` (via `getResourceIdsWithActions`) || List accounts | `ReadAccounts` (via `getResourceIdsWithActions`) || List accessible accounts | `ReadAccounts` AND (`LaunchSessions` OR `ViewCredentials`) |@@ -73,23 +74,44 @@ Resource memberships are scoped to either a `PamFolder` or a `PamAccount` via th## 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.+Defined in `pam/pam-enums.ts` as `PamAccountType`. Each type's full config lives in `pam-account/pam-account-schemas.ts` in the `ACCOUNT_TYPE_CONFIGS` map. A config entry holds everything the backend and frontend need for that type:++- `name` -- human-readable label (e.g. `"PostgreSQL"`), served to the frontend+- `icon` -- icon filename under the frontend's account-platform icons (e.g. `"Postgres.png"`)+- `connectionDetails` -- Zod schema for the non-secret connection fields+- `credentials` -- Zod schema for the secret credentials (a `ZodObject` or a `ZodDiscriminatedUnion`)+- `sanitizedCredentials` -- Zod allowlist of credential fields that are safe to return in API responses (e.g. `username` but never `password`). This is the single source of truth for what's a secret -- there is no string-matching denylist.+- `ui` -- optional sparse per-field hints (`{ label?, widget?, secret? }`) for fields whose label/widget can't be inferred from the schema. Anything not listed is inferred.++### Schema-Driven Forms++The frontend renders the create/edit account forms entirely from backend metadata -- there are **no per-type frontend components**. `buildPamAccountTypeMetadata()` walks each config's Zod schemas and emits `PamFieldDescriptor`s (`{ key, label, widget, required, secret, options?, showWhen? }`). The `GET /pam/accounts/types` endpoint serves these as `PamAccountTypeMetadata` (`{ type, name, icon, connectionFields, credentialFields }`).++How descriptors are derived:+- **Label** -- `ui[key].label`, else humanized from the field key.+- **Widget** -- `ui[key].widget`, else inferred from the Zod base type (`ZodNumber` -> `number`, `ZodBoolean` -> `boolean`, `ZodEnum` -> `select` with `options`, else `text`). `password`/`textarea` must be set via `ui` since they're not inferable.+- **Required** -- a field is optional if its schema is `ZodOptional`/`ZodDefault`/nullable (the builder peels these via `unwrapField`).+- **Secret** -- `ui[key].secret`, else `true` when the widget is `password`. Secret fields use the write-only `PamPasswordInput` (sentinel-based, see below).+- **Discriminated unions** (e.g. SSH `authMethod`) -- the discriminator becomes a `select`; each variant's non-shared fields get a `showWhen: { field, equals }` so the renderer reveals them conditionally.### Key Helpers- **`extractGatewayTarget(accountType, rawConnectionDetails)`** -- validated extraction of `{ host, port }` from decrypted connection details, dispatched by account type. Use this instead of raw type casts.+- **`sanitizeCredentials(accountType, decrypted)`** -- strips secret fields from decrypted credentials using the type's `sanitizedCredentials` allowlist; used by `getById` before returning credentials to the client.+- **`buildPamAccountTypeMetadata()`** -- builds the field descriptors served by `GET /pam/accounts/types`.- **`PamAccessMethod`** enum (`Web`, `Cli`) -- use instead of hardcoded `"web"`/`"cli"` strings.### 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. Add a case to `extractGatewayTarget` in `pam-account-schemas.ts`-4. If it supports web access: add a session handler in `pam-web-access/` and register it in `pam-session-handler-registry.ts`-5. Add the corresponding frontend enum value and any UI components-6. Update `PamAccountType` on the frontend enum in `frontend/src/hooks/api/pam/enums.ts`+Most types need only backend changes -- the frontend auto-renders from metadata.++1. Add the enum value to `PamAccountType` in `pam/pam-enums.ts` (and the matching frontend enum in `frontend/src/hooks/api/pam/enums.ts` -- the one shared string both sides need).+2. Add a config entry to `ACCOUNT_TYPE_CONFIGS` in `pam-account/pam-account-schemas.ts`: `name`, `icon`, `connectionDetails`, `credentials`, `sanitizedCredentials`, and any `ui` hints (set `widget: "password"`/`"textarea"` and `secret: true` where the schema can't express it).+3. Drop the icon image into `frontend/public/images/integrations/` matching the `icon` filename in the config. No component edit -- `AccountPlatformIcon` and the type pickers resolve the name/icon from `GET /pam/accounts/types`.+4. Add a case to `extractGatewayTarget` in `pam-account-schemas.ts`.+5. If it supports web access: add a session handler in `pam-web-access/` (export the handler function) and add an entry for it to the `SESSION_HANDLERS` map in `pam-session-handlers.ts`.-The router's `ConnectionDetailsSchema` and `SanitizedAccountDetailSchema` auto-derive from `ACCOUNT_TYPE_CONFIGS`, so no router changes are needed for new types.+No changes to the account form components, router schemas, or field renderers are needed. The per-type route bodies use `config.connectionDetails`/`config.credentials` directly, the detail response (`SanitizedAccountDetailSchema`) is a discriminated union auto-derived from `ACCOUNT_TYPE_CONFIGS` (each variant pulls `connectionDetails` and `sanitizedCredentials` from the config), and the frontend forms render from `GET /pam/accounts/types`.## Session Lifecyclediff --git a/backend/src/ee/services/pam/pam-permission.ts b/backend/src/ee/services/pam/pam-permission.tsindex b913827212..d4d8e6ca33 100644--- a/backend/src/ee/services/pam/pam-permission.ts+++ b/backend/src/ee/services/pam/pam-permission.ts@@ -2,6 +2,7 @@ import { createMongoAbility, ForbiddenError } from "@casl/ability";import { ActionProjectType, ResourceType } from "@app/db/schemas";import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { ForbiddenRequestError } 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";@@ -78,7 +79,8 @@ export const checkAccountAccess = async (ForbiddenError.from(permission).throwUnlessCan(action, ResourcePermissionSub.PamResource);return;} catch (err) {- if (!(err instanceof ForbiddenError)) throw err;+ // No folder access: fall back to direct account access+ if (!(err instanceof ForbiddenError) && !(err instanceof ForbiddenRequestError)) throw err;}}