Skip to content

Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.

feat(pam): view sensitive credentials/password for PAM accounts (#5925)

Saif Ur Rahman7f84ff48a8c0
diff --git a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts
index 0913c8fe36..9d5770e5b3 100644
--- a/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts
+++ b/backend/src/ee/routes/v1/pam-account-routers/pam-account-router.ts
@@ -4,17 +4,44 @@ import { z } from "zod";
import { PamAccountDependenciesSchema } from "@app/db/schemas";
import { AuditLogInfo, EventType, UserAgentType } from "@app/ee/services/audit-log/audit-log-types";
import { PamAccountOrderBy, PamAccountView } from "@app/ee/services/pam-account/pam-account-enums";
-import { SanitizedActiveDirectoryAccountWithResourceSchema } from "@app/ee/services/pam-resource/active-directory/active-directory-resource-schemas";
-import { SanitizedAwsIamAccountWithResourceSchema } from "@app/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas";
-import { SanitizedKubernetesAccountWithResourceSchema } from "@app/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas";
-import { SanitizedMsSQLAccountWithResourceSchema } from "@app/ee/services/pam-resource/mssql/mssql-resource-schemas";
-import { SanitizedMySQLAccountWithResourceSchema } from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas";
+import {
+ ActiveDirectoryAccountCredentialsSchema,
+ SanitizedActiveDirectoryAccountWithResourceSchema
+} from "@app/ee/services/pam-resource/active-directory/active-directory-resource-schemas";
+import {
+ AwsIamAccountCredentialsSchema,
+ SanitizedAwsIamAccountWithResourceSchema
+} from "@app/ee/services/pam-resource/aws-iam/aws-iam-resource-schemas";
+import {
+ KubernetesAccountCredentialsSchema,
+ SanitizedKubernetesAccountWithResourceSchema
+} from "@app/ee/services/pam-resource/kubernetes/kubernetes-resource-schemas";
+import {
+ MsSQLAccountCredentialsSchema,
+ SanitizedMsSQLAccountWithResourceSchema
+} from "@app/ee/services/pam-resource/mssql/mssql-resource-schemas";
+import {
+ MySQLAccountCredentialsSchema,
+ SanitizedMySQLAccountWithResourceSchema
+} from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas";
import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
import { GatewayAccessResponseSchema } from "@app/ee/services/pam-resource/pam-resource-schemas";
-import { SanitizedPostgresAccountWithResourceSchema } from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas";
-import { SanitizedRedisAccountWithResourceSchema } from "@app/ee/services/pam-resource/redis/redis-resource-schemas";
-import { SanitizedSSHAccountWithResourceSchema } from "@app/ee/services/pam-resource/ssh/ssh-resource-schemas";
-import { SanitizedWindowsAccountWithResourceSchema } from "@app/ee/services/pam-resource/windows-server/windows-server-resource-schemas";
+import {
+ PostgresAccountCredentialsSchema,
+ SanitizedPostgresAccountWithResourceSchema
+} from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas";
+import {
+ RedisAccountCredentialsSchema,
+ SanitizedRedisAccountWithResourceSchema
+} from "@app/ee/services/pam-resource/redis/redis-resource-schemas";
+import {
+ SanitizedSSHAccountWithResourceSchema,
+ SSHAccountCredentialsSchema
+} from "@app/ee/services/pam-resource/ssh/ssh-resource-schemas";
+import {
+ SanitizedWindowsAccountWithResourceSchema,
+ WindowsAccountCredentialsSchema
+} from "@app/ee/services/pam-resource/windows-server/windows-server-resource-schemas";
import { BadRequestError } from "@app/lib/errors";
import { logger } from "@app/lib/logger";
import { ms } from "@app/lib/ms";
@@ -50,6 +77,52 @@ const ListPamAccountsResponseSchema = z.object({
totalCount: z.number().default(0)
});
+const AccountCredentialsBaseSchema = z.object({
+ accountId: z.string().uuid(),
+ accountName: z.string(),
+ resourceName: z.string(),
+ projectId: z.string().uuid()
+});
+
+const AccountCredentialsResponseSchema = z.discriminatedUnion("resourceType", [
+ AccountCredentialsBaseSchema.extend({
+ resourceType: z.literal(PamResource.Postgres),
+ credentials: PostgresAccountCredentialsSchema
+ }),
+ AccountCredentialsBaseSchema.extend({
+ resourceType: z.literal(PamResource.MySQL),
+ credentials: MySQLAccountCredentialsSchema
+ }),
+ AccountCredentialsBaseSchema.extend({
+ resourceType: z.literal(PamResource.MsSQL),
+ credentials: MsSQLAccountCredentialsSchema
+ }),
+ AccountCredentialsBaseSchema.extend({
+ resourceType: z.literal(PamResource.SSH),
+ credentials: SSHAccountCredentialsSchema
+ }),
+ AccountCredentialsBaseSchema.extend({
+ resourceType: z.literal(PamResource.Redis),
+ credentials: RedisAccountCredentialsSchema
+ }),
+ AccountCredentialsBaseSchema.extend({
+ resourceType: z.literal(PamResource.Kubernetes),
+ credentials: KubernetesAccountCredentialsSchema
+ }),
+ AccountCredentialsBaseSchema.extend({
+ resourceType: z.literal(PamResource.AwsIam),
+ credentials: AwsIamAccountCredentialsSchema
+ }),
+ AccountCredentialsBaseSchema.extend({
+ resourceType: z.literal(PamResource.Windows),
+ credentials: WindowsAccountCredentialsSchema
+ }),
+ AccountCredentialsBaseSchema.extend({
+ resourceType: z.literal(PamResource.ActiveDirectory),
+ credentials: ActiveDirectoryAccountCredentialsSchema
+ })
+]);
+
export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
server.route({
method: "GET",
@@ -239,6 +312,54 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
}
});
+ server.route({
+ method: "POST",
+ url: "/:accountId/credentials",
+ config: {
+ rateLimit: writeLimit
+ },
+ schema: {
+ description: "View full (unsanitized) PAM account credentials",
+ params: z.object({
+ accountId: z.string().uuid()
+ }),
+ body: z.object({
+ mfaSessionId: z.string().optional()
+ }),
+ response: {
+ 200: AccountCredentialsResponseSchema
+ }
+ },
+ onRequest: verifyAuth([AuthMode.JWT]),
+ handler: async (req) => {
+ const result = await server.services.pamAccount.viewCredentials({
+ accountId: req.params.accountId,
+ mfaSessionId: req.body.mfaSessionId,
+ actorId: req.permission.id,
+ actor: req.permission.type,
+ actorAuthMethod: req.permission.authMethod,
+ actorOrgId: req.permission.orgId
+ });
+
+ await server.services.auditLog.createAuditLog({
+ ...req.auditLogInfo,
+ orgId: req.permission.orgId,
+ projectId: result.projectId,
+ event: {
+ type: EventType.PAM_ACCOUNT_READ_CREDENTIALS,
+ metadata: {
+ accountId: result.accountId,
+ accountName: result.accountName,
+ resourceId: result.resourceId,
+ resourceType: result.resourceType
+ }
+ }
+ });
+
+ return result as z.infer<typeof AccountCredentialsResponseSchema>;
+ }
+ });
+
server.route({
method: "GET",
url: "/",
diff --git a/backend/src/ee/services/audit-log/audit-log-types.ts b/backend/src/ee/services/audit-log/audit-log-types.ts
index 817b71b417..3e0144513e 100644
--- a/backend/src/ee/services/audit-log/audit-log-types.ts
+++ b/backend/src/ee/services/audit-log/audit-log-types.ts
@@ -607,6 +607,7 @@ export enum EventType {
PAM_ACCOUNT_DELETE = "pam-account-delete",
PAM_ACCOUNT_CREDENTIAL_ROTATION = "pam-account-credential-rotation",
PAM_ACCOUNT_CREDENTIAL_ROTATION_FAILED = "pam-account-credential-rotation-failed",
+ PAM_ACCOUNT_READ_CREDENTIALS = "pam-account-read-credentials",
PAM_WEB_ACCESS_SESSION_TICKET_CREATED = "pam-web-access-session-ticket-created",
PAM_RESOURCE_LIST = "pam-resource-list",
PAM_RESOURCE_GET = "pam-resource-get",
@@ -4861,6 +4862,16 @@ interface PamAccountCredentialRotationFailedEvent {
};
}
+interface PamAccountReadCredentialsEvent {
+ type: EventType.PAM_ACCOUNT_READ_CREDENTIALS;
+ metadata: {
+ accountId: string;
+ accountName: string;
+ resourceId: string;
+ resourceType: string;
+ };
+}
+
interface PamResourceListEvent {
type: EventType.PAM_RESOURCE_LIST;
metadata: {
@@ -6164,6 +6175,7 @@ export type Event =
| PamAccountDeleteEvent
| PamAccountCredentialRotationEvent
| PamAccountCredentialRotationFailedEvent
+ | PamAccountReadCredentialsEvent
| PamResourceListEvent
| PamResourceGetEvent
| PamResourceCreateEvent
diff --git a/backend/src/ee/services/pam-account/pam-account-fns.ts b/backend/src/ee/services/pam-account/pam-account-fns.ts
index 2497e6b7a5..679710e0ba 100644
--- a/backend/src/ee/services/pam-account/pam-account-fns.ts
+++ b/backend/src/ee/services/pam-account/pam-account-fns.ts
@@ -1,6 +1,7 @@
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
import { KmsDataKey } from "@app/services/kms/kms-types";
+import { PamResource } from "../pam-resource/pam-resource-enums";
import { TPamAccountCredentials, TPamResourceInternalMetadata } from "../pam-resource/pam-resource-types";
import { SSHAuthMethod } from "../pam-resource/ssh/ssh-resource-enums";
@@ -67,6 +68,19 @@ export const decryptAccountMessage = async ({
return decryptedPlainTextBlob.toString();
};
+// Returns false for account types where all credential fields are already visible in the sanitized view
+export const hasSensitiveCredentials = (resourceType: string, credentials: TPamAccountCredentials): boolean => {
+ if (resourceType === PamResource.AwsIam) return false;
+ if (resourceType === PamResource.Kubernetes) return false;
+ if (
+ resourceType === PamResource.SSH &&
+ "authMethod" in credentials &&
+ credentials.authMethod === SSHAuthMethod.Certificate
+ )
+ return false;
+ return true;
+};
+
const hasConfiguredCredentials = (credentials: TPamAccountCredentials): boolean => {
if ("password" in credentials && credentials.password) return true;
if ("privateKey" in credentials && credentials.privateKey) return true;
diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.ts
index ac3974a24b..5a7b6981f6 100644
--- a/backend/src/ee/services/pam-account/pam-account-service.ts
+++ b/backend/src/ee/services/pam-account/pam-account-service.ts
@@ -64,13 +64,19 @@ import { PamSessionStatus } from "../pam-session/pam-session-enums";
import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission";
import { TPamAccountDALFactory } from "./pam-account-dal";
import { PamAccountRotationStatus } from "./pam-account-enums";
-import { decryptAccount, decryptAccountCredentials, encryptAccountCredentials } from "./pam-account-fns";
+import {
+ decryptAccount,
+ decryptAccountCredentials,
+ encryptAccountCredentials,
+ hasSensitiveCredentials
+} from "./pam-account-fns";
import {
TAccessAccountDTO,
TCreateAccountDTO,
TGetAccountByIdDTO,
TListAccountsDTO,
- TUpdateAccountDTO
+ TUpdateAccountDTO,
+ TViewAccountCredentialsDTO
} from "./pam-account-types";
type TPamAccountServiceFactoryDep = {
@@ -1379,6 +1385,113 @@ export const pamAccountServiceFactory = ({
};
};
+ const viewCredentials = async ({
+ accountId,
+ mfaSessionId,
+ actor,
+ actorId,
+ actorAuthMethod,
+ actorOrgId
+ }: TViewAccountCredentialsDTO) => {
+ const accountWithResource = await pamAccountDAL.findByIdWithResourceDetails(accountId);
+ if (!accountWithResource) throw new NotFoundError({ message: `Account with ID '${accountId}' not found` });
+
+ const { permission } = await permissionService.getProjectPermission({
+ actor,
+ actorId,
+ projectId: accountWithResource.projectId,
+ actorAuthMethod,
+ actorOrgId,
+ actionProjectType: ActionProjectType.PAM
+ });
+
+ const metadataByAccountId = await pamAccountDAL.findMetadataByAccountIds([accountWithResource.id]);
+ const accountMetadata = metadataByAccountId[accountWithResource.id] || [];
+
+ ForbiddenError.from(permission).throwUnlessCan(
+ ProjectPermissionPamAccountActions.ReadCredentials,
+ subject(ProjectPermissionSub.PamAccounts, {
+ resourceName: accountWithResource.resource.name,
+ resourceType: accountWithResource.resource.resourceType,
+ accountName: accountWithResource.name,
+ metadata: accountMetadata
+ })
+ );
+
+ // Decrypt early so we can check if there are sensitive fields before triggering MFA
+ const credentials = await decryptAccountCredentials({
+ encryptedCredentials: accountWithResource.encryptedCredentials,
+ kmsService,
+ projectId: accountWithResource.projectId
+ });
+
+ if (!hasSensitiveCredentials(accountWithResource.resource.resourceType, credentials)) {
+ throw new BadRequestError({ message: "This account has no sensitive credentials to view" });
+ }
+
+ if (!mfaSessionId && accountWithResource.requireMfa) {
+ const project = await projectDAL.findById(accountWithResource.projectId);
+ if (!project)
+ throw new NotFoundError({ message: `Project with ID '${accountWithResource.projectId}' not found` });
+
+ const actorUser = await userDAL.findById(actorId);
+ if (!actorUser) throw new NotFoundError({ message: `User with ID '${actorId}' not found` });
+
+ const org = await orgDAL.findOrgById(project.orgId);
+ if (!org) throw new NotFoundError({ message: `Organization with ID '${project.orgId}' not found` });
+
+ const orgMfaMethod = org.enforceMfa ? (org.selectedMfaMethod as MfaMethod | null) : undefined;
+ const userMfaMethod = actorUser.isMfaEnabled ? (actorUser.selectedMfaMethod as MfaMethod | null) : undefined;
+ const mfaMethod = (orgMfaMethod ?? userMfaMethod ?? MfaMethod.EMAIL) as MfaMethod;
+
+ const newMfaSessionId = await mfaSessionService.createMfaSession(actorUser.id, accountWithResource.id, mfaMethod);
+
+ if (mfaMethod === MfaMethod.EMAIL && actorUser.email) {
+ await mfaSessionService.sendMfaCode(actorUser.id, actorUser.email);
+ }
+
+ throw new BadRequestError({
+ message: "MFA verification required to view PAM account credentials",
+ name: "SESSION_MFA_REQUIRED",
+ details: {
+ mfaSessionId: newMfaSessionId,
+ mfaMethod
+ }
+ });
+ }
+
+ if (mfaSessionId && accountWithResource.requireMfa) {
+ const mfaSession = await mfaSessionService.getMfaSession(mfaSessionId);
+ if (!mfaSession) {
+ throw new BadRequestError({ message: "MFA session not found or expired" });
+ }
+
+ if (mfaSession.userId !== actorId) {
+ throw new BadRequestError({ message: "MFA session does not belong to current user" });
+ }
+
+ if (mfaSession.resourceId !== accountWithResource.id) {
+ throw new BadRequestError({ message: "MFA session is for a different account" });
+ }
+
+ if (mfaSession.status !== MfaSessionStatus.ACTIVE) {
+ throw new BadRequestError({ message: "MFA session is not active. Please complete MFA verification first." });
+ }
+
+ await mfaSessionService.deleteMfaSession(mfaSessionId);
+ }
+
+ return {
+ credentials,
+ resourceType: accountWithResource.resource.resourceType,
+ accountId: accountWithResource.id,
+ accountName: accountWithResource.name,
+ resourceId: accountWithResource.resource.id,
+ resourceName: accountWithResource.resource.name,
+ projectId: accountWithResource.projectId
+ };
+ };
+
return {
create,
updateById,
@@ -1386,6 +1499,7 @@ export const pamAccountServiceFactory = ({
list,
getById,
access,
+ viewCredentials,
getSessionCredentials,
rotateAllDueAccounts,
triggerManualRotation
diff --git a/backend/src/ee/services/pam-account/pam-account-types.ts b/backend/src/ee/services/pam-account/pam-account-types.ts
index d66b966ef5..5b1d033ed7 100644
--- a/backend/src/ee/services/pam-account/pam-account-types.ts
+++ b/backend/src/ee/services/pam-account/pam-account-types.ts
@@ -45,3 +45,8 @@ export type TListAccountsDTO = {
export type TGetAccountByIdDTO = {
accountId: string;
} & Omit<TProjectPermission, "projectId">;
+
+export type TViewAccountCredentialsDTO = {
+ accountId: string;
+ mfaSessionId?: string;
+} & Omit<TProjectPermission, "projectId">;
diff --git a/backend/src/ee/services/permission/default-roles.ts b/backend/src/ee/services/permission/default-roles.ts
index bde55c3a79..fa3d43f8a0 100644
--- a/backend/src/ee/services/permission/default-roles.ts
+++ b/backend/src/ee/services/permission/default-roles.ts
@@ -392,7 +392,8 @@ const buildAdminPermissionRules = () => {
ProjectPermissionPamAccountActions.Create,
ProjectPermissionPamAccountActions.Edit,
ProjectPermissionPamAccountActions.Delete,
- ProjectPermissionPamAccountActions.TriggerRotation
+ ProjectPermissionPamAccountActions.TriggerRotation,
+ ProjectPermissionPamAccountActions.ReadCredentials
],
ProjectPermissionSub.PamAccounts
);
diff --git a/backend/src/ee/services/permission/project-permission.ts b/backend/src/ee/services/permission/project-permission.ts
index 29c7cdd9aa..f0e4ecf2ac 100644
--- a/backend/src/ee/services/permission/project-permission.ts
+++ b/backend/src/ee/services/permission/project-permission.ts
@@ -254,7 +254,8 @@ export enum ProjectPermissionPamAccountActions {
Create = "create",
Edit = "edit",
Delete = "delete",
- TriggerRotation = "trigger-rotation"
+ TriggerRotation = "trigger-rotation",
+ ReadCredentials = "read-credentials"
}
export enum ProjectPermissionPamSessionActions {
diff --git a/frontend/src/context/ProjectPermissionContext/types.ts b/frontend/src/context/ProjectPermissionContext/types.ts
index efab712870..d1125848a7 100644
--- a/frontend/src/context/ProjectPermissionContext/types.ts
+++ b/frontend/src/context/ProjectPermissionContext/types.ts
@@ -257,7 +257,8 @@ export enum ProjectPermissionPamAccountActions {
Create = "create",
Edit = "edit",
Delete = "delete",
- TriggerRotation = "trigger-rotation"
+ TriggerRotation = "trigger-rotation",
+ ReadCredentials = "read-credentials"
}
export enum ProjectPermissionPamSessionActions {
@@ -517,6 +518,7 @@ export type CertificatePolicySubjectFields = {
export type PamAccountSubjectFields = {
resourceName: string;
+ resourceType: string;
accountName: string;
metadata?: { key: string; value: string }[];
};
diff --git a/frontend/src/hooks/api/auditLogs/constants.tsx b/frontend/src/hooks/api/auditLogs/constants.tsx
index ea7191c6a2..997693067f 100644
--- a/frontend/src/hooks/api/auditLogs/constants.tsx
+++ b/frontend/src/hooks/api/auditLogs/constants.tsx
@@ -279,6 +279,7 @@ export const eventToNameMap: { [K in EventType]: string } = {
[EventType.PAM_ACCOUNT_CREATE]: "Create PAM Account",
[EventType.PAM_ACCOUNT_UPDATE]: "Update PAM Account",
[EventType.PAM_ACCOUNT_DELETE]: "Delete PAM Account",
+ [EventType.PAM_ACCOUNT_READ_CREDENTIALS]: "Read PAM Account Credentials",
[EventType.PAM_WEB_ACCESS_SESSION_TICKET_CREATED]: "Create PAM Web Access Session Ticket",
[EventType.PAM_RESOURCE_LIST]: "List PAM Resources",
[EventType.PAM_RESOURCE_GET]: "Get PAM Resource",
@@ -421,6 +422,7 @@ export const projectToEventsMap: Partial<Record<ProjectType, EventType[]>> = {
EventType.PAM_ACCOUNT_CREATE,
EventType.PAM_ACCOUNT_UPDATE,
EventType.PAM_ACCOUNT_DELETE,
+ EventType.PAM_ACCOUNT_READ_CREDENTIALS,
EventType.PAM_WEB_ACCESS_SESSION_TICKET_CREATED,
EventType.PAM_RESOURCE_LIST,
EventType.PAM_RESOURCE_GET,
diff --git a/frontend/src/hooks/api/auditLogs/enums.tsx b/frontend/src/hooks/api/auditLogs/enums.tsx
index 68c015cc2e..5956e5516d 100644
--- a/frontend/src/hooks/api/auditLogs/enums.tsx
+++ b/frontend/src/hooks/api/auditLogs/enums.tsx
@@ -274,6 +274,7 @@ export enum EventType {
PAM_ACCOUNT_CREATE = "pam-account-create",
PAM_ACCOUNT_UPDATE = "pam-account-update",
PAM_ACCOUNT_DELETE = "pam-account-delete",
+ PAM_ACCOUNT_READ_CREDENTIALS = "pam-account-read-credentials",
PAM_WEB_ACCESS_SESSION_TICKET_CREATED = "pam-web-access-session-ticket-created",
PAM_RESOURCE_LIST = "pam-resource-list",
PAM_RESOURCE_GET = "pam-resource-get",
diff --git a/frontend/src/hooks/api/pam/queries.tsx b/frontend/src/hooks/api/pam/queries.tsx
index 56290105dd..db79ce84fb 100644
--- a/frontend/src/hooks/api/pam/queries.tsx
+++ b/frontend/src/hooks/api/pam/queries.tsx
@@ -256,6 +256,15 @@ export const useGetPamAccountDependencies = (accountId?: string) => {
});
};
+export type TPamAccountCredentialsResponse = {
+ credentials: Record<string, unknown>;
+ resourceType: string;
+ accountId: string;
+ accountName: string;
+ resourceName: string;
+ projectId: string;
+};
+
// Rotation Rules
export const useGetPamRotationRules = (resourceId?: string) => {
return useQuery({
diff --git a/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountCredentialsSection.tsx b/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountCredentialsSection.tsx
index c160415291..218c43fcb1 100644
--- a/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountCredentialsSection.tsx
+++ b/frontend/src/pages/pam/PamAccountByIDPage/components/PamAccountCredentialsSection.tsx
@@ -1,4 +1,5 @@
-import { CopyIcon, PencilIcon } from "lucide-react";
+import { useReducer } from "react";
+import { CheckIcon, CopyIcon, EyeIcon, EyeOffIcon, PencilIcon } from "lucide-react";
import { createNotification } from "@app/components/notifications";
import { ProjectPermissionCan } from "@app/components/permissions";
@@ -11,16 +12,21 @@ import {
} from "@app/components/v3";
import { ProjectPermissionSub } from "@app/context";
import { ProjectPermissionPamAccountActions } from "@app/context/ProjectPermissionContext/types";
+import { useTimedReset } from "@app/hooks";
import {
PamResourceType,
TActiveDirectoryAccount,
TPamAccount,
TWindowsAccount
} from "@app/hooks/api/pam";
+import { TPamAccountCredentialsResponse } from "@app/hooks/api/pam/queries";
import { TAwsIamCredentials } from "@app/hooks/api/pam/types/aws-iam-resource";
import { TBaseSqlCredentials } from "@app/hooks/api/pam/types/shared/sql-resource";
import { SSHAuthMethod, TSSHCredentials } from "@app/hooks/api/pam/types/ssh-resource";
+import { SensitiveCredentialsGate } from "./SensitiveCredentialsGate";
+import { useCredentialsReveal } from "./useCredentialsReveal";
+
type Props = {
account: TPamAccount;
onEdit: VoidFunction;
@@ -123,13 +129,161 @@ const CredentialsContent = ({ account }: { account: TPamAccount }) => {
}
};
+const MASKED_VALUE = "••••••••••••";
+
+const SensitiveField = ({ label, value }: { label: string; value: string }) => {
+ const [isVisible, toggleVisibility] = useReducer((prev) => !prev, false);
+ const [, isCopied, setCopied] = useTimedReset<string>({
+ initialState: ""
+ });
+
+ const handleCopy = async () => {
+ try {
+ await navigator.clipboard.writeText(value);
+ setCopied("copied");
+ } catch {
+ createNotification({ type: "error", text: "Failed to copy to clipboard." });
+ }
+ };
+
+ return (
+ <Detail>
+ <DetailLabel>{label}</DetailLabel>
+ <DetailValue>
+ <div className="flex items-center gap-2">
+ <UnstableInput
+ value={isVisible ? value : MASKED_VALUE}
+ readOnly
+ className="flex-1 font-mono text-sm"
+ />
+ <UnstableIconButton variant="ghost" size="sm" onClick={toggleVisibility}>
+ {isVisible ? <EyeOffIcon /> : <EyeIcon />}
+ </UnstableIconButton>
+ <UnstableIconButton variant="ghost" size="sm" onClick={handleCopy}>
+ {isCopied ? <CheckIcon /> : <CopyIcon />}
+ </UnstableIconButton>
+ </div>
+ </DetailValue>
+ </Detail>
+ );
+};
+
+const MultilineSensitiveField = ({ label, value }: { label: string; value: string }) => {
+ const [, isCopied, setCopied] = useTimedReset<string>({
+ initialState: ""
+ });
+
+ const handleCopy = async () => {
+ try {
+ await navigator.clipboard.writeText(value);
+ setCopied("copied");
+ } catch {
+ createNotification({ type: "error", text: "Failed to copy to clipboard." });
+ }
+ };
+
+ return (
+ <Detail>
+ <DetailLabel>
+ <div className="flex w-full items-center justify-between">
+ {label}
+ <UnstableIconButton variant="ghost" size="sm" onClick={handleCopy}>
+ {isCopied ? <CheckIcon /> : <CopyIcon />}
+ </UnstableIconButton>
+ </div>
+ </DetailLabel>
+ <DetailValue>
+ <pre className="max-h-32 thin-scrollbar overflow-auto rounded-md border border-border bg-transparent px-3 py-2 font-mono text-sm break-all whitespace-pre-wrap">
+ {value}
+ </pre>
+ </DetailValue>
+ </Detail>
+ );
+};
+
+type SensitiveFieldDef = {
+ key: string;
+ label: string;
+ multiline?: boolean;
+};
+
+// Returns sensitive fields that require the "View Credentials" flow to reveal.
+// Non-sensitive fields (username, auth method, etc.) are already shown by CredentialsContent above.
+// When adding a new resource type, add a case here if it has credentials hidden from the sanitized view.
+const getSensitiveFieldDefs = (account: TPamAccount): SensitiveFieldDef[] => {
+ const { resourceType } = account.resource;
+
+ switch (resourceType) {
+ case PamResourceType.Postgres:
+ case PamResourceType.MySQL:
+ case PamResourceType.MsSQL:
+ case PamResourceType.Redis:
+ case PamResourceType.Windows:
+ case PamResourceType.ActiveDirectory:
+ return [{ key: "password", label: "Password" }];
+
+ case PamResourceType.SSH: {
+ const { authMethod } = account.credentials as TSSHCredentials;
+ if (authMethod === SSHAuthMethod.Password) return [{ key: "password", label: "Password" }];
+ if (authMethod === SSHAuthMethod.PublicKey)
+ return [{ key: "privateKey", label: "Private Key", multiline: true }];
+ return [];
+ }
+
+ default:
+ return [];
+ }
+};
+
+const RevealedCredentials = ({
+ credentialsData,
+ fieldDefs
+}: {
+ credentialsData: TPamAccountCredentialsResponse;
+ fieldDefs: SensitiveFieldDef[];
+}) => {
+ const { credentials } = credentialsData;
+
+ const presentFields = fieldDefs.filter((f) => {
+ const value = credentials[f.key];
+ return value !== undefined && value !== null && String(value).length > 0;
+ });
+
+ if (presentFields.length === 0) return null;
+
+ return (
+ <div className="flex flex-col gap-3">
+ {presentFields.map((field) =>
+ field.multiline ? (
+ <MultilineSensitiveField
+ key={field.key}
+ label={field.label}
+ value={String(credentials[field.key])}
+ />
+ ) : (
+ <SensitiveField
+ key={field.key}
+ label={field.label}
+ value={String(credentials[field.key])}
+ />
+ )
+ )}
+ </div>
+ );
+};
+
export const PamAccountCredentialsSection = ({ account, onEdit }: Props) => {
+ const { state, startReveal, reset } = useCredentialsReveal(account.id);
+
if (
Object.keys(account.credentials).length <= 0 ||
[PamResourceType.Kubernetes].includes(account.resource.resourceType)
)
return null;
+ const sensitiveFieldDefs = getSensitiveFieldDefs(account);
+ const hasSensitiveFields = sensitiveFieldDefs.length > 0;
+
return (
<div className="flex w-full flex-col gap-3 rounded-lg border border-border bg-container px-4 py-3">
<div className="flex items-center justify-between border-b border-border pb-2">
@@ -146,6 +300,30 @@ export const PamAccountCredentialsSection = ({ account, onEdit }: Props) => {
</ProjectPermissionCan>
</div>
<CredentialsContent account={account} />
+ {hasSensitiveFields && (
+ <SensitiveCredentialsGate
+ state={state}
+ accountName={account.name}
+ resourceName={account.resource.name}
+ resourceType={account.resource.resourceType}
+ metadata={account.metadata}
+ onReveal={() => {
+ if (!account.credentialsConfigured) {
+ createNotification({
+ type: "error",
+ text: "No password exists for this account."
+ });
+ return;
+ }
+ startReveal();
+ }}
+ onReset={reset}
+ >
+ {state.status === "revealed" && (
+ <RevealedCredentials credentialsData={state.data} fieldDefs={sensitiveFieldDefs} />
+ )}
+ </SensitiveCredentialsGate>
+ )}
</div>
);
};
diff --git a/frontend/src/pages/pam/PamAccountByIDPage/components/SensitiveCredentialsGate.tsx b/frontend/src/pages/pam/PamAccountByIDPage/components/SensitiveCredentialsGate.tsx
new file mode 100644
index 0000000000..3683650afa
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountByIDPage/components/SensitiveCredentialsGate.tsx
@@ -0,0 +1,104 @@
+import React from "react";
+import { subject } from "@casl/ability";
+import { EyeIcon, LoaderCircleIcon } from "lucide-react";
+
+import { ProjectPermissionCan } from "@app/components/permissions";
+import { Button, Tooltip, TooltipContent, TooltipTrigger } from "@app/components/v3";
+import { ProjectPermissionSub } from "@app/context";
+import { ProjectPermissionPamAccountActions } from "@app/context/ProjectPermissionContext/types";
+
+import { type RevealState } from "./useCredentialsReveal";
+
+type Props = {
+ state: RevealState;
+ accountName: string;
+ resourceName: string;
+ resourceType: string;
+ metadata?: { key: string; value: string }[];
+ onReveal: () => void;
+ onReset: () => void;
+ children: React.ReactNode;
+};
+
+const ButtonContent = ({ state }: { state: RevealState }) => {
+ if (state.status === "loading") {
+ return <LoaderCircleIcon className="animate-spin" />;
+ }
+
+ if (state.status === "mfa-verifying") {
+ return (
+ <>
+ <LoaderCircleIcon className="animate-spin" />
+ Waiting for MFA...
+ </>
+ );
+ }
+
+ return (
+ <>
+ <EyeIcon />
+ View Credentials
+ </>
+ );
+};
+
+export const SensitiveCredentialsGate = ({
+ state,
+ accountName,
+ resourceName,
+ resourceType,
+ metadata,
+ onReveal,
+ onReset,
+ children
+}: Props) => {
+ if (state.status === "revealed") {
+ return <div>{children}</div>;
+ }
+
+ const isMfaVerifying = state.status === "mfa-verifying";
+ const isLoading = state.status === "loading";
+
+ return (
+ <div className="flex flex-col gap-2">
+ <ProjectPermissionCan
+ I={ProjectPermissionPamAccountActions.ReadCredentials}
+ a={subject(ProjectPermissionSub.PamAccounts, {
+ resourceName,
+ resourceType,
+ accountName,
+ metadata: metadata ?? []
+ })}
+ >
+ {(isAllowed) => (
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span className="w-full">
+ <Button
+ variant="outline"
+ size="md"
+ className="relative"
+ isFullWidth
+ isDisabled={!isAllowed || isLoading || isMfaVerifying}
+ onClick={onReveal}
+ >
+ <ButtonContent state={state} />
+ </Button>
+ </span>
+ </TooltipTrigger>
+ {!isAllowed && (
+ <TooltipContent side="right">
+ You do not have permission to view credentials
+ </TooltipContent>
+ )}
+ </Tooltip>
+ )}
+ </ProjectPermissionCan>
+ {isMfaVerifying && (
+ <Button variant="ghost" size="xs" isFullWidth onClick={onReset}>
+ Cancel
+ </Button>
+ )}
+ </div>
+ );
+};
diff --git a/frontend/src/pages/pam/PamAccountByIDPage/components/useCredentialsReveal.ts b/frontend/src/pages/pam/PamAccountByIDPage/components/useCredentialsReveal.ts
new file mode 100644
index 0000000000..52bc7b4e42
--- /dev/null
+++ b/frontend/src/pages/pam/PamAccountByIDPage/components/useCredentialsReveal.ts
@@ -0,0 +1,143 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import axios from "axios";
+
+import { createNotification } from "@app/components/notifications";
+import { apiRequest } from "@app/config/request";
+import { MfaSessionStatus, TMfaSessionStatusResponse } from "@app/hooks/api/mfaSession";
+import { TPamAccountCredentialsResponse } from "@app/hooks/api/pam/queries";
+
+export type RevealState =
+ | { status: "hidden" }
+ | { status: "loading" }
+ | { status: "mfa-verifying" }
+ | { status: "revealed"; data: TPamAccountCredentialsResponse };
+
+const MFA_POLL_INTERVAL = 2000;
+const MFA_TIMEOUT = 5 * 60 * 1000;
+
+export const useCredentialsReveal = (accountId: string) => {
+ const [state, setState] = useState<RevealState>({ status: "hidden" });
+ const mfaPopupRef = useRef<Window | null>(null);
+ const pollIntervalRef = useRef<NodeJS.Timeout | undefined>();
+ const isPollingRef = useRef(false);
+
+ const cleanup = useCallback(() => {
+ if (pollIntervalRef.current) clearInterval(pollIntervalRef.current);
+ if (mfaPopupRef.current && !mfaPopupRef.current.closed) {
+ mfaPopupRef.current.close();
+ }
+ isPollingRef.current = false;
+ }, []);
+
+ const fetchCredentials = useCallback(
+ async (mfaSessionId?: string) => {
+ const { data } = await apiRequest.post<TPamAccountCredentialsResponse>(
+ `/api/v1/pam/accounts/${accountId}/credentials`,
+ mfaSessionId ? { mfaSessionId } : {}
+ );
+ return data;
+ },
+ [accountId]
+ );
+
+ const startMfaPolling = useCallback(
+ (mfaSessionId: string) => {
+ const startTime = Date.now();
+
+ pollIntervalRef.current = setInterval(async () => {
+ if (isPollingRef.current) return;
+ isPollingRef.current = true;
+
+ try {
+ if (Date.now() - startTime > MFA_TIMEOUT) {
+ clearInterval(pollIntervalRef.current);
+ createNotification({
+ type: "error",
+ text: "MFA verification timed out. If a popup did not appear, check that popups are not blocked for this site."
+ });
+ setState({ status: "hidden" });
+ return;
+ }
+
+ const resp = await apiRequest.get<TMfaSessionStatusResponse>(
+ `/api/v2/mfa-sessions/${mfaSessionId}/status`
+ );
+ if (resp.data.status === MfaSessionStatus.ACTIVE) {
+ clearInterval(pollIntervalRef.current);
+ if (mfaPopupRef.current && !mfaPopupRef.current.closed) {
+ mfaPopupRef.current.close();
+ }
+
+ setState({ status: "loading" });
+ try {
+ const data = await fetchCredentials(mfaSessionId);
+ setState({ status: "revealed", data });
+ } catch {
+ createNotification({
+ type: "error",
+ text: "Failed to fetch credentials after MFA verification."
+ });
+ setState({ status: "hidden" });
+ }
+ }
+ } catch {
+ clearInterval(pollIntervalRef.current);
+ createNotification({ type: "error", text: "MFA verification failed." });
+ setState({ status: "hidden" });
+ } finally {
+ isPollingRef.current = false;
+ }
+ }, MFA_POLL_INTERVAL);
+ },
+ [fetchCredentials]
+ );
+
+ const startReveal = useCallback(async () => {
+ setState({ status: "loading" });
+
+ try {
+ const data = await fetchCredentials();
+ setState({ status: "revealed", data });
+ } catch (err) {
+ if (axios.isAxiosError(err) && err.response?.data?.error === "SESSION_MFA_REQUIRED") {
+ const mfaSessionId = err.response.data.details?.mfaSessionId as string | undefined;
+
+ if (!mfaSessionId) {
+ createNotification({ type: "error", text: "MFA session could not be created." });
+ setState({ status: "hidden" });
+ return;
+ }
+
+ // Immediately open MFA popup and start polling
+ const mfaUrl = `${window.location.origin}/mfa-session/${mfaSessionId}`;
+ mfaPopupRef.current = window.open(mfaUrl, "_blank");
+
+ if (!mfaPopupRef.current) {
+ createNotification({
+ type: "error",
+ text: "Could not open MFA popup. Please allow popups for this site."
+ });
+ setState({ status: "hidden" });
+ return;
+ }
+
+ setState({ status: "mfa-verifying" });
+ startMfaPolling(mfaSessionId);
+ } else {
+ createNotification({ type: "error", text: "Failed to fetch credentials." });
+ setState({ status: "hidden" });
+ }
+ }
+ }, [fetchCredentials, startMfaPolling]);
+
+ const reset = useCallback(() => {
+ cleanup();
+ setState({ status: "hidden" });
+ }, [cleanup]);
+
+ useEffect(() => {
+ return cleanup;
+ }, [cleanup]);
+
+ return { state, startReveal, reset };
+};
diff --git a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
index c347130aaf..74f754f064 100644
--- a/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
+++ b/frontend/src/pages/project/RoleDetailsBySlugPage/components/ProjectRoleModifySection.utils.tsx
@@ -236,7 +236,8 @@ const PamAccountPolicyActionSchema = z.object({
[ProjectPermissionPamAccountActions.Create]: z.boolean().optional(),
[ProjectPermissionPamAccountActions.Read]: z.boolean().optional(),
[ProjectPermissionPamAccountActions.Edit]: z.boolean().optional(),
- [ProjectPermissionPamAccountActions.Delete]: z.boolean().optional()
+ [ProjectPermissionPamAccountActions.Delete]: z.boolean().optional(),
+ [ProjectPermissionPamAccountActions.ReadCredentials]: z.boolean().optional()
});
const PamSessionPolicyActionSchema = z.object({
@@ -1784,6 +1785,9 @@ export const rolePermission2Form = (permissions: TProjectPermission[] = []) => {
[ProjectPermissionPamAccountActions.Read]: action.includes(
ProjectPermissionPamAccountActions.Read
),
+ [ProjectPermissionPamAccountActions.ReadCredentials]: action.includes(
+ ProjectPermissionPamAccountActions.ReadCredentials
+ ),
conditions: conditions ? convertCaslConditionToFormOperator(conditions) : [],
inverted
});
@@ -3136,6 +3140,11 @@ export const PROJECT_PERMISSION_OBJECT: TProjectPermissionObject = {
label: "Remove",
value: ProjectPermissionPamAccountActions.Delete,
description: "Delete PAM accounts"
+ },
+ {
+ label: "View Credentials",
+ value: ProjectPermissionPamAccountActions.ReadCredentials,
+ description: "View full account credentials and connection details"
}
]
},