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: display pam aws credentials for cli access
x0322056154de3dfc86
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.tsindex 3df62afbb0..46e1067984 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@@ -556,11 +556,14 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.Redis) }),GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.SSH) }),GatewayAccessResponseSchema.extend({ resourceType: z.literal(PamResource.Kubernetes) }),- // AWS IAM (no gateway, returns console URL)+ // AWS IAM (no gateway, returns short-lived STS credentials usable by both CLI and console)z.object({sessionId: z.string(),resourceType: z.literal(PamResource.AwsIam),- consoleUrl: z.string().url(),+ accessKeyId: z.string(),+ secretAccessKey: z.string(),+ sessionToken: z.string(),+ expiresAt: z.string(),metadata: z.record(z.string(), z.string().optional()).optional()})])@@ -620,6 +623,51 @@ export const registerPamAccountRouter = async (server: FastifyZodProvider) => {}});+ // Mint an AWS Console federated sign-in URL from an existing AWS IAM session+ server.route({+ method: "POST",+ url: "/sessions/:sessionId/aws-console-url",+ config: {+ rateLimit: writeLimit+ },+ schema: {+ description: "Generate an AWS console sign-in URL for an existing PAM session",+ params: z.object({+ sessionId: z.string().uuid()+ }),+ body: z.object({+ projectId: z.string().uuid(),+ accessKeyId: z.string().min(1),+ secretAccessKey: z.string().min(1),+ sessionToken: z.string().min(1)+ }),+ response: {+ 200: z.object({+ consoleUrl: z.string().url()+ })+ }+ },+ onRequest: verifyAuth([AuthMode.JWT]),+ handler: async (req) => {+ if (req.auth.authMode !== AuthMode.JWT) {+ throw new BadRequestError({ message: "You can only access PAM accounts using JWT auth tokens." });+ }++ const result = await server.services.pamAccount.getAwsIamConsoleUrl(+ {+ sessionId: req.params.sessionId,+ projectId: req.body.projectId,+ accessKeyId: req.body.accessKeyId,+ secretAccessKey: req.body.secretAccessKey,+ sessionToken: req.body.sessionToken+ },+ req.permission+ );++ return { consoleUrl: result.consoleUrl };+ }+ });+// Web access ticket endpointserver.route({method: "POST",diff --git a/backend/src/ee/services/pam-account/pam-account-service.ts b/backend/src/ee/services/pam-account/pam-account-service.tsindex 16da4990e4..70f468f823 100644--- a/backend/src/ee/services/pam-account/pam-account-service.ts+++ b/backend/src/ee/services/pam-account/pam-account-service.ts@@ -4,8 +4,9 @@ import picomatch from "picomatch";import { ActionProjectType, OrganizationActionScope, TableName, TPamAccounts, TPamResources } from "@app/db/schemas";import { decryptDomainConnectionDetails } from "@app/ee/services/pam-domain/pam-domain-fns";import {+ exchangeCredentialsForConsoleUrl,extractAwsAccountIdFromArn,- generateConsoleFederationUrl,+ generateAwsIamSessionCredentials,TAwsIamAccountCredentials} from "@app/ee/services/pam-resource/aws-iam";import { parseMongoConnectionString } from "@app/ee/services/pam-resource/mongodb/mongodb-resource-factory";@@ -863,7 +864,7 @@ export const pamAccountServiceFactory = ({projectId: account.projectId})) as TAwsIamAccountCredentials;- const { consoleUrl, expiresAt } = await generateConsoleFederationUrl({+ const credentials = await generateAwsIamSessionCredentials({connectionDetails,targetRoleArn: awsCredentials.targetRoleArn,roleSessionName: actorEmail,@@ -884,23 +885,25 @@ export const pamAccountServiceFactory = ({accountId: account.id,resourceId: resource.id,userId: actor.id,- expiresAt,+ expiresAt: credentials.expiresAt,startedAt: new Date()});// Schedule session expiration job to run at expiresAt- await pamSessionExpirationService.scheduleSessionExpiration(session.id, expiresAt);+ await pamSessionExpirationService.scheduleSessionExpiration(session.id, credentials.expiresAt);return {sessionId: session.id,resourceType,account,- consoleUrl,+ accessKeyId: credentials.accessKeyId,+ secretAccessKey: credentials.secretAccessKey,+ sessionToken: credentials.sessionToken,+ expiresAt: credentials.expiresAt.toISOString(),metadata: {awsAccountId: extractAwsAccountIdFromArn(connectionDetails.roleArn),targetRoleArn: awsCredentials.targetRoleArn,- federatedUsername: actorEmail,- expiresAt: expiresAt.toISOString()+ federatedUsername: actorEmail}};}@@ -1046,6 +1049,50 @@ export const pamAccountServiceFactory = ({};};+ const getAwsIamConsoleUrl = async (+ {+ sessionId,+ projectId,+ accessKeyId,+ secretAccessKey,+ sessionToken+ }: {+ sessionId: string;+ projectId: string;+ accessKeyId: string;+ secretAccessKey: string;+ sessionToken: string;+ },+ actor: OrgServiceActor+ ) => {+ const session = await pamSessionDAL.findById(sessionId);+ if (!session) throw new NotFoundError({ message: `Session with ID '${sessionId}' not found` });++ if (session.projectId !== projectId) {+ throw new ForbiddenRequestError({ message: "Session does not belong to the specified project" });+ }++ if (session.userId !== actor.id) {+ throw new ForbiddenRequestError({ message: "Session does not belong to the current user" });+ }++ if (session.resourceType !== PamResource.AwsIam) {+ throw new BadRequestError({ message: "Session is not an AWS IAM session" });+ }++ if (session.endedAt || (session.expiresAt && session.expiresAt < new Date())) {+ throw new BadRequestError({ message: "Session has ended or expired" });+ }++ const consoleUrl = await exchangeCredentialsForConsoleUrl({+ accessKeyId,+ secretAccessKey,+ sessionToken+ });++ return { consoleUrl };+ };+const getSessionCredentials = async (sessionId: string, actor: OrgServiceActor) => {// To be hit by gateways only (identity-based or enrollment-flow)if (actor.type !== ActorType.IDENTITY && actor.type !== ActorType.GATEWAY) {@@ -1660,6 +1707,7 @@ export const pamAccountServiceFactory = ({list,getById,access,+ getAwsIamConsoleUrl,viewCredentials,getSessionCredentials,rotateAllDueAccounts,diff --git a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-federation.ts b/backend/src/ee/services/pam-resource/aws-iam/aws-iam-federation.tsindex 97415a0888..20b7e52fe4 100644--- a/backend/src/ee/services/pam-resource/aws-iam/aws-iam-federation.ts+++ b/backend/src/ee/services/pam-resource/aws-iam/aws-iam-federation.ts@@ -181,10 +181,19 @@ export const validateTargetRoleAssumption = async ({}};+export type TAwsIamSessionCredentials = {+ accessKeyId: string;+ secretAccessKey: string;+ sessionToken: string;+ expiresAt: Date;+};+/**- * Assumes the target role and generates a federated console sign-in URL.+ * Runs the STS role-chaining sequence and returns the temporary credentials+ * that the caller can either consume directly (CLI) or exchange for a+ * federated console sign-in URL via {@link exchangeCredentialsForConsoleUrl}.*/-export const generateConsoleFederationUrl = async ({+export const generateAwsIamSessionCredentials = async ({connectionDetails,targetRoleArn,roleSessionName,@@ -196,7 +205,7 @@ export const generateConsoleFederationUrl = async ({roleSessionName: string;projectId: string;sessionDuration: number;-}): Promise<{ consoleUrl: string; expiresAt: Date }> => {+}): Promise<TAwsIamSessionCredentials> => {const pamCredentials = await assumePamRole({connectionDetails,projectId,@@ -216,15 +225,31 @@ export const generateConsoleFederationUrl = async ({const { AccessKeyId, SecretAccessKey, SessionToken, Expiration } = targetCredentials!;- // Generate federation URL+ if (!AccessKeyId || !SecretAccessKey || !SessionToken) {+ throw new InternalServerError({+ message: "AWS STS returned credentials missing required fields"+ });+ }++ return {+ accessKeyId: AccessKeyId,+ secretAccessKey: SecretAccessKey,+ sessionToken: SessionToken,+ expiresAt: Expiration ?? new Date(Date.now() + sessionDuration * 1000)+ };+};++// Exchanges existing STS credentials for a one-shot AWS console sign-in URL+export const exchangeCredentialsForConsoleUrl = async (+ credentials: Pick<TAwsIamSessionCredentials, "accessKeyId" | "secretAccessKey" | "sessionToken">+): Promise<string> => {const sessionJson = JSON.stringify({- sessionId: AccessKeyId,- sessionKey: SecretAccessKey,- sessionToken: SessionToken+ sessionId: credentials.accessKeyId,+ sessionKey: credentials.secretAccessKey,+ sessionToken: credentials.sessionToken});const federationEndpoint = "https://signin.aws.amazon.com/federation";-const signinTokenUrl = `${federationEndpoint}?Action=getSigninToken&Session=${encodeURIComponent(sessionJson)}`;const tokenResponse = await request.get<{ SigninToken?: string }>(signinTokenUrl);@@ -236,10 +261,5 @@ export const generateConsoleFederationUrl = async ({}const consoleDestination = `https://console.aws.amazon.com/`;- const consoleUrl = `${federationEndpoint}?Action=login&SigninToken=${encodeURIComponent(tokenResponse.data.SigninToken)}&Destination=${encodeURIComponent(consoleDestination)}`;-- return {- consoleUrl,- expiresAt: Expiration ?? new Date(Date.now() + sessionDuration * 1000)- };+ return `${federationEndpoint}?Action=login&SigninToken=${encodeURIComponent(tokenResponse.data.SigninToken)}&Destination=${encodeURIComponent(consoleDestination)}`;};diff --git a/backend/src/lib/logger/logger.ts b/backend/src/lib/logger/logger.tsindex 591bc06556..3613c1acb8 100644--- a/backend/src/lib/logger/logger.ts+++ b/backend/src/lib/logger/logger.ts@@ -81,6 +81,9 @@ const redactedKeys = ["encryptedKey","plaintextProjectKey","accessKey",+ "accessKeyId",+ "secretAccessKey",+ "sessionToken","botKey","decryptedSecret","secrets",diff --git a/docs/documentation/platform/pam/getting-started/resources/aws-iam.mdx b/docs/documentation/platform/pam/getting-started/resources/aws-iam.mdxindex 58b58a8138..8975098a78 100644--- a/docs/documentation/platform/pam/getting-started/resources/aws-iam.mdx+++ b/docs/documentation/platform/pam/getting-started/resources/aws-iam.mdx@@ -1,14 +1,14 @@---title: "AWS IAM"sidebarTitle: "AWS IAM"-description: "Learn how to configure AWS Management Console access through Infisical PAM for secure, audited, and just-in-time access to AWS."+description: "Learn how to configure AWS access through Infisical PAM for secure, audited, and just-in-time access to AWS, covering both the AWS CLI and the Management Console."----Infisical PAM supports secure, just-in-time access to the **AWS Management Console** through federated sign-in. This allows your team to access AWS without sharing long-lived credentials, while maintaining a complete audit trail of who accessed what and when.+Infisical PAM supports secure, just-in-time access to AWS through STS role chaining. Each access request issues short-lived credentials that can be used directly with the **AWS CLI** or exchanged for a federated **AWS Management Console** sign-in URL. Both come from the same session, so there's no duplication and CloudTrail attribution stays consistent.## How It Works-Unlike database or SSH resources that require a Gateway for network connectivity, AWS Console access works differently. Infisical uses AWS STS (Security Token Service) to assume roles on your behalf and generates temporary federated sign-in URLs.+Unlike database or SSH resources that require a Gateway for network connectivity, AWS access works differently. Infisical uses AWS STS (Security Token Service) to assume roles on your behalf and returns the temporary credentials. Those credentials are usable directly by the AWS CLI, and can also be exchanged for a federated console sign-in URL on demand.```mermaidsequenceDiagram@@ -229,9 +229,9 @@ A PAM Account represents a specific Target Role that users can request access to</Step></Steps>-## Access the AWS Console+## Access AWS-Once your resource and accounts are configured, users can request access through Infisical:+Once your resource and accounts are configured, users can request access through Infisical. A single access request creates one session whose credentials power both the CLI and (optionally) the console. Clicking **Open in AWS Console** does not start a separate session.@@ -241,18 +241,47 @@ Once your resource and accounts are configured, users can request access through</Step><Step title="Select the account">- In the resource’s accounts section, find the AWS Console account you want to access.+ In the resource's accounts section, find the AWS account you want to access.</Step><Step title="Request Access">- Click the **Access** button for that account.+ Click the **Access** button for that account. Infisical will:- Infisical will:1. Assume the Resource Role using your project's External ID2. Assume the Target Role using role chaining- 3. Generate a federated sign-in URL- 4. Open the AWS Console in a new browser tab+ 3. Return the temporary STS credentials to your browser- The user will be signed into the AWS Console with the permissions of the Target Role.+ The credentials shown are valid until the configured session duration expires.+ </Step>++ <Step title="Use the AWS CLI">+ The access dialog shows three fields with copy buttons:++ - **Access Key ID**+ - **Secret Access Key**+ - **Session Token**++ Use them however your tooling expects. Common options:++ - Export as environment variables (Bash / Zsh):+ ```bash+ export AWS_ACCESS_KEY_ID=ASIA...+ export AWS_SECRET_ACCESS_KEY=...+ export AWS_SESSION_TOKEN=...+ ```+ - Equivalent `$env:` assignments in PowerShell+ - Append to a named profile in `~/.aws/credentials`:+ ```ini+ [infisical-pam]+ aws_access_key_id = ASIA...+ aws_secret_access_key = ...+ aws_session_token = ...+ ```++ All standard AWS SDKs and tooling will pick up the credentials automatically once they are in the environment or credentials file.+ </Step>++ <Step title="(Optional) Open the AWS Console">+ Click **Open in AWS Console** at the bottom of the access dialog. Infisical exchanges the same STS credentials for a federated sign-in URL and opens it in a new tab. No second session is created, and CloudTrail attribution stays consistent with your CLI activity.</Step></Steps>\ No newline at end of filediff --git a/frontend/src/hooks/api/pam/mutations.tsx b/frontend/src/hooks/api/pam/mutations.tsxindex 6d9dd4db84..3e41fdfcb7 100644--- a/frontend/src/hooks/api/pam/mutations.tsx+++ b/frontend/src/hooks/api/pam/mutations.tsx@@ -196,8 +196,14 @@ export type TAccessPamAccountDTO = {export type TAccessPamAccountResponse = {sessionId: string;resourceType: string;- consoleUrl?: string;metadata?: Record<string, string | undefined>;+ // AWS IAM credentials (raw STS) -- usable directly by the AWS CLI+ // and exchangeable for a federated console URL via /sessions/:id/aws-console-url+ accessKeyId?: string;+ secretAccessKey?: string;+ sessionToken?: string;+ expiresAt?: string;+ // Gateway-resource fields (Postgres, MySQL, etc.)relayClientCertificate?: string;relayClientPrivateKey?: string;relayServerCertificateChain?: string;@@ -232,6 +238,32 @@ export const useAccessPamAccount = () => {});};+export type TGetAwsIamConsoleUrlDTO = {+ sessionId: string;+ projectId: string;+ accessKeyId: string;+ secretAccessKey: string;+ sessionToken: string;+};++export const useGetAwsIamConsoleUrl = () => {+ return useMutation({+ mutationFn: async ({+ sessionId,+ projectId,+ accessKeyId,+ secretAccessKey,+ sessionToken+ }: TGetAwsIamConsoleUrlDTO) => {+ const { data } = await apiRequest.post<{ consoleUrl: string }>(+ `/api/v1/pam/accounts/sessions/${sessionId}/aws-console-url`,+ { projectId, accessKeyId, secretAccessKey, sessionToken }+ );+ return data;+ }+ });+};+// Account Dependenciesexport const useTogglePamAccountDependency = () => {const queryClient = useQueryClient();diff --git a/frontend/src/pages/pam/PamAccountByIDPage/PamAccountByIDPage.tsx b/frontend/src/pages/pam/PamAccountByIDPage/PamAccountByIDPage.tsxindex f19aa1d17c..6071608781 100644--- a/frontend/src/pages/pam/PamAccountByIDPage/PamAccountByIDPage.tsx+++ b/frontend/src/pages/pam/PamAccountByIDPage/PamAccountByIDPage.tsx@@ -45,7 +45,6 @@ import { PamAccessAccountModal } from "../PamAccountsPage/components/PamAccessAcimport { PamDeleteAccountModal } from "../PamAccountsPage/components/PamDeleteAccountModal";import { PamRequestAccountAccessModal } from "../PamAccountsPage/components/PamRequestAccountAccessModal";import { PamUpdateAccountModal } from "../PamAccountsPage/components/PamUpdateAccountModal";-import { useAccessAwsIamAccount } from "../PamAccountsPage/components/useAccessAwsIamAccount";import {PamAccountCredentialsSection,PamAccountDependenciesSection,@@ -83,7 +82,6 @@ const PageContent = () => {] as const);const queryClient = useQueryClient();- const { accessAwsIam, isPending: isAwsAccessPending } = useAccessAwsIamAccount();const { mutateAsync: checkPolicyMatch } = useCheckPolicyMatch();const rotateAccount = useManualRotateAccount();@@ -166,11 +164,7 @@ const PageContent = () => {return;}- if (account.resource?.resourceType === PamResourceType.AwsIam) {- accessAwsIam(account);- } else {- handlePopUpOpen("accessAccount", { account });- }+ handlePopUpOpen("accessAccount", { account });};const handleRotate = async () => {@@ -237,7 +231,7 @@ const PageContent = () => {I={ProjectPermissionPamAccountActions.Access}a={ProjectPermissionSub.PamAccounts}>- <Button variant="neutral" onClick={handleAccess} isPending={isAwsAccessPending}>+ <Button variant="neutral" onClick={handleAccess}><LogInIcon />Access</Button>diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsxindex d9f87b6ba0..7348aa3ce0 100644--- a/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAccessAccountModal.tsx@@ -11,6 +11,8 @@ import { ROUTE_PATHS } from "@app/const/routes";import { useOrganization } from "@app/context";import { PamResourceType, TPamAccount } from "@app/hooks/api/pam";+import { PamAwsIamAccessSection } from "./PamAwsIamAccessSection";+type Props = {account?: TPamAccount;isOpen: boolean;@@ -91,6 +93,8 @@ export const PamAccessAccountModal = ({ isOpen, onOpenChange, account, projectIdif (!account) return null;+ const isAwsIam = account.resource?.resourceType === PamResourceType.AwsIam;+const showWebAccess =account.resource?.resourceType === PamResourceType.Postgres ||account.resource?.resourceType === PamResourceType.SSH ||@@ -103,82 +107,94 @@ export const PamAccessAccountModal = ({ isOpen, onOpenChange, account, projectIdtitle="Access Account"subTitle={`Connect to ${account.name}`}>- <div className="py-1">- <p className="text-sm font-medium text-mineshaft-400">Terminal</p>- <p className="mb-2 text-xs text-mineshaft-400">Connect using the Infisical CLI</p>- <FormLabel- label="Duration"- tooltipText="The maximum duration of your session. Ex: 1h, 3w, 30d"- />- <Input- value={duration}- onChange={(e) => setDuration(e.target.value)}- placeholder="permanent"- isError={!isDurationValid}+ {isAwsIam ? (+ <PamAwsIamAccessSection+ account={account}+ projectId={projectId}+ onClose={() => onOpenChange(false)}/>- <FormLabel label="CLI Command" className="mt-4" />- <div className="flex gap-2">- <Input value={command} isDisabled />- <IconButton- ariaLabel="copy"- variant="outline_bg"- colorSchema="secondary"- onClick={() => {- navigator.clipboard.writeText(command);-- createNotification({- text: "Command copied to clipboard",- type: "info"- });-- onOpenChange(false);- }}- className="w-10"- >- <FontAwesomeIcon icon={faCopy} />- </IconButton>- </div>- <a- href="https://infisical.com/docs/cli/overview"- target="_blank"- className="mt-2 flex h-4 w-fit items-center gap-2 border-b border-mineshaft-400 text-sm text-mineshaft-400 transition-colors duration-100 hover:border-yellow-400 hover:text-yellow-400"- rel="noreferrer"- >- <span>Install the Infisical CLI</span>- <FontAwesomeIcon icon={faUpRightFromSquare} className="size-3" />- </a>- </div>- {showWebAccess && (+ ) : (<>- <div className="relative my-6">- <div className="absolute inset-0 flex items-center">- <div className="w-full border-t border-mineshaft-600" />- </div>- <div className="relative flex justify-center text-xs">- <span className="bg-mineshaft-800 px-2 text-mineshaft-400">OR</span>- </div>- </div><div className="py-1">- <p className="text-sm font-medium text-mineshaft-400">Browser</p>- <p className="mb-2 text-xs text-mineshaft-400">Connect directly from your browser</p>+ <p className="text-sm font-medium text-mineshaft-400">Terminal</p>+ <p className="mb-2 text-xs text-mineshaft-400">Connect using the Infisical CLI</p>+ <FormLabel+ label="Duration"+ tooltipText="The maximum duration of your session. Ex: 1h, 3w, 30d"+ />+ <Input+ value={duration}+ onChange={(e) => setDuration(e.target.value)}+ placeholder="permanent"+ isError={!isDurationValid}+ />+ <FormLabel label="CLI Command" className="mt-4" /><div className="flex gap-2">- <Link- to={ROUTE_PATHS.Pam.PamAccountAccessPage.path}- params={{- orgId: currentOrg.id,- projectId,- resourceType: account.resource?.resourceType ?? "",- resourceId: account.resource?.id ?? "",- accountId: account.id+ <Input value={command} isDisabled />+ <IconButton+ ariaLabel="copy"+ variant="outline_bg"+ colorSchema="secondary"+ onClick={() => {+ navigator.clipboard.writeText(command);++ createNotification({+ text: "Command copied to clipboard",+ type: "info"+ });++ onOpenChange(false);}}- target="_blank"- className="flex w-full items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-black transition-colors hover:bg-primary/80"+ className="w-10">- <FontAwesomeIcon icon={faTerminal} />- Connect in Browser- </Link>+ <FontAwesomeIcon icon={faCopy} />+ </IconButton></div>+ <a+ href="https://infisical.com/docs/cli/overview"+ target="_blank"+ className="mt-2 flex h-4 w-fit items-center gap-2 border-b border-mineshaft-400 text-sm text-mineshaft-400 transition-colors duration-100 hover:border-yellow-400 hover:text-yellow-400"+ rel="noreferrer"+ >+ <span>Install the Infisical CLI</span>+ <FontAwesomeIcon icon={faUpRightFromSquare} className="size-3" />+ </a></div>+ {showWebAccess && (+ <>+ <div className="relative my-6">+ <div className="absolute inset-0 flex items-center">+ <div className="w-full border-t border-mineshaft-600" />+ </div>+ <div className="relative flex justify-center text-xs">+ <span className="bg-mineshaft-800 px-2 text-mineshaft-400">OR</span>+ </div>+ </div>+ <div className="py-1">+ <p className="text-sm font-medium text-mineshaft-400">Browser</p>+ <p className="mb-2 text-xs text-mineshaft-400">+ Connect directly from your browser+ </p>+ <div className="flex gap-2">+ <Link+ to={ROUTE_PATHS.Pam.PamAccountAccessPage.path}+ params={{+ orgId: currentOrg.id,+ projectId,+ resourceType: account.resource?.resourceType ?? "",+ resourceId: account.resource?.id ?? "",+ accountId: account.id+ }}+ target="_blank"+ className="flex w-full items-center justify-center gap-2 rounded-md bg-primary px-4 py-2 text-sm font-medium text-black transition-colors hover:bg-primary/80"+ >+ <FontAwesomeIcon icon={faTerminal} />+ Connect in Browser+ </Link>+ </div>+ </div>+ </>+ )}</>)}</ModalContent>diff --git a/frontend/src/pages/pam/PamAccountsPage/components/PamAwsIamAccessSection.tsx b/frontend/src/pages/pam/PamAccountsPage/components/PamAwsIamAccessSection.tsxnew file mode 100644index 0000000000..20fc46a7c7--- /dev/null+++ b/frontend/src/pages/pam/PamAccountsPage/components/PamAwsIamAccessSection.tsx@@ -0,0 +1,203 @@+import { useEffect, useRef, useState } from "react";+import { CopyIcon, ExternalLinkIcon } from "lucide-react";++import { createNotification } from "@app/components/notifications";+import { ContentLoader } from "@app/components/v2";+import { Button, IconButton, Input, Label } from "@app/components/v3";+import { TPamAccount, useAccessPamAccount, useGetAwsIamConsoleUrl } from "@app/hooks/api/pam";+import { TAwsIamCredentials } from "@app/hooks/api/pam/types";++const formatExpiry = (expiresAt: string) => {+ const remainingMs = new Date(expiresAt).getTime() - Date.now();+ if (remainingMs <= 0) return "Expired";++ const totalMinutes = Math.floor(remainingMs / 60_000);+ const hours = Math.floor(totalMinutes / 60);+ const minutes = totalMinutes % 60;+ return hours > 0 ? `Expires in ${hours}h ${minutes}m` : `Expires in ${minutes}m`;+};++type TStsCredentials = {+ accessKeyId: string;+ secretAccessKey: string;+ sessionToken: string;+ expiresAt: string;+};++type Props = {+ account: TPamAccount;+ projectId: string;+ onClose: () => void;+};++export const PamAwsIamAccessSection = ({ account, projectId, onClose }: Props) => {+ const accessPamAccount = useAccessPamAccount();+ const getAwsIamConsoleUrl = useGetAwsIamConsoleUrl();++ const [credentials, setCredentials] = useState<TStsCredentials | null>(null);+ const [sessionId, setSessionId] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);+ const [, setNow] = useState(Date.now());++ // Guards against React 18 StrictMode's double-invoked effect, which would+ // otherwise issue two STS sessions for a single modal open+ const hasRequestedRef = useRef(false);++ useEffect(() => {+ const id = window.setInterval(() => setNow(Date.now()), 60_000);+ return () => window.clearInterval(id);+ }, []);++ useEffect(() => {+ if (hasRequestedRef.current) return;+ hasRequestedRef.current = true;++ const run = async () => {+ try {+ const response = await accessPamAccount.mutateAsync({+ accountId: account.id,+ resourceName: account.resource?.name ?? "",+ accountName: account.name,+ projectId,+ duration: `${(account.credentials as TAwsIamCredentials).defaultSessionDuration}s`+ });++ if (+ !response.accessKeyId ||+ !response.secretAccessKey ||+ !response.sessionToken ||+ !response.expiresAt+ ) {+ setError("Backend did not return AWS credentials");+ return;+ }++ setCredentials({+ accessKeyId: response.accessKeyId,+ secretAccessKey: response.secretAccessKey,+ sessionToken: response.sessionToken,+ expiresAt: response.expiresAt+ });+ setSessionId(response.sessionId);+ } catch (err) {+ setError(err instanceof Error ? err.message : "Failed to generate AWS session credentials");+ }+ };++ run().catch(() => {});+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, []);++ const handleCopy = (text: string, label: string) => {+ navigator.clipboard.writeText(text).catch(() => {});+ createNotification({ text: `${label} copied to clipboard`, type: "info" });+ };++ const handleOpenConsole = async () => {+ if (!sessionId || !credentials) return;+ try {+ const { consoleUrl } = await getAwsIamConsoleUrl.mutateAsync({+ sessionId,+ projectId,+ accessKeyId: credentials.accessKeyId,+ secretAccessKey: credentials.secretAccessKey,+ sessionToken: credentials.sessionToken+ });+ window.open(consoleUrl, "_blank", "noopener,noreferrer");+ createNotification({ text: "AWS Console opened in a new tab", type: "success" });+ onClose();+ } catch (err) {+ createNotification({+ text: err instanceof Error ? err.message : "Failed to open AWS Console",+ type: "error"+ });+ }+ };++ if (error) {+ return (+ <div+ role="alert"+ className="rounded-md border border-danger/20 bg-danger/5 p-4 text-sm text-danger"+ >+ {error}+ </div>+ );+ }++ if (!credentials) {+ return (+ <div className="flex h-40 items-center justify-center">+ <ContentLoader />+ </div>+ );+ }++ const fields = [+ { label: "Access Key ID", value: credentials.accessKeyId },+ { label: "Secret Access Key", value: credentials.secretAccessKey },+ { label: "Session Token", value: credentials.sessionToken }+ ];++ return (+ <div className="flex flex-col gap-4">+ <div>+ <div className="flex items-center justify-between">+ <div>+ <p className="text-sm font-medium text-foreground">Credentials</p>+ <p className="text-xs text-muted">+ Use with the AWS CLI, SDKs, or paste into <code>~/.aws/credentials</code>+ </p>+ </div>+ <p className="text-xs text-muted">{formatExpiry(credentials.expiresAt)}</p>+ </div>++ <div className="mt-3 flex flex-col gap-3">+ {fields.map(({ label, value }) => (+ <div key={label}>+ <Label className="mb-1 text-label">{label}</Label>+ <div className="flex gap-2">+ <Input value={value} readOnly />+ <IconButton+ aria-label={`Copy ${label}`}+ variant="outline"+ onClick={() => handleCopy(value, label)}+ >+ <CopyIcon />+ </IconButton>+ </div>+ </div>+ ))}+ </div>+ </div>++ <div className="relative my-2">+ <div className="absolute inset-0 flex items-center">+ <div className="w-full border-t border-border" />+ </div>+ <div className="relative flex justify-center text-xs">+ <span className="bg-popover px-2 text-muted">OR</span>+ </div>+ </div>++ <div>+ <p className="text-sm font-medium text-foreground">Browser</p>+ <p className="mb-2 text-xs text-muted">+ Open the AWS Console signed in as the same temporary session+ </p>+ <Button+ variant="outline"+ size="md"+ isFullWidth+ isPending={getAwsIamConsoleUrl.isPending}+ onClick={() => {+ handleOpenConsole().catch(() => {});+ }}+ >+ <ExternalLinkIcon />+ Open in AWS Console+ </Button>+ </div>+ </div>+ );+};diff --git a/frontend/src/pages/pam/PamAccountsPage/components/useAccessAwsIamAccount.tsx b/frontend/src/pages/pam/PamAccountsPage/components/useAccessAwsIamAccount.tsxdeleted file mode 100644index bda8e61733..0000000000--- a/frontend/src/pages/pam/PamAccountsPage/components/useAccessAwsIamAccount.tsx+++ /dev/null@@ -1,55 +0,0 @@-import { useState } from "react";--import { createNotification } from "@app/components/notifications";-import { PamResourceType, TPamAccount, useAccessPamAccount } from "@app/hooks/api/pam";-import { TAwsIamCredentials } from "@app/hooks/api/pam/types";--export const useAccessAwsIamAccount = () => {- const accessPamAccount = useAccessPamAccount();- const [loadingAccountId, setLoadingAccountId] = useState<string | null>(null);-- const accessAwsIam = async (account: TPamAccount) => {- if (account.resource?.resourceType !== PamResourceType.AwsIam) {- return false;- }-- setLoadingAccountId(account.id);-- try {- const response = await accessPamAccount.mutateAsync({- accountId: account.id,- resourceName: account.resource?.name ?? "",- accountName: account.name,- projectId: account.projectId,- duration: `${(account.credentials as TAwsIamCredentials).defaultSessionDuration}s`- });-- if (response.consoleUrl) {- // Open the AWS Console URL in a new tab- window.open(response.consoleUrl, "_blank", "noopener,noreferrer");-- createNotification({- text: "AWS Console opened in new tab",- type: "success"- });-- return true;- }-- createNotification({- text: "Failed to generate AWS Console URL",- type: "error"- });-- return false;- } finally {- setLoadingAccountId(null);- }- };-- return {- accessAwsIam,- isPending: accessPamAccount.isPending,- loadingAccountId- };-};diff --git a/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceAccountsSection.tsx b/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceAccountsSection.tsxindex 2b1c404794..1f84612ea6 100644--- a/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceAccountsSection.tsx+++ b/frontend/src/pages/pam/PamResourceByIDPage/components/PamResourceAccountsSection.tsx@@ -69,7 +69,6 @@ import { PamAddAccountModal } from "../../PamAccountsPage/components/PamAddAccouimport { PamDeleteAccountModal } from "../../PamAccountsPage/components/PamDeleteAccountModal";import { PamRequestAccountAccessModal } from "../../PamAccountsPage/components/PamRequestAccountAccessModal";import { PamUpdateAccountModal } from "../../PamAccountsPage/components/PamUpdateAccountModal";-import { useAccessAwsIamAccount } from "../../PamAccountsPage/components/useAccessAwsIamAccount";type Props = {resource: TPamResource;@@ -93,7 +92,6 @@ export const PamResourceAccountsSection = ({ resource }: Props) => {const params = useParams({ strict: false }) as { projectId?: string };const { projectId } = params;- const { accessAwsIam, loadingAccountId } = useAccessAwsIamAccount();const { mutateAsync: checkPolicyMatch } = useCheckPolicyMatch();const manualRotate = useManualRotateAccount();@@ -271,11 +269,7 @@ export const PamResourceAccountsSection = ({ resource }: Props) => {return;}- if (account.resource?.resourceType === PamResourceType.AwsIam) {- accessAwsIam(account);- } else {- handlePopUpOpen("accessAccount", { account });- }+ handlePopUpOpen("accessAccount", { account });};return (@@ -540,8 +534,6 @@ export const PamResourceAccountsSection = ({ resource }: Props) => {e.stopPropagation();accessAccount(account);}}- isPending={loadingAccountId === account.id}- isDisabled={loadingAccountId === account.id}><LogInIcon />Connect