simonw / llm-bedrock

Run prompts against models hosted on AWS Bedrock
Apache License 2.0
9 stars 0 forks source link

Get ~/.aws credentials working #10

Closed simonw closed 6 hours ago

simonw commented 8 hours ago

If you don't have a key set falling back on just instantiating boto3.Client and letting it pick up default credentials may work.

simonw commented 8 hours ago

Claude suggestion - prompt was Using boto3 how can I detect if the user is authenticated already ?​​​​​​​​​​​​​​​​

import boto3
from botocore.exceptions import ClientError, NoCredentialsError

def check_aws_authentication():
    """
    Check if AWS credentials are properly configured and authenticated.
    Returns a tuple of (is_authenticated: bool, message: str)
    """
    try:
        # Create a boto3 session
        session = boto3.Session()

        # Get the caller identity using STS
        sts = session.client('sts')
        identity = sts.get_caller_identity()

        return True, {
            'authenticated': True,
            'user_id': identity['UserId'],
            'account': identity['Account'],
            'arn': identity['Arn']
        }

    except NoCredentialsError:
        return False, {
            'authenticated': False,
            'error': 'No AWS credentials found. Please configure your credentials.'
        }
    except ClientError as e:
        return False, {
            'authenticated': False,
            'error': f'Authentication failed: {str(e)}'
        }

def get_current_credentials():
    """
    Get the current AWS credentials if they exist.
    Returns None if no credentials are found.
    """
    try:
        session = boto3.Session()
        credentials = session.get_credentials()

        if credentials is None:
            return None

        # Freeze the credentials
        frozen_credentials = credentials.get_frozen_credentials()

        return {
            'access_key': frozen_credentials.access_key,
            'secret_key': frozen_credentials.secret_key[:5] + '*****',  # Mask the secret key
            'token': frozen_credentials.token is not None,
            'method': credentials.method
        }

    except Exception as e:
        return None