-
-
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: Add Azure credential provider using DefaultAzureCredential()
#20384
Merged
ritchie46
merged 5 commits into
pola-rs:main
from
nameexhaustion:azure-cred-provider-python
Dec 20, 2024
Merged
Changes from all commits
Commits
Show all changes
5 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
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
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 |
---|---|---|
|
@@ -2,7 +2,9 @@ | |
|
||
import abc | ||
import importlib.util | ||
import json | ||
import os | ||
import subprocess | ||
import sys | ||
import zoneinfo | ||
from typing import IO, TYPE_CHECKING, Any, Callable, Literal, Optional, TypedDict, Union | ||
|
@@ -139,6 +141,147 @@ def _check_module_availability(cls) -> None: | |
raise ImportError(msg) | ||
|
||
|
||
class CredentialProviderAzure(CredentialProvider): | ||
""" | ||
Azure Credential Provider. | ||
|
||
Using this requires the `azure-identity` Python package to be installed. | ||
|
||
.. warning:: | ||
This functionality is considered **unstable**. It may be changed | ||
at any point without it being considered a breaking change. | ||
""" | ||
|
||
def __init__( | ||
self, | ||
*, | ||
scopes: list[str] | None = None, | ||
storage_account: str | None = None, | ||
_verbose: bool = False, | ||
) -> None: | ||
""" | ||
Initialize a credential provider for Microsoft Azure. | ||
|
||
This uses `azure.identity.DefaultAzureCredential()`. | ||
|
||
Parameters | ||
---------- | ||
scopes | ||
Scopes to pass to `get_token` | ||
storage_account | ||
If specified, an attempt will be made to retrieve the account keys | ||
for this account using the Azure CLI. If this is successful, the | ||
account keys will be used instead of | ||
`DefaultAzureCredential.get_token()` | ||
""" | ||
msg = "`CredentialProviderAzure` functionality is considered unstable" | ||
issue_unstable_warning(msg) | ||
|
||
self._check_module_availability() | ||
|
||
self.account_name = storage_account | ||
# Done like this to bypass mypy, we don't have stubs for azure.identity | ||
self.credential = importlib.import_module("azure.identity").__dict__[ | ||
"DefaultAzureCredential" | ||
]() | ||
self.scopes = scopes if scopes is not None else ["https://storage.azure.com/"] | ||
self._verbose = _verbose | ||
|
||
if self._verbose: | ||
print( | ||
( | ||
"CredentialProviderAzure " | ||
f"{self.account_name = } " | ||
f"{self.scopes = } " | ||
), | ||
file=sys.stderr, | ||
) | ||
|
||
def __call__(self) -> CredentialProviderFunctionReturn: | ||
"""Fetch the credentials.""" | ||
if self.account_name is not None: | ||
try: | ||
creds = { | ||
"account_key": self._get_azure_storage_account_key_az_cli( | ||
self.account_name | ||
) | ||
} | ||
|
||
if self._verbose: | ||
print( | ||
"[CredentialProviderAzure]: retrieved account keys from Azure CLI", | ||
file=sys.stderr, | ||
) | ||
except Exception as e: | ||
if self._verbose: | ||
print( | ||
f"[CredentialProviderAzure]: failed to retrieve account keys from Azure CLI: {e}", | ||
file=sys.stderr, | ||
) | ||
else: | ||
return creds, None # type: ignore[return-value] | ||
|
||
token = self.credential.get_token(*self.scopes) | ||
|
||
return { | ||
"bearer_token": token.token, | ||
}, token.expires_on | ||
|
||
@classmethod | ||
def _check_module_availability(cls) -> None: | ||
if importlib.util.find_spec("azure.identity") is None: | ||
msg = "azure-identity must be installed to use `CredentialProviderAzure`" | ||
raise ImportError(msg) | ||
|
||
@staticmethod | ||
def _extract_adls_uri_storage_account(uri: str) -> str | None: | ||
# "abfss://{CONTAINER}@{STORAGE_ACCOUNT}.dfs.core.windows.net/" | ||
# ^^^^^^^^^^^^^^^^^ | ||
try: | ||
return ( | ||
uri.split("://", 1)[1] | ||
.split("/", 1)[0] | ||
.split("@", 1)[1] | ||
.split(".dfs.core.windows.net", 1)[0] | ||
) | ||
|
||
except IndexError: | ||
return None | ||
|
||
@staticmethod | ||
def _get_azure_storage_account_key_az_cli(account_name: str) -> str: | ||
az_cmd = [ | ||
"az", | ||
"storage", | ||
"account", | ||
"keys", | ||
"list", | ||
"--output", | ||
"json", | ||
"--account-name", | ||
account_name, | ||
] | ||
|
||
cmd = az_cmd if sys.platform != "win32" else ["cmd", "/C", *az_cmd] | ||
|
||
# [ | ||
# { | ||
# "creationTime": "1970-01-01T00:00:00.000000+00:00", | ||
# "keyName": "key1", | ||
# "permissions": "FULL", | ||
# "value": "..." | ||
# }, | ||
# { | ||
# "creationTime": "1970-01-01T00:00:00.000000+00:00", | ||
# "keyName": "key2", | ||
# "permissions": "FULL", | ||
# "value": "..." | ||
# } | ||
# ] | ||
|
||
return json.loads(subprocess.check_output(cmd))[0]["value"] | ||
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. This is ported from some recently added logic to the rust side from (#20357), we need this here as the Python credential provider will override the one set by the Rust side if it is passed. |
||
|
||
|
||
class CredentialProviderGCP(CredentialProvider): | ||
""" | ||
GCP Credential Provider. | ||
|
@@ -165,7 +308,7 @@ def __init__( | |
---------- | ||
Parameters are passed to `google.auth.default()` | ||
""" | ||
msg = "`CredentialProviderAWS` functionality is considered unstable" | ||
msg = "`CredentialProviderGCP` functionality is considered unstable" | ||
issue_unstable_warning(msg) | ||
|
||
self._check_module_availability() | ||
|
@@ -194,7 +337,7 @@ def __init__( | |
self.creds = creds | ||
|
||
def __call__(self) -> CredentialProviderFunctionReturn: | ||
"""Fetch the credentials for the configured profile name.""" | ||
"""Fetch the credentials.""" | ||
import google.auth.transport.requests | ||
|
||
self.creds.refresh(google.auth.transport.requests.__dict__["Request"]()) | ||
|
@@ -238,6 +381,7 @@ def _maybe_init_credential_provider( | |
_first_scan_path, | ||
_get_path_scheme, | ||
_is_aws_cloud, | ||
_is_azure_cloud, | ||
_is_gcp_cloud, | ||
) | ||
|
||
|
@@ -265,6 +409,13 @@ def _maybe_init_credential_provider( | |
provider = ( | ||
CredentialProviderAWS() | ||
if _is_aws_cloud(scheme) | ||
else CredentialProviderAzure( | ||
storage_account=( | ||
CredentialProviderAzure._extract_adls_uri_storage_account(str(path)) | ||
), | ||
_verbose=verbose, | ||
) | ||
if _is_azure_cloud(scheme) | ||
else CredentialProviderGCP() | ||
if _is_gcp_cloud(scheme) | ||
else None | ||
|
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
Oops, something went wrong.
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.
Was this intended?