-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
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
feat(python): AssumeRole support for AWS Credential Provider #19346
Merged
Merged
Changes from all commits
Commits
Show all changes
6 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -5,7 +5,7 @@ | |
import os | ||
import sys | ||
import zoneinfo | ||
from typing import TYPE_CHECKING, Callable, Optional, Union | ||
from typing import TYPE_CHECKING, Any, Callable, Optional, TypedDict, Union | ||
|
||
if TYPE_CHECKING: | ||
if sys.version_info >= (3, 10): | ||
|
@@ -30,6 +30,23 @@ | |
] | ||
|
||
|
||
class AWSAssumeRoleKWArgs(TypedDict): | ||
"""Parameters for [STS.Client.assume_role()](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sts/client/assume_role.html#STS.Client.assume_role).""" | ||
|
||
RoleArn: str | ||
RoleSessionName: str | ||
PolicyArns: list[dict[str, str]] | ||
Policy: str | ||
DurationSeconds: int | ||
Tags: list[dict[str, str]] | ||
TransitiveTagKeys: list[str] | ||
ExternalId: str | ||
SerialNumber: str | ||
TokenCode: str | ||
SourceIdentity: str | ||
ProvidedContexts: list[dict[str, str]] | ||
|
||
|
||
class CredentialProvider(abc.ABC): | ||
""" | ||
Base class for credential providers. | ||
|
@@ -55,26 +72,39 @@ class CredentialProviderAWS(CredentialProvider): | |
at any point without it being considered a breaking change. | ||
""" | ||
|
||
def __init__(self, *, profile_name: str | None = None) -> None: | ||
def __init__( | ||
self, | ||
*, | ||
profile_name: str | None = None, | ||
assume_role: AWSAssumeRoleKWArgs | None = None, | ||
) -> None: | ||
""" | ||
Initialize a credential provider for AWS. | ||
|
||
Parameters | ||
---------- | ||
profile_name : str | ||
Profile name to use from credentials file. | ||
assume_role : AWSAssumeRoleKWArgs | None | ||
Configure a role to assume. These are passed as kwarg parameters to | ||
[STS.client.assume_role()](https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/sts/client/assume_role.html#STS.Client.assume_role) | ||
""" | ||
msg = "`CredentialProviderAWS` functionality is considered unstable" | ||
issue_unstable_warning(msg) | ||
|
||
self._check_module_availability() | ||
self.profile_name = profile_name | ||
self.assume_role = assume_role | ||
|
||
def __call__(self) -> CredentialProviderFunctionReturn: | ||
"""Fetch the credentials for the configured profile name.""" | ||
import boto3 | ||
|
||
session = boto3.Session(profile_name=self.profile_name) | ||
|
||
if self.assume_role is not None: | ||
return self._finish_assume_role(session) | ||
|
||
creds = session.get_credentials() | ||
|
||
if creds is None: | ||
|
@@ -87,6 +117,24 @@ def __call__(self) -> CredentialProviderFunctionReturn: | |
"aws_session_token": creds.token, | ||
}, None | ||
|
||
def _finish_assume_role(self, session: Any) -> CredentialProviderFunctionReturn: | ||
client = session.client("sts") | ||
|
||
sts_response = client.assume_role(**self.assume_role) | ||
creds = sts_response["Credentials"] | ||
|
||
expiry = creds["Expiration"] | ||
|
||
if expiry.tzinfo is None: | ||
msg = "expiration time in STS response did not contain timezone information" | ||
raise ValueError(msg) | ||
|
||
return { | ||
"aws_access_key_id": creds["AccessKeyId"], | ||
"aws_secret_access_key": creds["SecretAccessKey"], | ||
"aws_session_token": creds["SessionToken"], | ||
}, int(expiry.timestamp()) | ||
|
||
@classmethod | ||
def _check_module_availability(cls) -> None: | ||
if importlib.util.find_spec("boto3") is None: | ||
|
@@ -134,9 +182,10 @@ def __call__(self) -> CredentialProviderFunctionReturn: | |
|
||
return {"bearer_token": self.creds.token}, ( | ||
int( | ||
expiry.replace( | ||
# Google auth does not set this properly | ||
tzinfo=zoneinfo.ZoneInfo("UTC") | ||
( | ||
expiry.replace(tzinfo=zoneinfo.ZoneInfo("UTC")) | ||
if expiry.tzinfo is None | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. drive-by - in case a future version of google auth adds timezone info |
||
else expiry | ||
).timestamp() | ||
) | ||
if (expiry := self.creds.expiry) is not None | ||
|
@@ -153,21 +202,29 @@ def _check_module_availability(cls) -> None: | |
def _auto_select_credential_provider( | ||
source: ScanSource, | ||
) -> CredentialProvider | None: | ||
from polars.io.cloud._utils import _infer_cloud_type | ||
from polars.io.cloud._utils import ( | ||
_first_scan_path, | ||
_get_path_scheme, | ||
_is_aws_cloud, | ||
_is_gcp_cloud, | ||
) | ||
|
||
verbose = os.getenv("POLARS_VERBOSE") == "1" | ||
cloud_type = _infer_cloud_type(source) | ||
|
||
if (path := _first_scan_path(source)) is None: | ||
return None | ||
|
||
if (scheme := _get_path_scheme(path)) is None: | ||
return None | ||
|
||
provider = None | ||
|
||
try: | ||
provider = ( | ||
None | ||
if cloud_type is None | ||
else CredentialProviderAWS() | ||
if cloud_type == "aws" | ||
CredentialProviderAWS() | ||
if _is_aws_cloud(scheme) | ||
else CredentialProviderGCP() | ||
if cloud_type == "gcp" | ||
if _is_gcp_cloud(scheme) | ||
else None | ||
) | ||
except ImportError as e: | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
refactored to remove the exhaustive cloud-type identification - we only need AWS and GCP for now
also more efficient to use these functions directly as we avoid double-matching