Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
feat: built-in masking
Sheen Capadnganb4ff290d728f
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 7d0a8995c5..c803c32eaf 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@@ -2,7 +2,7 @@ import z from "zod";import { PamAccountsSchema } from "@app/db/schemas";import { EventType } from "@app/ee/services/audit-log/audit-log-types";-import { PamAccessStatus, PamAccountType, PamHeartbeatStatus } from "@app/ee/services/pam/pam-enums";+import { PamAccessStatus, PamAccountType, PamAccountWarning, PamHeartbeatStatus } from "@app/ee/services/pam/pam-enums";import {ACCOUNT_TYPE_CONFIGS,buildPamAccountTypeMetadata,@@ -58,6 +58,9 @@ const PamAccountListItemSchema = SanitizedAccountListItemSchema.extend({.array(z.nativeEnum(PamAccountAccessibilityIssue)).describe("Reasons the account cannot launch a session, if any"),isStale: z.boolean().describe("Whether the discovery source's latest scan no longer found this account."),+ warnings: z+ .array(z.nativeEnum(PamAccountWarning))+ .describe("Conditions worth surfacing on the account that do not block launching a session."),heartbeatStatus: z.nativeEnum(PamHeartbeatStatus).nullable()diff --git a/backend/src/ee/routes/v2/gateway-router.ts b/backend/src/ee/routes/v2/gateway-router.tsindex ac0cb8456a..2ab7e9e74b 100644--- a/backend/src/ee/routes/v2/gateway-router.ts+++ b/backend/src/ee/routes/v2/gateway-router.ts@@ -136,7 +136,8 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {.object({capabilities: z.object({- pkcs11: z.boolean().optional()+ pkcs11: z.boolean().optional(),+ sessionLogMaskingBuiltInDetection: z.boolean().optional()}).optional()})diff --git a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts b/backend/src/ee/services/gateway-v2/gateway-v2-service.tsindex 227cb3664a..31ba70b5de 100644--- a/backend/src/ee/services/gateway-v2/gateway-v2-service.ts+++ b/backend/src/ee/services/gateway-v2/gateway-v2-service.ts@@ -1055,7 +1055,7 @@ export const gatewayV2ServiceFactory = ({capabilities}: {orgPermission: OrgServiceActor;- capabilities?: { pkcs11?: boolean };+ capabilities?: { pkcs11?: boolean; sessionLogMaskingBuiltInDetection?: boolean };}) => {const nextCapabilities = capabilities ?? {};diff --git a/backend/src/ee/services/pam-account-template/pam-account-template-schemas.test.ts b/backend/src/ee/services/pam-account-template/pam-account-template-schemas.test.tsnew file mode 100644index 0000000000..1fee7f8fbf--- /dev/null+++ b/backend/src/ee/services/pam-account-template/pam-account-template-schemas.test.ts@@ -0,0 +1,47 @@+import { describe, expect, test } from "vitest";++import { PamTemplateSettingsInputSchema, PamTemplateSettingsSchema } from "./pam-account-template-schemas";++describe("session log masking settings", () => {+ describe("read path", () => {+ test("treats a template predating built-in detection as opted out", () => {+ const parsed = PamTemplateSettingsSchema.parse({});+ expect(parsed.sessionLogMaskingBuiltInDetection).toBe(false);+ });++ test("preserves an explicit choice", () => {+ expect(+ PamTemplateSettingsSchema.parse({ sessionLogMaskingBuiltInDetection: true }).sessionLogMaskingBuiltInDetection+ ).toBe(true);+ expect(+ PamTemplateSettingsSchema.parse({ sessionLogMaskingBuiltInDetection: false }).sessionLogMaskingBuiltInDetection+ ).toBe(false);+ });+ });++ describe("write path", () => {+ // A default here would switch detection on during an unrelated edit.+ test("leaves the field absent when the caller omits it", () => {+ const parsed = PamTemplateSettingsInputSchema.parse({ recordingStorageBackend: "postgres" });+ expect(parsed.sessionLogMaskingBuiltInDetection).toBeUndefined();+ expect("sessionLogMaskingBuiltInDetection" in parsed).toBe(false);+ });++ test("carries an explicit choice through", () => {+ expect(+ PamTemplateSettingsInputSchema.parse({ sessionLogMaskingBuiltInDetection: true })+ .sessionLogMaskingBuiltInDetection+ ).toBe(true);+ expect(+ PamTemplateSettingsInputSchema.parse({ sessionLogMaskingBuiltInDetection: false })+ .sessionLogMaskingBuiltInDetection+ ).toBe(false);+ });++ test("rejects a non-boolean", () => {+ expect(PamTemplateSettingsInputSchema.safeParse({ sessionLogMaskingBuiltInDetection: "yes" }).success).toBe(+ false+ );+ });+ });+});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 1e3d459cb4..678f458424 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@@ -36,14 +36,17 @@ export const PamTemplateSettingsSchema = z.object({passwordRequirements: PasswordRequirementsSchema.optional(),rotation: PamRotationConfigSchema.optional(),heartbeat: PamHeartbeatConfigSchema.optional(),- sessionLogMaskingPatterns: z.string().optional()+ sessionLogMaskingPatterns: z.string().optional(),+ sessionLogMaskingBuiltInDetection: z.boolean().default(false)});export const PamTemplateSettingsInputSchema = PamTemplateSettingsSchema.extend({- sessionLogMaskingPatterns: patternsStringSchema().optional()+ sessionLogMaskingPatterns: patternsStringSchema().optional(),+ sessionLogMaskingBuiltInDetection: z.boolean().optional()});export type TPamTemplateSettings = z.infer<typeof PamTemplateSettingsSchema>;+export type TPamTemplateSettingsInput = z.infer<typeof PamTemplateSettingsInputSchema>;export type TPamAccountSettingsOverrides = z.infer<typeof PamAccountSettingsOverridesSchema>;export type TPamRotationConfig = z.infer<typeof PamRotationConfigSchema>;export type TPamHeartbeatConfig = z.infer<typeof PamHeartbeatConfigSchema>;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 e78a4c9d7f..3d4e454e4c 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@@ -2,7 +2,7 @@ import { TPermissionServiceFactory } from "@app/ee/services/permission/permissioimport { DatabaseErrorCode } from "@app/lib/error-codes";import { BadRequestError, DatabaseError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";-import { PamAccountType, PamProductRole } from "../pam/pam-enums";+import { accountTypeSupportsSessionLogMasking, PamAccountType, PamProductRole } from "../pam/pam-enums";import { TActorContext, verifyProductMembership } from "../pam/pam-permission";import { validatePolicyValues } from "../pam/pam-policies";import {@@ -23,7 +23,8 @@ import {DEFAULT_HEARTBEAT_CONFIG,PamRecordingS3ConfigSchema,PamTemplateSettingsSchema,- TPamTemplateSettings+ TPamTemplateSettings,+ TPamTemplateSettingsInput} from "./pam-account-template-schemas";import {TCreatePamAccountTemplateDTO,@@ -65,7 +66,7 @@ export const pamAccountTemplateServiceFactory = (deps: TPamAccountTemplateServic// Reject rotation config on non-rotatable template types (the settings schema can't, since the type is a sibling// field). The supported-type list is derived from the registry so it never goes stale as types are added.- const validateTemplateRotationConfig = (accountType: string, settings: TPamTemplateSettings | undefined) => {+ const validateTemplateRotationConfig = (accountType: string, settings: TPamTemplateSettingsInput | undefined) => {if (!settings) return;const hasRotationConfig = settings.rotation !== undefined || settings.passwordRequirements !== undefined;if (hasRotationConfig && !isRotatableAccountType(accountType)) {@@ -103,7 +104,7 @@ export const pamAccountTemplateServiceFactory = (deps: TPamAccountTemplateServicconst validateTemplateRecordingS3Config = async (recordingConnectionId: string | null | undefined,- settings: TPamTemplateSettings | undefined,+ settings: TPamTemplateSettingsInput | undefined,ctx: TActorContext): Promise<TPamRecordingResolvedConfig | null> => {const isS3Backend = settings?.recordingStorageBackend === PamRecordingStorageBackend.AwsS3;@@ -165,12 +166,15 @@ export const pamAccountTemplateServiceFactory = (deps: TPamAccountTemplateServicconst resolvedS3Config = await validateTemplateRecordingS3Config(recordingConnectionId, settings, ctx);- // Credential health checking is on for a new template unless the caller says otherwise.+ // Credential health checking and built-in masking are on for a new template unless the caller+ // says otherwise.// Partial on purpose: the schema's defaults are applied on read, exactly as they were when create stored// no settings at all.const seededSettings: Partial<TPamTemplateSettings> = {...(settings ?? {}),- heartbeat: settings?.heartbeat ?? DEFAULT_HEARTBEAT_CONFIG+ heartbeat: settings?.heartbeat ?? DEFAULT_HEARTBEAT_CONFIG,+ sessionLogMaskingBuiltInDetection:+ settings?.sessionLogMaskingBuiltInDetection ?? accountTypeSupportsSessionLogMasking(type)};try {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 76ea19d9d8..fb9060eb9f 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 { TPamTemplateSettings } from "./pam-account-template-schemas";+import { TPamTemplateSettingsInput } from "./pam-account-template-schemas";export type TCreatePamAccountTemplateDTO = {projectId: string;@@ -7,7 +7,7 @@ export type TCreatePamAccountTemplateDTO = {description?: string;type: PamAccountType;policies?: Record<string, unknown>;- settings?: TPamTemplateSettings;+ settings?: TPamTemplateSettingsInput;gatewayId?: string;gatewayPoolId?: string;recordingConnectionId?: string;@@ -19,7 +19,7 @@ export type TUpdatePamAccountTemplateDTO = {name?: string;description?: string | null;policies?: Record<string, unknown>;- settings?: TPamTemplateSettings;+ settings?: TPamTemplateSettingsInput;gatewayId?: string | null;gatewayPoolId?: string | null;recordingConnectionId?: string | null;diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex 711bdf30d1..343402a582 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -2,6 +2,7 @@ import { createMongoAbility, ForbiddenError, MongoAbility, MongoQuery, RawRuleOfimport { packRules } from "@casl/ability/extra";import { RESOURCE_SCOPE, ResourceType, TPamAccountTemplates } from "@app/db/schemas";+import { TGatewayPoolMembershipDALFactory } from "@app/ee/services/gateway-pool/gateway-pool-membership-dal";import { TGatewayPoolServiceFactory } from "@app/ee/services/gateway-pool/gateway-pool-service";import { TGatewayV2DALFactory } from "@app/ee/services/gateway-v2/gateway-v2-dal";import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2-service";@@ -30,9 +31,11 @@ import { TUserDALFactory } from "@app/services/user/user-dal";import { testConnectionWithGateway } from "../gateway-v2/gateway-v2-fns";import {+ accountTypeSupportsSessionLogMasking,PamAccessStatus,PamAccessType,PamAccountType,+ PamAccountWarning,PamHeartbeatStatus,PamProductRole,PamSessionStatus@@ -116,7 +119,8 @@ type TPamAccountServiceFactoryDep = {"getProjectPermission" | "getResourcePermission" | "getOrgPermission">;kmsService: Pick<TKmsServiceFactory, "createCipherPairWithDataKey">;- gatewayV2DAL: Pick<TGatewayV2DALFactory, "findOne">;+ gatewayV2DAL: Pick<TGatewayV2DALFactory, "findOne" | "find">;+ gatewayPoolMembershipDAL: Pick<TGatewayPoolMembershipDALFactory, "find">;gatewayV2Service: Pick<TGatewayV2ServiceFactory,"getPlatformConnectionDetailsByGatewayId" | "getPAMConnectionDetails"@@ -206,6 +210,8 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>kmsService,gatewayV2Service,gatewayPoolService,+ gatewayPoolMembershipDAL,+ gatewayV2DAL,licenseService} = deps;@@ -238,6 +244,66 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>return { isAccessible: accessibilityIssues.length === 0, accessibilityIssues };};+ // The gateway performs the masking, so a build predating built-in detection ignores the+ // template's setting without reporting anything. Derived server-side because listing gateways is+ // an org-admin permission, and a PAM member who can see the account must still see this.+ const $resolveMaskingDegraded = async (+ orgId: string,+ accounts: {+ accountType: string;+ gatewayId?: string | null;+ gatewayPoolId?: string | null;+ templateGatewayId: string | null;+ templateGatewayPoolId: string | null;+ templateSettings: unknown;+ }[]+ ) => {+ const candidates = accounts.map((a) => ({+ enabled:+ accountTypeSupportsSessionLogMasking(a.accountType as PamAccountType) &&+ PamTemplateSettingsSchema.safeParse(a.templateSettings).data?.sessionLogMaskingBuiltInDetection === true,+ // Mirrors the session launch path: each field falls back to the template independently,+ // and a direct gateway wins over a pool.+ gatewayId: a.gatewayId ?? a.templateGatewayId,+ gatewayPoolId: a.gatewayPoolId ?? a.templateGatewayPoolId+ }));++ const poolIds = [+ ...new Set(candidates.filter((c) => c.enabled && !c.gatewayId && c.gatewayPoolId).map((c) => c.gatewayPoolId!))+ ];+ const memberships = poolIds.length ? await gatewayPoolMembershipDAL.find({ $in: { gatewayPoolId: poolIds } }) : [];+ const poolGatewayIds = new Map<string, string[]>();+ memberships.forEach((m) => {+ poolGatewayIds.set(m.gatewayPoolId, [...(poolGatewayIds.get(m.gatewayPoolId) ?? []), m.gatewayId]);+ });++ const gatewayIds = [+ ...new Set([+ ...candidates.filter((c) => c.enabled && c.gatewayId).map((c) => c.gatewayId!),+ ...[...poolGatewayIds.values()].flat()+ ])+ ];+ const gatewayIdSet = new Set(gatewayIds);+ const orgGateways = gatewayIdSet.size ? await gatewayV2DAL.find({ orgId }) : [];+ const gateways = orgGateways.filter((g) => gatewayIdSet.has(g.id));+ const unsupported = new Set(+ gateways+ .filter(+ (g) =>+ (g.capabilities as { sessionLogMaskingBuiltInDetection?: boolean } | undefined)+ ?.sessionLogMaskingBuiltInDetection !== true+ )+ .map((g) => g.id)+ );++ return candidates.map((c) => {+ if (!c.enabled) return false;+ if (c.gatewayId) return unsupported.has(c.gatewayId);+ if (c.gatewayPoolId) return (poolGatewayIds.get(c.gatewayPoolId) ?? []).some((id) => unsupported.has(id));+ return false;+ });+ };+const verifyMembership = (projectId: string, ctx: TActorContext) =>verifyProductMembership(permissionService, projectId, ctx);@@ -324,7 +390,9 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>)]);- return accounts.map((a) => {+ const maskingDegraded = await $resolveMaskingDegraded(ctx.actorOrgId, accounts);++ return accounts.map((a, idx) => {const { accessibilityIssues, isAccessible } = computeAccessibility(a);const { requiresApproval, requireReason, allowBreakGlass } = resolveAccessControls(a.templatePolicies);if (requiresApproval && a.folderId && !foldersWithApprovalPolicy.has(a.folderId)) {@@ -348,6 +416,7 @@ export const pamAccountServiceFactory = (deps: TPamAccountServiceFactoryDep) =>isAccessible: isAccessible && accessibilityIssues.length === 0,accessibilityIssues,isStale: a.isStale,+ warnings: maskingDegraded[idx] ? [PamAccountWarning.SessionLogMaskingDegraded] : [],heartbeatStatus: (a.heartbeatStatus as PamHeartbeatStatus | null) ?? null,heartbeatEnabled: Boolean(a.heartbeatEnabled),requiresApproval,diff --git a/backend/src/ee/services/pam-project/pam-project-bootstrap.ts b/backend/src/ee/services/pam-project/pam-project-bootstrap.tsindex 91ab69fb6b..3d5b538ae7 100644--- a/backend/src/ee/services/pam-project/pam-project-bootstrap.ts+++ b/backend/src/ee/services/pam-project/pam-project-bootstrap.ts@@ -7,7 +7,7 @@ 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 } from "../pam/pam-enums";+import { accountTypeSupportsSessionLogMasking, PamAccountType } from "../pam/pam-enums";import { TPamTemplateSettings } from "../pam-account-template/pam-account-template-schemas";import { PamRecordingStorageBackend } from "../pam-session-recording/pam-recording-enums";@@ -30,120 +30,31 @@ export type TDefaultTemplate = {settings: TPamTemplateSettings;};-export const DEFAULT_ACCOUNT_TEMPLATES: TDefaultTemplate[] = [- {- name: "ssh",- type: PamAccountType.SSH,- settings: {- recordingEnabled: true,- recordingStorageBackend: PamRecordingStorageBackend.Postgres- }- },- {- name: "postgres",- type: PamAccountType.Postgres,- settings: {- recordingEnabled: true,- recordingStorageBackend: PamRecordingStorageBackend.Postgres- }- },- {- name: "mysql",- type: PamAccountType.MySQL,- settings: {- recordingEnabled: true,- recordingStorageBackend: PamRecordingStorageBackend.Postgres- }- },- {- name: "mssql",- type: PamAccountType.MsSQL,- settings: {- recordingEnabled: true,- recordingStorageBackend: PamRecordingStorageBackend.Postgres- }- },- {- name: "oracledb",- type: PamAccountType.OracleDB,- settings: {- recordingEnabled: true,- recordingStorageBackend: PamRecordingStorageBackend.Postgres- }- },- {- name: "mongodb",- type: PamAccountType.MongoDB,- settings: {- recordingEnabled: true,- recordingStorageBackend: PamRecordingStorageBackend.Postgres- }- },- {- name: "redis",- type: PamAccountType.Redis,- settings: {- recordingEnabled: true,- recordingStorageBackend: PamRecordingStorageBackend.Postgres- }- },- {- name: "kubernetes",- type: PamAccountType.Kubernetes,- settings: {- recordingEnabled: true,- recordingStorageBackend: PamRecordingStorageBackend.Postgres- }- },- {- name: "aws-iam",- type: PamAccountType.AwsIam,- settings: {- recordingEnabled: true,- recordingStorageBackend: PamRecordingStorageBackend.Postgres- }- },- {- name: "gcp-service-account",- type: PamAccountType.GcpServiceAccount,- settings: {- recordingEnabled: true,- recordingStorageBackend: PamRecordingStorageBackend.Postgres- }- },- {- name: "azure-cli",- type: PamAccountType.AzureCli,- settings: {- recordingEnabled: true,- recordingStorageBackend: PamRecordingStorageBackend.Postgres- }- },- {- name: "windows",- type: PamAccountType.Windows,- settings: {- recordingEnabled: true,- recordingStorageBackend: PamRecordingStorageBackend.Postgres- }- },- {- name: "windows-ad",- type: PamAccountType.WindowsAd,- settings: {- recordingEnabled: true,- recordingStorageBackend: PamRecordingStorageBackend.Postgres- }- },- {- name: "snowflake",- type: PamAccountType.Snowflake,- settings: {- recordingEnabled: true,- recordingStorageBackend: PamRecordingStorageBackend.Postgres- }- }-];+const defaultTemplateSettings = (type: PamAccountType): TPamTemplateSettings => ({+ recordingEnabled: true,+ recordingStorageBackend: PamRecordingStorageBackend.Postgres,+ // A seeded template is a new template, so masking starts on, as it does in `create`.+ sessionLogMaskingBuiltInDetection: accountTypeSupportsSessionLogMasking(type)+});++export const DEFAULT_ACCOUNT_TEMPLATES: TDefaultTemplate[] = (+ [+ { name: "ssh", type: PamAccountType.SSH },+ { name: "postgres", type: PamAccountType.Postgres },+ { name: "mysql", type: PamAccountType.MySQL },+ { name: "mssql", type: PamAccountType.MsSQL },+ { name: "oracledb", type: PamAccountType.OracleDB },+ { name: "mongodb", type: PamAccountType.MongoDB },+ { name: "redis", type: PamAccountType.Redis },+ { name: "kubernetes", type: PamAccountType.Kubernetes },+ { name: "aws-iam", type: PamAccountType.AwsIam },+ { name: "gcp-service-account", type: PamAccountType.GcpServiceAccount },+ { name: "azure-cli", type: PamAccountType.AzureCli },+ { name: "windows", type: PamAccountType.Windows },+ { name: "windows-ad", type: PamAccountType.WindowsAd },+ { name: "snowflake", type: PamAccountType.Snowflake }+ ] as const+).map(({ name, type }) => ({ name, type, settings: defaultTemplateSettings(type) }));export const bootstrapPamProject = async ({ orgId, adminUserIds = [], adminIdentityIds = [], adminGroupIds = [] }: TBootstrapInput,diff --git a/backend/src/ee/services/pam-session/pam-session-service.ts b/backend/src/ee/services/pam-session/pam-session-service.tsindex 7f5ab12aa2..837ca0fadd 100644--- a/backend/src/ee/services/pam-session/pam-session-service.ts+++ b/backend/src/ee/services/pam-session/pam-session-service.ts@@ -19,6 +19,7 @@ import { TTelemetryServiceFactory } from "@app/services/telemetry/telemetry-servimport { TUserDALFactory } from "@app/services/user/user-dal";import {+ accountTypeSupportsSessionLogMasking,PamAccessMethod,PamAccessStatus,PamAccountType,@@ -36,8 +37,8 @@ import {verifyProductMembership} from "../pam/pam-permission";import {+ buildPamPolicyRules,PamPolicyType,- PamSettingType,policyAppliesTo,resolveAccessControls,resolvePolicy,@@ -374,19 +375,16 @@ export const pamSessionServiceFactory = ({: [];const parsedSettings = PamTemplateSettingsSchema.safeParse(account.templateSettings ?? {});- const maskingPatterns = parsedSettings.success- ? splitPatternString(parsedSettings.data.sessionLogMaskingPatterns)- : [];- const policyRules =- commandBlockingPatterns.length > 0 || maskingPatterns.length > 0- ? {- ...(commandBlockingPatterns.length > 0- ? { [PamPolicyType.CommandBlocking]: { patterns: commandBlockingPatterns } }- : {}),- ...(maskingPatterns.length > 0 ? { [PamSettingType.SessionLogMasking]: { patterns: maskingPatterns } } : {})- }- : null;+ const policyRules = buildPamPolicyRules({+ commandBlockingPatterns,+ maskingPatterns: parsedSettings.success ? splitPatternString(parsedSettings.data.sessionLogMaskingPatterns) : [],+ // Never send a rule the gateway has no way to honour.+ maskingBuiltInDetection:+ accountTypeSupportsSessionLogMasking(account.accountType as PamAccountType) &&+ parsedSettings.success &&+ parsedSettings.data.sessionLogMaskingBuiltInDetection+ });const normalizedConnectionDetails = buildSessionGatewayConnectionDetails(account.accountType as PamAccountType,diff --git a/backend/src/ee/services/pam/pam-enums.ts b/backend/src/ee/services/pam/pam-enums.tsindex 336dce1f55..e2665b69df 100644--- a/backend/src/ee/services/pam/pam-enums.ts+++ b/backend/src/ee/services/pam/pam-enums.ts@@ -101,3 +101,14 @@ export enum PamNotificationEvent {// Best-effort: the tunnel is torn down either way.export const PAM_CANCELLATION_FLUSH_TIMEOUT_MS = 5000;++// Informational conditions surfaced on an account. Unlike PamAccountAccessibilityIssue these gate+// nothing: the account launches, records and rotates as normal.+export enum PamAccountWarning {+ SessionLogMaskingDegraded = "session-log-masking-degraded"+}++// These are brokered over RDP, whose recordings are base64 frames rather than terminal text, so+// the gateway never masks them.+export const accountTypeSupportsSessionLogMasking = (accountType: PamAccountType): boolean =>+ accountType !== PamAccountType.Windows && accountType !== PamAccountType.WindowsAd;diff --git a/backend/src/ee/services/pam/pam-policies.test.ts b/backend/src/ee/services/pam/pam-policies.test.tsindex 66de4a9478..79787f5ef9 100644--- a/backend/src/ee/services/pam/pam-policies.test.ts+++ b/backend/src/ee/services/pam/pam-policies.test.ts@@ -1,7 +1,14 @@import { describe, expect, test } from "vitest";-import { PamAccountType } from "./pam-enums";-import { getApplicablePolicies, PamPolicyType, resolveAccessControls, validatePolicyValues } from "./pam-policies";+import { accountTypeSupportsSessionLogMasking, PamAccountType } from "./pam-enums";+import {+ buildPamPolicyRules,+ getApplicablePolicies,+ PamPolicyType,+ PamSettingType,+ resolveAccessControls,+ validatePolicyValues+} from "./pam-policies";describe("getApplicablePolicies", () => {test("returns the universal policies for any account type", () => {@@ -167,3 +174,58 @@ describe("resolveAccessControls", () => {});});});++describe("buildPamPolicyRules", () => {+ const empty = { commandBlockingPatterns: [], maskingPatterns: [], maskingBuiltInDetection: false };++ test("returns null when nothing is configured", () => {+ expect(buildPamPolicyRules(empty)).toBeNull();+ });++ test("emits command blocking on its own", () => {+ expect(buildPamPolicyRules({ ...empty, commandBlockingPatterns: ["rm\\s+-rf"] })).toEqual({+ [PamPolicyType.CommandBlocking]: { patterns: ["rm\\s+-rf"] }+ });+ });++ // Must serialize exactly as it did before built-in detection existed.+ test("emits custom masking patterns with detection off", () => {+ expect(buildPamPolicyRules({ ...empty, maskingPatterns: ["password=\\S+"] })).toEqual({+ [PamSettingType.SessionLogMasking]: { patterns: ["password=\\S+"], builtInDetection: false }+ });+ });++ // The case the old shape could not express.+ test("emits the masking rule for detection alone", () => {+ expect(buildPamPolicyRules({ ...empty, maskingBuiltInDetection: true })).toEqual({+ [PamSettingType.SessionLogMasking]: { patterns: [], builtInDetection: true }+ });+ });++ test("emits both arms together", () => {+ expect(+ buildPamPolicyRules({+ commandBlockingPatterns: ["shutdown"],+ maskingPatterns: ["token=\\S+"],+ maskingBuiltInDetection: true+ })+ ).toEqual({+ [PamPolicyType.CommandBlocking]: { patterns: ["shutdown"] },+ [PamSettingType.SessionLogMasking]: { patterns: ["token=\\S+"], builtInDetection: true }+ });+ });+});++describe("accountTypeSupportsSessionLogMasking", () => {+ test("is false for the RDP-brokered types", () => {+ expect(accountTypeSupportsSessionLogMasking(PamAccountType.Windows)).toBe(false);+ expect(accountTypeSupportsSessionLogMasking(PamAccountType.WindowsAd)).toBe(false);+ });++ test("is true for everything else", () => {+ const rest = Object.values(PamAccountType).filter(+ (type) => type !== PamAccountType.Windows && type !== PamAccountType.WindowsAd+ );+ expect(rest.every(accountTypeSupportsSessionLogMasking)).toBe(true);+ });+});diff --git a/backend/src/ee/services/pam/pam-policies.ts b/backend/src/ee/services/pam/pam-policies.tsindex b09d7d7ec5..444af8f886 100644--- a/backend/src/ee/services/pam/pam-policies.ts+++ b/backend/src/ee/services/pam/pam-policies.ts@@ -192,14 +192,51 @@ export type TPamAccessControls = {const PamPolicyRulePatternSchema = z.object({ patterns: z.array(z.string()) });+const PamSessionLogMaskingRuleSchema = PamPolicyRulePatternSchema.extend({+ builtInDetection: z.boolean()+});+export const PamPolicyRulesSchema = z.object({[PamPolicyType.CommandBlocking]: PamPolicyRulePatternSchema.optional(),- [PamSettingType.SessionLogMasking]: PamPolicyRulePatternSchema.optional()+ [PamSettingType.SessionLogMasking]: PamSessionLogMaskingRuleSchema.optional()}).nullable().optional();+export type TPamPolicyRules = z.infer<typeof PamPolicyRulesSchema>;++/**+ * Assembles the rules the gateway enforces during a session.+ *+ * The masking arm is emitted whenever built-in detection is on, even with no custom patterns —+ * an empty pattern list is no longer the same thing as "no masking".+ */+export const buildPamPolicyRules = ({+ commandBlockingPatterns,+ maskingPatterns,+ maskingBuiltInDetection+}: {+ commandBlockingPatterns: string[];+ maskingPatterns: string[];+ maskingBuiltInDetection: boolean;+}): TPamPolicyRules => {+ const rules: Record<string, unknown> = {};++ if (commandBlockingPatterns.length > 0) {+ rules[PamPolicyType.CommandBlocking] = { patterns: commandBlockingPatterns };+ }++ if (maskingBuiltInDetection || maskingPatterns.length > 0) {+ rules[PamSettingType.SessionLogMasking] = {+ patterns: maskingPatterns,+ builtInDetection: maskingBuiltInDetection+ };+ }++ return Object.keys(rules).length > 0 ? (rules as TPamPolicyRules) : null;+};+export const resolveAccessControls = (policyMap: unknown): TPamAccessControls => {const duration = resolvePolicy(policyMap, PamPolicyType.MaxSessionDuration);const requiresApproval = resolvePolicy(policyMap, PamPolicyType.RequiresApproval) === true;diff --git a/backend/src/server/routes/index.ts b/backend/src/server/routes/index.tsindex 8cec726cd8..2f4c45e6ef 100644--- a/backend/src/server/routes/index.ts+++ b/backend/src/server/routes/index.ts@@ -2099,6 +2099,7 @@ export const registerRoutes = async (const pamAccountService = pamAccountServiceFactory({pamAccountDAL,pamFolderDAL,+ gatewayPoolMembershipDAL,pamAccountTemplateDAL,membershipDAL,membershipRoleDAL,diff --git a/frontend/src/hooks/api/pam/enums.ts b/frontend/src/hooks/api/pam/enums.tsindex 98900ab83c..deb2037077 100644--- a/frontend/src/hooks/api/pam/enums.ts+++ b/frontend/src/hooks/api/pam/enums.ts@@ -39,6 +39,20 @@ export const ROTATABLE_PAM_ACCOUNT_TYPES = [export const isRotatablePamAccountType = (type: PamAccountType | string) =>(ROTATABLE_PAM_ACCOUNT_TYPES as string[]).includes(type);+// Informational conditions on an account. Unlike PamAccountAccessibilityIssue these gate nothing:+// the account launches, records and rotates as normal. Mirrors PamAccountWarning in+// backend/src/ee/services/pam/pam-enums.ts.+export enum PamAccountWarning {+ SessionLogMaskingDegraded = "session-log-masking-degraded"+}++// Brokered over RDP, whose recordings the gateway never masks. Mirrors+// accountTypeSupportsSessionLogMasking in backend/src/ee/services/pam/pam-enums.ts.+export const RDP_PAM_ACCOUNT_TYPES = [PamAccountType.Windows, PamAccountType.WindowsAd];++export const pamAccountTypeSupportsSessionLogMasking = (type: PamAccountType | string) =>+ !(RDP_PAM_ACCOUNT_TYPES as string[]).includes(type);+// Mirrors ORACLE_MAX_PASSWORD_LENGTH in backend/src/ee/services/pam-account/pam-account-schemas.ts, which is// what actually rejects a longer one. Change both together.export const ORACLE_MAX_PASSWORD_LENGTH = 30;diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsxindex 7257282c60..b34202195a 100644--- a/frontend/src/hooks/api/pam/queries.tsx+++ b/frontend/src/hooks/api/pam/queries.tsx@@ -14,6 +14,7 @@ import {PamAccessStatus,PamAccessType,PamAccountType,+ PamAccountWarning,PamApproverType,PamHeartbeatStatus,PamResourcePermissionActions,@@ -213,6 +214,7 @@ export type TPamAccountListItem = {accessibilityIssues: PamAccountAccessibilityIssue[];// the latest discovery scan didn't find it. Informational only, nothing about the account is blocked.isStale: boolean;+ warnings: PamAccountWarning[];heartbeatStatus?: PamHeartbeatStatus | null;heartbeatEnabled?: boolean;requiresApproval: boolean;diff --git a/frontend/src/pages/pam/PamAccountsPage/components/FolderAccountRow.tsx b/frontend/src/pages/pam/PamAccountsPage/components/FolderAccountRow.tsxindex 26067b77b4..86c8a54ea3 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/FolderAccountRow.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/FolderAccountRow.tsx@@ -10,6 +10,7 @@ import {import { PamSheetTab } from "@app/hooks/usePamSheetState";import { AccountHealthBadge } from "../../components/AccountHealthBadge";+import { AccountMaskingBadge } from "../../components/AccountMaskingBadge";import { AccountStaleBadge } from "../../components/AccountStaleBadge";import { PamAccountRow } from "../../components/PamAccountRow";import { AccountAccessibilityBadgeWithPermission } from "./AccountAccessibilityBadgeWithPermission";@@ -94,6 +95,7 @@ export const FolderAccountRow = ({issues={account.accessibilityIssues}/><AccountStaleBadge isStale={account.isStale} />+ <AccountMaskingBadge warnings={account.warnings} /><AccountHealthBadge status={account.heartbeatStatus} enabled={account.heartbeatEnabled} /></>}diff --git a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsxindex 3208a5996a..877a4748f7 100644--- a/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx+++ b/frontend/src/pages/pam/PamTemplatesPage/components/TemplateDetailSheet.tsx@@ -10,6 +10,7 @@ import {Alert,AlertDescription,AlertTitle,+ Badge,Card,CardContent,CardDescription,@@ -20,6 +21,7 @@ import {FieldDescription,FieldError,FieldLabel,+ FieldTitle,GatewayPicker,Input,Select,@@ -39,6 +41,7 @@ import {maxGeneratedPasswordLength,PAM_ROTATION_INTERVAL_OPTIONS,PamAccountType,+ pamAccountTypeSupportsSessionLogMasking,PamPolicyType,useGetPamAccountTemplate,usePamAccountTypeMap,@@ -73,6 +76,7 @@ const buildSettingsSchema = (maxPwLength: number) =>policies: z.record(z.unknown()),settings: z.object({sessionLogMaskingPatterns: z.string().optional(),+ sessionLogMaskingBuiltInDetection: z.boolean().optional(),rotationEnabled: z.boolean().optional(),heartbeatEnabled: z.boolean().optional(),heartbeatIntervalSeconds: z.number().optional(),@@ -302,6 +306,7 @@ const SettingsTab = ({policies: {},settings: {sessionLogMaskingPatterns: "",+ sessionLogMaskingBuiltInDetection: false,rotationEnabled: false,heartbeatEnabled: false,heartbeatIntervalSeconds: 86400,@@ -337,6 +342,8 @@ const SettingsTab = ({policies: (template.policies as Record<string, unknown>) ?? {},settings: {sessionLogMaskingPatterns: (settings.sessionLogMaskingPatterns as string) ?? "",+ sessionLogMaskingBuiltInDetection:+ (settings.sessionLogMaskingBuiltInDetection as boolean) ?? false,...(() => {const rotation = (settings.rotation ?? {}) as {enabled?: boolean;@@ -395,6 +402,8 @@ const SettingsTab = ({const heartbeatEnabled = watch("settings.heartbeatEnabled");const requiresRecording = accountTypeRequiresRecording(template.type);const showGatewaySettings = accountTypeMap[template.type]?.requiresGateway !== false;+ const supportsSessionLogMasking = pamAccountTypeSupportsSessionLogMasking(template.type);+const typeName = accountTypeMap[template.type]?.name ?? template.type;const isRotatableTemplateType = isRotatablePamAccountType(template.type);const requiresApproval = policies[PamPolicyType.RequiresApproval] === true;@@ -425,6 +434,11 @@ const SettingsTab = ({delete settings.sessionLogMaskingPatterns;}+ // Never deleted when false: an absent key means "never configured", which is a different thing.+ settings.sessionLogMaskingBuiltInDetection = Boolean(+ data.settings.sessionLogMaskingBuiltInDetection+ );+const isHeartbeatOn = Boolean(data.settings.heartbeatEnabled);settings.heartbeat = {enabled: isHeartbeatOn,@@ -947,31 +961,64 @@ const SettingsTab = ({</>)}- <Controller- control={control}- name="settings.sessionLogMaskingPatterns"- render={({ field, fieldState }) => (- <Field>- <FieldLabel>Session Log Masking</FieldLabel>- <FieldContent>- <TextArea- rows={5}- placeholder={"rm\\s+-rf.*\npassword\\s*=\\s*\\S+\n\\b\\d{3}-\\d{2}-\\d{4}\\b"}- value={field.value ?? ""}- isError={!!fieldState.error}- onChange={(e) => {- const val = e.target.value;- field.onChange(val.trim() ? val : "");- }}- />- <FieldDescription>- Matching content in session recordings will be masked (one regex per line).- </FieldDescription>- <FieldError>{fieldState.error?.message}</FieldError>- </FieldContent>- </Field>- )}- />+ {supportsSessionLogMasking && (+ <div className="flex flex-col gap-4 border-t border-border pt-6">+ <div>+ <p className="text-sm font-medium text-foreground">Session Log Masking</p>+ <p className="text-xs text-muted">+ What gets masked in recordings for accounts using this template.+ </p>+ </div>++ <Controller+ control={control}+ name="settings.sessionLogMaskingBuiltInDetection"+ render={({ field }) => (+ <Field orientation="horizontal" className="items-center!">+ <FieldContent>+ <FieldTitle>+ Built-in Detection+ <Badge variant="success">Recommended</Badge>+ </FieldTitle>+ <FieldDescription>+ API keys, tokens, private keys, and high-entropy values are detected and+ masked automatically.+ </FieldDescription>+ </FieldContent>+ <Toggle+ variant="pam"+ checked={field.value ?? false}+ onCheckedChange={field.onChange}+ />+ </Field>+ )}+ />++ <Controller+ control={control}+ name="settings.sessionLogMaskingPatterns"+ render={({ field, fieldState }) => (+ <Field>+ <FieldLabel>Custom patterns</FieldLabel>+ <FieldContent>+ <TextArea+ rows={5}+ placeholder={"acme_[a-z0-9]{24}\ninternal-vault://\\S+"}+ value={field.value ?? ""}+ isError={!!fieldState.error}+ onChange={(e) => {+ const val = e.target.value;+ field.onChange(val.trim() ? val : "");+ }}+ />+ <FieldDescription>One regex per line.</FieldDescription>+ <FieldError>{fieldState.error?.message}</FieldError>+ </FieldContent>+ </Field>+ )}+ />+ </div>+ )}</CardContent></Card>)}diff --git a/frontend/src/pages/pam/components/AccountMaskingBadge.tsx b/frontend/src/pages/pam/components/AccountMaskingBadge.tsxnew file mode 100644index 0000000000..3bb7c6ea4f--- /dev/null+++ b/frontend/src/pages/pam/components/AccountMaskingBadge.tsx@@ -0,0 +1,26 @@+import { AlertTriangle } from "lucide-react";++import { Badge, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";+import { PamAccountWarning } from "@app/hooks/api/pam";++export const AccountMaskingBadge = ({ warnings }: { warnings: PamAccountWarning[] }) => {+ if (!warnings.includes(PamAccountWarning.SessionLogMaskingDegraded)) return null;++ return (+ <Tooltip>+ <TooltipTrigger asChild>+ <Badge variant="neutral">+ <AlertTriangle className="size-3" />+ Partial masking+ </Badge>+ </TooltipTrigger>+ <TooltipContent className="max-w-xs">+ <p>+ This account's template enables built-in detection, but the gateway serving it runs a+ version that doesn't support it. Recordings are masked by the template's custom+ patterns only until the gateway is upgraded.+ </p>+ </TooltipContent>+ </Tooltip>+ );+};