Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DRIVERS-1746 Add native support for AWS IAM Roles for service accounts, EKS in particular #9

Merged
merged 6 commits into from
Jun 16, 2022
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ About
=====

MONGODB-AWS authentication support for PyMongo. pymongo-auth-aws uses
`botocore`_ and `requests`_.
`boto3`_ and `requests`_.

Support / Feedback
==================
Expand Down
38 changes: 38 additions & 0 deletions pymongo_auth_aws/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@
from base64 import standard_b64encode
from collections import namedtuple

import boto3
import requests

from botocore.exceptions import ClientError
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.credentials import Credentials
Expand All @@ -45,6 +47,26 @@ def _aws_temp_credentials():
if access_key and secret_key:
return AwsCredential(
access_key, secret_key, os.environ.get('AWS_SESSION_TOKEN'))
# Check if environment variables exposed by IAM Roles for Service Accounts (IRSA) are present.
# See https://docs.aws.amazon.com/eks/latest/userguide/iam-roles-for-service-accounts.html for details.
irsa_web_id_file = os.getenv('AWS_WEB_IDENTITY_TOKEN_FILE')
irsa_role_arn = os.getenv('AWS_ROLE_ARN')
if irsa_web_id_file and irsa_role_arn:
try:
with open(irsa_web_id_file) as f:
irsa_web_id_token = f.read()
# Check for errors raised by `open` from older Python versions.
except (OSError, IOError, InterruptedError) as exc:
basilnsage marked this conversation as resolved.
Show resolved Hide resolved
raise PyMongoAuthAwsError(
'temporary MONGODB-AWS credentials could not be obtained, '
'error: %s' % (exc,))
try:
return _irsa_assume_role(irsa_role_arn, irsa_web_id_token, 'pymongo-auth-aws')
except ClientError as error:
basilnsage marked this conversation as resolved.
Show resolved Hide resolved
error_message = error.response['Error']['Message']
ShaneHarvey marked this conversation as resolved.
Show resolved Hide resolved
raise PyMongoAuthAwsError(
'temporary MONGODB-AWS credentials could not be obtained, '
'error: %s' % (error_message,))
# If the environment variable
# AWS_CONTAINER_CREDENTIALS_RELATIVE_URI is set then drivers MUST
# assume that it was set by an AWS ECS agent and use the URI
Expand Down Expand Up @@ -101,6 +123,22 @@ def _aws_temp_credentials():
return AwsCredential(temp_user, temp_password, token)


def _irsa_assume_role(role_arn, token, role_session_name):
"""Call sts:AssumeRoleWithWebIdentity and return temporary credentials."""
sts_client = boto3.client('sts')
resp = sts_client.assume_role_with_web_identity(
RoleArn=role_arn,
RoleSessionName=role_session_name,
WebIdentityToken=token
)
creds = resp['Credentials']
access_key = creds['AccessKeyId']
secret_key = creds['SecretAccessKey']
session_token = creds['SessionToken']

return AwsCredential(access_key, secret_key, session_token)


_AWS4_HMAC_SHA256 = 'AWS4-HMAC-SHA256'
_AWS_SERVICE = 'sts'

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
description="MONGODB-AWS authentication support for PyMongo",
long_description=LONG_DESCRIPTION,
packages=find_packages(exclude=['test']),
install_requires=['requests<3.0.0', 'botocore'],
install_requires=['requests<3.0.0', 'boto3'],
author="Shane Harvey",
author_email="drivers-python-noreply@mongodb.com",
url="https://github.com/mongodb/pymongo-auth-aws",
Expand Down