diff --git a/src/quantum/azext_quantum/_storage.py b/src/quantum/azext_quantum/_storage.py deleted file mode 100644 index c0ccf0804ef..00000000000 --- a/src/quantum/azext_quantum/_storage.py +++ /dev/null @@ -1,128 +0,0 @@ -# -------------------------------------------------------------------------------------------- -# Copyright (c) Microsoft Corporation. All rights reserved. -# Licensed under the MIT License. See License.txt in the project root for license information. -# -------------------------------------------------------------------------------------------- - -# This file is a reduced version of -# https://github.com/microsoft/azure-quantum-python/blob/main/azure-quantum/azure/quantum/storage.py -# -# It only contains the functions required to do inputData blob upload for job submission. -# Other cosmetic changes were made to appease the Azure CLI CI/CD checks. It was included -# in this repo so there would not be a direct dependency on azure-quantum-python. - -# Unused imports were removed to reduce Pylint style-rule violations. -import logging -from datetime import datetime, timedelta -from typing import Any -# This "from" statment was changed so there is no dependency on the azure.storage.blob PyPI package -from .vendored_sdks.azure_storage_blob import ( - BlobServiceClient, - ContainerClient, - BlobClient, - BlobSasPermissions, - ContentSettings, - generate_blob_sas, -) - -logger = logging.getLogger(__name__) - - -def create_container( - connection_string: str, container_name: str -) -> ContainerClient: - """ - Creates and initialize a container; returns the client needed to access it. - """ - blob_service_client = BlobServiceClient.from_connection_string( - connection_string - ) - # The Azure CLI PR check pipeline fails with the following format: - # logger.info( - # f'{"Initializing storage client for account:"}' - # + f"{blob_service_client.account_name}" - # ) - # This passes the style check: - logger.info("Initializing storage client for account: %s", - blob_service_client.account_name) - - container_client = blob_service_client.get_container_client(container_name) - create_container_using_client(container_client) - return container_client - - -def create_container_using_client(container_client: ContainerClient): - """ - Creates the container if it doesn't already exist. - """ - if not container_client.exists(): - logger.debug( - " - uploading to **new** container: %s", - container_client.container_name - ) - container_client.create_container() - - -def upload_blob( - container: ContainerClient, - blob_name: str, - content_type: str, - content_encoding: str, - data: Any, - return_sas_token: bool = True, -) -> str: - """ - Uploads the given data to a blob record. - If a blob with the given name already exist, it throws an error. - - Returns a uri with a SAS token to access the newly created blob. - """ - create_container_using_client(container) - # The Azure CLI PR check pipeline fails with the following format: - # logger.info( - # f"Uploading blob '{blob_name}'" - # + f"to container '{container.container_name}'" - # + f"on account: '{container.account_name}'" - # ) - # This passes the style check: - logger.info("Uploading blob %s to container %s on account %s", - blob_name, container.container_name, container.account_name) - - content_settings = ContentSettings( - content_type=content_type, content_encoding=content_encoding - ) - - blob = container.get_blob_client(blob_name) - - blob.upload_blob(data, content_settings=content_settings) - logger.debug(" - blob '%s' uploaded. generating sas token.", blob_name) - - if return_sas_token: - uri = get_blob_uri_with_sas_token(blob) - else: - uri = remove_sas_token(blob.url) - logger.debug(" - blob access url: '%s'.", uri) - - return uri - - -def get_blob_uri_with_sas_token(blob: BlobClient): - """Returns a URI for the given blob that contains a SAS Token""" - sas_token = generate_blob_sas( - blob.account_name, - blob.container_name, - blob.blob_name, - account_key=blob.credential.account_key, - permission=BlobSasPermissions(read=True), - expiry=datetime.utcnow() + timedelta(days=14), - ) - - return blob.url + "?" + sas_token - - -def remove_sas_token(sas_uri: str) -> str: - """Removes the SAS Token from the given URI if it contains one""" - index = sas_uri.find("?") - if index != -1: - sas_uri = sas_uri[0:index] - - return sas_uri diff --git a/src/quantum/azext_quantum/operations/job.py b/src/quantum/azext_quantum/operations/job.py index f9ce5ee7438..857c904007d 100644 --- a/src/quantum/azext_quantum/operations/job.py +++ b/src/quantum/azext_quantum/operations/job.py @@ -13,13 +13,13 @@ import uuid import knack.log -from azure.cli.command_modules.storage.operations.account import show_storage_account_connection_string from azure.cli.core.azclierror import (FileOperationError, AzureInternalError, InvalidArgumentValueError, AzureResponseError, RequiredArgumentMissingError) -from .._storage import create_container, upload_blob - +from ..vendored_sdks.azure_quantum_python.workspace import Workspace +from ..vendored_sdks.azure_quantum_python.storage import upload_blob +from ..vendored_sdks.azure_storage_blob import ContainerClient from .._client_factory import cf_jobs from .._list_helper import repack_response_json from .workspace import WorkspaceInfo @@ -324,15 +324,19 @@ def submit(cmd, resource_group_name, workspace_name, location, target_id, job_in raise RequiredArgumentMissingError("No storage account specified or linked with workspace.") storage = ws.properties.storage_account.split('/')[-1] job_id = str(uuid.uuid4()) - container_name = "quantum-job-" + job_id - connection_string_dict = show_storage_account_connection_string(cmd, resource_group_name, storage) - connection_string = connection_string_dict["connectionString"] - container_client = create_container(connection_string, container_name) blob_name = "inputData" + resource_id = "/subscriptions/" + ws_info.subscription + "/resourceGroups/" + ws_info.resource_group + "/providers/Microsoft.Quantum/Workspaces/" + ws_info.name + workspace = Workspace(resource_id=resource_id, location=location) + + knack_logger.warning("Getting Azure credential token...") + container_uri = workspace.get_container_uri(job_id=job_id) + container_client = ContainerClient.from_container_url(container_uri) + knack_logger.warning("Uploading input data...") try: - blob_uri = upload_blob(container_client, blob_name, content_type, content_encoding, blob_data, False) + blob_uri = upload_blob(container_client, blob_name, content_type, content_encoding, blob_data, return_sas_token=False) + logger.debug(" - blob uri: %s", blob_uri) except Exception as e: # Unexplained behavior: # QIR bitcode input and QIO (gzip) input data get UnicodeDecodeError on jobs run in tests using @@ -343,9 +347,6 @@ def submit(cmd, resource_group_name, workspace_name, location, target_id, job_in error_msg += f"\nReason: {e.reason}" raise AzureResponseError(error_msg) from e - start_of_blob_name = blob_uri.find(blob_name) - container_uri = blob_uri[0:start_of_blob_name - 1] - # Combine separate command-line parameters (like shots, target_capability, and entry_point) with job_params if job_params is None: job_params = {} diff --git a/src/quantum/azext_quantum/tests/latest/test_quantum_jobs.py b/src/quantum/azext_quantum/tests/latest/test_quantum_jobs.py index 7a6da689165..32b17c14e54 100644 --- a/src/quantum/azext_quantum/tests/latest/test_quantum_jobs.py +++ b/src/quantum/azext_quantum/tests/latest/test_quantum_jobs.py @@ -212,6 +212,26 @@ def test_submit(self): self.cmd(f"az quantum workspace create -g {test_resource_group} -w {test_workspace_temp} -l {test_location} -a {test_storage} -r {test_provider_sku_list} --skip-autoadd") self.cmd(f"az quantum workspace set -g {test_resource_group} -w {test_workspace_temp} -l {test_location}") + # Submit a job to Rigetti and look for SAS tokens in URIs in the output + results = self.cmd("az quantum job submit -t rigetti.sim.qvm --job-input-format rigetti.quil.v1 -t rigetti.sim.qvm --job-input-file src/quantum/azext_quantum/tests/latest/input_data/bell-state.quil --job-output-format rigetti.quil-results.v1 -o json").get_output_in_json() + self.assertIn("?sv=", results["containerUri"]) + self.assertIn("&st=", results["containerUri"]) + self.assertIn("&se=", results["containerUri"]) + self.assertIn("&sp=", results["containerUri"]) + self.assertIn("&sig=", results["containerUri"]) + + self.assertIn("?sv=", results["inputDataUri"]) + self.assertIn("&st=", results["inputDataUri"]) + self.assertIn("&se=", results["inputDataUri"]) + self.assertIn("&sp=", results["inputDataUri"]) + self.assertIn("&sig=", results["inputDataUri"]) + + self.assertIn("?sv=", results["outputDataUri"]) + self.assertIn("&st=", results["outputDataUri"]) + self.assertIn("&se=", results["outputDataUri"]) + self.assertIn("&sp=", results["outputDataUri"]) + self.assertIn("&sig=", results["outputDataUri"]) + # Run a Quil pass-through job on Rigetti results = self.cmd("az quantum run -t rigetti.sim.qvm --job-input-format rigetti.quil.v1 -t rigetti.sim.qvm --job-input-file src/quantum/azext_quantum/tests/latest/input_data/bell-state.quil --job-output-format rigetti.quil-results.v1 -o json").get_output_in_json() self.assertIn("ro", results) @@ -233,7 +253,6 @@ def test_submit(self): results = str(self.cmd("az quantum job list --skip 1 -o json").get_output_in_json()) self.assertIn("ionq", results) - self.assertTrue("rigetti" not in results) results = str(self.cmd("az quantum job list --orderby Target --skip 1 -o json").get_output_in_json()) self.assertIn("rigetti", results) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/__init__.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/__init__.py new file mode 100644 index 00000000000..f21e763c762 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/__init__.py @@ -0,0 +1,66 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Credentials for Azure SDK clients.""" + +from ._auth_record import AuthenticationRecord +from ._exceptions import AuthenticationRequiredError, CredentialUnavailableError +from ._constants import AzureAuthorityHosts, KnownAuthorities +from ._credentials import ( + AuthorizationCodeCredential, + AzureDeveloperCliCredential, + AzureCliCredential, + AzurePowerShellCredential, + CertificateCredential, + ChainedTokenCredential, + ClientAssertionCredential, + ClientSecretCredential, + DefaultAzureCredential, + DeviceCodeCredential, + EnvironmentCredential, + InteractiveBrowserCredential, + ManagedIdentityCredential, + OnBehalfOfCredential, + SharedTokenCacheCredential, + UsernamePasswordCredential, + VisualStudioCodeCredential, + WorkloadIdentityCredential, + AzurePipelinesCredential, +) +from ._persistent_cache import TokenCachePersistenceOptions +from ._bearer_token_provider import get_bearer_token_provider + + +__all__ = [ + "AuthenticationRecord", + "AuthenticationRequiredError", + "AuthorizationCodeCredential", + "AzureAuthorityHosts", + "AzureCliCredential", + "AzureDeveloperCliCredential", + "AzurePipelinesCredential", + "AzurePowerShellCredential", + "CertificateCredential", + "ChainedTokenCredential", + "ClientAssertionCredential", + "ClientSecretCredential", + "CredentialUnavailableError", + "DefaultAzureCredential", + "DeviceCodeCredential", + "EnvironmentCredential", + "InteractiveBrowserCredential", + "KnownAuthorities", + "OnBehalfOfCredential", + "ManagedIdentityCredential", + "SharedTokenCacheCredential", + "TokenCachePersistenceOptions", + "UsernamePasswordCredential", + "VisualStudioCodeCredential", + "WorkloadIdentityCredential", + "get_bearer_token_provider", +] + +from ._version import VERSION + +__version__ = VERSION diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_auth_record.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_auth_record.py new file mode 100644 index 00000000000..63b3625e116 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_auth_record.py @@ -0,0 +1,114 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import json + + +SUPPORTED_VERSIONS = {"1.0"} + + +class AuthenticationRecord: + """Non-secret account information for an authenticated user + + This class enables :class:`DeviceCodeCredential` and :class:`InteractiveBrowserCredential` to access + previously cached authentication data. Applications shouldn't construct instances of this class. They should + instead acquire one from a credential's **authenticate** method, such as + :func:`InteractiveBrowserCredential.authenticate`. See the user_authentication sample for more details. + + :param str tenant_id: The tenant the account should authenticate in. + :param str client_id: The client ID of the application which performed the original authentication. + :param str authority: The authority host used to authenticate the account. + :param str home_account_id: A unique identifier of the account. + :param str username: The user principal or service principal name of the account. + """ + + def __init__(self, tenant_id: str, client_id: str, authority: str, home_account_id: str, username: str) -> None: + self._authority = authority + self._client_id = client_id + self._home_account_id = home_account_id + self._tenant_id = tenant_id + self._username = username + + @property + def authority(self) -> str: + """The authority host used to authenticate the account. + + :rtype: str + """ + return self._authority + + @property + def client_id(self) -> str: + """The client ID of the application which performed the original authentication. + + :rtype: str + """ + return self._client_id + + @property + def home_account_id(self) -> str: + """A unique identifier of the account. + + :rtype: str + """ + return self._home_account_id + + @property + def tenant_id(self) -> str: + """The tenant the account should authenticate in. + + :rtype: str + """ + return self._tenant_id + + @property + def username(self) -> str: + """The user principal or service principal name of the account. + + :rtype: str + """ + return self._username + + @classmethod + def deserialize(cls, data: str) -> "AuthenticationRecord": + """Deserialize a record. + + :param str data: A serialized record. + :return: The deserialized record. + :rtype: ~azure.identity.AuthenticationRecord + """ + + deserialized = json.loads(data) + + version = deserialized.get("version") + if version not in SUPPORTED_VERSIONS: + raise ValueError( + 'Unexpected version "{}". This package supports these versions: {}'.format(version, SUPPORTED_VERSIONS) + ) + + return cls( + authority=deserialized["authority"], + client_id=deserialized["clientId"], + home_account_id=deserialized["homeAccountId"], + tenant_id=deserialized["tenantId"], + username=deserialized["username"], + ) + + def serialize(self) -> str: + """Serialize the record. + + :return: The serialized record. + :rtype: str + """ + + record = { + "authority": self._authority, + "clientId": self._client_id, + "homeAccountId": self._home_account_id, + "tenantId": self._tenant_id, + "username": self._username, + "version": "1.0", + } + + return json.dumps(record) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_bearer_token_provider.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_bearer_token_provider.py new file mode 100644 index 00000000000..3617f56eab3 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_bearer_token_provider.py @@ -0,0 +1,46 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Callable + +from azure.core.credentials import TokenProvider +from azure.core.pipeline.policies import BearerTokenCredentialPolicy +from azure.core.pipeline import PipelineRequest, PipelineContext +from azure.core.rest import HttpRequest + + +def _make_request() -> PipelineRequest[HttpRequest]: + return PipelineRequest(HttpRequest("CredentialWrapper", "https://fakeurl"), PipelineContext(None)) + + +def get_bearer_token_provider(credential: TokenProvider, *scopes: str) -> Callable[[], str]: + """Returns a callable that provides a bearer token. + + It can be used for instance to write code like: + + .. code-block:: python + + from azure.identity import DefaultAzureCredential, get_bearer_token_provider + + credential = DefaultAzureCredential() + bearer_token_provider = get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default") + + # Usage + request.headers["Authorization"] = "Bearer " + bearer_token_provider() + + :param credential: The credential used to authenticate the request. + :type credential: ~azure.core.credentials.TokenCredential + :param str scopes: The scopes required for the bearer token. + :rtype: callable + :return: A callable that returns a bearer token. + """ + + policy = BearerTokenCredentialPolicy(credential, *scopes) + + def wrapper() -> str: + request = _make_request() + policy.on_request(request) + return request.http_request.headers["Authorization"][len("Bearer ") :] + + return wrapper diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_constants.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_constants.py new file mode 100644 index 00000000000..92d56a7d340 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_constants.py @@ -0,0 +1,67 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import warnings + +DEVELOPER_SIGN_ON_CLIENT_ID = "04b07795-8ddb-461a-bbee-02f9e1bf7b46" +AZURE_VSCODE_CLIENT_ID = "aebc6443-996d-45c2-90f0-388ff96faa56" +VSCODE_CREDENTIALS_SECTION = "VS Code Azure" +DEFAULT_REFRESH_OFFSET = 300 +DEFAULT_TOKEN_REFRESH_RETRY_DELAY = 30 + +CACHE_NON_CAE_SUFFIX = ".nocae" # cspell:disable-line +CACHE_CAE_SUFFIX = ".cae" + + +class AzureAuthorityHostsMeta(type): + def __getattr__(cls, name): + if name == "AZURE_GERMANY": + warnings.warn( + "AZURE_GERMANY is deprecated. Microsoft Cloud Germany was closed on October 29th, 2021.", + DeprecationWarning, + stacklevel=2, + ) + return "login.microsoftonline.de" + raise AttributeError(f"{name} not found in {cls.__name__}") + + +class AzureAuthorityHosts(metaclass=AzureAuthorityHostsMeta): + AZURE_CHINA = "login.chinacloudapi.cn" + AZURE_GOVERNMENT = "login.microsoftonline.us" + AZURE_PUBLIC_CLOUD = "login.microsoftonline.com" + + +class KnownAuthorities(AzureAuthorityHosts): + """Alias of :class:`AzureAuthorityHosts`""" + + +class EnvironmentVariables: + AZURE_CLIENT_ID = "AZURE_CLIENT_ID" + AZURE_CLIENT_SECRET = "AZURE_CLIENT_SECRET" + AZURE_TENANT_ID = "AZURE_TENANT_ID" + CLIENT_SECRET_VARS = (AZURE_CLIENT_ID, AZURE_CLIENT_SECRET, AZURE_TENANT_ID) + + AZURE_CLIENT_CERTIFICATE_PATH = "AZURE_CLIENT_CERTIFICATE_PATH" + AZURE_CLIENT_CERTIFICATE_PASSWORD = "AZURE_CLIENT_CERTIFICATE_PASSWORD" + AZURE_CLIENT_SEND_CERTIFICATE_CHAIN = "AZURE_CLIENT_SEND_CERTIFICATE_CHAIN" + CERT_VARS = (AZURE_CLIENT_ID, AZURE_CLIENT_CERTIFICATE_PATH, AZURE_TENANT_ID) + + AZURE_USERNAME = "AZURE_USERNAME" + AZURE_PASSWORD = "AZURE_PASSWORD" + USERNAME_PASSWORD_VARS = (AZURE_CLIENT_ID, AZURE_USERNAME, AZURE_PASSWORD) + + AZURE_POD_IDENTITY_AUTHORITY_HOST = "AZURE_POD_IDENTITY_AUTHORITY_HOST" + IDENTITY_ENDPOINT = "IDENTITY_ENDPOINT" + IDENTITY_HEADER = "IDENTITY_HEADER" + IDENTITY_SERVER_THUMBPRINT = "IDENTITY_SERVER_THUMBPRINT" + IMDS_ENDPOINT = "IMDS_ENDPOINT" + MSI_ENDPOINT = "MSI_ENDPOINT" + MSI_SECRET = "MSI_SECRET" + + AZURE_AUTHORITY_HOST = "AZURE_AUTHORITY_HOST" + AZURE_IDENTITY_DISABLE_MULTITENANTAUTH = "AZURE_IDENTITY_DISABLE_MULTITENANTAUTH" + AZURE_REGIONAL_AUTHORITY_NAME = "AZURE_REGIONAL_AUTHORITY_NAME" + + AZURE_FEDERATED_TOKEN_FILE = "AZURE_FEDERATED_TOKEN_FILE" + WORKLOAD_IDENTITY_VARS = (AZURE_AUTHORITY_HOST, AZURE_TENANT_ID, AZURE_FEDERATED_TOKEN_FILE) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/__init__.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/__init__.py new file mode 100644 index 00000000000..c560459b5e6 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/__init__.py @@ -0,0 +1,47 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from .authorization_code import AuthorizationCodeCredential +from .azure_powershell import AzurePowerShellCredential +from .browser import InteractiveBrowserCredential +from .certificate import CertificateCredential +from .chained import ChainedTokenCredential +from .client_secret import ClientSecretCredential +from .default import DefaultAzureCredential +from .environment import EnvironmentCredential +from .managed_identity import ManagedIdentityCredential +from .on_behalf_of import OnBehalfOfCredential +from .shared_cache import SharedTokenCacheCredential +from .azd_cli import AzureDeveloperCliCredential +from .azure_cli import AzureCliCredential +from .device_code import DeviceCodeCredential +from .user_password import UsernamePasswordCredential +from .vscode import VisualStudioCodeCredential +from .client_assertion import ClientAssertionCredential +from .workload_identity import WorkloadIdentityCredential +from .azure_pipelines import AzurePipelinesCredential + + +__all__ = [ + "AuthorizationCodeCredential", + "AzureCliCredential", + "AzureDeveloperCliCredential", + "AzurePipelinesCredential", + "AzurePowerShellCredential", + "CertificateCredential", + "ChainedTokenCredential", + "ClientAssertionCredential", + "ClientSecretCredential", + "DefaultAzureCredential", + "DeviceCodeCredential", + "EnvironmentCredential", + "InteractiveBrowserCredential", + "ManagedIdentityCredential", + "OnBehalfOfCredential", + "SharedTokenCacheCredential", + "AzureCliCredential", + "UsernamePasswordCredential", + "WorkloadIdentityCredential", + "VisualStudioCodeCredential", +] diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/app_service.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/app_service.py new file mode 100644 index 00000000000..ff4531cb852 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/app_service.py @@ -0,0 +1,39 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import os +from typing import Optional, Dict, Any +from azure.core.pipeline.transport import HttpRequest + +from .._constants import EnvironmentVariables +from .._internal.msal_managed_identity_client import MsalManagedIdentityClient + + +class AppServiceCredential(MsalManagedIdentityClient): + def get_unavailable_message(self, desc: str = "") -> str: + return f"App Service managed identity configuration not found in environment. {desc}" + + +def _get_client_args(**kwargs: Any) -> Optional[Dict]: + identity_config = kwargs.pop("identity_config", None) or {} + + url = os.environ.get(EnvironmentVariables.IDENTITY_ENDPOINT) + secret = os.environ.get(EnvironmentVariables.IDENTITY_HEADER) + if not (url and secret): + # App Service managed identity isn't available in this environment + return None + + return dict( + kwargs, + identity_config=identity_config, + base_headers={"X-IDENTITY-HEADER": secret}, + request_factory=functools.partial(_get_request, url), + ) + + +def _get_request(url: str, scope: str, identity_config: Dict) -> HttpRequest: + request = HttpRequest("GET", url) + request.format_parameters(dict({"api-version": "2019-08-01", "resource": scope}, **identity_config)) + return request diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/application.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/application.py new file mode 100644 index 00000000000..81a06fd989d --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/application.py @@ -0,0 +1,119 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import Any, Optional, cast + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions, SupportsTokenInfo, TokenCredential +from .chained import ChainedTokenCredential +from .environment import EnvironmentCredential +from .managed_identity import ManagedIdentityCredential +from .._constants import EnvironmentVariables +from .._internal import get_default_authority, normalize_authority + +_LOGGER = logging.getLogger(__name__) + + +class AzureApplicationCredential(ChainedTokenCredential): + """A credential for Microsoft Entra applications. + + This credential is designed for applications deployed to Azure (:class:`~azure.identity.DefaultAzureCredential` is + better suited to local development). It authenticates service principals and managed identities. + + For service principal authentication, set these environment variables to identify a principal: + + - **AZURE_TENANT_ID**: ID of the service principal's tenant. Also called its "directory" ID. + - **AZURE_CLIENT_ID**: the service principal's client ID + + And one of these to authenticate that principal: + + - **AZURE_CLIENT_SECRET**: one of the service principal's client secrets + + **or** + + - **AZURE_CLIENT_CERTIFICATE_PATH**: path to a PEM-encoded certificate file including the private key. The + certificate must not be password-protected. + + See `Azure CLI documentation `_ + for more information about creating and managing service principals. + + When this environment configuration is incomplete, the credential will attempt to authenticate a managed identity. + See `Microsoft Entra ID documentation + `__ for an overview + of managed identities. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud, which is the default when no value is given for this keyword argument or + environment variable AZURE_AUTHORITY_HOST. :class:`~azure.identity.AzureAuthorityHosts` defines authorities for + other clouds. Authority configuration applies only to service principal authentication. + :keyword str managed_identity_client_id: The client ID of a user-assigned managed identity. Defaults to the value + of the environment variable AZURE_CLIENT_ID, if any. If not specified, a system-assigned identity will be used. + """ + + def __init__(self, **kwargs: Any) -> None: + authority = kwargs.pop("authority", None) + authority = normalize_authority(authority) if authority else get_default_authority() + managed_identity_client_id = kwargs.pop( + "managed_identity_client_id", os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + ) + super(AzureApplicationCredential, self).__init__( + EnvironmentCredential(authority=authority, **kwargs), + ManagedIdentityCredential(client_id=managed_identity_client_id, **kwargs), + ) + + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The exception has a + `message` attribute listing each authentication attempt and its error message. + """ + if self._successful_credential: + token = cast(TokenCredential, self._successful_credential).get_token( + *scopes, claims=claims, tenant_id=tenant_id, **kwargs + ) + _LOGGER.info( + "%s acquired a token from %s", self.__class__.__name__, self._successful_credential.__class__.__name__ + ) + return token + + return super(AzureApplicationCredential, self).get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The exception has a + `message` attribute listing each authentication attempt and its error message. + """ + if self._successful_credential: + token_info = cast(SupportsTokenInfo, self._successful_credential).get_token_info(*scopes, options=options) + _LOGGER.info( + "%s acquired a token from %s", self.__class__.__name__, self._successful_credential.__class__.__name__ + ) + return token_info + + return cast(SupportsTokenInfo, super()).get_token_info(*scopes, options=options) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/authorization_code.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/authorization_code.py new file mode 100644 index 00000000000..c98aa26c9a0 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/authorization_code.py @@ -0,0 +1,141 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Optional, Any + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from azure.core.exceptions import ClientAuthenticationError +from .._internal.aad_client import AadClient +from .._internal.get_token_mixin import GetTokenMixin + + +class AuthorizationCodeCredential(GetTokenMixin): + """Authenticates by redeeming an authorization code previously obtained from Microsoft Entra ID. + + See `Microsoft Entra ID documentation + `__ for more information + about the authentication flow. + + :param str tenant_id: ID of the application's Microsoft Entra tenant. Also called its "directory" ID. + :param str client_id: The application's client ID + :param str authorization_code: The authorization code from the user's log-in + :param str redirect_uri: The application's redirect URI. Must match the URI used to request the authorization code. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword str client_secret: One of the application's client secrets. Required only for web apps and web APIs. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_authorization_code_credential] + :end-before: [END create_authorization_code_credential] + :language: python + :dedent: 4 + :caption: Create an AuthorizationCodeCredential. + """ + + def __init__( + self, tenant_id: str, client_id: str, authorization_code: str, redirect_uri: str, **kwargs: Any + ) -> None: + self._authorization_code: Optional[str] = authorization_code + self._client_id = client_id + self._client_secret = kwargs.pop("client_secret", None) + self._client = kwargs.pop("client", None) or AadClient(tenant_id, client_id, **kwargs) + self._redirect_uri = redirect_uri + super(AuthorizationCodeCredential, self).__init__() + + def __enter__(self) -> "AuthorizationCodeCredential": + self._client.__enter__() + return self + + def __exit__(self, *args: Any) -> None: + self._client.__exit__(*args) + + def close(self) -> None: + """Close the credential's transport session.""" + self.__exit__() + + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + The first time this method is called, the credential will redeem its authorization code. On subsequent calls + the credential will return a cached access token or redeem a refresh token, if it acquired a refresh token upon + redeeming the authorization code. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. Any error response from Microsoft Entra ID is available as the error's + ``response`` attribute. + """ + # pylint:disable=useless-super-delegation + return super(AuthorizationCodeCredential, self).get_token( + *scopes, claims=claims, tenant_id=tenant_id, client_secret=self._client_secret, **kwargs + ) + + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + The first time this method is called, the credential will redeem its authorization code. On subsequent calls + the credential will return a cached access token or redeem a refresh token, if it acquired a refresh token upon + redeeming the authorization code. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. Any error response from Microsoft Entra ID is available as the error's + ``response`` attribute. + """ + return super()._get_token_base( + *scopes, options=options, client_secret=self._client_secret, base_method_name="get_token_info" + ) + + def _acquire_token_silently(self, *scopes: str, **kwargs) -> Optional[AccessTokenInfo]: + return self._client.get_cached_access_token(scopes, **kwargs) + + def _request_token(self, *scopes: str, **kwargs) -> AccessTokenInfo: + if self._authorization_code: + token = self._client.obtain_token_by_authorization_code( + scopes=scopes, code=self._authorization_code, redirect_uri=self._redirect_uri, **kwargs + ) + self._authorization_code = None # auth codes are single-use + return token + + token = None + for refresh_token in self._client.get_cached_refresh_tokens(scopes): + if "secret" in refresh_token: + token = self._client.obtain_token_by_refresh_token(scopes, refresh_token["secret"], **kwargs) + if token: + break + + if not token: + raise ClientAuthenticationError( + message="No authorization code, cached access token, or refresh token available." + ) + + return token diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azd_cli.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azd_cli.py new file mode 100644 index 00000000000..319569482ab --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azd_cli.py @@ -0,0 +1,284 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ + +from datetime import datetime +import json +import os +import re +import shutil +import subprocess +import sys +from typing import Any, Dict, List, Optional + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from azure.core.exceptions import ClientAuthenticationError + +from .. import CredentialUnavailableError +from .._internal import resolve_tenant, within_dac, validate_tenant_id, validate_scope +from .._internal.decorators import log_get_token + +CLI_NOT_FOUND = ( + "Azure Developer CLI could not be found. " + "Please visit https://aka.ms/azure-dev for installation instructions and then," + "once installed, authenticate to your Azure account using 'azd auth login'." +) +COMMAND_LINE = "azd auth token --output json --scope {}" +EXECUTABLE_NAME = "azd" +NOT_LOGGED_IN = "Please run 'azd auth login' from a command prompt to authenticate before using this credential." + + +class AzureDeveloperCliCredential: + """Authenticates by requesting a token from the Azure Developer CLI. + + Azure Developer CLI is a command-line interface tool that allows developers to create, manage, and deploy + resources in Azure. It's built on top of the Azure CLI and provides additional functionality specific + to Azure developers. It allows users to authenticate as a user and/or a service principal against + `Microsoft Entra ID <"https://learn.microsoft.com/entra/fundamentals/">`__. + The AzureDeveloperCliCredential authenticates in a development environment and acquires a token on behalf of + the logged-in user or service principal in Azure Developer CLI. It acts as the Azure Developer CLI logged-in user + or service principal and executes an Azure CLI command underneath to authenticate the application against + Microsoft Entra ID. + + To use this credential, the developer needs to authenticate locally in Azure Developer CLI using one of the + commands below: + + * Run "azd auth login" in Azure Developer CLI to authenticate interactively as a user. + * Run "azd auth login --client-id 'client_id' --client-secret 'client_secret' --tenant-id 'tenant_id'" + to authenticate as a service principal. + + You may need to repeat this process after a certain time period, depending on the refresh token validity in your + organization. Generally, the refresh token validity period is a few weeks to a few months. + AzureDeveloperCliCredential will prompt you to sign in again. + + :keyword str tenant_id: Optional tenant to include in the token request. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + :keyword int process_timeout: Seconds to wait for the Azure Developer CLI process to respond. Defaults + to 10 seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START azure_developer_cli_credential] + :end-before: [END azure_developer_cli_credential] + :language: python + :dedent: 4 + :caption: Create an AzureDeveloperCliCredential. + """ + + def __init__( + self, + *, + tenant_id: str = "", + additionally_allowed_tenants: Optional[List[str]] = None, + process_timeout: int = 10, + ) -> None: + if tenant_id: + validate_tenant_id(tenant_id) + self.tenant_id = tenant_id + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + self._process_timeout = process_timeout + + def __enter__(self) -> "AzureDeveloperCliCredential": + return self + + def __exit__(self, *args: Any) -> None: + pass + + def close(self) -> None: + """Calling this method is unnecessary.""" + + @log_get_token + def get_token( + self, + *scopes: str, + claims: Optional[str] = None, # pylint:disable=unused-argument + tenant_id: Optional[str] = None, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. Applications calling this method directly must + also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke + the Azure Developer CLI. + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked + the Azure Developer CLI but didn't receive an access token. + """ + options: TokenRequestOptions = {} + if tenant_id: + options["tenant_id"] = tenant_id + + token_info = self._get_token_base(*scopes, options=options, **kwargs) + return AccessToken(token_info.token, token_info.expires_on) + + @log_get_token + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. Applications calling this method + directly must also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke + the Azure Developer CLI. + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked + the Azure Developer CLI but didn't receive an access token. + """ + return self._get_token_base(*scopes, options=options) + + def _get_token_base( + self, *scopes: str, options: Optional[TokenRequestOptions] = None, **kwargs: Any + ) -> AccessTokenInfo: + if not scopes: + raise ValueError("Missing scope in request. \n") + + tenant_id = options.get("tenant_id") if options else None + if tenant_id: + validate_tenant_id(tenant_id) + for scope in scopes: + validate_scope(scope) + + commandString = " --scope ".join(scopes) + command = COMMAND_LINE.format(commandString) + tenant = resolve_tenant( + default_tenant=self.tenant_id, + tenant_id=tenant_id, + additionally_allowed_tenants=self._additionally_allowed_tenants, + **kwargs, + ) + if tenant: + command += " --tenant-id " + tenant + output = _run_command(command, self._process_timeout) + + token = parse_token(output) + if not token: + sanitized_output = sanitize_output(output) + message = ( + f"Unexpected output from Azure Developer CLI: '{sanitized_output}'. \n" + f"To mitigate this issue, please refer to the troubleshooting guidelines here at " + f"https://aka.ms/azsdk/python/identity/azdevclicredential/troubleshoot." + ) + if within_dac.get(): + raise CredentialUnavailableError(message=message) + raise ClientAuthenticationError(message=message) + + return token + + +def parse_token(output: str) -> Optional[AccessTokenInfo]: + """Parse to an AccessToken. + + In particular, convert the "expiresOn" value to epoch seconds. This value is a naive local datetime as returned by + datetime.fromtimestamp. + + :param str output: The output of the Azure Developer CLI command. + :return: An AccessToken or None if the output isn't valid. + :rtype: azure.core.credentials.AccessToken or None + """ + try: + token = json.loads(output) + dt = datetime.strptime(token["expiresOn"], "%Y-%m-%dT%H:%M:%SZ") + expires_on = dt.timestamp() + + return AccessTokenInfo(token["token"], int(expires_on)) + except (KeyError, ValueError): + return None + + +def get_safe_working_dir() -> str: + """Invoke 'azd' from a directory controlled by the OS, not the executing program's directory. + + :return: The path to the directory. + :rtype: str + :raises ~azure.identity.CredentialUnavailableError: the SYSTEMROOT environment variable is not set. + """ + + if sys.platform.startswith("win"): + path = os.environ.get("SYSTEMROOT") + if not path: + raise CredentialUnavailableError( + message="Azure Developer CLI credential" + " expects a 'SystemRoot' environment variable" + ) + return path + + return "/bin" + + +def sanitize_output(output: str) -> str: + """Redact tokens from CLI output to prevent error messages revealing them. + + :param str output: The output of the Azure Developer CLI command. + :return: The output with tokens redacted. + :rtype: str + """ + return re.sub(r"\"token\": \"(.*?)(\"|$)", "****", output) + + +def _run_command(command: str, timeout: int) -> str: + # Ensure executable exists in PATH first. This avoids a subprocess call that would fail anyway. + if shutil.which(EXECUTABLE_NAME) is None: + raise CredentialUnavailableError(message=CLI_NOT_FOUND) + + if sys.platform.startswith("win"): + args = ["cmd", "/c", command] + else: + args = ["/bin/sh", "-c", command] + try: + working_directory = get_safe_working_dir() + + kwargs: Dict[str, Any] = { + "stderr": subprocess.PIPE, + "stdin": subprocess.DEVNULL, + "cwd": working_directory, + "universal_newlines": True, + "env": dict(os.environ, NO_COLOR="true"), + "timeout": timeout, + } + + return subprocess.check_output(args, **kwargs) + except subprocess.CalledProcessError as ex: + # non-zero return from shell + # Fallback check in case the executable is not found while executing subprocess. + if ex.returncode == 127 or ex.stderr.startswith("'azd' is not recognized"): + raise CredentialUnavailableError(message=CLI_NOT_FOUND) from ex + if "not logged in, run `azd auth login` to login" in ex.stderr and "AADSTS" not in ex.stderr: + raise CredentialUnavailableError(message=NOT_LOGGED_IN) from ex + + # return code is from the CLI -> propagate its output + if ex.stderr: + message = sanitize_output(ex.stderr) + else: + message = "Failed to invoke Azure Developer CLI" + if within_dac.get(): + raise CredentialUnavailableError(message=message) from ex + raise ClientAuthenticationError(message=message) from ex + except OSError as ex: + # failed to execute 'cmd' or '/bin/sh' + error = CredentialUnavailableError(message="Failed to execute '{}'".format(args[0])) + raise error from ex + except Exception as ex: # pylint:disable=broad-except + # could be a timeout, for example + error = CredentialUnavailableError(message="Failed to invoke the Azure Developer CLI") + raise error from ex diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azure_arc.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azure_arc.py new file mode 100644 index 00000000000..9c345e9efbf --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azure_arc.py @@ -0,0 +1,123 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +import sys +from typing import Dict + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.pipeline.transport import HttpRequest +from azure.core.pipeline.policies import HTTPPolicy +from azure.core.pipeline import PipelineRequest, PipelineResponse + +from .._internal.msal_managed_identity_client import MsalManagedIdentityClient + + +class AzureArcCredential(MsalManagedIdentityClient): + def get_unavailable_message(self, desc: str = "") -> str: + return f"Azure Arc managed identity configuration not found in environment. {desc}" + + +def _get_request(url: str, scope: str, identity_config: Dict) -> HttpRequest: + if identity_config: + raise ClientAuthenticationError( + message="User assigned managed identities are not supported by Azure Arc. To authenticate with the system " + "assigned identity omit the client id when constructing the credential, and if authenticating with " + "DefaultAzureCredential ensure the AZURE_CLIENT_ID environment variable is not set." + ) + + request = HttpRequest("GET", url) + request.format_parameters(dict({"api-version": "2020-06-01", "resource": scope}, **identity_config)) + return request + + +def _get_secret_key(response: PipelineResponse) -> str: + # expecting header containing path to secret key file + header = response.http_response.headers.get("WWW-Authenticate") + if not header: + raise ClientAuthenticationError(message="Did not receive a value from WWW-Authenticate header") + + # expecting header with structure like 'Basic realm=' + try: + key_file = header.split("=")[1] + except IndexError as ex: + raise ClientAuthenticationError( + message="Did not receive a correct value from WWW-Authenticate header: {}".format(header) + ) from ex + + try: + _validate_key_file(key_file) + except ValueError as ex: + raise ClientAuthenticationError(message="The key file path is invalid: {}".format(ex)) from ex + + with open(key_file, "r", encoding="utf-8") as file: + try: + return file.read() + except Exception as error: # pylint:disable=broad-except + # user is expected to have obtained read permission prior to this being called + raise ClientAuthenticationError( + message="Could not read file {} contents: {}".format(key_file, error) + ) from error + + +def _get_key_file_path() -> str: + """Returns the expected path for the Azure Arc MSI key file based on the current platform. + + Only Linux and Windows are supported. + + :return: The expected path. + :rtype: str + :raises ValueError: If the current platform is not supported. + """ + if sys.platform.startswith("linux"): + return "/var/opt/azcmagent/tokens" + if sys.platform.startswith("win"): + program_data_path = os.environ.get("PROGRAMDATA") + if not program_data_path: + raise ValueError("PROGRAMDATA environment variable is not set or is empty.") + return os.path.join(f"{program_data_path}", "AzureConnectedMachineAgent", "Tokens") + raise ValueError(f"Azure Arc MSI is not supported on this platform {sys.platform}") + + +def _validate_key_file(file_path: str) -> None: + """Validates that a given Azure Arc MSI file path is valid for use. + + A valid file will: + 1. Be in the expected path for the current platform. + 2. Have a `.key` extension. + 3. Be at most 4096 bytes in size. + + :param str file_path: The path to the key file. + :raises ClientAuthenticationError: If the file path is invalid. + """ + if not file_path: + raise ValueError("The file path must not be empty.") + + if not os.path.exists(file_path): + raise ValueError(f"The file path does not exist: {file_path}") + + expected_directory = _get_key_file_path() + if not os.path.dirname(file_path) == expected_directory: + raise ValueError(f"Unexpected file path from HIMDS service: {file_path}") + + if not file_path.endswith(".key"): + raise ValueError("The file path must have a '.key' extension.") + + if os.path.getsize(file_path) > 4096: + raise ValueError("The file size must be less than or equal to 4096 bytes.") + + +class ArcChallengeAuthPolicy(HTTPPolicy): + """Policy for handling Azure Arc's challenge authentication""" + + def send(self, request: PipelineRequest) -> PipelineResponse: + request.http_request.headers["Metadata"] = "true" + response = self.next.send(request) + + if response.http_response.status_code == 401: + secret_key = _get_secret_key(response) + request.http_request.headers["Authorization"] = "Basic {}".format(secret_key) + response = self.next.send(request) + + return response diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azure_cli.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azure_cli.py new file mode 100644 index 00000000000..b536581d07f --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azure_cli.py @@ -0,0 +1,275 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from datetime import datetime +import json +import os +import re +import shutil +import subprocess +import sys +from typing import List, Optional, Any, Dict + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from azure.core.exceptions import ClientAuthenticationError + +from .. import CredentialUnavailableError +from .._internal import ( + _scopes_to_resource, + resolve_tenant, + within_dac, + validate_tenant_id, + validate_scope, + validate_subscription, +) +from .._internal.decorators import log_get_token + + +CLI_NOT_FOUND = "Azure CLI not found on path" +COMMAND_LINE = "az account get-access-token --output json --resource {}" +EXECUTABLE_NAME = "az" +NOT_LOGGED_IN = "Please run 'az login' to set up an account" + + +class AzureCliCredential: + """Authenticates by requesting a token from the Azure CLI. + + This requires previously logging in to Azure via "az login", and will use the CLI's currently logged in identity. + + :keyword str tenant_id: Optional tenant to include in the token request. + :keyword str subscription: The name or ID of a subscription. Set this to acquire tokens for an account other + than the Azure CLI's current account. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + :keyword int process_timeout: Seconds to wait for the Azure CLI process to respond. Defaults to 10 seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_azure_cli_credential] + :end-before: [END create_azure_cli_credential] + :language: python + :dedent: 4 + :caption: Create an AzureCliCredential. + """ + + def __init__( + self, + *, + tenant_id: str = "", + subscription: Optional[str] = None, + additionally_allowed_tenants: Optional[List[str]] = None, + process_timeout: int = 10, + ) -> None: + if tenant_id: + validate_tenant_id(tenant_id) + if subscription: + validate_subscription(subscription) + + self.tenant_id = tenant_id + self.subscription = subscription + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + self._process_timeout = process_timeout + + def __enter__(self) -> "AzureCliCredential": + return self + + def __exit__(self, *args: Any) -> None: + pass + + def close(self) -> None: + """Calling this method is unnecessary.""" + + @log_get_token + def get_token( + self, + *scopes: str, + claims: Optional[str] = None, # pylint:disable=unused-argument + tenant_id: Optional[str] = None, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. Applications calling this method directly must + also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke the Azure CLI. + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked the Azure CLI but didn't + receive an access token. + """ + + options: TokenRequestOptions = {} + if tenant_id: + options["tenant_id"] = tenant_id + + token_info = self._get_token_base(*scopes, options=options, **kwargs) + return AccessToken(token_info.token, token_info.expires_on) + + @log_get_token + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. Applications calling this method + directly must also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scopes for the access token. This credential allows only one scope per request. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke the Azure CLI. + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked the Azure CLI but didn't + receive an access token. + """ + return self._get_token_base(*scopes, options=options) + + def _get_token_base( + self, *scopes: str, options: Optional[TokenRequestOptions] = None, **kwargs: Any + ) -> AccessTokenInfo: + + tenant_id = options.get("tenant_id") if options else None + if tenant_id: + validate_tenant_id(tenant_id) + for scope in scopes: + validate_scope(scope) + + resource = _scopes_to_resource(*scopes) + command = COMMAND_LINE.format(resource) + tenant = resolve_tenant( + default_tenant=self.tenant_id, + tenant_id=tenant_id, + additionally_allowed_tenants=self._additionally_allowed_tenants, + **kwargs, + ) + if tenant: + command += " --tenant " + tenant + + if self.subscription: + command += f' --subscription "{self.subscription}"' + output = _run_command(command, self._process_timeout) + + token = parse_token(output) + if not token: + sanitized_output = sanitize_output(output) + message = ( + f"Unexpected output from Azure CLI: '{sanitized_output}'. \n" + f"To mitigate this issue, please refer to the troubleshooting guidelines here at " + f"https://aka.ms/azsdk/python/identity/azclicredential/troubleshoot." + ) + if within_dac.get(): + raise CredentialUnavailableError(message=message) + raise ClientAuthenticationError(message=message) + + return token + + +def parse_token(output) -> Optional[AccessTokenInfo]: + """Parse output of 'az account get-access-token' to an AccessToken. + + In particular, convert the "expiresOn" value to epoch seconds. This value is a naive local datetime as returned by + datetime.fromtimestamp. + + :param str output: Output of 'az' command. + :return: An AccessToken or None if the output isn't valid. + :rtype: azure.core.credentials.AccessToken or None + """ + try: + token = json.loads(output) + + # Use "expires_on" if it's present, otherwise use "expiresOn". + if "expires_on" in token: + return AccessTokenInfo(token["accessToken"], int(token["expires_on"])) + + dt = datetime.strptime(token["expiresOn"], "%Y-%m-%d %H:%M:%S.%f") + expires_on = dt.timestamp() + return AccessTokenInfo(token["accessToken"], int(expires_on)) + except (KeyError, ValueError): + return None + + +def get_safe_working_dir() -> str: + """Invoke 'az' from a directory controlled by the OS, not the executing program's directory. + + :return: The path to the directory. + :rtype: str + """ + + if sys.platform.startswith("win"): + path = os.environ.get("SYSTEMROOT") + if not path: + raise CredentialUnavailableError(message="Environment variable 'SYSTEMROOT' has no value") + return path + + return "/bin" + + +def sanitize_output(output: str) -> str: + """Redact access tokens from CLI output to prevent error messages revealing them. + + :param str output: The output of the Azure CLI. + :return: The output with access tokens redacted. + :rtype: str + """ + return re.sub(r"\"accessToken\": \"(.*?)(\"|$)", "****", output) + + +def _run_command(command: str, timeout: int) -> str: + # Ensure executable exists in PATH first. This avoids a subprocess call that would fail anyway. + if shutil.which(EXECUTABLE_NAME) is None: + raise CredentialUnavailableError(message=CLI_NOT_FOUND) + + if sys.platform.startswith("win"): + args = ["cmd", "/c", command] + else: + args = ["/bin/sh", "-c", command] + try: + working_directory = get_safe_working_dir() + + kwargs: Dict[str, Any] = { + "stderr": subprocess.PIPE, + "stdin": subprocess.DEVNULL, + "cwd": working_directory, + "universal_newlines": True, + "timeout": timeout, + "env": dict(os.environ, AZURE_CORE_NO_COLOR="true"), + } + return subprocess.check_output(args, **kwargs) + except subprocess.CalledProcessError as ex: + # non-zero return from shell + # Fallback check in case the executable is not found while executing subprocess. + if ex.returncode == 127 or ex.stderr.startswith("'az' is not recognized"): + raise CredentialUnavailableError(message=CLI_NOT_FOUND) from ex + if ("az login" in ex.stderr or "az account set" in ex.stderr) and "AADSTS" not in ex.stderr: + raise CredentialUnavailableError(message=NOT_LOGGED_IN) from ex + + # return code is from the CLI -> propagate its output + if ex.stderr: + message = sanitize_output(ex.stderr) + else: + message = "Failed to invoke Azure CLI" + if within_dac.get(): + raise CredentialUnavailableError(message=message) from ex + raise ClientAuthenticationError(message=message) from ex + except OSError as ex: + # failed to execute 'cmd' or '/bin/sh' + error = CredentialUnavailableError(message="Failed to execute '{}'".format(args[0])) + raise error from ex + except Exception as ex: # pylint:disable=broad-except + # could be a timeout, for example + error = CredentialUnavailableError(message="Failed to invoke the Azure CLI") + raise error from ex diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azure_ml.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azure_ml.py new file mode 100644 index 00000000000..bed313195c2 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azure_ml.py @@ -0,0 +1,80 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import os +from typing import Optional, Dict + +from azure.core.pipeline.transport import HttpRequest + +from .._constants import EnvironmentVariables +from .._internal.msal_managed_identity_client import MsalManagedIdentityClient + + +class AzureMLCredential(MsalManagedIdentityClient): + def get_unavailable_message(self, desc: str = "") -> str: + return f"Azure ML managed identity configuration not found in environment. {desc}" + + +def _get_client_args(**kwargs) -> Optional[Dict]: + identity_config = kwargs.pop("identity_config", None) or {} + + url = os.environ.get(EnvironmentVariables.MSI_ENDPOINT) + secret = os.environ.get(EnvironmentVariables.MSI_SECRET) + if not (url and secret): + # Azure ML managed identity isn't available in this environment + return None + + if kwargs.get("client_id"): + identity_config["clientid"] = kwargs.pop("client_id") + + return dict( + kwargs, + _content_callback=_parse_expires_on, + identity_config=identity_config, + base_headers={"secret": secret}, + request_factory=functools.partial(_get_request, url), + ) + + +def _get_request(url: str, scope: str, identity_config: Dict) -> HttpRequest: + request = HttpRequest("GET", url) + request.format_parameters(dict({"api-version": "2017-09-01", "resource": scope}, **identity_config)) + return request + + +def _parse_expires_on(content: Dict) -> None: + """Parse an App Service MSI version 2017-09-01 expires_on value to epoch seconds. + + This version of the API returns expires_on as a UTC datetime string rather than epoch seconds. The string's + format depends on the OS. Responses on Windows include AM/PM, for example "1/16/2020 5:24:12 AM +00:00". + Responses on Linux do not, for example "06/20/2019 02:57:58 +00:00". + + :param dict content: a deserialized response from an App Service MSI. + :raises ValueError: ``expires_on`` didn't match an expected format + """ + + # Azure ML sets the same environment variables as App Service but returns expires_on as an integer. + # That means we could have an Azure ML response here, so let's first try to parse expires_on as an int. + try: + content["expires_on"] = int(content["expires_on"]) + return + except ValueError: + pass + + import calendar + import time + + expires_on = content["expires_on"] + if expires_on.endswith(" +00:00"): + date_string = expires_on[: -len(" +00:00")] + for format_string in ("%m/%d/%Y %H:%M:%S", "%m/%d/%Y %I:%M:%S %p"): # (Linux, Windows) + try: + t = time.strptime(date_string, format_string) + content["expires_on"] = calendar.timegm(t) + return + except ValueError: + pass + + raise ValueError("'{}' doesn't match the expected format".format(expires_on)) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azure_pipelines.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azure_pipelines.py new file mode 100644 index 00000000000..3501f626ae6 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azure_pipelines.py @@ -0,0 +1,176 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +# cspell:ignore oidcrequesturi +import os +from typing import Any, Optional + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from azure.core.rest import HttpRequest, HttpResponse + +from .client_assertion import ClientAssertionCredential +from .. import CredentialUnavailableError +from .._internal import validate_tenant_id +from .._internal.pipeline import build_pipeline + + +SYSTEM_OIDCREQUESTURI = "SYSTEM_OIDCREQUESTURI" +OIDC_API_VERSION = "7.1" +TROUBLESHOOTING_GUIDE = "https://aka.ms/azsdk/python/identity/azurepipelinescredential/troubleshoot" + + +def build_oidc_request(service_connection_id: str, access_token: str) -> HttpRequest: + base_uri = os.environ[SYSTEM_OIDCREQUESTURI].rstrip("/") + url = f"{base_uri}?api-version={OIDC_API_VERSION}&serviceConnectionId={service_connection_id}" + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {access_token}", + # Prevents the service from responding with a redirect HTTP status code (useful for automation). + "X-TFS-FedAuthRedirect": "Suppress", + } + return HttpRequest("POST", url, headers=headers) + + +def validate_env_vars(): + if SYSTEM_OIDCREQUESTURI not in os.environ: + raise CredentialUnavailableError( + message=f"Missing value for the {SYSTEM_OIDCREQUESTURI} environment variable. " + f"AzurePipelinesCredential is intended for use in Azure Pipelines where the " + f"{SYSTEM_OIDCREQUESTURI} environment variable is set. Please refer to the " + f"troubleshooting guide at {TROUBLESHOOTING_GUIDE}." + ) + + +class AzurePipelinesCredential: + """Authenticates using Microsoft Entra Workload ID in Azure Pipelines. + + This credential enables authentication in Azure Pipelines using workload identity federation for Azure service + connections. + + :keyword str tenant_id: The tenant ID for the service connection. Required. + :keyword str client_id: The client ID for the service connection. Required. + :keyword str service_connection_id: The service connection ID for the service connection associated with the + pipeline. From the service connection's configuration page URL in the Azure DevOps web portal, the ID + is the value of the "resourceId" query parameter. Required. + :keyword str system_access_token: The pipeline's System.AccessToken value. It is recommended to assign the value + of System.AccessToken to a secure variable in the Azure Pipelines environment. See + https://learn.microsoft.com/azure/devops/pipelines/build/variables#systemaccesstoken for more info. Required. + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_azure_pipelines_credential] + :end-before: [END create_azure_pipelines_credential] + :language: python + :dedent: 4 + :caption: Create an AzurePipelinesCredential. + """ + + def __init__( + self, + *, + tenant_id: str, + client_id: str, + service_connection_id: str, + system_access_token: str, + **kwargs: Any, + ) -> None: + + if not system_access_token or not tenant_id or not client_id or not service_connection_id: + raise ValueError( + "'tenant_id', 'client_id', 'service_connection_id', and 'system_access_token' must be passed in as " + f"keyword arguments. Please refer to the troubleshooting guide at {TROUBLESHOOTING_GUIDE}." + ) + validate_tenant_id(tenant_id) + self._system_access_token = system_access_token + self._service_connection_id = service_connection_id + self._client_assertion_credential = ClientAssertionCredential( + tenant_id=tenant_id, client_id=client_id, func=self._get_oidc_token, **kwargs + ) + self._pipeline = build_pipeline(**kwargs) + + def get_token( + self, + *scopes: str, + claims: Optional[str] = None, + tenant_id: Optional[str] = None, + enable_cae: bool = False, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested + token. Defaults to False. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks + required data, state, or platform support + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + validate_env_vars() + return self._client_assertion_credential.get_token( + *scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs + ) + + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scope for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + validate_env_vars() + return self._client_assertion_credential.get_token_info(*scopes, options=options) + + def _get_oidc_token(self) -> str: + request = build_oidc_request(self._service_connection_id, self._system_access_token) + response = self._pipeline.run(request, retry_on_methods=[request.method]) + http_response: HttpResponse = response.http_response + if http_response.status_code not in [200]: + raise ClientAuthenticationError( + message="Unexpected response from OIDC token endpoint.", response=http_response + ) + json_response = http_response.json() + if "oidcToken" not in json_response: + raise ClientAuthenticationError(message="OIDC token not found in response.") + return json_response["oidcToken"] + + def __enter__(self): + self._client_assertion_credential.__enter__() + self._pipeline.__enter__() + return self + + def __exit__(self, *args): + self._client_assertion_credential.__exit__(*args) + self._pipeline.__exit__(*args) + + def close(self) -> None: + """Close the credential's transport session.""" + self.__exit__() diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azure_powershell.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azure_powershell.py new file mode 100644 index 00000000000..92dd0432bce --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/azure_powershell.py @@ -0,0 +1,265 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import base64 +import logging +import subprocess +import sys +from typing import Any, List, Tuple, Optional + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from azure.core.exceptions import ClientAuthenticationError + +from .azure_cli import get_safe_working_dir +from .. import CredentialUnavailableError +from .._internal import _scopes_to_resource, resolve_tenant, within_dac, validate_tenant_id, validate_scope +from .._internal.decorators import log_get_token + + +_LOGGER = logging.getLogger(__name__) + +AZ_ACCOUNT_NOT_INSTALLED = "Az.Account module >= 2.2.0 is not installed" +BLOCKED_BY_EXECUTION_POLICY = "Execution policy prevented invoking Azure PowerShell" +NO_AZ_ACCOUNT_MODULE = "NO_AZ_ACCOUNT_MODULE" +POWERSHELL_NOT_INSTALLED = "PowerShell is not installed" +RUN_CONNECT_AZ_ACCOUNT = 'Please run "Connect-AzAccount" to set up account' +SCRIPT = """$ErrorActionPreference = 'Stop' +[version]$minimumVersion = '2.2.0' + +$m = Import-Module Az.Accounts -MinimumVersion $minimumVersion -PassThru -ErrorAction SilentlyContinue + +if (! $m) {{ + Write-Output {} + exit +}} + +$params = @{{ 'ResourceUrl' = '{}'; 'WarningAction' = 'Ignore' }} + +$tenantId = '{}' +if ($tenantId.Length -gt 0) {{ + $params['TenantId'] = $tenantId +}} + +$useSecureString = $m.Version -ge [version]'2.17.0' +if ($useSecureString) {{ + $params['AsSecureString'] = $true +}} + +$token = Get-AzAccessToken @params +$tokenValue = $token.Token +if ($useSecureString) {{ + $tokenValue = $tokenValue | ConvertFrom-SecureString -AsPlainText +}} +Write-Output "`nazsdk%$($tokenValue)%$($token.ExpiresOn.ToUnixTimeSeconds())`n" +""" + + +class AzurePowerShellCredential: + """Authenticates by requesting a token from Azure PowerShell. + + This requires previously logging in to Azure via "Connect-AzAccount", and will use the currently logged in identity. + + :keyword str tenant_id: Optional tenant to include in the token request. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + :keyword int process_timeout: Seconds to wait for the Azure PowerShell process to respond. Defaults to 10 seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_azure_power_shell_credential] + :end-before: [END create_azure_power_shell_credential] + :language: python + :dedent: 4 + :caption: Create an AzurePowerShellCredential. + """ + + def __init__( + self, + *, + tenant_id: str = "", + additionally_allowed_tenants: Optional[List[str]] = None, + process_timeout: int = 10, + ) -> None: + if tenant_id: + validate_tenant_id(tenant_id) + self.tenant_id = tenant_id + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + self._process_timeout = process_timeout + + def __enter__(self) -> "AzurePowerShellCredential": + return self + + def __exit__(self, *args: Any) -> None: + pass + + def close(self) -> None: + """Calling this method is unnecessary.""" + + @log_get_token + def get_token( + self, + *scopes: str, + claims: Optional[str] = None, # pylint:disable=unused-argument + tenant_id: Optional[str] = None, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. Applications calling this method directly must + also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke Azure PowerShell, or + no account is authenticated + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked Azure PowerShell but didn't + receive an access token + """ + + options: TokenRequestOptions = {} + if tenant_id: + options["tenant_id"] = tenant_id + + token_info = self._get_token_base(*scopes, options=options, **kwargs) + return AccessToken(token_info.token, token_info.expires_on) + + @log_get_token + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. Applications calling this method + directly must also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scopes for the access token. TThis credential allows only one scope per request. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke Azure PowerShell, or + no account is authenticated + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked Azure PowerShell but didn't + receive an access token + """ + return self._get_token_base(*scopes, options=options) + + def _get_token_base( + self, *scopes: str, options: Optional[TokenRequestOptions] = None, **kwargs: Any + ) -> AccessTokenInfo: + + tenant_id = options.get("tenant_id") if options else None + if tenant_id: + validate_tenant_id(tenant_id) + for scope in scopes: + validate_scope(scope) + + tenant_id = resolve_tenant( + default_tenant=self.tenant_id, + tenant_id=tenant_id, + additionally_allowed_tenants=self._additionally_allowed_tenants, + **kwargs, + ) + command_line = get_command_line(scopes, tenant_id) + output = run_command_line(command_line, self._process_timeout) + token = parse_token(output) + return token + + +def run_command_line(command_line: List[str], timeout: int) -> str: + stdout = stderr = "" + proc = None + kwargs = {"timeout": timeout} + + try: + proc = start_process(command_line) + stdout, stderr = proc.communicate(**kwargs) + if sys.platform.startswith("win") and ("' is not recognized" in stderr or proc.returncode == 9009): + # pwsh.exe isn't on the path; try powershell.exe + command_line[-1] = command_line[-1].replace("pwsh", "powershell", 1) + proc = start_process(command_line) + stdout, stderr = proc.communicate(**kwargs) + + except Exception as ex: # pylint:disable=broad-except + # failed to execute "cmd" or "/bin/sh", or timed out; PowerShell and Az.Account may or may not be installed + # (handling Exception here because subprocess.SubprocessError and .TimeoutExpired were added in 3.3) + if proc and not proc.returncode: + proc.kill() + error = CredentialUnavailableError( + message="Failed to invoke PowerShell.\n" + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https://aka.ms/azsdk/python/identity/powershellcredential/troubleshoot." + ) + raise error from ex + + raise_for_error(proc.returncode, stdout, stderr) + return stdout + + +def start_process(args: List[str]) -> "subprocess.Popen": + working_directory = get_safe_working_dir() + proc = subprocess.Popen( # pylint:disable=consider-using-with + args, + cwd=working_directory, + stdout=subprocess.PIPE, + stderr=subprocess.PIPE, + stdin=subprocess.DEVNULL, + universal_newlines=True, + ) + return proc + + +def parse_token(output: str) -> AccessTokenInfo: + for line in output.split(): + if line.startswith("azsdk%"): + _, token, expires_on = line.split("%") + return AccessTokenInfo(token, int(expires_on)) + + if within_dac.get(): + raise CredentialUnavailableError(message='Unexpected output from Get-AzAccessToken: "{}"'.format(output)) + raise ClientAuthenticationError(message='Unexpected output from Get-AzAccessToken: "{}"'.format(output)) + + +def get_command_line(scopes: Tuple[str, ...], tenant_id: str) -> List[str]: + tenant_argument = tenant_id if tenant_id else "" + resource = _scopes_to_resource(*scopes) + script = SCRIPT.format(NO_AZ_ACCOUNT_MODULE, resource, tenant_argument) + encoded_script = base64.b64encode(script.encode("utf-16-le")).decode() + + command = "pwsh -NoProfile -NonInteractive -EncodedCommand " + encoded_script + if sys.platform.startswith("win"): + return ["cmd", "/c", command + " & exit"] + return ["/bin/sh", "-c", command] + + +def raise_for_error(return_code: int, stdout: str, stderr: str) -> None: + if return_code == 0: + if NO_AZ_ACCOUNT_MODULE in stdout: + raise CredentialUnavailableError(AZ_ACCOUNT_NOT_INSTALLED) + return + + if return_code == 127 or "' is not recognized" in stderr: + raise CredentialUnavailableError(message=POWERSHELL_NOT_INSTALLED) + if "Run Connect-AzAccount to login" in stderr: + raise CredentialUnavailableError(message=RUN_CONNECT_AZ_ACCOUNT) + if "AuthorizationManager check failed" in stderr: + raise CredentialUnavailableError(message=BLOCKED_BY_EXECUTION_POLICY) + + if stderr: + # stderr is too noisy to include with an exception but may be useful for debugging + _LOGGER.debug('%s received an error from Azure PowerShell: "%s"', AzurePowerShellCredential.__name__, stderr) + raise CredentialUnavailableError( + message="Failed to invoke PowerShell. Enable debug logging for additional information." + ) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/browser.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/browser.py new file mode 100644 index 00000000000..0f7db54f4c8 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/browser.py @@ -0,0 +1,157 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import platform +import socket +from typing import Dict, Any +import subprocess +import webbrowser +from urllib.parse import urlparse + +from azure.core.exceptions import ClientAuthenticationError + +from .. import CredentialUnavailableError +from .._constants import DEVELOPER_SIGN_ON_CLIENT_ID +from .._internal import AuthCodeRedirectServer, InteractiveCredential, wrap_exceptions, within_dac + + +class InteractiveBrowserCredential(InteractiveCredential): + """Opens a browser to interactively authenticate a user. + + :func:`~get_token` opens a browser to a login URL provided by Microsoft Entra ID and authenticates a user + there with the authorization code flow, using PKCE (Proof Key for Code Exchange) internally to protect the code. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword str tenant_id: a Microsoft Entra tenant ID. Defaults to the "organizations" tenant, which can + authenticate work or school accounts. + :keyword str client_id: Client ID of the Microsoft Entra application that users will sign into. It is recommended + that developers register their applications and assign appropriate roles. For more information, + visit https://aka.ms/azsdk/identity/AppRegistrationAndRoleAssignment. If not specified, users will + authenticate to an Azure development application, which is not recommended for production scenarios. + :keyword str login_hint: a username suggestion to pre-fill the login page's username/email address field. A user + may still log in with a different username. + :keyword str redirect_uri: a redirect URI for the application identified by `client_id` as configured in Azure + Active Directory, for example "http://localhost:8400". This is only required when passing a value for + **client_id**, and must match a redirect URI in the application's registration. The credential must be able to + bind a socket to this URI. + :keyword AuthenticationRecord authentication_record: :class:`AuthenticationRecord` returned by :func:`authenticate` + :keyword bool disable_automatic_authentication: if True, :func:`get_token` will raise + :class:`AuthenticationRequiredError` when user interaction is required to acquire a token. Defaults to False. + :keyword cache_persistence_options: configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword int timeout: seconds to wait for the user to complete authentication. Defaults to 300 (5 minutes). + :keyword bool disable_instance_discovery: Determines whether or not instance discovery is performed when attempting + to authenticate. Setting this to true will completely disable both instance discovery and authority validation. + This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in + private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from + https://login.microsoft.com/ to validate the authority. By setting this to **True**, the validation of the + authority is disabled. As a result, it is crucial to ensure that the configured authority host is valid and + trustworthy. + :keyword bool enable_support_logging: Enables additional support logging in the underlying MSAL library. + This logging potentially contains personally identifiable information and is intended to be used only for + troubleshooting purposes. + :raises ValueError: invalid **redirect_uri** + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_interactive_browser_credential] + :end-before: [END create_interactive_browser_credential] + :language: python + :dedent: 4 + :caption: Create an InteractiveBrowserCredential. + """ + + def __init__(self, **kwargs: Any) -> None: + redirect_uri = kwargs.pop("redirect_uri", None) + if redirect_uri: + self._parsed_url = urlparse(redirect_uri) + if not (self._parsed_url.hostname and self._parsed_url.port): + raise ValueError('"redirect_uri" must be a URL with port number, for example "http://localhost:8400"') + else: + self._parsed_url = None + + self._login_hint = kwargs.pop("login_hint", None) + self._timeout = kwargs.pop("timeout", 300) + self._server_class = kwargs.pop("_server_class", AuthCodeRedirectServer) + client_id = kwargs.pop("client_id", DEVELOPER_SIGN_ON_CLIENT_ID) + super(InteractiveBrowserCredential, self).__init__(client_id=client_id, **kwargs) + + @wrap_exceptions + def _request_token(self, *scopes: str, **kwargs) -> Dict: + + # start an HTTP server to receive the redirect + server = None + redirect_uri: str = "" + if self._parsed_url: + try: + redirect_uri = "http://{}:{}".format(self._parsed_url.hostname, self._parsed_url.port) + server = self._server_class(self._parsed_url.hostname, self._parsed_url.port, timeout=self._timeout) + except socket.error as ex: + raise CredentialUnavailableError(message="Couldn't start an HTTP server on " + redirect_uri) from ex + else: + for port in range(8400, 9000): + try: + server = self._server_class("localhost", port, timeout=self._timeout) + redirect_uri = "http://localhost:{}".format(port) + break + except socket.error: + continue # keep looking for an open port + + if not server: + raise CredentialUnavailableError(message="Couldn't start an HTTP server on localhost") + + # get the url the user must visit to authenticate + scopes = list(scopes) # type: ignore + claims = kwargs.get("claims") + app = self._get_app(**kwargs) + flow = app.initiate_auth_code_flow( + scopes, + redirect_uri=redirect_uri, + prompt="select_account", + claims_challenge=claims, + login_hint=self._login_hint, + ) + if "auth_uri" not in flow: + raise CredentialUnavailableError("Failed to begin authentication flow") + + if not _open_browser(flow["auth_uri"]): + raise CredentialUnavailableError(message="Failed to open a browser") + + # block until the server times out or receives the post-authentication redirect + response = server.wait_for_redirect() + if not response: + if within_dac.get(): + raise CredentialUnavailableError( + message="Timed out after waiting {} seconds for the user to authenticate".format(self._timeout) + ) + raise ClientAuthenticationError( + message="Timed out after waiting {} seconds for the user to authenticate".format(self._timeout) + ) + + # redeem the authorization code for a token + return app.acquire_token_by_auth_code_flow(flow, response, scopes=scopes, claims_challenge=claims) + + +def _open_browser(url): + opened = webbrowser.open(url) + if not opened: + uname = platform.uname() + system = uname[0].lower() + release = uname[2].lower() + if "microsoft" in release and system == "linux": + kwargs = {"timeout": 5} + + try: + exit_code = subprocess.call( + ["powershell.exe", "-NoProfile", "-Command", 'Start-Process "{}"'.format(url)], **kwargs + ) + opened = exit_code == 0 + except Exception: # pylint:disable=broad-except + # powershell.exe isn't available, or the subprocess timed out + pass + return opened diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/certificate.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/certificate.py new file mode 100644 index 00000000000..e7ce646e998 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/certificate.py @@ -0,0 +1,182 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from binascii import hexlify +from typing import cast, NamedTuple, Union, Dict, Any, Optional + +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey +from cryptography.hazmat.backends import default_backend + +from .._internal import validate_tenant_id +from .._internal.client_credential_base import ClientCredentialBase + + +class CertificateCredential(ClientCredentialBase): + """Authenticates as a service principal using a certificate. + + The certificate must have an RSA private key, because this credential signs assertions using RS256. See + `Microsoft Entra ID documentation + `__ + for more information on configuring certificate authentication. + + :param str tenant_id: ID of the service principal's tenant. Also called its "directory" ID. + :param str client_id: The service principal's client ID + :param str certificate_path: Optional path to a certificate file in PEM or PKCS12 format, including the private + key. If not provided, **certificate_data** is required. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword bytes certificate_data: The bytes of a certificate in PEM or PKCS12 format, including the private key + :keyword password: The certificate's password. If a unicode string, it will be encoded as UTF-8. If the certificate + requires a different encoding, pass appropriately encoded bytes instead. + :paramtype password: str or bytes + :keyword bool send_certificate_chain: If True, the credential will send the public certificate chain in the x5c + header of each token request's JWT. This is required for Subject Name/Issuer (SNI) authentication. Defaults to + False. + :keyword cache_persistence_options: Configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword bool disable_instance_discovery: Determines whether or not instance discovery is performed when attempting + to authenticate. Setting this to true will completely disable both instance discovery and authority validation. + This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in + private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from + https://login.microsoft.com/ to validate the authority. By setting this to **True**, the validation of the + authority is disabled. As a result, it is crucial to ensure that the configured authority host is valid and + trustworthy. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_certificate_credential] + :end-before: [END create_certificate_credential] + :language: python + :dedent: 4 + :caption: Create a CertificateCredential. + """ + + def __init__(self, tenant_id: str, client_id: str, certificate_path: Optional[str] = None, **kwargs: Any) -> None: + validate_tenant_id(tenant_id) + + client_credential = get_client_credential(certificate_path, **kwargs) + + super(CertificateCredential, self).__init__( + client_id=client_id, client_credential=client_credential, tenant_id=tenant_id, **kwargs + ) + + +def extract_cert_chain(pem_bytes: bytes) -> bytes: + """Extract a certificate chain from a PEM file's bytes, removing line breaks. + + :param bytes pem_bytes: The PEM file's bytes + :return: The certificate chain + :rtype: bytes + """ + + # if index raises ValueError, there's no PEM-encoded cert + start = pem_bytes.index(b"-----BEGIN CERTIFICATE-----") + footer = b"-----END CERTIFICATE-----" + end = pem_bytes.rindex(footer) + chain = pem_bytes[start : end + len(footer) + 1] + + return b"".join(chain.splitlines()) + + +_Cert = NamedTuple("_Cert", [("pem_bytes", bytes), ("private_key", "Any"), ("fingerprint", bytes)]) + + +def load_pem_certificate(certificate_data: bytes, password: Optional[bytes] = None) -> _Cert: + private_key = serialization.load_pem_private_key(certificate_data, password, backend=default_backend()) + cert = x509.load_pem_x509_certificate(certificate_data, default_backend()) + fingerprint = cert.fingerprint(hashes.SHA1()) # nosec + return _Cert(certificate_data, private_key, fingerprint) + + +def load_pkcs12_certificate(certificate_data: bytes, password: Optional[bytes] = None) -> _Cert: + from cryptography.hazmat.primitives.serialization import Encoding, NoEncryption, pkcs12, PrivateFormat + + try: + private_key, cert, additional_certs = pkcs12.load_key_and_certificates( + certificate_data, password, backend=default_backend() + ) + except ValueError as ex: + # mentioning PEM here because we raise this error when certificate_data is garbage + raise ValueError("Failed to deserialize certificate in PEM or PKCS12 format") from ex + if not private_key: + raise ValueError("The certificate must include its private key") + if not cert: + raise ValueError("Failed to deserialize certificate in PEM or PKCS12 format") + + # This serializes the private key without any encryption it may have had. Doing so doesn't violate security + # boundaries because this representation of the key is kept in memory. We already have the key and its + # password, if any, in memory. + key_bytes = private_key.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()) + pem_sections = [key_bytes] + [c.public_bytes(Encoding.PEM) for c in [cert] + additional_certs] + pem_bytes = b"".join(pem_sections) + + fingerprint = cert.fingerprint(hashes.SHA1()) # nosec + + return _Cert(pem_bytes, private_key, fingerprint) + + +def get_client_credential( + certificate_path: Optional[str] = None, + password: Optional[Union[bytes, str]] = None, + certificate_data: Optional[bytes] = None, + send_certificate_chain: bool = False, + **_: Any +) -> Dict: + """Load a certificate from a filesystem path or bytes, return it as a dict suitable for msal.ClientApplication. + + :param str certificate_path: Path to a PEM or PKCS12 certificate file. + :param bytes password: The certificate's password, if any. + :param bytes certificate_data: The PEM or PKCS12 certificate's bytes. + :param bool send_certificate_chain: Whether to send the certificate chain. Defaults to False. + + :return: The certificate as a dict + :rtype: dict + """ + + if certificate_path: + if certificate_data: + raise ValueError('Please specify either "certificate_path" or "certificate_data", not both') + with open(certificate_path, "rb") as f: + certificate_data = f.read() + elif not certificate_data: + raise ValueError('CertificateCredential requires a value for either "certificate_path" or "certificate_data"') + + if password: + # if password is already bytes, no need to encode. + if isinstance(password, str): + password = password.encode("utf-8") + password = cast("Optional[bytes]", password) + + if b"-----BEGIN" in certificate_data: + cert = load_pem_certificate(certificate_data, password) + else: + cert = load_pkcs12_certificate(certificate_data, password) + password = None # load_pkcs12_certificate returns cert.pem_bytes decrypted + + if not isinstance(cert.private_key, RSAPrivateKey): + raise ValueError("The certificate must have an RSA private key because RS256 is used for signing") + + client_credential = {"private_key": cert.pem_bytes, "thumbprint": hexlify(cert.fingerprint).decode("utf-8")} + if password: + client_credential["passphrase"] = password + + if send_certificate_chain: + try: + # the JWT needs the whole chain but load_pem_x509_certificate deserializes only the signing cert + chain = extract_cert_chain(cert.pem_bytes) + client_credential["public_certificate"] = chain.decode("utf-8") + except ValueError as ex: + # we shouldn't land here--cryptography already loaded the cert and would have raised if it were malformed + raise ValueError("Malformed certificate") from ex + + return client_credential diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/chained.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/chained.py new file mode 100644 index 00000000000..13db8759226 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/chained.py @@ -0,0 +1,219 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +from typing import Any, Optional, cast +from azure.core.exceptions import ClientAuthenticationError + +from azure.core.credentials import ( + AccessToken, + AccessTokenInfo, + TokenRequestOptions, + SupportsTokenInfo, + TokenCredential, + TokenProvider, +) +from .. import CredentialUnavailableError +from .._internal import within_credential_chain + +_LOGGER = logging.getLogger(__name__) + + +def _get_error_message(history): + attempts = [] + for credential, error in history: + if error: + attempts.append("{}: {}".format(credential.__class__.__name__, error)) + else: + attempts.append(credential.__class__.__name__) + return """ +Attempted credentials:\n\t{}""".format( + "\n\t".join(attempts) + ) + + +class ChainedTokenCredential: + """A sequence of credentials that is itself a credential. + + Its :func:`get_token` method calls ``get_token`` on each credential in the sequence, in order, returning the first + valid token received. For more information, see `ChainedTokenCredential overview + <"https://aka.ms/azsdk/python/identity/credential-chains#chainedtokencredential-overview">`__. + + :param credentials: credential instances to form the chain + :type credentials: ~azure.core.credentials.TokenCredential + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_chained_token_credential] + :end-before: [END create_chained_token_credential] + :language: python + :dedent: 4 + :caption: Create a ChainedTokenCredential. + """ + + def __init__(self, *credentials: TokenProvider) -> None: + if not credentials: + raise ValueError("at least one credential is required") + + self._successful_credential: Optional[TokenProvider] = None + self.credentials = credentials + + def __enter__(self) -> "ChainedTokenCredential": + for credential in self.credentials: + credential.__enter__() # type: ignore + return self + + def __exit__(self, *args: Any) -> None: + for credential in self.credentials: + credential.__exit__(*args) # type: ignore + + def close(self) -> None: + """Close the transport session of each credential in the chain.""" + self.__exit__() + + def get_token( + self, + *scopes: str, + claims: Optional[str] = None, + tenant_id: Optional[str] = None, + enable_cae: bool = False, + **kwargs: Any, + ) -> AccessToken: + """Request a token from each chained credential, in order, returning the first token received. + + If no credential provides a token, raises :class:`azure.core.exceptions.ClientAuthenticationError` + with an error message from each credential. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested + token. Defaults to False. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.core.exceptions.ClientAuthenticationError: no credential in the chain provided a token + """ + + within_credential_chain.set(True) + history = [] + for credential in self.credentials: + try: + # Prioritize "get_token". Fall back to "get_token_info" if not available. + if hasattr(credential, "get_token"): + token = cast(TokenCredential, credential).get_token( + *scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs + ) + else: + options: TokenRequestOptions = {} + if claims: + options["claims"] = claims + if tenant_id: + options["tenant_id"] = tenant_id + options["enable_cae"] = enable_cae + token_info = cast(SupportsTokenInfo, credential).get_token_info(*scopes, options=options) + token = AccessToken(token_info.token, token_info.expires_on) + + _LOGGER.info("%s acquired a token from %s", self.__class__.__name__, credential.__class__.__name__) + self._successful_credential = credential + within_credential_chain.set(False) + return token + + except CredentialUnavailableError as ex: + # credential didn't attempt authentication because it lacks required data or state -> continue + history.append((credential, ex.message)) + except Exception as ex: # pylint: disable=broad-except + # credential failed to authenticate, or something unexpectedly raised -> break + history.append((credential, str(ex))) + _LOGGER.debug( + '%s.get_token failed: %s raised unexpected error "%s"', + self.__class__.__name__, + credential.__class__.__name__, + ex, + exc_info=True, + ) + break + within_credential_chain.set(False) + attempts = _get_error_message(history) + message = ( + self.__class__.__name__ + + " failed to retrieve a token from the included credentials." + + attempts + + "\nTo mitigate this issue, please refer to the troubleshooting guidelines here at " + "https://aka.ms/azsdk/python/identity/defaultazurecredential/troubleshoot." + ) + _LOGGER.warning(message) + raise ClientAuthenticationError(message=message) + + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request a token from each chained credential, in order, returning the first token received. + + If no credential provides a token, raises :class:`azure.core.exceptions.ClientAuthenticationError` + with an error message from each credential. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + + :raises ~azure.core.exceptions.ClientAuthenticationError: no credential in the chain provided a token. + """ + within_credential_chain.set(True) + history = [] + options = options or {} + for credential in self.credentials: + try: + # Prioritize "get_token_info". Fall back to "get_token" if not available. + if hasattr(credential, "get_token_info"): + token_info = cast(SupportsTokenInfo, credential).get_token_info(*scopes, options=options) + else: + if options.get("pop"): + raise CredentialUnavailableError( + "Proof of possession arguments are not supported for this credential." + ) + token = cast(TokenCredential, credential).get_token(*scopes, **options) + token_info = AccessTokenInfo(token=token.token, expires_on=token.expires_on) + + _LOGGER.info("%s acquired a token from %s", self.__class__.__name__, credential.__class__.__name__) + self._successful_credential = credential + within_credential_chain.set(False) + return token_info + except CredentialUnavailableError as ex: + # credential didn't attempt authentication because it lacks required data or state -> continue + history.append((credential, ex.message)) + except Exception as ex: # pylint: disable=broad-except + # credential failed to authenticate, or something unexpectedly raised -> break + history.append((credential, str(ex))) + _LOGGER.debug( + '%s.get_token_info failed: %s raised unexpected error "%s"', + self.__class__.__name__, + credential.__class__.__name__, + ex, + exc_info=True, + ) + break + + within_credential_chain.set(False) + attempts = _get_error_message(history) + message = ( + self.__class__.__name__ + + " failed to retrieve a token from the included credentials." + + attempts + + "\nTo mitigate this issue, please refer to the troubleshooting guidelines here at " + "https://aka.ms/azsdk/python/identity/defaultazurecredential/troubleshoot." + ) + _LOGGER.warning(message) + raise ClientAuthenticationError(message=message) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/client_assertion.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/client_assertion.py new file mode 100644 index 00000000000..bb371381c6b --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/client_assertion.py @@ -0,0 +1,77 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Callable, Optional, Any + +from azure.core.credentials import AccessTokenInfo +from .._internal import AadClient +from .._internal.get_token_mixin import GetTokenMixin + + +class ClientAssertionCredential(GetTokenMixin): + """Authenticates a service principal with a JWT assertion. + + This credential is for advanced scenarios. :class:`~azure.identity.CertificateCredential` has a more + convenient API for the most common assertion scenario, authenticating a service principal with a certificate. + + :param str tenant_id: ID of the principal's tenant. Also called its "directory" ID. + :param str client_id: The principal's client ID + :param func: A callable that returns a string assertion. The credential will call this every time it + acquires a new token. + :paramtype func: Callable[[], str] + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example + "login.microsoftonline.com", the authority for Azure Public Cloud (which is the default). + :class:`~azure.identity.AzureAuthorityHosts` defines authorities for other clouds. + :keyword cache_persistence_options: configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_client_assertion_credential] + :end-before: [END create_client_assertion_credential] + :language: python + :dedent: 4 + :caption: Create a ClientAssertionCredential. + """ + + def __init__(self, tenant_id: str, client_id: str, func: Callable[[], str], **kwargs: Any) -> None: + self._func = func + authority = kwargs.pop("authority", None) + cache = kwargs.pop("cache", None) + cae_cache = kwargs.pop("cae_cache", None) + additionally_allowed_tenants = kwargs.pop("additionally_allowed_tenants", None) + self._client = AadClient( + tenant_id, + client_id, + authority=authority, + cache=cache, + cae_cache=cae_cache, + additionally_allowed_tenants=additionally_allowed_tenants, + **kwargs + ) + super().__init__() + + def __enter__(self) -> "ClientAssertionCredential": + self._client.__enter__() + return self + + def __exit__(self, *args: Any) -> None: + self._client.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessTokenInfo]: + return self._client.get_cached_access_token(scopes, **kwargs) + + def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + assertion = self._func() + token = self._client.obtain_token_by_jwt_assertion(scopes, assertion, **kwargs) + return token diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/client_secret.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/client_secret.py new file mode 100644 index 00000000000..0ac73a74415 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/client_secret.py @@ -0,0 +1,53 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Any +from .._internal.client_credential_base import ClientCredentialBase + + +class ClientSecretCredential(ClientCredentialBase): + """Authenticates as a service principal using a client secret. + + :param str tenant_id: ID of the service principal's tenant. Also called its "directory" ID. + :param str client_id: The service principal's client ID + :param str client_secret: One of the service principal's client secrets + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword cache_persistence_options: Configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword bool disable_instance_discovery: Determines whether or not instance discovery is performed when attempting + to authenticate. Setting this to true will completely disable both instance discovery and authority validation. + This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in + private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from + https://login.microsoft.com/ to validate the authority. By setting this to **True**, the validation of the + authority is disabled. As a result, it is crucial to ensure that the configured authority host is valid and + trustworthy. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_client_secret_credential] + :end-before: [END create_client_secret_credential] + :language: python + :dedent: 4 + :caption: Create a ClientSecretCredential. + """ + + def __init__(self, tenant_id: str, client_id: str, client_secret: str, **kwargs: Any) -> None: + if not client_id: + raise ValueError("client_id should be the id of a Microsoft Entra application") + if not client_secret: + raise ValueError("secret should be a Microsoft Entra application's client secret") + if not tenant_id: + raise ValueError("tenant_id should be a Microsoft Entra tenant's id (also called its 'directory id')") + + super(ClientSecretCredential, self).__init__( + client_id=client_id, client_credential=client_secret, tenant_id=tenant_id, **kwargs + ) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/cloud_shell.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/cloud_shell.py new file mode 100644 index 00000000000..61aefdb0c28 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/cloud_shell.py @@ -0,0 +1,47 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import os +from typing import Any, Optional, Dict, Mapping + +from azure.core.pipeline.transport import HttpRequest + +from .._constants import EnvironmentVariables +from .._internal import within_dac +from .._internal.managed_identity_client import ManagedIdentityClient +from .._internal.managed_identity_base import ManagedIdentityBase + + +def validate_client_id_and_config(client_id: Optional[str], identity_config: Optional[Mapping[str, str]]) -> None: + if within_dac.get(): + return + if client_id: + raise ValueError("client_id should not be set for cloud shell managed identity.") + if identity_config: + valid_keys = {"object_id", "resource_id", "client_id"} + if len(identity_config.keys() & valid_keys) > 0: + raise ValueError(f"identity_config must not contain the following keys: {', '.join(valid_keys)}") + + +class CloudShellCredential(ManagedIdentityBase): + def get_client(self, **kwargs: Any) -> Optional[ManagedIdentityClient]: + client_id = kwargs.get("client_id") + identity_config = kwargs.get("identity_config") + validate_client_id_and_config(client_id, identity_config) + + url = os.environ.get(EnvironmentVariables.MSI_ENDPOINT) + if url: + return ManagedIdentityClient( + request_factory=functools.partial(_get_request, url), base_headers={"Metadata": "true"}, **kwargs + ) + return None + + def get_unavailable_message(self, desc: str = "") -> str: + return f"Cloud Shell managed identity configuration not found in environment. {desc}" + + +def _get_request(url: str, scope: str, identity_config: Dict) -> HttpRequest: + request = HttpRequest("POST", url, data=dict({"resource": scope}, **identity_config)) + return request diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/default.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/default.py new file mode 100644 index 00000000000..426fad01e9c --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/default.py @@ -0,0 +1,258 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import List, Any, Optional, cast + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions, SupportsTokenInfo, TokenCredential +from .._constants import EnvironmentVariables +from .._internal import get_default_authority, normalize_authority, within_dac +from .azure_powershell import AzurePowerShellCredential +from .browser import InteractiveBrowserCredential +from .chained import ChainedTokenCredential +from .environment import EnvironmentCredential +from .managed_identity import ManagedIdentityCredential +from .shared_cache import SharedTokenCacheCredential +from .azure_cli import AzureCliCredential +from .azd_cli import AzureDeveloperCliCredential +from .vscode import VisualStudioCodeCredential +from .workload_identity import WorkloadIdentityCredential + +_LOGGER = logging.getLogger(__name__) + + +class DefaultAzureCredential(ChainedTokenCredential): + """A credential capable of handling most Azure SDK authentication scenarios. For more information, See + `Usage guidance for DefaultAzureCredential + <"https://aka.ms/azsdk/python/identity/credential-chains#usage-guidance-for-defaultazurecredential">`__. + + The identity it uses depends on the environment. When an access token is needed, it requests one using these + identities in turn, stopping when one provides a token: + + 1. A service principal configured by environment variables. See :class:`~azure.identity.EnvironmentCredential` for + more details. + 2. WorkloadIdentityCredential if environment variable configuration is set by the Azure workload + identity webhook. + 3. An Azure managed identity. See :class:`~azure.identity.ManagedIdentityCredential` for more details. + 4. On Windows only: a user who has signed in with a Microsoft application, such as Visual Studio. If multiple + identities are in the cache, then the value of the environment variable ``AZURE_USERNAME`` is used to select + which identity to use. See :class:`~azure.identity.SharedTokenCacheCredential` for more details. + 5. The identity currently logged in to the Azure CLI. + 6. The identity currently logged in to Azure PowerShell. + 7. The identity currently logged in to the Azure Developer CLI. + + This default behavior is configurable with keyword arguments. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example 'login.microsoftonline.com', + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. Managed identities ignore this because they reside in a single cloud. + :keyword bool exclude_workload_identity_credential: Whether to exclude the workload identity from the credential. + Defaults to **False**. + :keyword bool exclude_developer_cli_credential: Whether to exclude the Azure Developer CLI + from the credential. Defaults to **False**. + :keyword bool exclude_cli_credential: Whether to exclude the Azure CLI from the credential. Defaults to **False**. + :keyword bool exclude_environment_credential: Whether to exclude a service principal configured by environment + variables from the credential. Defaults to **False**. + :keyword bool exclude_managed_identity_credential: Whether to exclude managed identity from the credential. + Defaults to **False**. + :keyword bool exclude_powershell_credential: Whether to exclude Azure PowerShell. Defaults to **False**. + :keyword bool exclude_visual_studio_code_credential: Whether to exclude stored credential from VS Code. + Defaults to **True**. + :keyword bool exclude_shared_token_cache_credential: Whether to exclude the shared token cache. Defaults to + **False**. + :keyword bool exclude_interactive_browser_credential: Whether to exclude interactive browser authentication (see + :class:`~azure.identity.InteractiveBrowserCredential`). Defaults to **True**. + :keyword str interactive_browser_tenant_id: Tenant ID to use when authenticating a user through + :class:`~azure.identity.InteractiveBrowserCredential`. Defaults to the value of environment variable + AZURE_TENANT_ID, if any. If unspecified, users will authenticate in their home tenants. + :keyword str managed_identity_client_id: The client ID of a user-assigned managed identity. Defaults to the value + of the environment variable AZURE_CLIENT_ID, if any. If not specified, a system-assigned identity will be used. + :keyword str workload_identity_client_id: The client ID of an identity assigned to the pod. Defaults to the value + of the environment variable AZURE_CLIENT_ID, if any. If not specified, the pod's default identity will be used. + :keyword str workload_identity_tenant_id: Preferred tenant for :class:`~azure.identity.WorkloadIdentityCredential`. + Defaults to the value of environment variable AZURE_TENANT_ID, if any. + :keyword str interactive_browser_client_id: The client ID to be used in interactive browser credential. If not + specified, users will authenticate to an Azure development application. + :keyword str shared_cache_username: Preferred username for :class:`~azure.identity.SharedTokenCacheCredential`. + Defaults to the value of environment variable AZURE_USERNAME, if any. + :keyword str shared_cache_tenant_id: Preferred tenant for :class:`~azure.identity.SharedTokenCacheCredential`. + Defaults to the value of environment variable AZURE_TENANT_ID, if any. + :keyword str visual_studio_code_tenant_id: Tenant ID to use when authenticating with + :class:`~azure.identity.VisualStudioCodeCredential`. Defaults to the "Azure: Tenant" setting in VS Code's user + settings or, when that setting has no value, the "organizations" tenant, which supports only Azure Active + Directory work or school accounts. + :keyword int process_timeout: The timeout in seconds to use for developer credentials that run + subprocesses (e.g. AzureCliCredential, AzurePowerShellCredential). Defaults to **10** seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_default_credential] + :end-before: [END create_default_credential] + :language: python + :dedent: 4 + :caption: Create a DefaultAzureCredential. + """ + + def __init__(self, **kwargs: Any) -> None: # pylint: disable=too-many-statements, too-many-locals + if "tenant_id" in kwargs: + raise TypeError("'tenant_id' is not supported in DefaultAzureCredential.") + + authority = kwargs.pop("authority", None) + + vscode_tenant_id = kwargs.pop( + "visual_studio_code_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + vscode_args = dict(kwargs) + if authority: + vscode_args["authority"] = authority + if vscode_tenant_id: + vscode_args["tenant_id"] = vscode_tenant_id + + authority = normalize_authority(authority) if authority else get_default_authority() + + interactive_browser_tenant_id = kwargs.pop( + "interactive_browser_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + + managed_identity_client_id = kwargs.pop( + "managed_identity_client_id", os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + ) + workload_identity_client_id = kwargs.pop("workload_identity_client_id", managed_identity_client_id) + workload_identity_tenant_id = kwargs.pop( + "workload_identity_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + interactive_browser_client_id = kwargs.pop("interactive_browser_client_id", None) + + shared_cache_username = kwargs.pop("shared_cache_username", os.environ.get(EnvironmentVariables.AZURE_USERNAME)) + shared_cache_tenant_id = kwargs.pop( + "shared_cache_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + + process_timeout = kwargs.pop("process_timeout", 10) + + exclude_workload_identity_credential = kwargs.pop("exclude_workload_identity_credential", False) + exclude_environment_credential = kwargs.pop("exclude_environment_credential", False) + exclude_managed_identity_credential = kwargs.pop("exclude_managed_identity_credential", False) + exclude_shared_token_cache_credential = kwargs.pop("exclude_shared_token_cache_credential", False) + exclude_visual_studio_code_credential = kwargs.pop("exclude_visual_studio_code_credential", True) + exclude_developer_cli_credential = kwargs.pop("exclude_developer_cli_credential", False) + exclude_cli_credential = kwargs.pop("exclude_cli_credential", False) + exclude_interactive_browser_credential = kwargs.pop("exclude_interactive_browser_credential", True) + exclude_powershell_credential = kwargs.pop("exclude_powershell_credential", False) + + credentials: List[SupportsTokenInfo] = [] + within_dac.set(True) + if not exclude_environment_credential: + credentials.append(EnvironmentCredential(authority=authority, _within_dac=True, **kwargs)) + if not exclude_workload_identity_credential: + if all(os.environ.get(var) for var in EnvironmentVariables.WORKLOAD_IDENTITY_VARS): + client_id = workload_identity_client_id + credentials.append( + WorkloadIdentityCredential( + client_id=cast(str, client_id), + tenant_id=workload_identity_tenant_id, + token_file_path=os.environ[EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE], + **kwargs + ) + ) + if not exclude_managed_identity_credential: + credentials.append( + ManagedIdentityCredential( + client_id=managed_identity_client_id, + _exclude_workload_identity_credential=exclude_workload_identity_credential, + **kwargs + ) + ) + if not exclude_shared_token_cache_credential and SharedTokenCacheCredential.supported(): + try: + # username and/or tenant_id are only required when the cache contains tokens for multiple identities + shared_cache = SharedTokenCacheCredential( + username=shared_cache_username, tenant_id=shared_cache_tenant_id, authority=authority, **kwargs + ) + credentials.append(shared_cache) + except Exception as ex: # pylint:disable=broad-except + _LOGGER.info("Shared token cache is unavailable: '%s'", ex) + if not exclude_visual_studio_code_credential: + credentials.append(VisualStudioCodeCredential(**vscode_args)) + if not exclude_cli_credential: + credentials.append(AzureCliCredential(process_timeout=process_timeout)) + if not exclude_powershell_credential: + credentials.append(AzurePowerShellCredential(process_timeout=process_timeout)) + if not exclude_developer_cli_credential: + credentials.append(AzureDeveloperCliCredential(process_timeout=process_timeout)) + if not exclude_interactive_browser_credential: + if interactive_browser_client_id: + credentials.append( + InteractiveBrowserCredential( + tenant_id=interactive_browser_tenant_id, client_id=interactive_browser_client_id, **kwargs + ) + ) + else: + credentials.append(InteractiveBrowserCredential(tenant_id=interactive_browser_tenant_id, **kwargs)) + within_dac.set(False) + super(DefaultAzureCredential, self).__init__(*credentials) + + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The exception has a + `message` attribute listing each authentication attempt and its error message. + """ + if self._successful_credential: + token = cast(TokenCredential, self._successful_credential).get_token( + *scopes, claims=claims, tenant_id=tenant_id, **kwargs + ) + _LOGGER.info( + "%s acquired a token from %s", self.__class__.__name__, self._successful_credential.__class__.__name__ + ) + return token + within_dac.set(True) + token = super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + within_dac.set(False) + return token + + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The exception has a + `message` attribute listing each authentication attempt and its error message. + """ + if self._successful_credential: + token_info = cast(SupportsTokenInfo, self._successful_credential).get_token_info(*scopes, options=options) + _LOGGER.info( + "%s acquired a token from %s", self.__class__.__name__, self._successful_credential.__class__.__name__ + ) + return token_info + + within_dac.set(True) + token_info = cast(SupportsTokenInfo, super()).get_token_info(*scopes, options=options) + within_dac.set(False) + return token_info diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/device_code.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/device_code.py new file mode 100644 index 00000000000..6af24a98aab --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/device_code.py @@ -0,0 +1,118 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from datetime import datetime, timezone +import time +from typing import Dict, Optional, Callable, Any + +from azure.core.exceptions import ClientAuthenticationError + +from .._constants import DEVELOPER_SIGN_ON_CLIENT_ID +from .._internal import InteractiveCredential, wrap_exceptions + + +class DeviceCodeCredential(InteractiveCredential): + """Authenticates users through the device code flow. + + When :func:`get_token` is called, this credential acquires a verification URL and code from Microsoft Entra ID. + A user must browse to the URL, enter the code, and authenticate with Microsoft Entra ID. If the user + authenticates successfully, the credential receives an access token. + + This credential is primarily useful for authenticating a user in an environment without a web browser, such as an + SSH session. If a web browser is available, :class:`~azure.identity.InteractiveBrowserCredential` is more + convenient because it automatically opens a browser to the login page. + + :param str client_id: Client ID of the Microsoft Entra application that users will sign into. It is recommended + that developers register their applications and assign appropriate roles. For more information, + visit https://aka.ms/azsdk/identity/AppRegistrationAndRoleAssignment. If not specified, users will + authenticate to an Azure development application, which is not recommended for production scenarios. + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword str tenant_id: a Microsoft Entra tenant ID. Defaults to the "organizations" tenant, which can + authenticate work or school accounts. **Required for single-tenant applications.** + :keyword int timeout: seconds to wait for the user to authenticate. Defaults to the validity period of the + device code as set by Microsoft Entra ID, which also prevails when **timeout** is longer. + :keyword prompt_callback: A callback enabling control of how authentication + instructions are presented. Must accept arguments (``verification_uri``, ``user_code``, ``expires_on``): + + - ``verification_uri`` (str) the URL the user must visit + - ``user_code`` (str) the code the user must enter there + - ``expires_on`` (datetime.datetime) the UTC time at which the code will expire + + If this argument isn't provided, the credential will print instructions to stdout. + :paramtype prompt_callback: Callable[str, str, ~datetime.datetime] + :keyword AuthenticationRecord authentication_record: :class:`AuthenticationRecord` returned by :func:`authenticate` + :keyword bool disable_automatic_authentication: if True, :func:`get_token` will raise + :class:`AuthenticationRequiredError` when user interaction is required to acquire a token. Defaults to False. + :keyword cache_persistence_options: configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword bool disable_instance_discovery: Determines whether or not instance discovery is performed when attempting + to authenticate. Setting this to true will completely disable both instance discovery and authority validation. + This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in + private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from + https://login.microsoft.com/ to validate the authority. By setting this to **True**, the validation of the + authority is disabled. As a result, it is crucial to ensure that the configured authority host is valid and + trustworthy. + :keyword bool enable_support_logging: Enables additional support logging in the underlying MSAL library. + This logging potentially contains personally identifiable information and is intended to be used only for + troubleshooting purposes. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_device_code_credential] + :end-before: [END create_device_code_credential] + :language: python + :dedent: 4 + :caption: Create a DeviceCodeCredential. + """ + + def __init__( + self, + client_id: str = DEVELOPER_SIGN_ON_CLIENT_ID, + *, + timeout: Optional[int] = None, + prompt_callback: Optional[Callable[[str, str, datetime], None]] = None, + **kwargs: Any + ) -> None: + self._timeout = timeout + self._prompt_callback = prompt_callback + super(DeviceCodeCredential, self).__init__(client_id=client_id, **kwargs) + + @wrap_exceptions + def _request_token(self, *scopes: str, **kwargs: Any) -> Dict: + # MSAL requires scopes be a list + scopes = list(scopes) # type: ignore + + app = self._get_app(**kwargs) + flow = app.initiate_device_flow(scopes) + if "error" in flow: + raise ClientAuthenticationError( + message="Couldn't begin authentication: {}".format(flow.get("error_description") or flow.get("error")) + ) + if self._prompt_callback: + self._prompt_callback( + flow["verification_uri"], flow["user_code"], datetime.fromtimestamp(flow["expires_at"], timezone.utc) + ) + else: + print(flow["message"]) + + if self._timeout is not None and self._timeout < flow["expires_in"]: + # user specified an effective timeout we will observe + deadline = int(time.time()) + self._timeout + result = app.acquire_token_by_device_flow( + flow, exit_condition=lambda flow: time.time() > deadline, claims_challenge=kwargs.get("claims") + ) + else: + # MSAL will stop polling when the device code expires + result = app.acquire_token_by_device_flow(flow, claims_challenge=kwargs.get("claims")) + + # raise for a timeout here because the error is particular to this class + if "access_token" not in result and result.get("error") == "authorization_pending": + raise ClientAuthenticationError(message="Timed out waiting for user to authenticate") + + # base class will raise for other errors + return result diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/environment.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/environment.py new file mode 100644 index 00000000000..8f87a1d9ff9 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/environment.py @@ -0,0 +1,183 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import Optional, Union, Any, cast +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions, SupportsTokenInfo + +from .. import CredentialUnavailableError +from .._constants import EnvironmentVariables +from .._internal.decorators import log_get_token +from .certificate import CertificateCredential +from .client_secret import ClientSecretCredential +from .user_password import UsernamePasswordCredential + +EnvironmentCredentialTypes = Union[CertificateCredential, ClientSecretCredential, UsernamePasswordCredential] + +_LOGGER = logging.getLogger(__name__) + + +class EnvironmentCredential: + """A credential configured by environment variables. + + This credential is capable of authenticating as a service principal using a client secret or a certificate, or as + a user with a username and password. Configuration is attempted in this order, using these environment variables: + + Service principal with secret: + - **AZURE_TENANT_ID**: ID of the service principal's tenant. Also called its 'directory' ID. + - **AZURE_CLIENT_ID**: the service principal's client ID + - **AZURE_CLIENT_SECRET**: one of the service principal's client secrets + - **AZURE_AUTHORITY_HOST**: authority of a Microsoft Entra endpoint, for example + "login.microsoftonline.com", the authority for Azure Public Cloud, which is the default + when no value is given. + + Service principal with certificate: + - **AZURE_TENANT_ID**: ID of the service principal's tenant. Also called its 'directory' ID. + - **AZURE_CLIENT_ID**: the service principal's client ID + - **AZURE_CLIENT_CERTIFICATE_PATH**: path to a PEM or PKCS12 certificate file including the private key. + - **AZURE_CLIENT_CERTIFICATE_PASSWORD**: (optional) password of the certificate file, if any. + - **AZURE_CLIENT_SEND_CERTIFICATE_CHAIN**: (optional) If True, the credential will send the public certificate + chain in the x5c header of each token request's JWT. This is required for Subject Name/Issuer (SNI) + authentication. Defaults to False. + - **AZURE_AUTHORITY_HOST**: authority of a Microsoft Entra endpoint, for example + "login.microsoftonline.com", the authority for Azure Public Cloud, which is the default + when no value is given. + + User with username and password: + - **AZURE_CLIENT_ID**: the application's client ID + - **AZURE_USERNAME**: a username (usually an email address) + - **AZURE_PASSWORD**: that user's password + - **AZURE_TENANT_ID**: (optional) ID of the service principal's tenant. Also called its 'directory' ID. + If not provided, defaults to the 'organizations' tenant, which supports only Microsoft Entra work or + school accounts. + - **AZURE_AUTHORITY_HOST**: authority of a Microsoft Entra endpoint, for example + "login.microsoftonline.com", the authority for Azure Public Cloud, which is the default + when no value is given. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_environment_credential] + :end-before: [END create_environment_credential] + :language: python + :dedent: 4 + :caption: Create an EnvironmentCredential. + """ + + def __init__(self, **kwargs: Any) -> None: + self._credential: Optional[EnvironmentCredentialTypes] = None + + if all(os.environ.get(v) is not None for v in EnvironmentVariables.CLIENT_SECRET_VARS): + self._credential = ClientSecretCredential( + client_id=os.environ[EnvironmentVariables.AZURE_CLIENT_ID], + client_secret=os.environ[EnvironmentVariables.AZURE_CLIENT_SECRET], + tenant_id=os.environ[EnvironmentVariables.AZURE_TENANT_ID], + **kwargs + ) + elif all(os.environ.get(v) is not None for v in EnvironmentVariables.CERT_VARS): + self._credential = CertificateCredential( + client_id=os.environ[EnvironmentVariables.AZURE_CLIENT_ID], + tenant_id=os.environ[EnvironmentVariables.AZURE_TENANT_ID], + certificate_path=os.environ[EnvironmentVariables.AZURE_CLIENT_CERTIFICATE_PATH], + password=os.environ.get(EnvironmentVariables.AZURE_CLIENT_CERTIFICATE_PASSWORD), + send_certificate_chain=bool( + os.environ.get(EnvironmentVariables.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN, False) + ), + **kwargs + ) + elif all(os.environ.get(v) is not None for v in EnvironmentVariables.USERNAME_PASSWORD_VARS): + self._credential = UsernamePasswordCredential( + client_id=os.environ[EnvironmentVariables.AZURE_CLIENT_ID], + username=os.environ[EnvironmentVariables.AZURE_USERNAME], + password=os.environ[EnvironmentVariables.AZURE_PASSWORD], + tenant_id=os.environ.get(EnvironmentVariables.AZURE_TENANT_ID), # optional for username/password auth + **kwargs + ) + + if self._credential: + _LOGGER.info("Environment is configured for %s", self._credential.__class__.__name__) + else: + expected_variables = set( + EnvironmentVariables.CERT_VARS + + EnvironmentVariables.CLIENT_SECRET_VARS + + EnvironmentVariables.USERNAME_PASSWORD_VARS + ) + set_variables = [v for v in expected_variables if v in os.environ] + if set_variables: + _LOGGER.log( + logging.INFO if kwargs.get("_within_dac") else logging.WARNING, + "Incomplete environment configuration for EnvironmentCredential. These variables are set: %s", + ", ".join(set_variables), + ) + else: + _LOGGER.info("No environment configuration found.") + + def __enter__(self) -> "EnvironmentCredential": + if self._credential: + self._credential.__enter__() + return self + + def __exit__(self, *args: Any) -> None: + if self._credential: + self._credential.__exit__(*args) + + def close(self) -> None: + """Close the credential's transport session.""" + self.__exit__() + + @log_get_token + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + + :raises ~azure.identity.CredentialUnavailableError: environment variable configuration is incomplete + """ + if not self._credential: + message = ( + "EnvironmentCredential authentication unavailable. Environment variables are not fully configured.\n" + "Visit https://aka.ms/azsdk/python/identity/environmentcredential/troubleshoot to troubleshoot " + "this issue." + ) + raise CredentialUnavailableError(message=message) + return self._credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + @log_get_token + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scope for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + + :raises ~azure.identity.CredentialUnavailableError: environment variable configuration is incomplete. + """ + if not self._credential: + message = ( + "EnvironmentCredential authentication unavailable. Environment variables are not fully configured.\n" + "Visit https://aka.ms/azsdk/python/identity/environmentcredential/troubleshoot to troubleshoot " + "this issue." + ) + raise CredentialUnavailableError(message=message) + return cast(SupportsTokenInfo, self._credential).get_token_info(*scopes, options=options) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/imds.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/imds.py new file mode 100644 index 00000000000..6528f23b83e --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/imds.py @@ -0,0 +1,129 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +import json +from typing import Any, Optional, Dict + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError +from azure.core.pipeline.transport import HttpRequest +from azure.core.credentials import AccessTokenInfo + +from .. import CredentialUnavailableError +from .._constants import EnvironmentVariables +from .._internal import within_credential_chain +from .._internal.managed_identity_client import ManagedIdentityClient +from .._internal.msal_managed_identity_client import MsalManagedIdentityClient + + +IMDS_AUTHORITY = "http://169.254.169.254" +IMDS_TOKEN_PATH = "/metadata/identity/oauth2/token" + +PIPELINE_SETTINGS = { + "connection_timeout": 2, + # Five retries, with each retry sleeping for [0.0s, 1.6s, 3.2s, 6.4s, 12.8s] between attempts. + "retry_backoff_factor": 0.8, + "retry_backoff_max": 60, + "retry_on_status_codes": [404, 410, 429] + list(range(500, 600)), + "retry_status": 5, + "retry_total": 5, +} + + +def _get_request(scope: str, identity_config: Dict) -> HttpRequest: + url = ( + os.environ.get(EnvironmentVariables.AZURE_POD_IDENTITY_AUTHORITY_HOST, IMDS_AUTHORITY).strip("/") + + IMDS_TOKEN_PATH + ) + request = HttpRequest("GET", url) + request.format_parameters(dict({"api-version": "2018-02-01", "resource": scope}, **identity_config)) + return request + + +def _check_forbidden_response(ex: HttpResponseError) -> None: + """Special case handling for Docker Desktop. + + Docker Desktop proxies all HTTP traffic, and if the IMDS endpoint is unreachable, it + responds with a 403 with a message that contains "unreachable". + + :param ~azure.core.exceptions.HttpResponseError ex: The exception raised by the request + :raises ~azure.core.exceptions.CredentialUnavailableError: When the IMDS endpoint is unreachable + """ + if ex.status_code == 403: + if ex.message and "unreachable" in ex.message: + error_message = f"ManagedIdentityCredential authentication unavailable. Error: {ex.message}" + raise CredentialUnavailableError(message=error_message) from ex + + +class ImdsCredential(MsalManagedIdentityClient): + def __init__(self, **kwargs: Any) -> None: + super(ImdsCredential, self).__init__(**kwargs) + self._config = kwargs + + if EnvironmentVariables.AZURE_POD_IDENTITY_AUTHORITY_HOST in os.environ: + self._endpoint_available: Optional[bool] = True + else: + self._endpoint_available = None + + def __enter__(self) -> "ImdsCredential": + self._client.__enter__() + return self + + def __exit__(self, *args): + self._client.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + + if within_credential_chain.get() and not self._endpoint_available: + # If within a chain (e.g. DefaultAzureCredential), we do a quick check to see if the IMDS endpoint + # is available to avoid hanging for a long time if the endpoint isn't available. + try: + client = ManagedIdentityClient(_get_request, **dict(PIPELINE_SETTINGS, **self._config)) + client.request_token(*scopes, connection_timeout=1, retry_total=0) + self._endpoint_available = True + except HttpResponseError as ex: + # IMDS responded + _check_forbidden_response(ex) + self._endpoint_available = True + except Exception as ex: # pylint:disable=broad-except + error_message = ( + "ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint." + ) + raise CredentialUnavailableError(error_message) from ex + + try: + token_info = super()._request_token(*scopes) + except CredentialUnavailableError: + # Response is not json, skip the IMDS credential + raise + except HttpResponseError as ex: + # 400 in response to a token request indicates managed identity is disabled, + # or the identity with the specified client_id is not available + if ex.status_code == 400: + error_message = ( + "ManagedIdentityCredential authentication unavailable. " + "No identity has been assigned to this resource." + ) + + if ex.message: + error_message += f" Error: {ex.message}" + + raise CredentialUnavailableError(message=error_message) from ex + + _check_forbidden_response(ex) + # any other error is unexpected + raise ClientAuthenticationError(message=ex.message, response=ex.response) from ex + except json.decoder.JSONDecodeError as ex: + raise CredentialUnavailableError(message="ManagedIdentityCredential authentication unavailable.") from ex + except Exception as ex: # pylint:disable=broad-except + # if anything else was raised, assume the endpoint is unavailable + error_message = "ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint." + raise CredentialUnavailableError(error_message) from ex + return token_info + + def get_unavailable_message(self, desc: str = "") -> str: + return f"ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint. {desc}" diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/managed_identity.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/managed_identity.py new file mode 100644 index 00000000000..dd6409cb7da --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/managed_identity.py @@ -0,0 +1,185 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import Optional, Any, Mapping, cast + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions, TokenCredential, SupportsTokenInfo +from .. import CredentialUnavailableError +from .._constants import EnvironmentVariables +from .._internal.decorators import log_get_token + + +_LOGGER = logging.getLogger(__name__) + + +def validate_identity_config(client_id: Optional[str], identity_config: Optional[Mapping[str, str]]) -> None: + if identity_config: + if client_id: + if any(key in identity_config for key in ("object_id", "resource_id", "client_id")): + raise ValueError( + "identity_config must not contain 'object_id', 'resource_id', or 'client_id' when 'client_id' is " + "provided as a keyword argument." + ) + # Only one of these keys should be present if one is present. + valid_keys = {"object_id", "resource_id", "client_id"} + if len(identity_config.keys() & valid_keys) > 1: + raise ValueError( + f"identity_config must not contain more than one of the following keys: {', '.join(valid_keys)}" + ) + + +class ManagedIdentityCredential: + """Authenticates with an Azure managed identity in any hosting environment which supports managed identities. + + This credential defaults to using a system-assigned identity. To configure a user-assigned identity, use one of + the keyword arguments. See `Microsoft Entra ID documentation + `__ for more + information about configuring managed identity for applications. + + :keyword str client_id: a user-assigned identity's client ID or, when using Pod Identity, the client ID of a + Microsoft Entra app registration. This argument is supported in all hosting environments. + :keyword identity_config: a mapping ``{parameter_name: value}`` specifying a user-assigned identity by its object + or resource ID, for example ``{"object_id": "..."}``. Check the documentation for your hosting environment to + learn what values it expects. + :paramtype identity_config: Mapping[str, str] + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_managed_identity_credential] + :end-before: [END create_managed_identity_credential] + :language: python + :dedent: 4 + :caption: Create a ManagedIdentityCredential. + """ + + def __init__( + self, *, client_id: Optional[str] = None, identity_config: Optional[Mapping[str, str]] = None, **kwargs: Any + ) -> None: + validate_identity_config(client_id, identity_config) + self._credential: Optional[SupportsTokenInfo] = None + exclude_workload_identity = kwargs.pop("_exclude_workload_identity_credential", False) + if os.environ.get(EnvironmentVariables.IDENTITY_ENDPOINT): + if os.environ.get(EnvironmentVariables.IDENTITY_HEADER): + if os.environ.get(EnvironmentVariables.IDENTITY_SERVER_THUMBPRINT): + _LOGGER.info("%s will use Service Fabric managed identity", self.__class__.__name__) + from .service_fabric import ServiceFabricCredential + + self._credential = ServiceFabricCredential( + client_id=client_id, identity_config=identity_config, **kwargs + ) + else: + _LOGGER.info("%s will use App Service managed identity", self.__class__.__name__) + from .app_service import AppServiceCredential + + self._credential = AppServiceCredential( + client_id=client_id, identity_config=identity_config, **kwargs + ) + elif os.environ.get(EnvironmentVariables.IMDS_ENDPOINT): + _LOGGER.info("%s will use Azure Arc managed identity", self.__class__.__name__) + from .azure_arc import AzureArcCredential + + self._credential = AzureArcCredential(client_id=client_id, identity_config=identity_config, **kwargs) + elif os.environ.get(EnvironmentVariables.MSI_ENDPOINT): + if os.environ.get(EnvironmentVariables.MSI_SECRET): + _LOGGER.info("%s will use Azure ML managed identity", self.__class__.__name__) + from .azure_ml import AzureMLCredential + + self._credential = AzureMLCredential(client_id=client_id, identity_config=identity_config, **kwargs) + else: + _LOGGER.info("%s will use Cloud Shell managed identity", self.__class__.__name__) + from .cloud_shell import CloudShellCredential + + self._credential = CloudShellCredential(client_id=client_id, identity_config=identity_config, **kwargs) + elif ( + all(os.environ.get(var) for var in EnvironmentVariables.WORKLOAD_IDENTITY_VARS) + and not exclude_workload_identity + ): + _LOGGER.info("%s will use workload identity", self.__class__.__name__) + from .workload_identity import WorkloadIdentityCredential + + workload_client_id = client_id or os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + if not workload_client_id: + raise ValueError('Configure the environment with a client ID or pass a value for "client_id" argument') + + self._credential = WorkloadIdentityCredential( + tenant_id=os.environ[EnvironmentVariables.AZURE_TENANT_ID], + client_id=workload_client_id, + token_file_path=os.environ[EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE], + **kwargs, + ) + else: + from .imds import ImdsCredential + + _LOGGER.info("%s will use IMDS", self.__class__.__name__) + self._credential = ImdsCredential(client_id=client_id, identity_config=identity_config, **kwargs) + + def __enter__(self) -> "ManagedIdentityCredential": + if self._credential: + self._credential.__enter__() # type: ignore + return self + + def __exit__(self, *args: Any) -> None: + if self._credential: + self._credential.__exit__(*args) # type: ignore + + def close(self) -> None: + """Close the credential's transport session.""" + self.__exit__() + + @log_get_token + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: not used by this credential; any value provided will be ignored. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: managed identity isn't available in the hosting environment + """ + + if not self._credential: + raise CredentialUnavailableError( + message="No managed identity endpoint found. \n" + "The Target Azure platform could not be determined from environment variables. \n" + "Visit https://aka.ms/azsdk/python/identity/managedidentitycredential/troubleshoot to " + "troubleshoot this issue." + ) + return cast(TokenCredential, self._credential).get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + @log_get_token + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + :raises ~azure.identity.CredentialUnavailableError: managed identity isn't available in the hosting environment. + """ + if not self._credential: + raise CredentialUnavailableError( + message="No managed identity endpoint found. \n" + "The Target Azure platform could not be determined from environment variables. \n" + "Visit https://aka.ms/azsdk/python/identity/managedidentitycredential/troubleshoot to " + "troubleshoot this issue." + ) + return cast(SupportsTokenInfo, self._credential).get_token_info(*scopes, options=options) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/on_behalf_of.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/on_behalf_of.py new file mode 100644 index 00000000000..ae3f92e5b59 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/on_behalf_of.py @@ -0,0 +1,168 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import time +from typing import Any, Optional, Callable, Union, Dict + +import msal + +from azure.core.credentials import AccessTokenInfo +from azure.core.exceptions import ClientAuthenticationError + +from .certificate import get_client_credential +from .._internal.decorators import wrap_exceptions +from .._internal.get_token_mixin import GetTokenMixin +from .._internal.interactive import _build_auth_record +from .._internal.msal_credentials import MsalCredential +from .. import AuthenticationRecord + + +class OnBehalfOfCredential(MsalCredential, GetTokenMixin): + """Authenticates a service principal via the on-behalf-of flow. + + This flow is typically used by middle-tier services that authorize requests to other services with a delegated + user identity. Because this is not an interactive authentication flow, an application using it must have admin + consent for any delegated permissions before requesting tokens for them. See `Microsoft Entra ID documentation + `__ for a more detailed + description of the on-behalf-of flow. + + :param str tenant_id: ID of the service principal's tenant. Also called its "directory" ID. + :param str client_id: The service principal's client ID. + :keyword str client_secret: Optional. A client secret to authenticate the service principal. + One of **client_secret**, **client_certificate**, or **client_assertion_func** must be provided. + :keyword bytes client_certificate: Optional. The bytes of a certificate in PEM or PKCS12 format including + the private key to authenticate the service principal. One of **client_secret**, **client_certificate**, + or **client_assertion_func** must be provided. + :keyword client_assertion_func: Optional. Function that returns client assertions that authenticate the + application to Microsoft Entra ID. This function is called each time the credential requests a token. It must + return a valid assertion for the target resource. + :paramtype client_assertion_func: Callable[[], str] + :keyword str user_assertion: Required. The access token the credential will use as the user assertion when + requesting on-behalf-of tokens. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword password: A certificate password. Used only when **client_certificate** is provided. If this value + is a unicode string, it will be encoded as UTF-8. If the certificate requires a different encoding, pass + appropriately encoded bytes instead. + :paramtype password: str or bytes + :keyword bool send_certificate_chain: If True when **client_certificate** is provided, the credential will send + the public certificate chain in the x5c header of each token request's JWT. This is required for Subject + Name/Issuer (SNI) authentication. Defaults to False. + :keyword bool disable_instance_discovery: Determines whether or not instance discovery is performed when attempting + to authenticate. Setting this to true will completely disable both instance discovery and authority validation. + This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in + private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from + https://login.microsoft.com/ to validate the authority. By setting this to **True**, the validation of the + authority is disabled. As a result, it is crucial to ensure that the configured authority host is valid and + trustworthy. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_on_behalf_of_credential] + :end-before: [END create_on_behalf_of_credential] + :language: python + :dedent: 4 + :caption: Create an OnBehalfOfCredential. + """ + + def __init__( + self, + tenant_id: str, + client_id: str, + *, + client_certificate: Optional[bytes] = None, + client_secret: Optional[str] = None, + client_assertion_func: Optional[Callable[[], str]] = None, + user_assertion: str, + password: Optional[Union[bytes, str]] = None, + send_certificate_chain: bool = False, + **kwargs: Any + ) -> None: + self._assertion = user_assertion + if not self._assertion: + raise TypeError('"user_assertion" must not be empty.') + + if client_assertion_func: + if client_certificate or client_secret: + raise ValueError( + "It is invalid to specify more than one of the following: " + '"client_assertion_func", "client_certificate" or "client_secret".' + ) + credential: Union[str, Dict[str, Any]] = { + "client_assertion": client_assertion_func, + } + elif client_certificate: + if client_secret: + raise ValueError('Specifying both "client_certificate" and "client_secret" is not valid.') + try: + credential = get_client_credential( + certificate_path=None, + password=password, + certificate_data=client_certificate, + send_certificate_chain=send_certificate_chain, + ) + except ValueError as ex: + # client_certificate isn't a valid cert. + message = '"client_certificate" is not a valid certificate in PEM or PKCS12 format' + raise ValueError(message) from ex + elif client_secret: + credential = client_secret + else: + raise TypeError('Either "client_certificate", "client_secret", or "client_assertion_func" must be provided') + + super(OnBehalfOfCredential, self).__init__( + client_id=client_id, client_credential=credential, tenant_id=tenant_id, **kwargs + ) + self._auth_record: Optional[AuthenticationRecord] = None + + @wrap_exceptions + def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessTokenInfo]: + if self._auth_record: + claims = kwargs.get("claims") + app = self._get_app(**kwargs) + for account in app.get_accounts(username=self._auth_record.username): + if account.get("home_account_id") != self._auth_record.home_account_id: + continue + + now = int(time.time()) + result = app.acquire_token_silent_with_error(list(scopes), account=account, claims_challenge=claims) + if result and "access_token" in result and "expires_in" in result: + refresh_on = int(result["refresh_on"]) if "refresh_on" in result else None + return AccessTokenInfo( + result["access_token"], + now + int(result["expires_in"]), + token_type=result.get("token_type", "Bearer"), + refresh_on=refresh_on, + ) + + return None + + @wrap_exceptions + def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + app: msal.ConfidentialClientApplication = self._get_app(**kwargs) + request_time = int(time.time()) + result = app.acquire_token_on_behalf_of(self._assertion, list(scopes), claims_challenge=kwargs.get("claims")) + if "access_token" not in result or "expires_in" not in result: + message = "Authentication failed: {}".format(result.get("error_description") or result.get("error")) + response = self._client.get_error_response(result) + raise ClientAuthenticationError(message=message, response=response) + + try: + self._auth_record = _build_auth_record(result) + except ClientAuthenticationError: + pass # non-fatal; we'll use the assertion again next time instead of a refresh token + + refresh_on = int(result["refresh_on"]) if "refresh_on" in result else None + return AccessTokenInfo( + result["access_token"], + request_time + int(result["expires_in"]), + token_type=result.get("token_type", "Bearer"), + refresh_on=refresh_on, + ) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/service_fabric.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/service_fabric.py new file mode 100644 index 00000000000..6478df4eb23 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/service_fabric.py @@ -0,0 +1,39 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import os +from typing import Dict, Optional, Any + +from azure.core.pipeline.transport import HttpRequest + +from .._constants import EnvironmentVariables +from .._internal.msal_managed_identity_client import MsalManagedIdentityClient + + +class ServiceFabricCredential(MsalManagedIdentityClient): + def get_unavailable_message(self, desc: str = "") -> str: + return f"Service Fabric managed identity configuration not found in environment. {desc}" + + +def _get_client_args(**kwargs: Any) -> Optional[Dict]: + url = os.environ.get(EnvironmentVariables.IDENTITY_ENDPOINT) + secret = os.environ.get(EnvironmentVariables.IDENTITY_HEADER) + thumbprint = os.environ.get(EnvironmentVariables.IDENTITY_SERVER_THUMBPRINT) + if not (url and secret and thumbprint): + # Service Fabric managed identity isn't available in this environment + return None + + return dict( + kwargs, + base_headers={"Secret": secret}, + connection_verify=False, + request_factory=functools.partial(_get_request, url), + ) + + +def _get_request(url: str, scope: str, identity_config: Dict) -> HttpRequest: + request = HttpRequest("GET", url) + request.format_parameters(dict({"api-version": "2019-07-01-preview", "resource": scope}, **identity_config)) + return request diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/shared_cache.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/shared_cache.py new file mode 100644 index 00000000000..39e895c6997 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/shared_cache.py @@ -0,0 +1,202 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Any, Optional, TypeVar, cast +from azure.core.credentials import AccessToken, TokenRequestOptions, AccessTokenInfo, SupportsTokenInfo, TokenCredential + +from .silent import SilentAuthenticationCredential +from .. import CredentialUnavailableError +from .._constants import DEVELOPER_SIGN_ON_CLIENT_ID +from .._internal import AadClient, AadClientBase +from .._internal.decorators import log_get_token +from .._internal.shared_token_cache import NO_TOKEN, SharedTokenCacheBase + + +T = TypeVar("T", bound="_SharedTokenCacheCredential") + + +class SharedTokenCacheCredential: + """Authenticates using tokens in the local cache shared between Microsoft applications. + + :param str username: Username (typically an email address) of the user to authenticate as. This is used when the + local cache contains tokens for multiple identities. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example 'login.microsoftonline.com', + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword str tenant_id: a Microsoft Entra tenant ID. Used to select an account when the cache contains + tokens for multiple identities. + :keyword AuthenticationRecord authentication_record: an authentication record returned by a user credential such as + :class:`DeviceCodeCredential` or :class:`InteractiveBrowserCredential` + :keyword cache_persistence_options: configuration for persistent token caching. If not provided, the credential + will use the persistent cache shared by Microsoft development applications + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + """ + + def __init__(self, username: Optional[str] = None, **kwargs: Any) -> None: + if "authentication_record" in kwargs: + self._credential: SupportsTokenInfo = SilentAuthenticationCredential(**kwargs) + else: + self._credential = _SharedTokenCacheCredential(username=username, **kwargs) + + def __enter__(self) -> "SharedTokenCacheCredential": + self._credential.__enter__() # type: ignore + return self + + def __exit__(self, *args: Any) -> None: + self._credential.__exit__(*args) # type: ignore + + def close(self) -> None: + """Close the credential's transport session.""" + self.__exit__() + + @log_get_token + def get_token( + self, + *scopes: str, + claims: Optional[str] = None, + tenant_id: Optional[str] = None, + enable_cae: bool = False, + **kwargs: Any, + ) -> AccessToken: + """Get an access token for `scopes` from the shared cache. + + If no access token is cached, attempt to acquire one using a cached refresh token. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure + :keyword str tenant_id: not used by this credential; any value provided will be ignored. + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested + token. Defaults to False. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: the cache is unavailable or contains insufficient user + information + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + return cast(TokenCredential, self._credential).get_token( + *scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs + ) + + @log_get_token + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + If no access token is cached, attempt to acquire one using a cached refresh token. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scope for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + :raises ~azure.identity.CredentialUnavailableError: the cache is unavailable or contains insufficient user + information. + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + return cast(SupportsTokenInfo, self._credential).get_token_info(*scopes, options=options) + + @staticmethod + def supported() -> bool: + """Whether the shared token cache is supported on the current platform. + + :return: True if the shared token cache is supported on the current platform, otherwise False. + :rtype: bool + """ + return SharedTokenCacheBase.supported() + + +class _SharedTokenCacheCredential(SharedTokenCacheBase): + """The original SharedTokenCacheCredential, which doesn't use msal.ClientApplication""" + + def __enter__(self: T) -> T: + if self._client: + self._client.__enter__() # type: ignore + return self + + def __exit__(self, *args): + if self._client: + self._client.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def get_token( + self, + *scopes: str, + claims: Optional[str] = None, + tenant_id: Optional[str] = None, + enable_cae: bool = False, + **kwargs: Any, + ) -> AccessToken: + options: TokenRequestOptions = {} + if claims: + options["claims"] = claims + if tenant_id: + options["tenant_id"] = tenant_id + options["enable_cae"] = enable_cae + + token_info = self._get_token_base(*scopes, options=options, base_method_name="get_token", **kwargs) + return AccessToken(token_info.token, token_info.expires_on) + + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + return self._get_token_base(*scopes, options=options, base_method_name="get_token_info") + + def _get_token_base( + self, + *scopes: str, + options: Optional[TokenRequestOptions] = None, + base_method_name: str = "get_token_info", + **kwargs: Any, + ) -> AccessTokenInfo: + if not scopes: + raise ValueError(f"'{base_method_name}' requires at least one scope") + + if not self._client_initialized: + self._initialize_client() + + options = options or {} + claims = options.get("claims") + tenant_id = options.get("tenant_id") + is_cae = options.get("enable_cae", False) + + token_cache = self._cae_cache if is_cae else self._cache + + # Try to load the cache if it is None. + if not token_cache: + token_cache = self._initialize_cache(is_cae=is_cae) + + # If the cache is still None, raise an error. + if not token_cache: + raise CredentialUnavailableError(message="Shared token cache unavailable") + + account = self._get_account(self._username, self._tenant_id, is_cae=is_cae) + + token = self._get_cached_access_token(scopes, account, is_cae=is_cae) + if token: + return token + + # try each refresh token, returning the first access token acquired + for refresh_token in self._get_refresh_tokens(account, is_cae=is_cae): + token = cast(AadClient, self._client).obtain_token_by_refresh_token( + scopes, refresh_token, claims=claims, tenant_id=tenant_id, enable_cae=is_cae, **kwargs + ) + return token + + raise CredentialUnavailableError(message=NO_TOKEN.format(account.get("username"))) + + def _get_auth_client(self, **kwargs: Any) -> AadClientBase: + return AadClient(client_id=DEVELOPER_SIGN_ON_CLIENT_ID, **kwargs) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/silent.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/silent.py new file mode 100644 index 00000000000..485fba665d1 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/silent.py @@ -0,0 +1,224 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import platform +import time +from typing import Dict, Optional, Any + +from msal import PublicClientApplication, TokenCache + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from azure.core.exceptions import ClientAuthenticationError + +from .. import CredentialUnavailableError +from .._internal import resolve_tenant, validate_tenant_id, within_dac +from .._internal.decorators import wrap_exceptions +from .._internal.msal_client import MsalClient +from .._internal.shared_token_cache import NO_TOKEN +from .._persistent_cache import _load_persistent_cache, TokenCachePersistenceOptions +from .. import AuthenticationRecord + + +class SilentAuthenticationCredential: + """Internal class for authenticating from the default shared cache given an AuthenticationRecord. + + :param authentication_record: an AuthenticationRecord from which to authenticate + :type authentication_record: ~azure.identity.AuthenticationRecord + :keyword str tenant_id: tenant ID of the application the credential is authenticating for. Defaults to the tenant + """ + + def __init__( + self, authentication_record: AuthenticationRecord, *, tenant_id: Optional[str] = None, **kwargs + ) -> None: + self._auth_record = authentication_record + + # authenticate in the tenant that produced the record unless "tenant_id" specifies another + self._tenant_id = tenant_id or self._auth_record.tenant_id + validate_tenant_id(self._tenant_id) + self._cache = kwargs.pop("_cache", None) + self._cae_cache = kwargs.pop("_cae_cache", None) + if self._cache or self._cae_cache: + self._custom_cache = True + else: + self._custom_cache = False + + self._cache_persistence_options = kwargs.pop("cache_persistence_options", None) + + self._client_applications: Dict[str, PublicClientApplication] = {} + self._cae_client_applications: Dict[str, PublicClientApplication] = {} + + self._additionally_allowed_tenants = kwargs.pop("additionally_allowed_tenants", []) + self._client = MsalClient(**kwargs) + + def __enter__(self) -> "SilentAuthenticationCredential": + self._client.__enter__() + return self + + def __exit__(self, *args): + self._client.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def get_token( + self, + *scopes: str, + claims: Optional[str] = None, + tenant_id: Optional[str] = None, + enable_cae: bool = False, + **kwargs: Any, + ) -> AccessToken: + options: TokenRequestOptions = {} + if claims: + options["claims"] = claims + if tenant_id: + options["tenant_id"] = tenant_id + options["enable_cae"] = enable_cae + + token_info = self._get_token_base(*scopes, options=options, base_method_name="get_token", **kwargs) + return AccessToken(token_info.token, token_info.expires_on) + + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + return self._get_token_base(*scopes, options=options, base_method_name="get_token_info") + + def _get_token_base( + self, + *scopes: str, + options: Optional[TokenRequestOptions] = None, + base_method_name: str = "get_token_info", + **kwargs: Any, + ) -> AccessTokenInfo: + + if not scopes: + raise ValueError(f"'{base_method_name}' requires at least one scope") + + options = options or {} + claims = options.get("claims") + tenant_id = options.get("tenant_id") + enable_cae = options.get("enable_cae", False) + + token_cache = self._cae_cache if enable_cae else self._cache + + # Try to load the cache if it is None. + if not token_cache: + token_cache = self._initialize_cache(is_cae=enable_cae) + + # If the cache is still None, raise an error. + if not token_cache: + if within_dac.get(): + raise CredentialUnavailableError(message="Shared token cache unavailable") + raise ClientAuthenticationError(message="Shared token cache unavailable") + + return self._acquire_token_silent(*scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs) + + def _initialize_cache(self, is_cae: bool = False) -> Optional[TokenCache]: + + # If no cache options were provided, the default cache will be used. This credential accepts the + # user's default cache regardless of whether it's encrypted. It doesn't create a new cache. If the + # default cache exists, the user must have created it earlier. If it's unencrypted, the user must + # have allowed that. + cache_options = self._cache_persistence_options or TokenCachePersistenceOptions(allow_unencrypted_storage=True) + + if platform.system() not in {"Darwin", "Linux", "Windows"}: + raise CredentialUnavailableError(message="Shared token cache is not supported on this platform.") + + if not self._cache and not is_cae: + try: + self._cache = _load_persistent_cache(cache_options, is_cae) + except Exception: # pylint:disable=broad-except + return None + + if not self._cae_cache and is_cae: + try: + self._cae_cache = _load_persistent_cache(cache_options, is_cae) + except Exception: # pylint:disable=broad-except + return None + + return self._cae_cache if is_cae else self._cache + + def _get_client_application(self, **kwargs: Any): + tenant_id = resolve_tenant( + self._tenant_id, additionally_allowed_tenants=self._additionally_allowed_tenants, **kwargs + ) + + client_applications_map = self._client_applications + capabilities = None + token_cache = self._cache + + if kwargs.get("enable_cae"): + client_applications_map = self._cae_client_applications + # CP1 = can handle claims challenges (CAE) + capabilities = ["CP1"] + token_cache = self._cae_cache + + if tenant_id not in client_applications_map: + client_applications_map[tenant_id] = PublicClientApplication( + client_id=self._auth_record.client_id, + authority="https://{}/{}".format(self._auth_record.authority, tenant_id), + token_cache=token_cache, + http_client=self._client, + client_capabilities=capabilities, + ) + return client_applications_map[tenant_id] + + @wrap_exceptions + def _acquire_token_silent(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + """Silently acquire a token from MSAL. + + :param str scopes: desired scopes for the access token + :return: an access token + :rtype: ~azure.core.credentials.AccessToken + """ + + result = None + + client_application = self._get_client_application(**kwargs) + accounts_for_user = client_application.get_accounts(username=self._auth_record.username) + if not accounts_for_user: + raise CredentialUnavailableError("The cache contains no account matching the given AuthenticationRecord.") + + for account in accounts_for_user: + if account.get("home_account_id") != self._auth_record.home_account_id: + continue + + now = int(time.time()) + result = client_application.acquire_token_silent_with_error( + list(scopes), account=account, claims_challenge=kwargs.get("claims") + ) + + if result and "access_token" in result and "expires_in" in result: + refresh_on = int(result["refresh_on"]) if "refresh_on" in result else None + return AccessTokenInfo( + result["access_token"], + now + int(result["expires_in"]), + token_type=result.get("token_type", "Bearer"), + refresh_on=refresh_on, + ) + + # if we get this far, the cache contained a matching account but MSAL failed to authenticate it silently + if result: + # cache contains a matching refresh token but STS returned an error response when MSAL tried to use it + message = "Token acquisition failed" + details = result.get("error_description") or result.get("error") + if details: + message += ": {}".format(details) + raise ClientAuthenticationError(message=message) + + # cache doesn't contain a matching refresh (or access) token + raise CredentialUnavailableError(message=NO_TOKEN.format(self._auth_record.username)) + + def __getstate__(self) -> Dict[str, Any]: + state = self.__dict__.copy() + # Remove the non-picklable entries + if not self._custom_cache: + del state["_cache"] + del state["_cae_cache"] + return state + + def __setstate__(self, state: Dict[str, Any]) -> None: + self.__dict__.update(state) + # Re-create the unpickable entries + if not self._custom_cache: + self._cache = None + self._cae_cache = None diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/user_password.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/user_password.py new file mode 100644 index 00000000000..5ca7a3efc41 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/user_password.py @@ -0,0 +1,79 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Any, Dict + +from .._internal import InteractiveCredential, wrap_exceptions + + +class UsernamePasswordCredential(InteractiveCredential): + """Authenticates a user with a username and password. + + In general, Microsoft doesn't recommend this kind of authentication, because it's less secure than other + authentication flows. + + Authentication with this credential is not interactive, so it is **not compatible with any form of + multi-factor authentication or consent prompting**. The application must already have consent from the user or + a directory admin. + + This credential can only authenticate work and school accounts; Microsoft accounts are not supported. + See `Microsoft Entra ID documentation + `__ for more information about + account types. + + :param str client_id: The application's client ID + :param str username: The user's username (usually an email address) + :param str password: The user's password + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword str tenant_id: Tenant ID or a domain associated with a tenant. If not provided, defaults to the + "organizations" tenant, which supports only Microsoft Entra work or school accounts. + :keyword cache_persistence_options: Configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword bool disable_instance_discovery: Determines whether or not instance discovery is performed when attempting + to authenticate. Setting this to true will completely disable both instance discovery and authority validation. + This functionality is intended for use in scenarios where the metadata endpoint cannot be reached, such as in + private clouds or Azure Stack. The process of instance discovery entails retrieving authority metadata from + https://login.microsoft.com/ to validate the authority. By setting this to **True**, the validation of the + authority is disabled. As a result, it is crucial to ensure that the configured authority host is valid and + trustworthy. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + :keyword bool enable_support_logging: Enables additional support logging in the underlying MSAL library. + This logging potentially contains personally identifiable information and is intended to be used only for + troubleshooting purposes. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_username_password_credential] + :end-before: [END create_username_password_credential] + :language: python + :dedent: 4 + :caption: Create a UsernamePasswordCredential. + """ + + def __init__(self, client_id: str, username: str, password: str, **kwargs: Any) -> None: + # The base class will accept an AuthenticationRecord, allowing this credential to authenticate silently the + # first time it's asked for a token. However, we want to ensure this first authentication is not silent, to + # validate the given password. This class therefore doesn't document the authentication_record argument, and we + # discard it here. + kwargs.pop("authentication_record", None) + super(UsernamePasswordCredential, self).__init__(client_id=client_id, **kwargs) + self._username = username + self._password = password + + @wrap_exceptions + def _request_token(self, *scopes: str, **kwargs: Any) -> Dict: + app = self._get_app(**kwargs) + return app.acquire_token_by_username_password( + username=self._username, + password=self._password, + scopes=list(scopes), + claims_challenge=kwargs.get("claims"), + ) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/vscode.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/vscode.py new file mode 100644 index 00000000000..0c6b4a8e1b2 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/vscode.py @@ -0,0 +1,216 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +import os +import sys +from typing import cast, Any, Dict, Optional + +from azure.core.credentials import AccessToken, TokenRequestOptions, AccessTokenInfo +from azure.core.exceptions import ClientAuthenticationError +from .._exceptions import CredentialUnavailableError +from .._constants import AzureAuthorityHosts, AZURE_VSCODE_CLIENT_ID, EnvironmentVariables +from .._internal import normalize_authority, validate_tenant_id, within_dac +from .._internal.aad_client import AadClient, AadClientBase +from .._internal.get_token_mixin import GetTokenMixin +from .._internal.decorators import log_get_token + +if sys.platform.startswith("win"): + from .._internal.win_vscode_adapter import get_refresh_token, get_user_settings +elif sys.platform.startswith("darwin"): + from .._internal.macos_vscode_adapter import get_refresh_token, get_user_settings +else: + from .._internal.linux_vscode_adapter import get_refresh_token, get_user_settings + + +class _VSCodeCredentialBase(abc.ABC): + def __init__(self, **kwargs: Any) -> None: + super(_VSCodeCredentialBase, self).__init__() + + user_settings = get_user_settings() + self._cloud = user_settings.get("azure.cloud", "AzureCloud") + self._refresh_token = None + self._unavailable_reason = "" + + self._client = kwargs.get("_client") + if not self._client: + self._initialize(user_settings, **kwargs) + if not (self._client or self._unavailable_reason): + self._unavailable_reason = "Initialization failed" + + @abc.abstractmethod + def _get_client(self, **kwargs: Any) -> AadClientBase: + pass + + def _get_refresh_token(self) -> str: + if not self._refresh_token: + self._refresh_token = get_refresh_token(self._cloud) + if not self._refresh_token: + message = ( + "Failed to get Azure user details from Visual Studio Code. " + "Currently, the VisualStudioCodeCredential only works with the Azure " + "Account extension version 0.9.11 and earlier. A long-term fix is in " + "progress, see https://github.com/Azure/azure-sdk-for-python/issues/25713" + ) + raise CredentialUnavailableError(message=message) + return self._refresh_token + + def _initialize(self, vscode_user_settings: Dict, **kwargs: Any) -> None: + """Build a client from kwargs merged with VS Code user settings. + + The first stable version of this credential defaulted to Public Cloud and the "organizations" + tenant when it failed to read VS Code user settings. That behavior is preserved here. + + :param dict vscode_user_settings: VS Code user settings + """ + + # Precedence for authority: + # 1) VisualStudioCodeCredential(authority=...) + # 2) $AZURE_AUTHORITY_HOST + # 3) authority matching VS Code's "azure.cloud" setting + # 4) default: Public Cloud + authority = kwargs.pop("authority", None) or os.environ.get(EnvironmentVariables.AZURE_AUTHORITY_HOST) + if not authority: + # the application didn't specify an authority, so we figure it out from VS Code settings + if self._cloud == "AzureCloud": + authority = AzureAuthorityHosts.AZURE_PUBLIC_CLOUD + elif self._cloud == "AzureChinaCloud": + authority = AzureAuthorityHosts.AZURE_CHINA + elif self._cloud == "AzureUSGovernment": + authority = AzureAuthorityHosts.AZURE_GOVERNMENT + else: + # If the value is anything else ("AzureCustomCloud" is the only other known value), + # we need the user to provide the authority because VS Code has no setting for it and + # we can't guess confidently. + self._unavailable_reason = ( + 'VS Code is configured to use a custom cloud. Set keyword argument "authority"' + + ' with the Microsoft Entra endpoint for cloud "{}"'.format(self._cloud) + ) + return + + # Precedence for tenant ID: + # 1) VisualStudioCodeCredential(tenant_id=...) + # 2) "azure.tenant" in VS Code user settings + # 3) default: organizations + tenant_id = kwargs.pop("tenant_id", None) or vscode_user_settings.get("azure.tenant", "organizations") + validate_tenant_id(tenant_id) + if tenant_id.lower() == "adfs": + self._unavailable_reason = "VisualStudioCodeCredential authentication unavailable. ADFS is not supported." + return + + self._client = self._get_client( + authority=normalize_authority(authority), client_id=AZURE_VSCODE_CLIENT_ID, tenant_id=tenant_id, **kwargs + ) + + +class VisualStudioCodeCredential(_VSCodeCredentialBase, GetTokenMixin): + """Authenticates as the Azure user signed in to Visual Studio Code via the 'Azure Account' extension. + + It's a `known issue `_ that this credential doesn't + work with `Azure Account extension `_ + versions newer than **0.9.11**. A long-term fix to this problem is in progress. In the meantime, consider + authenticating with :class:`AzureCliCredential`. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com". + This argument is required for a custom cloud and usually unnecessary otherwise. Defaults to the authority + matching the "Azure: Cloud" setting in VS Code's user settings or, when that setting has no value, the + authority for Azure Public Cloud. + :keyword str tenant_id: ID of the tenant the credential should authenticate in. Defaults to the "Azure: Tenant" + setting in VS Code's user settings or, when that setting has no value, the "organizations" tenant, which + supports only Microsoft Entra work or school accounts. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + """ + + def __enter__(self) -> "VisualStudioCodeCredential": + if self._client: + self._client.__enter__() + return self + + def __exit__(self, *args: Any) -> None: + if self._client: + self._client.__exit__(*args) + + def close(self) -> None: + """Close the credential's transport session.""" + self.__exit__() + + @log_get_token + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes` as the user currently signed in to Visual Studio Code. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: the credential cannot retrieve user details from Visual + Studio Code + """ + if self._unavailable_reason: + error_message = ( + self._unavailable_reason + "\n" + "Visit https://aka.ms/azsdk/python/identity/vscodecredential/troubleshoot" + " to troubleshoot this issue." + ) + raise CredentialUnavailableError(message=error_message) + if within_dac.get(): + try: + token = super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + return token + except ClientAuthenticationError as ex: + raise CredentialUnavailableError(message=ex.message) from ex + return super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes` as the user currently signed in to Visual Studio Code. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + :raises ~azure.identity.CredentialUnavailableError: the credential cannot retrieve user details from Visual + Studio Code. + """ + if self._unavailable_reason: + error_message = ( + self._unavailable_reason + "\n" + "Visit https://aka.ms/azsdk/python/identity/vscodecredential/troubleshoot" + " to troubleshoot this issue." + ) + raise CredentialUnavailableError(message=error_message) + if within_dac.get(): + try: + token = super().get_token_info(*scopes, options=options) + return token + except ClientAuthenticationError as ex: + raise CredentialUnavailableError(message=ex.message) from ex + return super().get_token_info(*scopes, options=options) + + def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessTokenInfo]: + self._client = cast(AadClient, self._client) + return self._client.get_cached_access_token(scopes, **kwargs) + + def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + refresh_token = self._get_refresh_token() + self._client = cast(AadClient, self._client) + return self._client.obtain_token_by_refresh_token(scopes, refresh_token, **kwargs) + + def _get_client(self, **kwargs: Any) -> AadClient: + return AadClient(**kwargs) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/workload_identity.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/workload_identity.py new file mode 100644 index 00000000000..36749ee3f93 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_credentials/workload_identity.py @@ -0,0 +1,97 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +import time +from typing import Any +from typing import Optional + +from .client_assertion import ClientAssertionCredential +from .._constants import EnvironmentVariables + + +class TokenFileMixin: + + _token_file_path: str + + def __init__(self, **_: Any) -> None: + super(TokenFileMixin, self).__init__() + self._jwt = "" + self._last_read_time = 0 + + def _get_service_account_token(self) -> str: + now = int(time.time()) + if now - self._last_read_time > 600: + with open(self._token_file_path, encoding="utf-8") as f: + self._jwt = f.read() + self._last_read_time = now + return self._jwt + + +class WorkloadIdentityCredential(ClientAssertionCredential, TokenFileMixin): + """Authenticates using Microsoft Entra Workload ID. + + Workload identity authentication is a feature in Azure that allows applications running on virtual machines (VMs) + to access other Azure resources without the need for a service principal or managed identity. With workload + identity authentication, applications authenticate themselves using their own identity, rather than using a shared + service principal or managed identity. Under the hood, workload identity authentication uses the concept of Service + Account Credentials (SACs), which are automatically created by Azure and stored securely in the VM. By using + workload identity authentication, you can avoid the need to manage and rotate service principals or managed + identities for each application on each VM. Additionally, because SACs are created automatically and managed by + Azure, you don't need to worry about storing and securing sensitive credentials themselves. + + The WorkloadIdentityCredential supports Azure workload identity authentication on Azure Kubernetes and acquires + a token using the service account credentials available in the Azure Kubernetes environment. Refer + to `this workload identity overview `__ + for more information. + + :keyword str tenant_id: ID of the application's Microsoft Entra tenant. Also called its "directory" ID. + :keyword str client_id: The client ID of a Microsoft Entra app registration. + :keyword str token_file_path: The path to a file containing a Kubernetes service account token that authenticates + the identity. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START workload_identity_credential] + :end-before: [END workload_identity_credential] + :language: python + :dedent: 4 + :caption: Create a WorkloadIdentityCredential. + """ + + def __init__( + self, + *, + tenant_id: Optional[str] = None, + client_id: Optional[str] = None, + token_file_path: Optional[str] = None, + **kwargs: Any, + ) -> None: + tenant_id = tenant_id or os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + client_id = client_id or os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + token_file_path = token_file_path or os.environ.get(EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE) + if not tenant_id: + raise ValueError( + "'tenant_id' is required. Please pass it in or set the " + f"{EnvironmentVariables.AZURE_TENANT_ID} environment variable" + ) + if not client_id: + raise ValueError( + "'client_id' is required. Please pass it in or set the " + f"{EnvironmentVariables.AZURE_CLIENT_ID} environment variable" + ) + if not token_file_path: + raise ValueError( + "'token_file_path' is required. Please pass it in or set the " + f"{EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE} environment variable" + ) + self._token_file_path = token_file_path + super(WorkloadIdentityCredential, self).__init__( + tenant_id=tenant_id, + client_id=client_id, + func=self._get_service_account_token, + token_file_path=token_file_path, + **kwargs, + ) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_enums.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_enums.py new file mode 100644 index 00000000000..1ce876a2d0c --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_enums.py @@ -0,0 +1,67 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class RegionalAuthority(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Identifies a regional authority for authentication""" + + #: Attempt to discover the appropriate authority. This works on some Azure hosts, such as VMs and + #: Azure Functions. The non-regional authority is used when discovery fails. + AUTO_DISCOVER_REGION = "tryautodetect" + + ASIA_EAST = "eastasia" + ASIA_SOUTHEAST = "southeastasia" + AUSTRALIA_CENTRAL = "australiacentral" + AUSTRALIA_CENTRAL_2 = "australiacentral2" + AUSTRALIA_EAST = "australiaeast" + AUSTRALIA_SOUTHEAST = "australiasoutheast" + BRAZIL_SOUTH = "brazilsouth" + CANADA_CENTRAL = "canadacentral" + CANADA_EAST = "canadaeast" + CHINA_EAST = "chinaeast" + CHINA_EAST_2 = "chinaeast2" + CHINA_NORTH = "chinanorth" + CHINA_NORTH_2 = "chinanorth2" + EUROPE_NORTH = "northeurope" + EUROPE_WEST = "westeurope" + FRANCE_CENTRAL = "francecentral" + FRANCE_SOUTH = "francesouth" + GERMANY_CENTRAL = "germanycentral" + GERMANY_NORTH = "germanynorth" + GERMANY_NORTHEAST = "germanynortheast" + GERMANY_WEST_CENTRAL = "germanywestcentral" + GOVERNMENT_US_ARIZONA = "usgovarizona" + GOVERNMENT_US_DOD_CENTRAL = "usdodcentral" + GOVERNMENT_US_DOD_EAST = "usdodeast" + GOVERNMENT_US_IOWA = "usgoviowa" + GOVERNMENT_US_TEXAS = "usgovtexas" + GOVERNMENT_US_VIRGINIA = "usgovvirginia" + INDIA_CENTRAL = "centralindia" + INDIA_SOUTH = "southindia" + INDIA_WEST = "westindia" + JAPAN_EAST = "japaneast" + JAPAN_WEST = "japanwest" + KOREA_CENTRAL = "koreacentral" + KOREA_SOUTH = "koreasouth" + NORWAY_EAST = "norwayeast" + NORWAY_WEST = "norwaywest" + SOUTH_AFRICA_NORTH = "southafricanorth" + SOUTH_AFRICA_WEST = "southafricawest" + SWITZERLAND_NORTH = "switzerlandnorth" + SWITZERLAND_WEST = "switzerlandwest" + UAE_CENTRAL = "uaecentral" + UAE_NORTH = "uaenorth" + UK_SOUTH = "uksouth" + UK_WEST = "ukwest" + US_CENTRAL = "centralus" + US_EAST = "eastus" + US_EAST_2 = "eastus2" + US_NORTH_CENTRAL = "northcentralus" + US_SOUTH_CENTRAL = "southcentralus" + US_WEST = "westus" + US_WEST_2 = "westus2" + US_WEST_CENTRAL = "westcentralus" diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_exceptions.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_exceptions.py new file mode 100644 index 00000000000..f0230825b9b --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_exceptions.py @@ -0,0 +1,50 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Any, Iterable, Optional + +from azure.core.exceptions import ClientAuthenticationError + + +class CredentialUnavailableError(ClientAuthenticationError): + """The credential did not attempt to authenticate because required data or state is unavailable.""" + + +class AuthenticationRequiredError(CredentialUnavailableError): + """Interactive authentication is required to acquire a token. + + This error is raised only by interactive user credentials configured not to automatically prompt for user + interaction as needed. Its properties provide additional information that may be required to authenticate. The + control_interactive_prompts sample demonstrates handling this error by calling a credential's "authenticate" + method. + + :param str scopes: Scopes requested during the failed authentication + :param str message: An error message explaining the reason for the exception. + :param str claims: Additional claims required in the next authentication. + """ + + def __init__( + self, scopes: Iterable[str], message: Optional[str] = None, claims: Optional[str] = None, **kwargs: Any + ) -> None: + self._claims = claims + self._scopes = scopes + if not message: + message = "Interactive authentication is required to get a token. Call 'authenticate' to begin." + super(AuthenticationRequiredError, self).__init__(message=message, **kwargs) + + @property + def scopes(self) -> Iterable[str]: + """Scopes requested during the failed authentication. + + :rtype: ~typing.Iterable[str] + """ + return self._scopes + + @property + def claims(self) -> Optional[str]: + """Additional claims required in the next authentication. + + :rtype: str or None + """ + return self._claims diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/__init__.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/__init__.py new file mode 100644 index 00000000000..6bc3387d009 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/__init__.py @@ -0,0 +1,58 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from .aad_client import AadClient +from .aad_client_base import AadClientBase +from .auth_code_redirect_handler import AuthCodeRedirectServer +from .aadclient_certificate import AadClientCertificate +from .decorators import wrap_exceptions +from .interactive import InteractiveCredential +from .utils import ( + get_default_authority, + normalize_authority, + resolve_tenant, + validate_scope, + validate_subscription, + validate_tenant_id, + within_credential_chain, + within_dac, +) + + +def _scopes_to_resource(*scopes) -> str: + """Convert a AADv2 scope to an AADv1 resource. + + :param str scopes: scope to convert + :return: the first scope, converted to an AADv1 resource + :rtype: str + :raises: ValueError if scopes is empty or contains more than one scope + """ + + if len(scopes) != 1: + raise ValueError("This credential requires exactly one scope per token request.") + + resource = scopes[0] + if resource.endswith("/.default"): + resource = resource[: -len("/.default")] + + return resource + + +__all__ = [ + "_scopes_to_resource", + "AadClient", + "AadClientBase", + "AuthCodeRedirectServer", + "AadClientCertificate", + "get_default_authority", + "InteractiveCredential", + "normalize_authority", + "resolve_tenant", + "validate_scope", + "validate_subscription", + "within_credential_chain", + "within_dac", + "wrap_exceptions", + "validate_tenant_id", +] diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/aad_client.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/aad_client.py new file mode 100644 index 00000000000..02fb0c922f5 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/aad_client.py @@ -0,0 +1,77 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import time +from typing import Iterable, Union, Optional, Any + +from azure.core.credentials import AccessTokenInfo +from azure.core.pipeline import Pipeline +from azure.core.pipeline.transport import HttpRequest +from .aad_client_base import AadClientBase +from .aadclient_certificate import AadClientCertificate +from .pipeline import build_pipeline + + +class AadClient(AadClientBase): + def __enter__(self) -> "AadClient": + self._pipeline.__enter__() + return self + + def __exit__(self, *args): + self._pipeline.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def obtain_token_by_authorization_code( + self, scopes: Iterable[str], code: str, redirect_uri: str, client_secret: Optional[str] = None, **kwargs: Any + ) -> AccessTokenInfo: + request = self._get_auth_code_request( + scopes=scopes, code=code, redirect_uri=redirect_uri, client_secret=client_secret, **kwargs + ) + return self._run_pipeline(request, **kwargs) + + def obtain_token_by_client_certificate( + self, scopes: Iterable[str], certificate: AadClientCertificate, **kwargs: Any + ) -> AccessTokenInfo: + request = self._get_client_certificate_request(scopes, certificate, **kwargs) + return self._run_pipeline(request, **kwargs) + + def obtain_token_by_client_secret(self, scopes: Iterable[str], secret: str, **kwargs: Any) -> AccessTokenInfo: + request = self._get_client_secret_request(scopes, secret, **kwargs) + return self._run_pipeline(request, **kwargs) + + def obtain_token_by_jwt_assertion(self, scopes: Iterable[str], assertion: str, **kwargs: Any) -> AccessTokenInfo: + request = self._get_jwt_assertion_request(scopes, assertion, **kwargs) + return self._run_pipeline(request, **kwargs) + + def obtain_token_by_refresh_token( + self, scopes: Iterable[str], refresh_token: str, **kwargs: Any + ) -> AccessTokenInfo: + request = self._get_refresh_token_request(scopes, refresh_token, **kwargs) + return self._run_pipeline(request, **kwargs) + + def obtain_token_on_behalf_of( + self, + scopes: Iterable[str], + client_credential: Union[str, AadClientCertificate], + user_assertion: str, + **kwargs: Any + ) -> AccessTokenInfo: + # no need for an implementation, non-async OnBehalfOfCredential acquires tokens through MSAL + raise NotImplementedError() + + def _build_pipeline(self, **kwargs: Any) -> Pipeline: + return build_pipeline(**kwargs) + + def _run_pipeline(self, request: HttpRequest, **kwargs: Any) -> AccessTokenInfo: + # remove tenant_id and claims kwarg that could have been passed from credential's get_token method + # tenant_id is already part of `request` at this point + kwargs.pop("tenant_id", None) + kwargs.pop("claims", None) + kwargs.pop("client_secret", None) + enable_cae = kwargs.pop("enable_cae", False) + now = int(time.time()) + response = self._pipeline.run(request, retry_on_methods=self._POST, **kwargs) + return self._process_response(response, now, enable_cae=enable_cae, **kwargs) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/aad_client_base.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/aad_client_base.py new file mode 100644 index 00000000000..ab8137701b0 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/aad_client_base.py @@ -0,0 +1,420 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +import base64 +import json +import time +from uuid import uuid4 +from typing import TYPE_CHECKING, List, Any, Iterable, Optional, Union, Dict, cast + +from msal import TokenCache + +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.policies import ContentDecodePolicy +from azure.core.pipeline.transport import HttpRequest +from azure.core.credentials import AccessTokenInfo +from azure.core.exceptions import ClientAuthenticationError +from .utils import get_default_authority, normalize_authority, resolve_tenant +from .aadclient_certificate import AadClientCertificate +from .._persistent_cache import _load_persistent_cache + + +if TYPE_CHECKING: + from azure.core.pipeline import AsyncPipeline, Pipeline + from azure.core.pipeline.policies import AsyncHTTPPolicy, HTTPPolicy, SansIOHTTPPolicy + from azure.core.pipeline.transport import AsyncHttpTransport, HttpTransport + + PipelineType = Union[AsyncPipeline, Pipeline] + PolicyType = Union[AsyncHTTPPolicy, HTTPPolicy, SansIOHTTPPolicy] + TransportType = Union[AsyncHttpTransport, HttpTransport] + +JWT_BEARER_ASSERTION = "urn:ietf:params:oauth:client-assertion-type:jwt-bearer" + + +class AadClientBase(abc.ABC): + _POST = ["POST"] + + def __init__( + self, + tenant_id: str, + client_id: str, + authority: Optional[str] = None, + cache: Optional[TokenCache] = None, + cae_cache: Optional[TokenCache] = None, + *, + additionally_allowed_tenants: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + self._authority = normalize_authority(authority) if authority else get_default_authority() + + self._tenant_id = tenant_id + self._client_id = client_id + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + self._pipeline = self._build_pipeline(**kwargs) + + self._cache = cache + self._cae_cache = cae_cache + self._cache_options = kwargs.pop("cache_persistence_options", None) + if self._cache or self._cae_cache: + self._custom_cache = True + else: + self._custom_cache = False + + def _get_cache(self, **kwargs: Any) -> TokenCache: + cache = self._cae_cache if kwargs.get("enable_cae") else self._cache + if not cache: + cache = self._initialize_cache(is_cae=bool(kwargs.get("enable_cae"))) + return cache + + def _initialize_cache(self, is_cae: bool = False) -> TokenCache: + if self._cache_options: + if is_cae: + self._cae_cache = _load_persistent_cache(self._cache_options, is_cae) + else: + self._cache = _load_persistent_cache(self._cache_options, is_cae) + else: + if is_cae: + self._cae_cache = TokenCache() + else: + self._cache = TokenCache() + return cast(TokenCache, self._cae_cache if is_cae else self._cache) + + def get_cached_access_token(self, scopes: Iterable[str], **kwargs: Any) -> Optional[AccessTokenInfo]: + tenant = resolve_tenant( + self._tenant_id, additionally_allowed_tenants=self._additionally_allowed_tenants, **kwargs + ) + + cache = self._get_cache(**kwargs) + for token in cache.search( + TokenCache.CredentialType.ACCESS_TOKEN, + target=list(scopes), + query={"client_id": self._client_id, "realm": tenant}, + ): + expires_on = int(token["expires_on"]) + if expires_on > int(time.time()): + refresh_on = int(token["refresh_on"]) if "refresh_on" in token else None + return AccessTokenInfo( + token["secret"], expires_on, token_type=token.get("token_type", "Bearer"), refresh_on=refresh_on + ) + return None + + def get_cached_refresh_tokens(self, scopes: Iterable[str], **kwargs) -> List[Dict]: + # Assumes all cached refresh tokens belong to the same user + cache = self._get_cache(**kwargs) + return list(cache.search(TokenCache.CredentialType.REFRESH_TOKEN, target=list(scopes))) + + @abc.abstractmethod + def obtain_token_by_authorization_code(self, scopes, code, redirect_uri, client_secret=None, **kwargs): + pass + + @abc.abstractmethod + def obtain_token_by_jwt_assertion(self, scopes, assertion, **kwargs): + pass + + @abc.abstractmethod + def obtain_token_by_client_certificate(self, scopes, certificate, **kwargs): + pass + + @abc.abstractmethod + def obtain_token_by_client_secret(self, scopes, secret, **kwargs): + pass + + @abc.abstractmethod + def obtain_token_by_refresh_token(self, scopes, refresh_token, **kwargs): + pass + + @abc.abstractmethod + def obtain_token_on_behalf_of(self, scopes, client_credential, user_assertion, **kwargs): + pass + + @abc.abstractmethod + def _build_pipeline(self, **kwargs): + pass + + def _process_response(self, response: PipelineResponse, request_time: int, **kwargs) -> AccessTokenInfo: + content = response.context.get( + ContentDecodePolicy.CONTEXT_NAME + ) or ContentDecodePolicy.deserialize_from_http_generics(response.http_response) + + cache = self._get_cache(**kwargs) + if response.http_request.body.get("grant_type") == "refresh_token": + if content.get("error") == "invalid_grant": + # the request's refresh token is invalid -> evict it from the cache + cache_entries = list( + cache.search( + TokenCache.CredentialType.REFRESH_TOKEN, + query={"secret": response.http_request.body["refresh_token"]}, + ) + ) + for invalid_token in cache_entries: + cache.remove_rt(invalid_token) + if "refresh_token" in content: + # Microsoft Entra ID returned a new refresh token -> update the cache entry + cache_entries = list( + cache.search( + TokenCache.CredentialType.REFRESH_TOKEN, + query={"secret": response.http_request.body["refresh_token"]}, + ) + ) + # If the old token is in multiple cache entries, the cache is in a state we don't + # expect or know how to reason about, so we update nothing. + if len(cache_entries) == 1: + cache.update_rt(cache_entries[0], content["refresh_token"]) + del content["refresh_token"] # prevent caching a redundant entry + + _raise_for_error(response, content) + + if "expires_on" in content: + expires_on = int(content["expires_on"]) + elif "expires_in" in content: + expires_on = request_time + int(content["expires_in"]) + else: + _scrub_secrets(content) + raise ClientAuthenticationError(message="Unexpected response from Microsoft Entra ID: {}".format(content)) + + expires_in = int(content.get("expires_in") or expires_on - request_time) + if "refresh_in" not in content and expires_in >= 7200: + # MSAL TokenCache expects "refresh_in" + content["refresh_in"] = expires_in // 2 + + refresh_on = request_time + int(content["refresh_in"]) if "refresh_in" in content else None + token = AccessTokenInfo( + content["access_token"], expires_on, token_type=content.get("token_type", "Bearer"), refresh_on=refresh_on + ) + + # caching is the final step because 'add' mutates 'content' + cache.add( + event={ + "client_id": self._client_id, + "response": content, + "scope": response.http_request.body["scope"].split(), + "token_endpoint": response.http_request.url, + }, + now=request_time, + ) + + return token + + def _get_auth_code_request( + self, scopes: Iterable[str], code: str, redirect_uri: str, client_secret: Optional[str] = None, **kwargs: Any + ) -> HttpRequest: + data = { + "client_id": self._client_id, + "code": code, + "grant_type": "authorization_code", + "redirect_uri": redirect_uri, + "scope": " ".join(scopes), + } + + claims = _merge_claims_challenge_and_capabilities( + ["CP1"] if kwargs.get("enable_cae") else [], kwargs.get("claims") + ) + if claims: + data["claims"] = claims + if client_secret: + data["client_secret"] = client_secret + + request = self._post(data, **kwargs) + return request + + def _get_jwt_assertion_request(self, scopes: Iterable[str], assertion: str, **kwargs: Any) -> HttpRequest: + data = { + "client_assertion": assertion, + "client_assertion_type": JWT_BEARER_ASSERTION, + "client_id": self._client_id, + "grant_type": "client_credentials", + "scope": " ".join(scopes), + } + + claims = _merge_claims_challenge_and_capabilities( + ["CP1"] if kwargs.get("enable_cae") else [], kwargs.get("claims") + ) + if claims: + data["claims"] = claims + + request = self._post(data, **kwargs) + return request + + def _get_client_certificate_assertion(self, certificate: AadClientCertificate, **kwargs: Any) -> str: + now = int(time.time()) + header = json.dumps({"typ": "JWT", "alg": "RS256", "x5t": certificate.thumbprint}).encode("utf-8") + payload = json.dumps( + { + "jti": str(uuid4()), + "aud": self._get_token_url(**kwargs), + "iss": self._client_id, + "sub": self._client_id, + "nbf": now, + "exp": now + (60 * 30), + } + ).encode("utf-8") + jws = base64.urlsafe_b64encode(header) + b"." + base64.urlsafe_b64encode(payload) + signature = certificate.sign(jws) + jwt_bytes = jws + b"." + base64.urlsafe_b64encode(signature) + return jwt_bytes.decode("utf-8") + + def _get_client_certificate_request( + self, scopes: Iterable[str], certificate: AadClientCertificate, **kwargs: Any + ) -> HttpRequest: + assertion = self._get_client_certificate_assertion(certificate, **kwargs) + return self._get_jwt_assertion_request(scopes, assertion, **kwargs) + + def _get_client_secret_request(self, scopes: Iterable[str], secret: str, **kwargs: Any) -> HttpRequest: + data = { + "client_id": self._client_id, + "client_secret": secret, + "grant_type": "client_credentials", + "scope": " ".join(scopes), + } + + claims = _merge_claims_challenge_and_capabilities( + ["CP1"] if kwargs.get("enable_cae") else [], kwargs.get("claims") + ) + if claims: + data["claims"] = claims + + request = self._post(data, **kwargs) + return request + + def _get_on_behalf_of_request( + self, + scopes: Iterable[str], + client_credential: Union[str, AadClientCertificate, Dict[str, Any]], + user_assertion: str, + **kwargs: Any + ) -> HttpRequest: + data = { + "assertion": user_assertion, + "client_id": self._client_id, + "grant_type": "urn:ietf:params:oauth:grant-type:jwt-bearer", + "requested_token_use": "on_behalf_of", + "scope": " ".join(scopes), + } + + claims = _merge_claims_challenge_and_capabilities( + ["CP1"] if kwargs.get("enable_cae") else [], kwargs.get("claims") + ) + if claims: + data["claims"] = claims + + if isinstance(client_credential, AadClientCertificate): + data["client_assertion"] = self._get_client_certificate_assertion(client_credential) + data["client_assertion_type"] = JWT_BEARER_ASSERTION + elif isinstance(client_credential, dict): + func = client_credential["client_assertion"] + data["client_assertion"] = func() + data["client_assertion_type"] = JWT_BEARER_ASSERTION + else: + data["client_secret"] = client_credential + + request = self._post(data, **kwargs) + return request + + def _get_refresh_token_request(self, scopes: Iterable[str], refresh_token: str, **kwargs: Any) -> HttpRequest: + data = { + "grant_type": "refresh_token", + "refresh_token": refresh_token, + "scope": " ".join(scopes), + "client_id": self._client_id, + "client_info": 1, # request Microsoft Entra ID include home_account_id in its response + } + client_secret = kwargs.pop("client_secret", None) + if client_secret: + data["client_secret"] = client_secret + + claims = _merge_claims_challenge_and_capabilities( + ["CP1"] if kwargs.get("enable_cae") else [], kwargs.get("claims") + ) + if claims: + data["claims"] = claims + + request = self._post(data, **kwargs) + return request + + def _get_refresh_token_on_behalf_of_request( + self, + scopes: Iterable[str], + client_credential: Union[str, AadClientCertificate, Dict[str, Any]], + refresh_token: str, + **kwargs: Any + ) -> HttpRequest: + data = { + "grant_type": "refresh_token", + "refresh_token": refresh_token, + "scope": " ".join(scopes), + "client_id": self._client_id, + "client_info": 1, # request Microsoft Entra ID include home_account_id in its response + } + claims = _merge_claims_challenge_and_capabilities( + ["CP1"] if kwargs.get("enable_cae") else [], kwargs.get("claims") + ) + if claims: + data["claims"] = claims + + if isinstance(client_credential, AadClientCertificate): + data["client_assertion"] = self._get_client_certificate_assertion(client_credential) + data["client_assertion_type"] = JWT_BEARER_ASSERTION + elif isinstance(client_credential, dict): + func = client_credential["client_assertion"] + data["client_assertion"] = func() + data["client_assertion_type"] = JWT_BEARER_ASSERTION + else: + data["client_secret"] = client_credential + request = self._post(data, **kwargs) + return request + + def _get_token_url(self, **kwargs: Any) -> str: + tenant = resolve_tenant( + self._tenant_id, additionally_allowed_tenants=self._additionally_allowed_tenants, **kwargs + ) + return "/".join((self._authority, tenant, "oauth2/v2.0/token")) + + def _post(self, data: Dict, **kwargs: Any) -> HttpRequest: + url = self._get_token_url(**kwargs) + return HttpRequest("POST", url, data=data, headers={"Content-Type": "application/x-www-form-urlencoded"}) + + def __getstate__(self) -> Dict[str, Any]: + state = self.__dict__.copy() + # Remove the non-picklable entries + if not self._custom_cache: + del state["_cache"] + del state["_cae_cache"] + return state + + def __setstate__(self, state: Dict[str, Any]) -> None: + self.__dict__.update(state) + # Re-create the unpickable entries + if not self._custom_cache: + self._cache = None + self._cae_cache = None + + +def _merge_claims_challenge_and_capabilities(capabilities, claims_challenge): + # Represent capabilities as {"access_token": {"xms_cc": {"values": capabilities}}} + # and then merge/add it into incoming claims + if not capabilities: + return claims_challenge + claims_dict = json.loads(claims_challenge) if claims_challenge else {} + for key in ["access_token"]: + claims_dict.setdefault(key, {}).update(xms_cc={"values": capabilities}) + return json.dumps(claims_dict) + + +def _scrub_secrets(response: Dict) -> None: + for secret in ("access_token", "refresh_token"): + if secret in response: + response[secret] = "***" + + +def _raise_for_error(response: PipelineResponse, content: Dict) -> None: + if "error" not in content: + return + + _scrub_secrets(content) + if "error_description" in content: + message = "Microsoft Entra ID error '({}) {}'".format(content["error"], content["error_description"]) + else: + message = "Microsoft Entra ID error '{}'".format(content) + raise ClientAuthenticationError(message=message, response=response.http_response) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/aadclient_certificate.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/aadclient_certificate.py new file mode 100644 index 00000000000..e6371c8f2d5 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/aadclient_certificate.py @@ -0,0 +1,46 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import base64 +from typing import Optional +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import padding +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey +from cryptography.hazmat.backends import default_backend + + +class AadClientCertificate: + """Wraps 'cryptography' to provide the crypto operations AadClient requires for certificate authentication. + + :param bytes pem_bytes: bytes of a a PEM-encoded certificate including the (RSA) private key + :param bytes password: (optional) the certificate's password + """ + + def __init__(self, pem_bytes: bytes, password: Optional[bytes] = None) -> None: + private_key = serialization.load_pem_private_key(pem_bytes, password=password, backend=default_backend()) + if not isinstance(private_key, RSAPrivateKey): + raise ValueError("The certificate must have an RSA private key because RS256 is used for signing") + self._private_key = private_key + + cert = x509.load_pem_x509_certificate(pem_bytes, default_backend()) + fingerprint = cert.fingerprint(hashes.SHA1()) # nosec + self._thumbprint = base64.urlsafe_b64encode(fingerprint).decode("utf-8") + + @property + def thumbprint(self) -> str: + """The certificate's SHA1 thumbprint as a base64url-encoded string. + + :rtype: str + """ + return self._thumbprint + + def sign(self, plaintext: bytes) -> bytes: + """Sign bytes using RS256. + + :param bytes plaintext: Bytes to sign. + :return: The signature. + :rtype: bytes + """ + return self._private_key.sign(plaintext, padding.PKCS1v15(), hashes.SHA256()) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/auth_code_redirect_handler.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/auth_code_redirect_handler.py new file mode 100644 index 00000000000..7883d19dfab --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/auth_code_redirect_handler.py @@ -0,0 +1,62 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Any, Mapping + +from http.server import HTTPServer, BaseHTTPRequestHandler +from urllib.parse import parse_qs + + +class AuthCodeRedirectHandler(BaseHTTPRequestHandler): + """HTTP request handler to capture the authentication server's response. + Mostly from the Azure CLI: https://github.com/Azure/azure-cli/blob/dev/src/azure-cli-core/azure/cli/core/_profile.py + """ + + def do_GET(self): + if self.path.endswith("/favicon.ico"): # deal with legacy IE + self.send_response(204) + return + + query = self.path.split("?", 1)[-1] + parsed = parse_qs(query, keep_blank_values=True) + self.server.query_params = {k: v[0] if isinstance(v, list) and len(v) == 1 else v for k, v in parsed.items()} + + self.send_response(200) + self.send_header("Content-Type", "text/html") + self.end_headers() + + self.wfile.write(b"Authentication complete. You can close this window.") + + def log_message(self, format, *args): # pylint: disable=redefined-builtin,unused-argument + pass # this prevents server dumping messages to stdout + + +class AuthCodeRedirectServer(HTTPServer): + """HTTP server that listens for the redirect request following an authorization code authentication""" + + query_params = {} # type: Mapping[str, Any] + + def __init__(self, hostname, port, timeout): + # type: (str, int, int) -> None + HTTPServer.__init__(self, (hostname, port), AuthCodeRedirectHandler) + self.timeout = timeout + + def wait_for_redirect(self): + # type: () -> Mapping[str, Any] + while not self.query_params: + try: + self.handle_request() + except (IOError, ValueError): + # socket has been closed, probably by handle_timeout + break + + # ensure the underlying socket is closed (a no-op when the socket is already closed) + self.server_close() + + # if we timed out, this returns an empty dict + return self.query_params + + def handle_timeout(self): + """Break the request-handling loop by tearing down the server""" + self.server_close() diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/client_credential_base.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/client_credential_base.py new file mode 100644 index 00000000000..59c6dec8885 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/client_credential_base.py @@ -0,0 +1,57 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import time +from typing import Any, Optional, Dict + +from azure.core.credentials import AccessTokenInfo +from azure.core.exceptions import ClientAuthenticationError +from .get_token_mixin import GetTokenMixin + +from . import wrap_exceptions +from .msal_credentials import MsalCredential + + +def _get_known_kwargs(kwargs: Dict[str, Any]): + # Remove kwargs not expected by MSAL. These aren't typically passed by users, but this is a precaution. + known_kwargs = {"force_refresh", "authority", "correlation_id", "data"} + return {k: v for k, v in kwargs.items() if k in known_kwargs} + + +class ClientCredentialBase(MsalCredential, GetTokenMixin): + """Base class for credentials authenticating a service principal with a certificate or secret""" + + @wrap_exceptions + def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessTokenInfo]: + app = self._get_app(**kwargs) + request_time = int(time.time()) + result = app.acquire_token_silent_with_error( + list(scopes), account=None, claims_challenge=kwargs.pop("claims", None), **_get_known_kwargs(kwargs) + ) + if result and "access_token" in result and "expires_in" in result: + refresh_on = int(result["refresh_on"]) if "refresh_on" in result else None + return AccessTokenInfo( + result["access_token"], + request_time + int(result["expires_in"]), + token_type=result.get("token_type", "Bearer"), + refresh_on=refresh_on, + ) + return None + + @wrap_exceptions + def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + app = self._get_app(**kwargs) + request_time = int(time.time()) + result = app.acquire_token_for_client(list(scopes), claims_challenge=kwargs.pop("claims", None)) + if "access_token" not in result: + message = "Authentication failed: {}".format(result.get("error_description") or result.get("error")) + raise ClientAuthenticationError(message=message) + + refresh_on = int(result["refresh_on"]) if "refresh_on" in result else None + return AccessTokenInfo( + result["access_token"], + request_time + int(result["expires_in"]), + token_type=result.get("token_type", "Bearer"), + refresh_on=refresh_on, + ) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/decorators.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/decorators.py new file mode 100644 index 00000000000..ca2ef77a926 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/decorators.py @@ -0,0 +1,77 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import logging +import json +import base64 + +from azure.core.exceptions import ClientAuthenticationError + +from .utils import within_credential_chain + + +_LOGGER = logging.getLogger(__name__) + + +def log_get_token(fn): + + @functools.wraps(fn) + def wrapper(*args, **kwargs): + try: + token = fn(*args, **kwargs) + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.INFO, "%s succeeded", fn.__qualname__ + ) + if _LOGGER.isEnabledFor(logging.DEBUG): + try: + base64_meta_data = token.token.split(".")[1].encode("utf-8") + b"==" + json_bytes = base64.decodebytes(base64_meta_data) + json_string = json_bytes.decode("utf-8") + json_dict = json.loads(json_string) + upn = json_dict.get("upn", "unavailableUpn") + appid = json_dict.get("appid", "") + tid = json_dict.get("tid", "") + oid = json_dict.get("oid", "") + log_string = ( + f"[Authenticated account] Client ID: {appid}. " + f"Tenant ID: {tid}. User Principal Name: {upn}. Object ID (user): {oid}" + ) + _LOGGER.debug(log_string) + except Exception as ex: # pylint: disable=broad-except + _LOGGER.debug("Failed to log the account information: %s", ex, exc_info=True) + return token + except Exception as ex: # pylint: disable=broad-except + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.WARNING, + "%s failed: %s", + fn.__qualname__, + ex, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + raise + + return wrapper + + +def wrap_exceptions(fn): + """Prevents leaking exceptions defined outside azure-core by raising ClientAuthenticationError from them. + + :param fn: The function to wrap. + :type fn: ~typing.Callable + :return: The wrapped function. + :rtype: callable + """ + + @functools.wraps(fn) + def wrapper(*args, **kwargs): + try: + return fn(*args, **kwargs) + except ClientAuthenticationError: + raise + except Exception as ex: # pylint:disable=broad-except + auth_error = ClientAuthenticationError(message="Authentication failed: {}".format(ex)) + raise auth_error from ex + + return wrapper diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/get_token_mixin.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/get_token_mixin.py new file mode 100644 index 00000000000..16fd1ea9f9c --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/get_token_mixin.py @@ -0,0 +1,165 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +import logging +import time +from typing import Any, Optional + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from .utils import within_credential_chain +from .._constants import DEFAULT_REFRESH_OFFSET, DEFAULT_TOKEN_REFRESH_RETRY_DELAY + +_LOGGER = logging.getLogger(__name__) + + +class GetTokenMixin(abc.ABC): + def __init__(self, *args: Any, **kwargs: Any) -> None: + self._last_request_time = 0 + + # https://github.com/python/mypy/issues/5887 + super(GetTokenMixin, self).__init__(*args, **kwargs) # type: ignore + + @abc.abstractmethod + def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessTokenInfo]: + """Attempt to acquire an access token from a cache or by redeeming a refresh token. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + + :return: An access token with the desired scopes if successful; otherwise, None. + :rtype: ~azure.core.credentials.AccessTokenInfo or None + """ + + @abc.abstractmethod + def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + """Request an access token from the STS. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessTokenInfo + """ + + def _should_refresh(self, token: AccessTokenInfo) -> bool: + now = int(time.time()) + if token.refresh_on is not None and now >= token.refresh_on: + return True + if token.expires_on - now > DEFAULT_REFRESH_OFFSET: + return False + if now - self._last_request_time < DEFAULT_TOKEN_REFRESH_RETRY_DELAY: + return False + return True + + def get_token( + self, + *scopes: str, + claims: Optional[str] = None, + tenant_id: Optional[str] = None, + enable_cae: bool = False, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested + token. Defaults to False. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks + required data, state, or platform support + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + options: TokenRequestOptions = {} + if claims: + options["claims"] = claims + if tenant_id: + options["tenant_id"] = tenant_id + options["enable_cae"] = enable_cae + + token_info = self._get_token_base(*scopes, options=options, base_method_name="get_token", **kwargs) + return AccessToken(token_info.token, token_info.expires_on) + + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks + required data, state, or platform support + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + return self._get_token_base(*scopes, options=options, base_method_name="get_token_info") + + def _get_token_base( + self, + *scopes: str, + options: Optional[TokenRequestOptions] = None, + base_method_name: str = "get_token_info", + **kwargs: Any, + ) -> AccessTokenInfo: + if not scopes: + raise ValueError(f'"{base_method_name}" requires at least one scope') + + options = options or {} + claims = options.get("claims") + tenant_id = options.get("tenant_id") + enable_cae = options.get("enable_cae", False) + + try: + token = self._acquire_token_silently( + *scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs + ) + if not token: + self._last_request_time = int(time.time()) + token = self._request_token( + *scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs + ) + elif self._should_refresh(token): + try: + self._last_request_time = int(time.time()) + token = self._request_token( + *scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs + ) + except Exception: # pylint:disable=broad-except + pass + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.INFO, + "%s.%s succeeded", + self.__class__.__name__, + base_method_name, + ) + return token + + except Exception as ex: + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.WARNING, + "%s.%s failed: %s", + self.__class__.__name__, + base_method_name, + ex, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + raise diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/interactive.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/interactive.py new file mode 100644 index 00000000000..953b30dc391 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/interactive.py @@ -0,0 +1,302 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Base class for credentials using MSAL for interactive user authentication""" + +import abc +import base64 +import json +import logging +import time +from typing import Any, Optional, Iterable, Dict +from urllib.parse import urlparse + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from azure.core.exceptions import ClientAuthenticationError + +from .msal_credentials import MsalCredential +from .._auth_record import AuthenticationRecord +from .._constants import KnownAuthorities +from .._exceptions import AuthenticationRequiredError, CredentialUnavailableError +from .._internal import wrap_exceptions + +ABC = abc.ABC + +_LOGGER = logging.getLogger(__name__) + +_DEFAULT_AUTHENTICATE_SCOPES = { + "https://" + KnownAuthorities.AZURE_CHINA: ("https://management.core.chinacloudapi.cn//.default",), + "https://" + KnownAuthorities.AZURE_GOVERNMENT: ("https://management.core.usgovcloudapi.net//.default",), + "https://" + KnownAuthorities.AZURE_PUBLIC_CLOUD: ("https://management.core.windows.net//.default",), +} + + +def _decode_client_info(raw) -> str: + """Decode client info. Taken from msal.oauth2cli.oidc. + + :param str raw: base64-encoded client info + :return: decoded client info + :rtype: str + """ + + raw += "=" * (-len(raw) % 4) + raw = str(raw) # On Python 2.7, argument of urlsafe_b64decode must be str, not unicode. + return base64.urlsafe_b64decode(raw).decode("utf-8") + + +def _build_auth_record(response): + """Build an AuthenticationRecord from the result of an MSAL ClientApplication token request. + + :param response: The result of a token request + :type response: dict[str, typing.Any] + :return: An AuthenticationRecord + :rtype: ~azure.identity.AuthenticationRecord + :raises ~azure.core.exceptions.ClientAuthenticationError: If the response doesn't contain expected data + """ + + try: + id_token = response["id_token_claims"] + + if "client_info" in response: + client_info = json.loads(_decode_client_info(response["client_info"])) + home_account_id = "{uid}.{utid}".format(**client_info) + else: + # MSAL uses the subject claim as home_account_id when the STS doesn't provide client_info + home_account_id = id_token["sub"] + + # "iss" is the URL of the issuing tenant e.g. https://authority/tenant + issuer = urlparse(id_token["iss"]) + + # tenant which issued the token, not necessarily user's home tenant + tenant_id = id_token.get("tid") or issuer.path.strip("/") + + # Microsoft Entra ID returns "preferred_username", ADFS returns "upn" + username = id_token.get("preferred_username") or id_token["upn"] + + return AuthenticationRecord( + authority=issuer.netloc, + client_id=id_token["aud"], + home_account_id=home_account_id, + tenant_id=tenant_id, + username=username, + ) + except (KeyError, ValueError) as ex: + auth_error = ClientAuthenticationError( + message="Failed to build AuthenticationRecord from unexpected identity token" + ) + raise auth_error from ex + + +class InteractiveCredential(MsalCredential, ABC): + def __init__( + self, + *, + authentication_record: Optional[AuthenticationRecord] = None, + disable_automatic_authentication: bool = False, + **kwargs: Any, + ) -> None: + self._disable_automatic_authentication = disable_automatic_authentication + self._auth_record = authentication_record + if self._auth_record: + kwargs.pop("client_id", None) # authentication_record overrides client_id argument + tenant_id = kwargs.pop("tenant_id", None) or self._auth_record.tenant_id + super(InteractiveCredential, self).__init__( + client_id=self._auth_record.client_id, + authority=self._auth_record.authority, + tenant_id=tenant_id, + **kwargs, + ) + else: + super(InteractiveCredential, self).__init__(**kwargs) + + def get_token( + self, + *scopes: str, + claims: Optional[str] = None, + tenant_id: Optional[str] = None, + enable_cae: bool = False, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure + :keyword str tenant_id: optional tenant to include in the token request. + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested + token. Defaults to False. + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks + required data, state, or platform support + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + :raises AuthenticationRequiredError: user interaction is necessary to acquire a token, and the credential is + configured not to begin this automatically. Call :func:`authenticate` to begin interactive authentication. + """ + options: TokenRequestOptions = {} + if claims: + options["claims"] = claims + if tenant_id: + options["tenant_id"] = tenant_id + options["enable_cae"] = enable_cae + + token_info = self._get_token_base(*scopes, options=options, base_method_name="get_token", **kwargs) + return AccessToken(token_info.token, token_info.expires_on) + + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + + :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks + required data, state, or platform support + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + :raises AuthenticationRequiredError: user interaction is necessary to acquire a token, and the credential is + configured not to begin this automatically. Call :func:`authenticate` to begin interactive authentication. + """ + return self._get_token_base(*scopes, options=options, base_method_name="get_token_info") + + def _get_token_base( + self, + *scopes: str, + options: Optional[TokenRequestOptions] = None, + base_method_name: str = "get_token_info", + **kwargs: Any, + ) -> AccessTokenInfo: + if not scopes: + message = f"'{base_method_name}' requires at least one scope" + _LOGGER.warning("%s.%s failed: %s", self.__class__.__name__, base_method_name, message) + raise ValueError(message) + + allow_prompt = kwargs.pop("_allow_prompt", not self._disable_automatic_authentication) + options = options or {} + claims = options.get("claims") + tenant_id = options.get("tenant_id") + enable_cae = options.get("enable_cae", False) + + # Check for arbitrary additional options to enable intermediary support for PoP tokens. + for key in options: + if key not in TokenRequestOptions.__annotations__: # pylint:disable=no-member + kwargs.setdefault(key, options[key]) # type: ignore + + try: + token = self._acquire_token_silent( + *scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs + ) + _LOGGER.info("%s.%s succeeded", self.__class__.__name__, base_method_name) + return token + except Exception as ex: # pylint:disable=broad-except + if not (isinstance(ex, AuthenticationRequiredError) and allow_prompt): + _LOGGER.warning( + "%s.%s failed: %s", + self.__class__.__name__, + base_method_name, + ex, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + raise + + # silent authentication failed -> authenticate interactively + now = int(time.time()) + + try: + result = self._request_token(*scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs) + if "access_token" not in result: + message = "Authentication failed: {}".format(result.get("error_description") or result.get("error")) + response = self._client.get_error_response(result) + raise ClientAuthenticationError(message=message, response=response) + + # this may be the first authentication, or the user may have authenticated a different identity + self._auth_record = _build_auth_record(result) + except Exception as ex: # pylint:disable=broad-except + _LOGGER.warning( + "%s.%s failed: %s", + self.__class__.__name__, + base_method_name, + ex, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + raise + + _LOGGER.info("%s.%s succeeded", self.__class__.__name__, base_method_name) + refresh_on = int(result["refresh_on"]) if "refresh_on" in result else None + return AccessTokenInfo( + result["access_token"], + now + int(result["expires_in"]), + token_type=result.get("token_type", "Bearer"), + refresh_on=refresh_on, + ) + + def authenticate( + self, *, scopes: Optional[Iterable[str]] = None, claims: Optional[str] = None, **kwargs: Any + ) -> AuthenticationRecord: + """Interactively authenticate a user. This method will always generate a challenge to the user. + + :keyword Iterable[str] scopes: scopes to request during authentication, such as those provided by + :func:`AuthenticationRequiredError.scopes`. If provided, successful authentication will cache an access token + for these scopes. + :keyword str claims: additional claims required in the token, such as those provided by + :func:`AuthenticationRequiredError.claims` + :rtype: ~azure.identity.AuthenticationRecord + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + + if not scopes: + if self._authority not in _DEFAULT_AUTHENTICATE_SCOPES: + # the credential is configured to use a cloud whose ARM scope we can't determine + raise CredentialUnavailableError( + message="Authenticating in this environment requires a value for the 'scopes' keyword argument." + ) + + scopes = _DEFAULT_AUTHENTICATE_SCOPES[self._authority] + + _ = self.get_token(*scopes, _allow_prompt=True, claims=claims, **kwargs) + return self._auth_record # type: ignore + + @wrap_exceptions + def _acquire_token_silent(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + result = None + claims = kwargs.get("claims") + if self._auth_record: + app = self._get_app(**kwargs) + for account in app.get_accounts(username=self._auth_record.username): + if account.get("home_account_id") != self._auth_record.home_account_id: + continue + + now = int(time.time()) + result = app.acquire_token_silent_with_error(list(scopes), account=account, claims_challenge=claims) + if result and "access_token" in result and "expires_in" in result: + refresh_on = int(result["refresh_on"]) if "refresh_on" in result else None + return AccessTokenInfo( + result["access_token"], + now + int(result["expires_in"]), + token_type=result.get("token_type", "Bearer"), + refresh_on=refresh_on, + ) + + # if we get this far, result is either None or the content of a Microsoft Entra ID error response + if result: + response = self._client.get_error_response(result) + raise AuthenticationRequiredError(scopes, claims=claims, response=response) + raise AuthenticationRequiredError(scopes, claims=claims) + + @abc.abstractmethod + def _request_token(self, *scopes, **kwargs) -> Dict: + pass diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/linux_vscode_adapter.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/linux_vscode_adapter.py new file mode 100644 index 00000000000..d0be19f1313 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/linux_vscode_adapter.py @@ -0,0 +1,100 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +import json +import logging +import ctypes as ct +from .._constants import VSCODE_CREDENTIALS_SECTION + +_LOGGER = logging.getLogger(__name__) + + +def _c_str(string): + return ct.c_char_p(string.encode("utf-8")) + + +class _SECRET_SCHEMA_ATTRIBUTE(ct.Structure): + _fields_ = [ + ("name", ct.c_char_p), + ("type", ct.c_uint), + ] + + +class _SECRET_SCHEMA(ct.Structure): + _fields_ = [ + ("name", ct.c_char_p), + ("flags", ct.c_uint), + ("attributes", _SECRET_SCHEMA_ATTRIBUTE * 2), + ] + + +_PSECRET_SCHEMA = ct.POINTER(_SECRET_SCHEMA) + + +try: + _libsecret = ct.cdll.LoadLibrary("libsecret-1.so.0") + _libsecret.secret_password_lookup_sync.argtypes = [ + ct.c_void_p, + ct.c_void_p, + ct.c_void_p, + ct.c_char_p, + ct.c_char_p, + ct.c_char_p, + ct.c_char_p, + ct.c_void_p, + ] + _libsecret.secret_password_lookup_sync.restype = ct.c_char_p + _libsecret.secret_password_free.argtypes = [ct.c_char_p] +except OSError: + _libsecret = None # type: ignore + + +def _get_refresh_token(service_name, account_name): + if not _libsecret: + return None + + err = ct.c_int() + attributes = [_SECRET_SCHEMA_ATTRIBUTE(_c_str("service"), 0), _SECRET_SCHEMA_ATTRIBUTE(_c_str("account"), 0)] + pattributes = (_SECRET_SCHEMA_ATTRIBUTE * 2)(*attributes) + schema = _SECRET_SCHEMA() + pschema = _PSECRET_SCHEMA(schema) + ct.memset(pschema, 0, ct.sizeof(schema)) + schema.name = _c_str("org.freedesktop.Secret.Generic") # pylint: disable=attribute-defined-outside-init + schema.flags = 2 # pylint: disable=attribute-defined-outside-init + schema.attributes = pattributes # pylint: disable=attribute-defined-outside-init + p_str = _libsecret.secret_password_lookup_sync( + pschema, + None, + ct.byref(err), + _c_str("service"), + _c_str(service_name), + _c_str("account"), + _c_str(account_name), + None, + ) + if err.value == 0 and p_str: + return p_str.decode("utf-8") + + return None + + +def get_user_settings(): + try: + path = os.path.join(os.environ["HOME"], ".config", "Code", "User", "settings.json") + with open(path, encoding="utf-8") as file: + return json.load(file) + except Exception as ex: # pylint:disable=broad-except + _LOGGER.debug('Exception reading VS Code user settings: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG)) + return {} + + +def get_refresh_token(cloud_name): + try: + return _get_refresh_token(VSCODE_CREDENTIALS_SECTION, cloud_name) + except Exception as ex: # pylint:disable=broad-except + _LOGGER.debug( + 'Exception retrieving VS Code credentials: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG) + ) + return None diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/macos_vscode_adapter.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/macos_vscode_adapter.py new file mode 100644 index 00000000000..96643cd10d5 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/macos_vscode_adapter.py @@ -0,0 +1,34 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +import json +import logging +from msal_extensions.osx import Keychain, KeychainError +from .._constants import VSCODE_CREDENTIALS_SECTION + +_LOGGER = logging.getLogger(__name__) + + +def get_user_settings(): + try: + path = os.path.join(os.environ["HOME"], "Library", "Application Support", "Code", "User", "settings.json") + with open(path, encoding="utf-8") as file: + return json.load(file) + except Exception as ex: # pylint:disable=broad-except + _LOGGER.debug('Exception reading VS Code user settings: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG)) + return {} + + +def get_refresh_token(cloud_name): + try: + key_chain = Keychain() + return key_chain.get_generic_password(VSCODE_CREDENTIALS_SECTION, cloud_name) + except KeychainError: + return None + except Exception as ex: # pylint:disable=broad-except + _LOGGER.debug( + 'Exception retrieving VS Code credentials: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG) + ) + return None diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/managed_identity_base.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/managed_identity_base.py new file mode 100644 index 00000000000..949ac14a844 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/managed_identity_base.py @@ -0,0 +1,61 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +from typing import cast, Any, Optional, TypeVar + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from .. import CredentialUnavailableError +from .._internal.managed_identity_client import ManagedIdentityClient +from .._internal.get_token_mixin import GetTokenMixin + +T = TypeVar("T", bound="ManagedIdentityBase") + + +class ManagedIdentityBase(GetTokenMixin): + """Base class for internal credentials using ManagedIdentityClient""" + + def __init__(self, **kwargs: Any) -> None: + super(ManagedIdentityBase, self).__init__() + self._client = self.get_client(**kwargs) + + @abc.abstractmethod + def get_client(self, **kwargs: Any) -> Optional[ManagedIdentityClient]: + pass + + @abc.abstractmethod + def get_unavailable_message(self, desc: str = "") -> str: + pass + + def __enter__(self: T) -> T: + if self._client: + self._client.__enter__() + return self + + def __exit__(self, *args): + if self._client: + self._client.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + if not self._client: + raise CredentialUnavailableError(message=self.get_unavailable_message()) + return super(ManagedIdentityBase, self).get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + if not self._client: + raise CredentialUnavailableError(message=self.get_unavailable_message()) + return super().get_token_info(*scopes, options=options) + + def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessTokenInfo]: + # casting because mypy can't determine that these methods are called + # only by get_token, which raises when self._client is None + return cast(ManagedIdentityClient, self._client).get_cached_token(*scopes) + + def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + return cast(ManagedIdentityClient, self._client).request_token(*scopes, **kwargs) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/managed_identity_client.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/managed_identity_client.py new file mode 100644 index 00000000000..299baad23dc --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/managed_identity_client.py @@ -0,0 +1,151 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +import time +from typing import Any, Callable, Dict, Optional + +from msal import TokenCache + +from azure.core.credentials import AccessTokenInfo +from azure.core.exceptions import ClientAuthenticationError, DecodeError +from azure.core.pipeline.policies import ContentDecodePolicy +from azure.core.pipeline import PipelineResponse +from azure.core.pipeline.transport import HttpRequest +from .. import CredentialUnavailableError +from .._internal import _scopes_to_resource +from .._internal.pipeline import build_pipeline + + +class ManagedIdentityClientBase(abc.ABC): + # pylint:disable=missing-client-constructor-parameter-credential + def __init__( + self, + request_factory: Callable[[str, dict], HttpRequest], + client_id: Optional[str] = None, + identity_config: Optional[Dict] = None, + **kwargs: Any + ) -> None: + self._custom_cache = False + self._cache = kwargs.pop("_cache", None) + if self._cache: + self._custom_cache = True + else: + self._cache = TokenCache() + self._content_callback = kwargs.pop("_content_callback", None) + self._identity_config = identity_config or {} + if client_id: + self._identity_config["client_id"] = client_id + self._pipeline = self._build_pipeline(**kwargs) + self._request_factory = request_factory + + def _process_response(self, response: PipelineResponse, request_time: int) -> AccessTokenInfo: + content = response.context.get(ContentDecodePolicy.CONTEXT_NAME) + if not content: + try: + content = ContentDecodePolicy.deserialize_from_text( + response.http_response.text(), mime_type="application/json" + ) + except DecodeError as ex: + if response.http_response.content_type.startswith("application/json"): + message = "Failed to deserialize JSON from response" + raise ClientAuthenticationError(message=message, response=response.http_response) from ex + message = 'Unexpected content type "{}"'.format(response.http_response.content_type) + raise CredentialUnavailableError(message=message, response=response.http_response) from ex + + if not content: + raise ClientAuthenticationError(message="No token received.", response=response.http_response) + + if "access_token" not in content or not ("expires_in" in content or "expires_on" in content): + if content and "access_token" in content: + content["access_token"] = "****" + raise ClientAuthenticationError( + message='Unexpected response "{}"'.format(content), response=response.http_response + ) + + if self._content_callback: + self._content_callback(content) + + expires_on = int(content.get("expires_on") or int(content["expires_in"]) + request_time) + content["expires_on"] = expires_on + + expires_in = int(content.get("expires_in") or expires_on - request_time) + if "refresh_in" not in content and expires_in >= 7200: + # MSAL TokenCache expects "refresh_in" + content["refresh_in"] = expires_in // 2 + + refresh_on = request_time + int(content["refresh_in"]) if "refresh_in" in content else None + token = AccessTokenInfo( + content["access_token"], + content["expires_on"], + token_type=content.get("token_type", "Bearer"), + refresh_on=refresh_on, + ) + + # caching is the final step because TokenCache.add mutates its "event" + self._cache.add( + event={"response": content, "scope": [content["resource"]]}, + now=request_time, + ) + + return token + + def get_cached_token(self, *scopes: str) -> Optional[AccessTokenInfo]: + resource = _scopes_to_resource(*scopes) + now = time.time() + for token in self._cache.search(TokenCache.CredentialType.ACCESS_TOKEN, target=[resource]): + expires_on = int(token["expires_on"]) + refresh_on = int(token["refresh_on"]) if "refresh_on" in token else None + if expires_on > now and (not refresh_on or refresh_on > now): + return AccessTokenInfo( + token["secret"], expires_on, token_type=token.get("token_type", "Bearer"), refresh_on=refresh_on + ) + + return None + + @abc.abstractmethod + def request_token(self, *scopes, **kwargs): + pass + + @abc.abstractmethod + def _build_pipeline(self, **kwargs): + pass + + def __getstate__(self) -> Dict[str, Any]: + state = self.__dict__.copy() + # Remove the non-picklable entries + if not self._custom_cache: + del state["_cache"] + return state + + def __setstate__(self, state: Dict[str, Any]) -> None: + self.__dict__.update(state) + # Re-create the unpickable entries + if not self._custom_cache: + self._cache = TokenCache() + + +class ManagedIdentityClient(ManagedIdentityClientBase): + def __enter__(self) -> "ManagedIdentityClient": + self._pipeline.__enter__() + return self + + def __exit__(self, *args: Any) -> None: + self._pipeline.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + resource = _scopes_to_resource(*scopes) + request = self._request_factory(resource, self._identity_config) + kwargs.pop("tenant_id", None) + kwargs.pop("claims", None) + request_time = int(time.time()) + response = self._pipeline.run(request, retry_on_methods=[request.method], **kwargs) + token = self._process_response(response, request_time) + return token + + def _build_pipeline(self, **kwargs): + return build_pipeline(**kwargs) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/msal_client.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/msal_client.py new file mode 100644 index 00000000000..0726488c81e --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/msal_client.py @@ -0,0 +1,145 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import threading +from typing import Any, Dict, Optional, Union + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.pipeline.policies import ContentDecodePolicy +from azure.core.pipeline.transport import ( # pylint:disable=unknown-option-value,no-legacy-azure-core-http-response-import + HttpRequest, + HttpResponse, +) +from azure.core.pipeline import PipelineResponse +from .pipeline import build_pipeline + +RequestData = Union[Dict[str, str], str] +_POST = ["POST"] + + +class MsalResponse: + """Wraps HttpResponse according to msal.oauth2cli.http. + + :param response: The response to wrap. + :type response: ~azure.core.pipeline.transport.HttpResponse + """ + + def __init__(self, response: PipelineResponse) -> None: + self._response = response + self.headers = response.http_response.headers if response.http_response else {} + + @property + def status_code(self) -> int: + return self._response.http_response.status_code + + @property + def text(self) -> str: + return self._response.http_response.text(encoding="utf-8") + + def raise_for_status(self): + if self.status_code < 400: + return + + if ContentDecodePolicy.CONTEXT_NAME in self._response.context: + content = self._response.context[ContentDecodePolicy.CONTEXT_NAME] + if not content: + message = "Unexpected response from Microsoft Entra ID" + elif "error" in content or "error_description" in content: + message = "Authentication failed: {}".format(content.get("error_description") or content.get("error")) + else: + for secret in ("access_token", "refresh_token"): + if secret in content: + content[secret] = "***" + message = 'Unexpected response from Microsoft Entra ID: "{}"'.format(content) + else: + message = "Unexpected response from Microsoft Entra ID" + + raise ClientAuthenticationError(message=message, response=self._response.http_response) + + +class MsalClient: # pylint:disable=client-accepts-api-version-keyword + """Wraps Pipeline according to msal.oauth2cli.http""" + + def __init__(self, **kwargs: Any) -> None: # pylint:disable=missing-client-constructor-parameter-credential + self._local = threading.local() + self._pipeline = build_pipeline(**kwargs) + + def __enter__(self) -> "MsalClient": + self._pipeline.__enter__() + return self + + def __exit__(self, *args: Any) -> None: + self._pipeline.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def post( + self, + url: str, + params: Optional[Dict[str, str]] = None, + data: Optional[RequestData] = None, + headers: Optional[Dict[str, str]] = None, + **kwargs: Any + ) -> MsalResponse: + # pylint:disable=unused-argument + request = HttpRequest("POST", url, headers=headers) + if params: + request.format_parameters(params) + if data: + if isinstance(data, dict): + request.headers["Content-Type"] = "application/x-www-form-urlencoded" + request.set_formdata_body(data) + elif isinstance(data, str): + body_bytes = data.encode("utf-8") + request.set_bytes_body(body_bytes) + else: + raise ValueError('expected "data" to be text or a dict') + + response = self._pipeline.run(request, stream=False, retry_on_methods=_POST) + self._store_auth_error(response) + return MsalResponse(response) + + def get( + self, url: str, params: Optional[Dict[str, str]] = None, headers: Optional[Dict[str, str]] = None, **kwargs: Any + ) -> MsalResponse: + # pylint:disable=unused-argument + request = HttpRequest("GET", url, headers=headers) + if params: + request.format_parameters(params) + response = self._pipeline.run(request, stream=False) + self._store_auth_error(response) + return MsalResponse(response) + + def get_error_response(self, msal_result: Dict) -> Optional[HttpResponse]: + """Get the HTTP response associated with an MSAL error. + + :param msal_result: The result of an MSAL request. + :type msal_result: dict + :return: The HTTP response associated with the error, if any. + :rtype: ~azure.core.pipeline.transport.HttpResponse or None + """ + error_code, response = getattr(self._local, "error", (None, None)) + if response and error_code == msal_result.get("error"): + return response + return None + + def _store_auth_error(self, response: PipelineResponse) -> None: + if response.http_response.status_code >= 400: + # if the body doesn't contain "error", this isn't an OAuth 2 error, i.e. this isn't a + # response to an auth request, so no credential will want to include it with an exception + content = response.context.get(ContentDecodePolicy.CONTEXT_NAME) + if content and "error" in content: + self._local.error = (content["error"], response.http_response) + + def __getstate__(self) -> Dict[str, Any]: # pylint:disable=client-method-name-no-double-underscore + state = self.__dict__.copy() + # Remove the non-picklable entries + del state["_local"] + return state + + def __setstate__(self, state: Dict[str, Any]) -> None: # pylint:disable=client-method-name-no-double-underscore + self.__dict__.update(state) + # Re-create the unpickable entries + self._local = threading.local() diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/msal_credentials.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/msal_credentials.py new file mode 100644 index 00000000000..0747a571a37 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/msal_credentials.py @@ -0,0 +1,147 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +from typing import Any, List, Union, Dict, Optional +from typing_extensions import Self + +import msal + +from .msal_client import MsalClient +from .utils import get_default_authority, normalize_authority, resolve_tenant, validate_tenant_id +from .._constants import EnvironmentVariables +from .._persistent_cache import _load_persistent_cache + + +class MsalCredential: # pylint: disable=too-many-instance-attributes + """Base class for credentials wrapping MSAL applications. + + :param str client_id: the principal's client ID + :param client_credential: client credential data for the application + :type client_credential: dict + """ + + def __init__( + self, + client_id: str, + client_credential: Optional[Union[str, Dict[str, Any]]] = None, + *, + additionally_allowed_tenants: Optional[List[str]] = None, + authority: Optional[str] = None, + disable_instance_discovery: Optional[bool] = None, + tenant_id: Optional[str] = None, + enable_support_logging: Optional[bool] = None, + **kwargs: Any, + ) -> None: + self._instance_discovery = None if disable_instance_discovery is None else not disable_instance_discovery + self._authority = normalize_authority(authority) if authority else get_default_authority() + self._regional_authority = os.environ.get(EnvironmentVariables.AZURE_REGIONAL_AUTHORITY_NAME) + if self._regional_authority and self._regional_authority.lower() in ["tryautodetect", "true"]: + self._regional_authority = msal.ConfidentialClientApplication.ATTEMPT_REGION_DISCOVERY + self._tenant_id = tenant_id or "organizations" + validate_tenant_id(self._tenant_id) + self._client = MsalClient(**kwargs) + self._client_credential = client_credential + self._client_id = client_id + self._enable_support_logging = enable_support_logging + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + + self._client_applications: Dict[str, msal.ClientApplication] = {} + self._cae_client_applications: Dict[str, msal.ClientApplication] = {} + + self._cache = kwargs.pop("_cache", None) + self._cae_cache = kwargs.pop("_cae_cache", None) + if self._cache or self._cae_cache: + self._custom_cache = True + else: + self._custom_cache = False + self._cache_options = kwargs.pop("cache_persistence_options", None) + + super(MsalCredential, self).__init__() + + def __enter__(self) -> Self: + self._client.__enter__() + return self + + def __exit__(self, *args: Any) -> None: + self._client.__exit__(*args) + + def close(self) -> None: + self.__exit__() + + def _initialize_cache(self, is_cae: bool = False) -> msal.TokenCache: + if self._cache_options: + if is_cae: + self._cae_cache = _load_persistent_cache(self._cache_options, is_cae) + else: + self._cache = _load_persistent_cache(self._cache_options, is_cae) + else: + if is_cae: + self._cae_cache = msal.TokenCache() + else: + self._cache = msal.TokenCache() + + return self._cae_cache if is_cae else self._cache + + def _get_app(self, **kwargs: Any) -> msal.ClientApplication: + tenant_id = resolve_tenant( + self._tenant_id, additionally_allowed_tenants=self._additionally_allowed_tenants, **kwargs + ) + + client_applications_map = self._client_applications + capabilities = None + token_cache = self._cache + + app_class = msal.ConfidentialClientApplication if self._client_credential else msal.PublicClientApplication + + if kwargs.get("enable_cae"): + client_applications_map = self._cae_client_applications + capabilities = ["CP1"] + token_cache = self._cae_cache + + if not token_cache: + token_cache = self._initialize_cache(is_cae=bool(kwargs.get("enable_cae"))) + + if tenant_id not in client_applications_map: + try: + client_applications_map[tenant_id] = app_class( + client_id=self._client_id, + client_credential=self._client_credential, + client_capabilities=capabilities, + authority="{}/{}".format(self._authority, tenant_id), + azure_region=self._regional_authority, + token_cache=token_cache, + http_client=self._client, + instance_discovery=self._instance_discovery, + enable_pii_log=self._enable_support_logging, + ) + except ValueError as ex: + if "invalid_instance" in str(ex): + raise ValueError( # pylint: disable=raise-missing-from + f"The authority provided, {self._authority}, is not well-known. If this authority is valid " + "and trustworthy, you can disable this check by passing in " + "'disable_instance_discovery=True' when constructing the credential." + ) + raise + + return client_applications_map[tenant_id] + + def __getstate__(self) -> Dict[str, Any]: + state = self.__dict__.copy() + # Remove the non-picklable entries + del state["_client_applications"] + del state["_cae_client_applications"] + if not self._custom_cache: + del state["_cache"] + del state["_cae_cache"] + return state + + def __setstate__(self, state: Dict[str, Any]) -> None: + self.__dict__.update(state) + # Re-create the unpickable entries + self._client_applications = {} + self._cae_client_applications = {} + if not self._custom_cache: + self._cache = None + self._cae_cache = None diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/msal_managed_identity_client.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/msal_managed_identity_client.py new file mode 100644 index 00000000000..db210c5a13a --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/msal_managed_identity_client.py @@ -0,0 +1,210 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Any, Optional, Dict, cast, Union, Mapping +import abc +import time +import logging + +import msal +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from azure.core.exceptions import ClientAuthenticationError + +from .msal_client import MsalClient +from .utils import within_credential_chain +from .._internal import _scopes_to_resource +from .._exceptions import CredentialUnavailableError + +_LOGGER = logging.getLogger(__name__) + + +class MsalManagedIdentityClient(abc.ABC): # pylint:disable=client-accepts-api-version-keyword + """Base class for managed identity client wrapping MSAL ManagedIdentityClient.""" + + # pylint:disable=missing-client-constructor-parameter-credential + def __init__( + self, *, client_id: Optional[str] = None, identity_config: Optional[Mapping[str, str]] = None, **kwargs: Any + ) -> None: + self._settings = {"client_id": client_id, "identity_config": identity_config or {}} + self._client = MsalClient(**kwargs) + managed_identity = self.get_managed_identity() + self._msal_client = msal.ManagedIdentityClient(managed_identity, http_client=self._client) + + def __enter__(self) -> "MsalManagedIdentityClient": + self._client.__enter__() + return self + + def __exit__(self, *args: Any) -> None: + self._client.__exit__(*args) + + @abc.abstractmethod + def get_unavailable_message(self, desc: str = "") -> str: + pass + + def close(self) -> None: + self.__exit__() + + def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: # pylint:disable=unused-argument + if not scopes: + raise ValueError('"get_token" requires at least one scope') + resource = _scopes_to_resource(*scopes) + result = self._msal_client.acquire_token_for_client(resource=resource) + now = int(time.time()) + if result and "access_token" in result and "expires_in" in result: + refresh_on = int(result["refresh_on"]) if "refresh_on" in result else None + return AccessTokenInfo( + result["access_token"], + now + int(result["expires_in"]), + token_type=result.get("token_type", "Bearer"), + refresh_on=refresh_on, + ) + if result and "error" in result: + error_desc = cast(str, result["error"]) + error_message = self.get_unavailable_message(error_desc) + raise CredentialUnavailableError(error_message) + + def get_managed_identity(self) -> Union[msal.UserAssignedManagedIdentity, msal.SystemAssignedManagedIdentity]: + """ + Get the managed identity configuration. + + :rtype: msal.UserAssignedManagedIdentity or msal.SystemAssignedManagedIdentity + :return: The managed identity configuration. + """ + + if "client_id" in self._settings and self._settings["client_id"]: + return msal.UserAssignedManagedIdentity(client_id=self._settings["client_id"]) + identity_config = cast(Dict, self._settings.get("identity_config")) or {} + if "client_id" in identity_config and identity_config["client_id"]: + return msal.UserAssignedManagedIdentity(client_id=identity_config["client_id"]) + if "resource_id" in identity_config and identity_config["resource_id"]: + return msal.UserAssignedManagedIdentity(resource_id=identity_config["resource_id"]) + if "object_id" in identity_config and identity_config["object_id"]: + return msal.UserAssignedManagedIdentity(object_id=identity_config["object_id"]) + return msal.SystemAssignedManagedIdentity() + + def get_token( + self, + *scopes: str, + claims: Optional[str] = None, + tenant_id: Optional[str] = None, + enable_cae: bool = False, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested + token. Defaults to False. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks + required data, state, or platform support + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + options: TokenRequestOptions = {} + if claims: + options["claims"] = claims + if tenant_id: + options["tenant_id"] = tenant_id + options["enable_cae"] = enable_cae + + token_info = self._get_token_base(*scopes, options=options, base_method_name="get_token", **kwargs) + return AccessToken(token_info.token, token_info.expires_on) + + def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks + required data, state, or platform support + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + return self._get_token_base(*scopes, options=options, base_method_name="get_token_info") + + def _get_token_base( + self, + *scopes: str, + options: Optional[TokenRequestOptions] = None, + base_method_name: str = "get_token_info", + **kwargs: Any, + ) -> AccessTokenInfo: + if not scopes: + raise ValueError(f'"{base_method_name}" requires at least one scope') + _scopes_to_resource(*scopes) + token = None + + options = options or {} + claims = options.get("claims") + tenant_id = options.get("tenant_id") + enable_cae = options.get("enable_cae", False) + + try: + token = self._request_token(*scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs) + if token: + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.INFO, + "%s.%s succeeded", + self.__class__.__name__, + base_method_name, + ) + return token + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.WARNING, + "%s.%s failed", + self.__class__.__name__, + base_method_name, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + raise CredentialUnavailableError(self.get_unavailable_message()) + except msal.ManagedIdentityError as ex: + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.WARNING, + "%s.%s failed: %s", + self.__class__.__name__, + base_method_name, + ex, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + raise ClientAuthenticationError(self.get_unavailable_message(str(ex))) from ex + except Exception as ex: # pylint:disable=broad-except + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.WARNING, + "%s.%s failed: %s", + self.__class__.__name__, + base_method_name, + ex, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + raise + + def __getstate__(self) -> Dict[str, Any]: # pylint:disable=client-method-name-no-double-underscore + state = self.__dict__.copy() + # Remove the non-picklable entries + del state["_msal_client"] + return state + + def __setstate__(self, state: Dict[str, Any]) -> None: # pylint:disable=client-method-name-no-double-underscore + self.__dict__.update(state) + # Re-create the unpickable entries + managed_identity = self.get_managed_identity() + self._msal_client = msal.ManagedIdentityClient(managed_identity, http_client=self._client) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/pipeline.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/pipeline.py new file mode 100644 index 00000000000..de714e49e75 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/pipeline.py @@ -0,0 +1,94 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from azure.core.configuration import Configuration +from azure.core.pipeline import Pipeline +from azure.core.pipeline.policies import ( + ContentDecodePolicy, + CustomHookPolicy, + DistributedTracingPolicy, + HeadersPolicy, + NetworkTraceLoggingPolicy, + ProxyPolicy, + RetryPolicy, + UserAgentPolicy, + HttpLoggingPolicy, +) + + +from .user_agent import USER_AGENT + + +def _get_config(**kwargs) -> Configuration: + """Configuration common to a/sync pipelines. + + :return: A configuration object. + :rtype: ~azure.core.configuration.Configuration + """ + config: Configuration = Configuration(**kwargs) + config.custom_hook_policy = CustomHookPolicy(**kwargs) + config.headers_policy = HeadersPolicy(**kwargs) + config.http_logging_policy = HttpLoggingPolicy(**kwargs) + config.logging_policy = NetworkTraceLoggingPolicy(**kwargs) + config.proxy_policy = ProxyPolicy(**kwargs) + config.user_agent_policy = UserAgentPolicy(base_user_agent=USER_AGENT, **kwargs) + return config + + +def _get_policies(config, _per_retry_policies=None, **kwargs): + policies = [ + config.headers_policy, + config.user_agent_policy, + config.proxy_policy, + ContentDecodePolicy(**kwargs), + config.retry_policy, + ] + + if _per_retry_policies: + policies.extend(_per_retry_policies) + + policies.extend( + [ + config.custom_hook_policy, + config.logging_policy, + DistributedTracingPolicy(**kwargs), + config.http_logging_policy, + ] + ) + + return policies + + +def build_pipeline(transport=None, policies=None, **kwargs): + if not policies: + config = _get_config(**kwargs) + config.retry_policy = RetryPolicy(**kwargs) + policies = _get_policies(config, **kwargs) + if not transport: + from azure.core.pipeline.transport import ( # pylint: disable=non-abstract-transport-import, no-name-in-module + RequestsTransport, + ) + + transport = RequestsTransport(**kwargs) + + return Pipeline(transport, policies=policies) + + +def build_async_pipeline(transport=None, policies=None, **kwargs): + from azure.core.pipeline import AsyncPipeline + + if not policies: + from azure.core.pipeline.policies import AsyncRetryPolicy + + config = _get_config(**kwargs) + config.retry_policy = AsyncRetryPolicy(**kwargs) + policies = _get_policies(config, **kwargs) + if not transport: + from azure.core.pipeline.transport import ( # pylint: disable=non-abstract-transport-import, no-name-in-module + AioHttpTransport, + ) + + transport = AioHttpTransport(**kwargs) + + return AsyncPipeline(transport, policies=policies) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/shared_token_cache.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/shared_token_cache.py new file mode 100644 index 00000000000..c1c777e47d0 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/shared_token_cache.py @@ -0,0 +1,291 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +import platform +import time +from typing import Any, Iterable, List, Mapping, Optional, cast, Dict +from urllib.parse import urlparse +import msal + +from azure.core.credentials import AccessTokenInfo +from .. import CredentialUnavailableError +from .._constants import KnownAuthorities +from .._internal import get_default_authority, normalize_authority, wrap_exceptions +from .._persistent_cache import _load_persistent_cache, TokenCachePersistenceOptions +from .._internal import AadClientBase + +ABC = abc.ABC +CacheItem = Mapping[str, str] + +MULTIPLE_ACCOUNTS = """SharedTokenCacheCredential authentication unavailable. Multiple accounts +were found in the cache. Use username and tenant id to disambiguate.""" + +MULTIPLE_MATCHING_ACCOUNTS = """SharedTokenCacheCredential authentication unavailable. Multiple accounts +matching the specified{}{} were found in the cache.""" + +NO_ACCOUNTS = """SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache.""" + +NO_MATCHING_ACCOUNTS = """SharedTokenCacheCredential authentication unavailable. No account +matching the specified{}{} was found in the cache.""" + +NO_TOKEN = """Token acquisition failed for user '{}'. To fix, re-authenticate +through developer tooling supporting Azure single sign on""" + +# build a dictionary {authority: {its known aliases}}, aliases taken from MSAL.NET's KnownMetadataProvider +KNOWN_ALIASES = { + alias: aliases # N.B. aliases includes alias itself + for aliases in ( + frozenset((KnownAuthorities.AZURE_CHINA, "login.partner.microsoftonline.cn")), + frozenset((KnownAuthorities.AZURE_PUBLIC_CLOUD, "login.windows.net", "login.microsoft.com", "sts.windows.net")), + frozenset((KnownAuthorities.AZURE_GOVERNMENT, "login.usgovcloudapi.net")), + ) + for alias in aliases +} + + +def _account_to_string(account): + username = account.get("username") + home_account_id = account.get("home_account_id", "").split(".") + tenant_id = home_account_id[-1] if len(home_account_id) == 2 else "" + return "(username: {}, tenant: {})".format(username, tenant_id) + + +def _filtered_accounts( + accounts: Iterable[CacheItem], username: Optional[str] = None, tenant_id: Optional[str] = None +) -> List[CacheItem]: + """Return accounts matching username and/or tenant_id. + + :param accounts: accounts from the MSAL cache + :type accounts: Iterable[CacheItem] + :param str username: an account's username + :param str tenant_id: an account's tenant ID + :return: accounts matching username and/or tenant_id + :rtype: list[CacheItem] + """ + + filtered_accounts = [] + for account in accounts: + if username and account.get("username") != username: + continue + if tenant_id: + try: + _, tenant = account["home_account_id"].split(".") + if tenant_id != tenant: + continue + except Exception: # pylint:disable=broad-except + continue + filtered_accounts.append(account) + return filtered_accounts + + +class SharedTokenCacheBase(ABC): # pylint: disable=too-many-instance-attributes + def __init__( + self, + username: Optional[str] = None, + *, + authority: Optional[str] = None, + tenant_id: Optional[str] = None, + **kwargs: Any + ) -> None: # pylint:disable=unused-argument + self._authority = normalize_authority(authority) if authority else get_default_authority() + environment = urlparse(self._authority).netloc + self._environment_aliases = KNOWN_ALIASES.get(environment) or frozenset((environment,)) + self._username = username + self._tenant_id = tenant_id + self._cache = kwargs.pop("_cache", None) + self._cae_cache = kwargs.pop("_cae_cache", None) + if self._cache or self._cae_cache: + self._custom_cache = True + else: + self._custom_cache = False + self._cache_persistence_options = kwargs.pop("cache_persistence_options", None) + self._client_kwargs = kwargs + self._client_kwargs["tenant_id"] = "organizations" + self._client = cast(AadClientBase, None) + self._client_initialized = False + + def _initialize_client(self) -> None: + if self._client_initialized: + return + + self._client = self._get_auth_client( + authority=self._authority, cache=self._cache, cae_cache=self._cae_cache, **self._client_kwargs + ) + self._client_initialized = True + + def _initialize_cache(self, is_cae: bool = False) -> Optional[msal.TokenCache]: + + # If no cache options were provided, the default cache will be used. This credential accepts the + # user's default cache regardless of whether it's encrypted. It doesn't create a new cache. If the + # default cache exists, the user must have created it earlier. If it's unencrypted, the user must + # have allowed that. + cache_options = self._cache_persistence_options or TokenCachePersistenceOptions(allow_unencrypted_storage=True) + if not self.supported(): + raise CredentialUnavailableError(message="Shared token cache is not supported on this platform.") + + if not self._cache and not is_cae: + try: + self._cache = _load_persistent_cache(cache_options, is_cae) + self._client._cache = self._cache # pylint:disable=protected-access + except Exception: # pylint:disable=broad-except + return None + + if not self._cae_cache and is_cae: + try: + self._cae_cache = _load_persistent_cache(cache_options, is_cae) + self._client._cae_cache = self._cae_cache # pylint:disable=protected-access + except Exception: # pylint:disable=broad-except + return None + + return self._cae_cache if is_cae else self._cache + + @abc.abstractmethod + def _get_auth_client(self, **kwargs) -> AadClientBase: + pass + + def _get_cache_items_for_authority( + self, credential_type: msal.TokenCache.CredentialType, is_cae: bool = False + ) -> List[CacheItem]: + """Return cache items matching this credential's authority or one of its aliases. + + :param credential_type: the type of credential to look for in the cache + :param bool is_cae: whether to look in the CAE cache + :type credential_type: msal.TokenCache.CredentialType + :return: a list of cache items + :rtype: list[CacheItem] + """ + + cache = cast(msal.TokenCache, self._cae_cache if is_cae else self._cache) + items = [] + for item in cache.search(credential_type): + environment = item.get("environment") + if environment in self._environment_aliases: + items.append(item) + return items + + def _get_accounts_having_matching_refresh_tokens(self, is_cae: bool = False) -> Iterable[CacheItem]: + """Returns an iterable of cached accounts which have a matching refresh token. + + :param bool is_cae: whether to look in the CAE cache + :return: an iterable of cached accounts + :rtype: Iterable[CacheItem] + """ + + refresh_tokens = self._get_cache_items_for_authority(msal.TokenCache.CredentialType.REFRESH_TOKEN, is_cae) + all_accounts = self._get_cache_items_for_authority(msal.TokenCache.CredentialType.ACCOUNT, is_cae) + + accounts = {} + for refresh_token in refresh_tokens: + home_account_id = refresh_token.get("home_account_id") + if not home_account_id: + continue + for account in all_accounts: + # When the token has no family, msal.net falls back to matching client_id, + # which won't work for the shared cache because we don't know the IDs of + # all contributing apps. It should be unnecessary anyway because the + # apps should all belong to the family. + if home_account_id == account.get("home_account_id") and "family_id" in refresh_token: + accounts[account["home_account_id"]] = account + return accounts.values() + + @wrap_exceptions + def _get_account( + self, username: Optional[str] = None, tenant_id: Optional[str] = None, is_cae: bool = False + ) -> CacheItem: + """Returns exactly one account which has a refresh token and matches username and/or tenant_id. + + :param str username: an account's username + :param str tenant_id: an account's tenant ID + :param bool is_cae: whether to use the CAE cache + :return: an account + :rtype: CacheItem + """ + + accounts = self._get_accounts_having_matching_refresh_tokens(is_cae) + if not accounts: + # cache is empty or contains no refresh token -> user needs to sign in + raise CredentialUnavailableError(message=NO_ACCOUNTS) + + filtered_accounts = _filtered_accounts(accounts, username, tenant_id) + if len(filtered_accounts) == 1: + return filtered_accounts[0] + + # no, or multiple, accounts after filtering -> choose the best error message + cached_accounts = ", ".join(_account_to_string(account) for account in accounts) + if username or tenant_id: + username_string = " username: {}".format(username) if username else "" + tenant_string = " tenant: {}".format(tenant_id) if tenant_id else "" + if filtered_accounts: + message = MULTIPLE_MATCHING_ACCOUNTS.format(username_string, tenant_string) + else: + message = NO_MATCHING_ACCOUNTS.format(username_string, tenant_string) + else: + message = MULTIPLE_ACCOUNTS.format(cached_accounts) + + raise CredentialUnavailableError(message=message) + + def _get_cached_access_token( + self, scopes: Iterable[str], account: CacheItem, is_cae: bool = False + ) -> Optional[AccessTokenInfo]: + if "home_account_id" not in account: + return None + + cache = cast(msal.TokenCache, self._cae_cache if is_cae else self._cache) + try: + cache_entries = cache.search( + msal.TokenCache.CredentialType.ACCESS_TOKEN, + target=list(scopes), + query={"home_account_id": account["home_account_id"]}, + ) + for token in cache_entries: + expires_on = int(token["expires_on"]) + refresh_on = int(token["refresh_on"]) if "refresh_on" in token else None + if expires_on - 300 > int(time.time()): + return AccessTokenInfo( + token["secret"], expires_on, token_type=token.get("token_type", "Bearer"), refresh_on=refresh_on + ) + except Exception as ex: # pylint:disable=broad-except + message = "Error accessing cached data: {}".format(ex) + raise CredentialUnavailableError(message=message) from ex + + return None + + def _get_refresh_tokens(self, account, is_cae: bool = False) -> List[str]: + if "home_account_id" not in account: + return [] + + cache = cast(msal.TokenCache, self._cae_cache if is_cae else self._cache) + try: + cache_entries = cache.search( + msal.TokenCache.CredentialType.REFRESH_TOKEN, query={"home_account_id": account["home_account_id"]} + ) + return [token["secret"] for token in cache_entries if "secret" in token] + except Exception as ex: # pylint:disable=broad-except + message = "Error accessing cached data: {}".format(ex) + raise CredentialUnavailableError(message=message) from ex + + @staticmethod + def supported() -> bool: + """Whether the shared token cache is supported on the current platform. + + :return: True if the shared token cache is supported on the current platform. + :rtype: bool + """ + return platform.system() in {"Darwin", "Linux", "Windows"} + + def __getstate__(self) -> Dict[str, Any]: + state = self.__dict__.copy() + # Remove the non-picklable entries + if not self._custom_cache: + del state["_cache"] + del state["_cae_cache"] + return state + + def __setstate__(self, state: Dict[str, Any]) -> None: + self.__dict__.update(state) + # Re-create the unpickable entries + if not self._custom_cache: + self._cache = None + self._cae_cache = None diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/user_agent.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/user_agent.py new file mode 100644 index 00000000000..f21dfbd945f --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/user_agent.py @@ -0,0 +1,9 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import platform + +from .._version import VERSION + +USER_AGENT = "azsdk-python-identity/{} Python/{} ({})".format(VERSION, platform.python_version(), platform.platform()) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/utils.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/utils.py new file mode 100644 index 00000000000..381d2fcd628 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/utils.py @@ -0,0 +1,134 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +import logging +from contextvars import ContextVar +from string import ascii_letters, digits +from typing import List, Optional + +from urllib.parse import urlparse + +from azure.core.exceptions import ClientAuthenticationError +from .._constants import EnvironmentVariables, KnownAuthorities + +within_credential_chain = ContextVar("within_credential_chain", default=False) +within_dac = ContextVar("within_dac", default=False) + +_LOGGER = logging.getLogger(__name__) + +VALID_TENANT_ID_CHARACTERS = frozenset(ascii_letters + digits + "-.") +VALID_SCOPE_CHARACTERS = frozenset(ascii_letters + digits + "_-.:/") +VALID_SUBSCRIPTION_CHARACTERS = frozenset(ascii_letters + digits + "_-. ") + + +def normalize_authority(authority: str) -> str: + """Ensure authority uses https, strip trailing spaces and /. + + :param str authority: authority to normalize + :return: normalized authority + :rtype: str + :raises: ValueError if authority is not a valid https URL + """ + + parsed = urlparse(authority) + if not parsed.scheme: + return "https://" + authority.rstrip(" /") + if parsed.scheme != "https": + raise ValueError( + "'{}' is an invalid authority. The value must be a TLS protected (https) URL.".format(authority) + ) + + return authority.rstrip(" /") + + +def get_default_authority() -> str: + authority = os.environ.get(EnvironmentVariables.AZURE_AUTHORITY_HOST, KnownAuthorities.AZURE_PUBLIC_CLOUD) + return normalize_authority(authority) + + +def validate_scope(scope: str) -> None: + """Raise ValueError if scope is empty or contains a character invalid for a scope + + :param str scope: scope to validate + :raises: ValueError if scope is empty or contains a character invalid for a scope. + """ + if not scope or any(c not in VALID_SCOPE_CHARACTERS for c in scope): + raise ValueError( + "An invalid scope was provided. Only alphanumeric characters, '.', '-', '_', ':', and '/' are allowed." + ) + + +def validate_tenant_id(tenant_id: str) -> None: + """Raise ValueError if tenant_id is empty or contains a character invalid for a tenant ID. + + :param str tenant_id: tenant ID to validate + :raises: ValueError if tenant_id is empty or contains a character invalid for a tenant ID. + """ + if not tenant_id or any(c not in VALID_TENANT_ID_CHARACTERS for c in tenant_id): + raise ValueError( + "Invalid tenant ID provided. You can locate your tenant ID by following the instructions here: " + "https://learn.microsoft.com/partner-center/find-ids-and-domain-names" + ) + + +def validate_subscription(subscription: str) -> None: + """Raise ValueError if subscription is empty or contains a character invalid for a subscription name/ID. + + :param str subscription: subscription ID to validate + :raises: ValueError if subscription is empty or contains a character invalid for a subscription ID. + """ + if not subscription or any(c not in VALID_SUBSCRIPTION_CHARACTERS for c in subscription): + raise ValueError( + "Invalid subscription provided. You can locate your subscription by following the " + "instructions listed here: https://learn.microsoft.com/azure/azure-portal/get-subscription-tenant-id" + ) + + +def resolve_tenant( + default_tenant: str, + tenant_id: Optional[str] = None, + *, + additionally_allowed_tenants: Optional[List[str]] = None, + **_ +) -> str: + """Returns the correct tenant for a token request given a credential's configuration. + + :param str default_tenant: The tenant ID configured on the credential. + :param str tenant_id: The tenant ID requested by the user. + :keyword list[str] additionally_allowed_tenants: The list of additionally allowed tenants. + :return: The tenant ID to use for the token request. + :rtype: str + :raises: ~azure.core.exceptions.ClientAuthenticationError + """ + if tenant_id is None or tenant_id == default_tenant: + return default_tenant + if default_tenant == "adfs" or os.environ.get(EnvironmentVariables.AZURE_IDENTITY_DISABLE_MULTITENANTAUTH): + _LOGGER.info( + "A token was request for a different tenant than was configured on the credential, " + "but the configured value was used since multi tenant authentication has been disabled. " + "Configured tenant ID: %s, Requested tenant ID %s", + default_tenant, + tenant_id, + ) + return default_tenant + if not default_tenant: + return tenant_id + if additionally_allowed_tenants is None: + additionally_allowed_tenants = [] + if "*" in additionally_allowed_tenants or tenant_id in additionally_allowed_tenants: + _LOGGER.info( + "A token was requested for a different tenant than was configured on the credential, " + "and the requested tenant ID was used to authenticate. Configured tenant ID: %s, " + "Requested tenant ID %s", + default_tenant, + tenant_id, + ) + return tenant_id + raise ClientAuthenticationError( + message="The current credential is not configured to acquire tokens for tenant {}. " + "To enable acquiring tokens for this tenant add it to the additionally_allowed_tenants " + 'when creating the credential, or add "*" to additionally_allowed_tenants to allow ' + "acquiring tokens for any tenant.".format(tenant_id) + ) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/win_vscode_adapter.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/win_vscode_adapter.py new file mode 100644 index 00000000000..2cec7ba49e9 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_internal/win_vscode_adapter.py @@ -0,0 +1,77 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +import json +import logging +import ctypes as ct +from .._constants import VSCODE_CREDENTIALS_SECTION + +try: + import ctypes.wintypes as wt +except (IOError, ValueError): + pass + +_LOGGER = logging.getLogger(__name__) + +SUPPORTED_CREDKEYS = set(("Type", "TargetName", "Persist", "UserName", "Comment", "CredentialBlob")) + +_PBYTE = ct.POINTER(ct.c_byte) + + +class _CREDENTIAL(ct.Structure): + _fields_ = [ + ("Flags", wt.DWORD), + ("Type", wt.DWORD), + ("TargetName", ct.c_wchar_p), + ("Comment", ct.c_wchar_p), + ("LastWritten", wt.FILETIME), + ("CredentialBlobSize", wt.DWORD), + ("CredentialBlob", _PBYTE), + ("Persist", wt.DWORD), + ("AttributeCount", wt.DWORD), + ("Attributes", ct.c_void_p), + ("TargetAlias", ct.c_wchar_p), + ("UserName", ct.c_wchar_p), + ] + + +_PCREDENTIAL = ct.POINTER(_CREDENTIAL) + +_advapi = ct.WinDLL("advapi32") # type: ignore +_advapi.CredReadW.argtypes = [wt.LPCWSTR, wt.DWORD, wt.DWORD, ct.POINTER(_PCREDENTIAL)] +_advapi.CredReadW.restype = wt.BOOL +_advapi.CredFree.argtypes = [_PCREDENTIAL] + + +def _read_credential(service_name, account_name): + target = "{}/{}".format(service_name, account_name) + cred_ptr = _PCREDENTIAL() + if _advapi.CredReadW(target, 1, 0, ct.byref(cred_ptr)): + cred_blob = cred_ptr.contents.CredentialBlob + cred_blob_size = cred_ptr.contents.CredentialBlobSize + cred = "".join(map(chr, cred_blob[:cred_blob_size])) + _advapi.CredFree(cred_ptr) + return cred + return None + + +def get_user_settings(): + try: + path = os.path.join(os.environ["APPDATA"], "Code", "User", "settings.json") + with open(path, encoding="utf-8") as file: + return json.load(file) + except Exception as ex: # pylint:disable=broad-except + _LOGGER.debug('Exception reading VS Code user settings: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG)) + return {} + + +def get_refresh_token(cloud_name): + try: + return _read_credential(VSCODE_CREDENTIALS_SECTION, cloud_name) + except Exception as ex: # pylint: disable=broad-except + _LOGGER.debug( + 'Exception retrieving VS Code credentials: "%s"', ex, exc_info=_LOGGER.isEnabledFor(logging.DEBUG) + ) + return None diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_persistent_cache.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_persistent_cache.py new file mode 100644 index 00000000000..972f6d4ba4d --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_persistent_cache.py @@ -0,0 +1,116 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +import sys +from typing import TYPE_CHECKING, Any + +from ._constants import CACHE_CAE_SUFFIX, CACHE_NON_CAE_SUFFIX + +if TYPE_CHECKING: + import msal_extensions + +_LOGGER = logging.getLogger(__name__) + + +class TokenCachePersistenceOptions: + """Options for persistent token caching. + + Most credentials accept an instance of this class to configure persistent token caching. The default values + configure a credential to use a cache shared with Microsoft developer tools and + :class:`~azure.identity.SharedTokenCacheCredential`. To isolate a credential's data from other applications, + specify a `name` for the cache. + + By default, the cache is encrypted with the current platform's user data protection API, and will raise an error + when this is not available. To configure the cache to fall back to an unencrypted file instead of raising an + error, specify `allow_unencrypted_storage=True`. + + .. warning:: The cache contains authentication secrets. If the cache is not encrypted, protecting it is the + application's responsibility. A breach of its contents will fully compromise accounts. + + .. admonition:: Example: + + .. literalinclude:: ../tests/test_persistent_cache.py + :start-after: [START snippet] + :end-before: [END snippet] + :language: python + :caption: Configuring a credential for persistent caching + :dedent: 8 + + :keyword str name: prefix name of the cache, used to isolate its data from other applications. Defaults to the + name of the cache shared by Microsoft dev tools and :class:`~azure.identity.SharedTokenCacheCredential`. + Additional strings may be appended to the name for further isolation. + :keyword bool allow_unencrypted_storage: whether the cache should fall back to storing its data in plain text when + encryption isn't possible. False by default. Setting this to True does not disable encryption. The cache will + always try to encrypt its data. + """ + + def __init__(self, *, allow_unencrypted_storage: bool = False, name: str = "msal.cache", **kwargs: Any) -> None: + # pylint:disable=unused-argument + self.allow_unencrypted_storage = allow_unencrypted_storage + self.name = name + + +def _load_persistent_cache( + options: TokenCachePersistenceOptions, is_cae: bool = False +) -> "msal_extensions.PersistedTokenCache": + import msal_extensions + + cache_suffix = CACHE_CAE_SUFFIX if is_cae else CACHE_NON_CAE_SUFFIX + persistence = _get_persistence( + allow_unencrypted=options.allow_unencrypted_storage, + account_name="MSALCache", + cache_name=options.name + cache_suffix, + ) + return msal_extensions.PersistedTokenCache(persistence) + + +def _get_persistence(allow_unencrypted, account_name, cache_name): + # type: (bool, str, str) -> msal_extensions.persistence.BasePersistence + """Get an msal_extensions persistence instance for the current platform. + + On Windows the cache is a file protected by the Data Protection API. On Linux and macOS the cache is stored by + libsecret and Keychain, respectively. On those platforms the cache uses the modified timestamp of a file on disk to + decide whether to reload the cache. + + :param bool allow_unencrypted: when True, the cache will be kept in plaintext should encryption be impossible in the + current environment + :param str account_name: the name of the account for which the cache is storing tokens + :param str cache_name: the name of the cache + :return: an msal_extensions persistence instance + :rtype: ~msal_extensions.persistence.BasePersistence + """ + import msal_extensions + + if sys.platform.startswith("win") and "LOCALAPPDATA" in os.environ: + cache_location = os.path.join(os.environ["LOCALAPPDATA"], ".IdentityService", cache_name) + return msal_extensions.FilePersistenceWithDataProtection(cache_location) + + if sys.platform.startswith("darwin"): + # the cache uses this file's modified timestamp to decide whether to reload + file_path = os.path.expanduser(os.path.join("~", ".IdentityService", cache_name)) + return msal_extensions.KeychainPersistence(file_path, "Microsoft.Developer.IdentityService", account_name) + + if sys.platform.startswith("linux"): + # The cache uses this file's modified timestamp to decide whether to reload. Note this path is the same + # as that of the plaintext fallback: a new encrypted cache will stomp an unencrypted cache. + file_path = os.path.expanduser(os.path.join("~", ".IdentityService", cache_name)) + try: + return msal_extensions.LibsecretPersistence( + file_path, cache_name, {"MsalClientID": "Microsoft.Developer.IdentityService"}, label=account_name + ) + except Exception as ex: # pylint:disable=broad-except + _LOGGER.debug('msal-extensions is unable to encrypt a persistent cache: "%s"', ex, exc_info=True) + if not allow_unencrypted: + error = ValueError( + "Cache encryption is impossible because libsecret dependencies are not installed or are unusable," + + " for example because no display is available (as in an SSH session). The chained exception has" + + ' more information. Specify "allow_unencrypted_storage=True" to store the cache unencrypted' + + " instead of raising this exception." + ) + raise error from ex + return msal_extensions.FilePersistence(file_path) + + raise NotImplementedError("A persistent cache is not available in this environment.") diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/_version.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_version.py new file mode 100644 index 00000000000..effc6910515 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/_version.py @@ -0,0 +1,5 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +VERSION = "1.19.1" diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/__init__.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/__init__.py new file mode 100644 index 00000000000..e21f985650d --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/__init__.py @@ -0,0 +1,46 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Credentials for asynchronous Azure SDK clients.""" + +from ._credentials import ( + AuthorizationCodeCredential, + AzureDeveloperCliCredential, + AzureCliCredential, + AzurePowerShellCredential, + CertificateCredential, + ChainedTokenCredential, + ClientSecretCredential, + DefaultAzureCredential, + EnvironmentCredential, + ManagedIdentityCredential, + OnBehalfOfCredential, + SharedTokenCacheCredential, + VisualStudioCodeCredential, + ClientAssertionCredential, + WorkloadIdentityCredential, + AzurePipelinesCredential, +) +from ._bearer_token_provider import get_bearer_token_provider + + +__all__ = [ + "AuthorizationCodeCredential", + "AzureDeveloperCliCredential", + "AzureCliCredential", + "AzurePipelinesCredential", + "AzurePowerShellCredential", + "CertificateCredential", + "ClientSecretCredential", + "DefaultAzureCredential", + "EnvironmentCredential", + "ManagedIdentityCredential", + "OnBehalfOfCredential", + "ChainedTokenCredential", + "SharedTokenCacheCredential", + "VisualStudioCodeCredential", + "ClientAssertionCredential", + "WorkloadIdentityCredential", + "get_bearer_token_provider", +] diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_bearer_token_provider.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_bearer_token_provider.py new file mode 100644 index 00000000000..bde068e1055 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_bearer_token_provider.py @@ -0,0 +1,47 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Callable, Coroutine, Any + +from azure.core.credentials_async import AsyncTokenCredential +from azure.core.pipeline.policies import AsyncBearerTokenCredentialPolicy +from azure.core.pipeline import PipelineRequest, PipelineContext +from azure.core.rest import HttpRequest + + +def _make_request() -> PipelineRequest[HttpRequest]: + return PipelineRequest(HttpRequest("CredentialWrapper", "https://fakeurl"), PipelineContext(None)) + + +def get_bearer_token_provider(credential: AsyncTokenCredential, *scopes: str) -> Callable[[], Coroutine[Any, Any, str]]: + """Returns a callable that provides a bearer token. + + It can be used for instance to write code like: + + .. code-block:: python + + from azure.identity.aio import DefaultAzureCredential, get_bearer_token_provider + + credential = DefaultAzureCredential() + bearer_token_provider = get_bearer_token_provider(credential, "https://cognitiveservices.azure.com/.default") + + + # Usage + request.headers["Authorization"] = "Bearer " + await bearer_token_provider() + + :param credential: The credential used to authenticate the request. + :type credential: ~azure.core.credentials_async.AsyncTokenCredential + :param str scopes: The scopes required for the bearer token. + :rtype: coroutine + :return: A coroutine that returns a bearer token. + """ + + policy = AsyncBearerTokenCredentialPolicy(credential, *scopes) + + async def wrapper() -> str: + request = _make_request() + await policy.on_request(request) + return request.http_request.headers["Authorization"][len("Bearer ") :] + + return wrapper diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/__init__.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/__init__.py new file mode 100644 index 00000000000..2b51197f095 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/__init__.py @@ -0,0 +1,40 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from .authorization_code import AuthorizationCodeCredential +from .azure_powershell import AzurePowerShellCredential +from .chained import ChainedTokenCredential +from .default import DefaultAzureCredential +from .environment import EnvironmentCredential +from .managed_identity import ManagedIdentityCredential +from .on_behalf_of import OnBehalfOfCredential +from .certificate import CertificateCredential +from .client_secret import ClientSecretCredential +from .shared_cache import SharedTokenCacheCredential +from .azure_cli import AzureCliCredential +from .azd_cli import AzureDeveloperCliCredential +from .vscode import VisualStudioCodeCredential +from .client_assertion import ClientAssertionCredential +from .workload_identity import WorkloadIdentityCredential +from .azure_pipelines import AzurePipelinesCredential + + +__all__ = [ + "AuthorizationCodeCredential", + "AzureCliCredential", + "AzureDeveloperCliCredential", + "AzurePipelinesCredential", + "AzurePowerShellCredential", + "CertificateCredential", + "ChainedTokenCredential", + "ClientSecretCredential", + "DefaultAzureCredential", + "EnvironmentCredential", + "ManagedIdentityCredential", + "OnBehalfOfCredential", + "SharedTokenCacheCredential", + "VisualStudioCodeCredential", + "ClientAssertionCredential", + "WorkloadIdentityCredential", +] diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/app_service.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/app_service.py new file mode 100644 index 00000000000..c8ee6965de1 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/app_service.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Optional, Any + +from .._internal.managed_identity_base import AsyncManagedIdentityBase +from .._internal.managed_identity_client import AsyncManagedIdentityClient +from ..._credentials.app_service import _get_client_args + + +class AppServiceCredential(AsyncManagedIdentityBase): + def get_client(self, **kwargs: Any) -> Optional[AsyncManagedIdentityClient]: + client_args = _get_client_args(**kwargs) + if client_args: + return AsyncManagedIdentityClient(**client_args) + return None + + def get_unavailable_message(self, desc: str = "") -> str: + return f"App Service managed identity configuration not found in environment. {desc}" diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/application.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/application.py new file mode 100644 index 00000000000..980171ef1e6 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/application.py @@ -0,0 +1,121 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import Optional, Any, cast + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from azure.core.credentials_async import AsyncSupportsTokenInfo, AsyncTokenCredential +from .chained import ChainedTokenCredential +from .environment import EnvironmentCredential +from .managed_identity import ManagedIdentityCredential +from ..._constants import EnvironmentVariables +from ..._internal import get_default_authority, normalize_authority + +_LOGGER = logging.getLogger(__name__) + + +class AzureApplicationCredential(ChainedTokenCredential): + """A credential for Microsoft Entra applications. + + This credential is designed for applications deployed to Azure (:class:`~azure.identity.aio.DefaultAzureCredential` + is better suited to local development). It authenticates service principals and managed identities. + + For service principal authentication, set these environment variables to identify a principal: + + - **AZURE_TENANT_ID**: ID of the service principal's tenant. Also called its "directory" ID. + - **AZURE_CLIENT_ID**: the service principal's client ID + + And one of these to authenticate that principal: + + - **AZURE_CLIENT_SECRET**: one of the service principal's client secrets + + **or** + + - **AZURE_CLIENT_CERTIFICATE_PATH**: path to a PEM-encoded certificate file including the private key. The + certificate must not be password-protected. + + See `Azure CLI documentation `_ + for more information about creating and managing service principals. + + When this environment configuration is incomplete, the credential will attempt to authenticate a managed identity. + See `Microsoft Entra ID documentation + `__ for an overview + of managed identities. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud, which is the default when no value is given for this keyword argument or + environment variable AZURE_AUTHORITY_HOST. :class:`~azure.identity.AzureAuthorityHosts` defines authorities for + other clouds. Authority configuration applies only to service principal authentication. + :keyword str managed_identity_client_id: The client ID of a user-assigned managed identity. Defaults to the value + of the environment variable AZURE_CLIENT_ID, if any. If not specified, a system-assigned identity will be used. + """ + + def __init__( + self, *, authority: Optional[str] = None, managed_identity_client_id: Optional[str] = None, **kwargs: Any + ) -> None: + authority = normalize_authority(authority) if authority else get_default_authority() + managed_identity_client_id = managed_identity_client_id or os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + super().__init__( + EnvironmentCredential(authority=authority, **kwargs), + ManagedIdentityCredential(client_id=managed_identity_client_id, **kwargs), + ) + + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Asynchronously request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The exception has a + `message` attribute listing each authentication attempt and its error message. + """ + if self._successful_credential: + token = await cast(AsyncTokenCredential, self._successful_credential).get_token( + *scopes, claims=claims, tenant_id=tenant_id, **kwargs + ) + _LOGGER.info( + "%s acquired a token from %s", self.__class__.__name__, self._successful_credential.__class__.__name__ + ) + return token + + return await super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The exception has a + `message` attribute listing each authentication attempt and its error message. + """ + if self._successful_credential: + token_info = await cast(AsyncSupportsTokenInfo, self._successful_credential).get_token_info( + *scopes, options=options + ) + _LOGGER.info( + "%s acquired a token from %s", self.__class__.__name__, self._successful_credential.__class__.__name__ + ) + return token_info + + return await cast(AsyncSupportsTokenInfo, super()).get_token_info(*scopes, options=options) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/authorization_code.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/authorization_code.py new file mode 100644 index 00000000000..c075cd30055 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/authorization_code.py @@ -0,0 +1,147 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Optional, Any, cast + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from .._internal import AadClient, AsyncContextManager +from .._internal.get_token_mixin import GetTokenMixin + + +class AuthorizationCodeCredential(AsyncContextManager, GetTokenMixin): + """Authenticates by redeeming an authorization code previously obtained from Microsoft Entra ID. + + See `Microsoft Entra ID documentation + `__ for more information + about the authentication flow. + + :param str tenant_id: ID of the application's Microsoft Entra tenant. Also called its "directory" ID. + :param str client_id: The application's client ID + :param str authorization_code: The authorization code from the user's log-in + :param str redirect_uri: The application's redirect URI. Must match the URI used to request the authorization code. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword str client_secret: One of the application's client secrets. Required only for web apps and web APIs. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_authorization_code_credential_async] + :end-before: [END create_authorization_code_credential_async] + :language: python + :dedent: 4 + :caption: Create an AuthorizationCodeCredential. + """ + + async def __aenter__(self) -> "AuthorizationCodeCredential": + if self._client: + await self._client.__aenter__() + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + + if self._client: + await self._client.__aexit__() + + def __init__( + self, + tenant_id: str, + client_id: str, + authorization_code: str, + redirect_uri: str, + *, + client_secret: Optional[str] = None, + **kwargs: Any + ) -> None: + self._authorization_code: Optional[str] = authorization_code + self._client_id = client_id + self._client_secret = client_secret + self._client = kwargs.pop("client", None) or AadClient(tenant_id, client_id, **kwargs) + self._redirect_uri = redirect_uri + super().__init__() + + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + The first time this method is called, the credential will redeem its authorization code. On subsequent calls + the credential will return a cached access token or redeem a refresh token, if it acquired a refresh token upon + redeeming the authorization code. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. Any error response from Microsoft Entra ID is available as the error's + ``response`` attribute. + """ + return await super(AuthorizationCodeCredential, self).get_token( + *scopes, claims=claims, tenant_id=tenant_id, client_secret=self._client_secret, **kwargs + ) + + async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + The first time this method is called, the credential will redeem its authorization code. On subsequent calls + the credential will return a cached access token or redeem a refresh token, if it acquired a refresh token upon + redeeming the authorization code. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. Any error response from Microsoft Entra ID is available as the error's + ``response`` attribute. + """ + return await super()._get_token_base( + *scopes, options=options, client_secret=self._client_secret, base_method_name="get_token_info" + ) + + async def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessTokenInfo]: + return self._client.get_cached_access_token(scopes, **kwargs) + + async def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + if self._authorization_code: + token = await self._client.obtain_token_by_authorization_code( + scopes=scopes, code=self._authorization_code, redirect_uri=self._redirect_uri, **kwargs + ) + self._authorization_code = None # auth codes are single-use + return token + + token = cast(AccessTokenInfo, None) + for refresh_token in self._client.get_cached_refresh_tokens(scopes): + if "secret" in refresh_token: + token = await self._client.obtain_token_by_refresh_token(scopes, refresh_token["secret"], **kwargs) + if token: + break + + if not token: + raise ClientAuthenticationError( + message="No authorization code, cached access token, or refresh token available." + ) + + return token diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azd_cli.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azd_cli.py new file mode 100644 index 00000000000..eafeb5affd4 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azd_cli.py @@ -0,0 +1,232 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import asyncio +import os +import shutil +import sys +from typing import Any, List, Optional + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from .._internal import AsyncContextManager +from .._internal.decorators import log_get_token_async +from ... import CredentialUnavailableError +from ..._credentials.azd_cli import ( + AzureDeveloperCliCredential as _SyncAzureDeveloperCliCredential, + CLI_NOT_FOUND, + COMMAND_LINE, + EXECUTABLE_NAME, + get_safe_working_dir, + NOT_LOGGED_IN, + parse_token, + sanitize_output, +) +from ..._internal import resolve_tenant, within_dac, validate_tenant_id, validate_scope + + +class AzureDeveloperCliCredential(AsyncContextManager): + """Authenticates by requesting a token from the Azure Developer CLI. + + Azure Developer CLI is a command-line interface tool that allows developers to create, manage, and deploy + resources in Azure. It's built on top of the Azure CLI and provides additional functionality specific + to Azure developers. It allows users to authenticate as a user and/or a service principal against + `Microsoft Entra ID <"https://learn.microsoft.com/entra/fundamentals/">`__. + The AzureDeveloperCliCredential authenticates in a development environment and acquires a token on behalf of + the logged-in user or service principal in Azure Developer CLI. It acts as the Azure Developer CLI logged-in user + or service principal and executes an Azure CLI command underneath to authenticate the application against + Microsoft Entra ID. + + To use this credential, the developer needs to authenticate locally in Azure Developer CLI using one of the + commands below: + + * Run "azd auth login" in Azure Developer CLI to authenticate interactively as a user. + * Run "azd auth login --client-id 'client_id' --client-secret 'client_secret' --tenant-id 'tenant_id'" + to authenticate as a service principal. + + You may need to repeat this process after a certain time period, depending on the refresh token validity in your + organization. Generally, the refresh token validity period is a few weeks to a few months. + AzureDeveloperCliCredential will prompt you to sign in again. + + :keyword str tenant_id: Optional tenant to include in the token request. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + :keyword int process_timeout: Seconds to wait for the Azure Developer CLI process to respond. Defaults + to 10 seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START azure_developer_cli_credential_async] + :end-before: [END azure_developer_cli_credential_async] + :language: python + :dedent: 4 + :caption: Create an AzureDeveloperCliCredential. + """ + + def __init__( + self, + *, + tenant_id: str = "", + additionally_allowed_tenants: Optional[List[str]] = None, + process_timeout: int = 10, + ) -> None: + if tenant_id: + validate_tenant_id(tenant_id) + self.tenant_id = tenant_id + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + self._process_timeout = process_timeout + + @log_get_token_async + async def get_token( + self, + *scopes: str, + claims: Optional[str] = None, # pylint:disable=unused-argument + tenant_id: Optional[str] = None, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. Applications calling this method directly must + also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke the Azure Developer CLI. + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked the Azure Developer CLI + but didn't receive an access token. + """ + # only ProactorEventLoop supports subprocesses on Windows (and it isn't the default loop on Python < 3.8) + if sys.platform.startswith("win") and not isinstance(asyncio.get_event_loop(), asyncio.ProactorEventLoop): + return _SyncAzureDeveloperCliCredential().get_token(*scopes, tenant_id=tenant_id, **kwargs) + + options: TokenRequestOptions = {} + if tenant_id: + options["tenant_id"] = tenant_id + + token_info = await self._get_token_base(*scopes, options=options, **kwargs) + return AccessToken(token_info.token, token_info.expires_on) + + @log_get_token_async + async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. Applications calling this method + directly must also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke + the Azure Developer CLI. + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked + the Azure Developer CLI but didn't receive an access token. + """ + # only ProactorEventLoop supports subprocesses on Windows (and it isn't the default loop on Python < 3.8) + if sys.platform.startswith("win") and not isinstance(asyncio.get_event_loop(), asyncio.ProactorEventLoop): + return _SyncAzureDeveloperCliCredential().get_token_info(*scopes, options=options) + return await self._get_token_base(*scopes, options=options) + + async def _get_token_base( + self, *scopes: str, options: Optional[TokenRequestOptions] = None, **kwargs: Any + ) -> AccessTokenInfo: + if not scopes: + raise ValueError("Missing scope in request. \n") + + tenant_id = options.get("tenant_id") if options else None + if tenant_id: + validate_tenant_id(tenant_id) + for scope in scopes: + validate_scope(scope) + + commandString = " --scope ".join(scopes) + command = COMMAND_LINE.format(commandString) + tenant = resolve_tenant( + default_tenant=self.tenant_id, + tenant_id=tenant_id, + additionally_allowed_tenants=self._additionally_allowed_tenants, + **kwargs, + ) + + if tenant: + command += " --tenant-id " + tenant + output = await _run_command(command, self._process_timeout) + + token = parse_token(output) + if not token: + sanitized_output = sanitize_output(output) + message = ( + f"Unexpected output from Azure Developer CLI: '{sanitized_output}'. \n" + f"To mitigate this issue, please refer to the troubleshooting guidelines here at " + f"https://aka.ms/azsdk/python/identity/azdevclicredential/troubleshoot." + ) + if within_dac.get(): + raise CredentialUnavailableError(message=message) + raise ClientAuthenticationError(message=message) + + return token + + async def close(self) -> None: + """Calling this method is unnecessary""" + + +async def _run_command(command: str, timeout: int) -> str: + # Ensure executable exists in PATH first. This avoids a subprocess call that would fail anyway. + if shutil.which(EXECUTABLE_NAME) is None: + raise CredentialUnavailableError(message=CLI_NOT_FOUND) + + if sys.platform.startswith("win"): + args = ("cmd", "/c " + command) + else: + args = ("/bin/sh", "-c", command) + + working_directory = get_safe_working_dir() + + try: + proc = await asyncio.create_subprocess_exec( + *args, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + stdin=asyncio.subprocess.DEVNULL, + cwd=working_directory, + env=dict(os.environ, NO_COLOR="true"), + ) + stdout_b, stderr_b = await asyncio.wait_for(proc.communicate(), timeout) + output = stdout_b.decode() + stderr = stderr_b.decode() + except asyncio.TimeoutError as ex: + proc.kill() + raise CredentialUnavailableError(message="Timed out waiting for Azure Developer CLI") from ex + except OSError as ex: + # failed to execute 'cmd' or '/bin/sh' + error = CredentialUnavailableError(message="Failed to execute '{}'".format(args[0])) + raise error from ex + + if proc.returncode == 0: + return output + + # Fallback check in case the executable is not found while executing subprocess. + if proc.returncode == 127 or stderr.startswith("'azd' is not recognized"): + raise CredentialUnavailableError(CLI_NOT_FOUND) + + if "not logged in, run `azd auth login` to login" in stderr and "AADSTS" not in stderr: + raise CredentialUnavailableError(message=NOT_LOGGED_IN) + + message = sanitize_output(stderr) if stderr else "Failed to invoke Azure Developer CLI" + if within_dac.get(): + raise CredentialUnavailableError(message=message) + raise ClientAuthenticationError(message=message) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azure_arc.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azure_arc.py new file mode 100644 index 00000000000..d9c5690d03d --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azure_arc.py @@ -0,0 +1,45 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import os +from typing import Optional, Any + +from azure.core.pipeline.policies import AsyncHTTPPolicy +from azure.core.pipeline import PipelineRequest, PipelineResponse +from .._internal.managed_identity_base import AsyncManagedIdentityBase +from .._internal.managed_identity_client import AsyncManagedIdentityClient +from ..._constants import EnvironmentVariables +from ..._credentials.azure_arc import _get_request, _get_secret_key + + +class AzureArcCredential(AsyncManagedIdentityBase): + def get_client(self, **kwargs: Any) -> Optional[AsyncManagedIdentityClient]: + url = os.environ.get(EnvironmentVariables.IDENTITY_ENDPOINT) + imds = os.environ.get(EnvironmentVariables.IMDS_ENDPOINT) + if url and imds: + return AsyncManagedIdentityClient( + _per_retry_policies=[ArcChallengeAuthPolicy()], + request_factory=functools.partial(_get_request, url), + **kwargs, + ) + return None + + def get_unavailable_message(self, desc: str = "") -> str: + return f"Azure Arc managed identity configuration not found in environment. {desc}" + + +class ArcChallengeAuthPolicy(AsyncHTTPPolicy): + """Policy for handling Azure Arc's challenge authentication""" + + async def send(self, request: PipelineRequest) -> PipelineResponse: + request.http_request.headers["Metadata"] = "true" + response = await self.next.send(request) + + if response.http_response.status_code == 401: + secret_key = _get_secret_key(response) + request.http_request.headers["Authorization"] = "Basic {}".format(secret_key) + response = await self.next.send(request) + + return response diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azure_cli.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azure_cli.py new file mode 100644 index 00000000000..e7c210ebf28 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azure_cli.py @@ -0,0 +1,225 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import asyncio +import os +import shutil +import sys +from typing import Any, List, Optional + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from .._internal import AsyncContextManager +from .._internal.decorators import log_get_token_async +from ... import CredentialUnavailableError +from ..._credentials.azure_cli import ( + AzureCliCredential as _SyncAzureCliCredential, + CLI_NOT_FOUND, + COMMAND_LINE, + EXECUTABLE_NAME, + get_safe_working_dir, + NOT_LOGGED_IN, + parse_token, + sanitize_output, +) +from ..._internal import ( + _scopes_to_resource, + resolve_tenant, + within_dac, + validate_tenant_id, + validate_scope, + validate_subscription, +) + + +class AzureCliCredential(AsyncContextManager): + """Authenticates by requesting a token from the Azure CLI. + + This requires previously logging in to Azure via "az login", and will use the CLI's currently logged in identity. + + :keyword str tenant_id: Optional tenant to include in the token request. + :keyword str subscription: The name or ID of a subscription. Set this to acquire tokens for an account other + than the Azure CLI's current account. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + :keyword int process_timeout: Seconds to wait for the Azure CLI process to respond. Defaults to 10 seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_azure_cli_credential_async] + :end-before: [END create_azure_cli_credential_async] + :language: python + :dedent: 4 + :caption: Create an AzureCliCredential. + """ + + def __init__( + self, + *, + tenant_id: str = "", + subscription: Optional[str] = None, + additionally_allowed_tenants: Optional[List[str]] = None, + process_timeout: int = 10, + ) -> None: + if tenant_id: + validate_tenant_id(tenant_id) + if subscription: + validate_subscription(subscription) + + self.tenant_id = tenant_id + self.subscription = subscription + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + self._process_timeout = process_timeout + + @log_get_token_async + async def get_token( + self, + *scopes: str, + claims: Optional[str] = None, # pylint:disable=unused-argument + tenant_id: Optional[str] = None, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. Applications calling this method directly must + also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke the Azure CLI. + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked the Azure CLI but didn't + receive an access token. + """ + # only ProactorEventLoop supports subprocesses on Windows (and it isn't the default loop on Python < 3.8) + if sys.platform.startswith("win") and not isinstance(asyncio.get_event_loop(), asyncio.ProactorEventLoop): + return _SyncAzureCliCredential().get_token(*scopes, tenant_id=tenant_id, **kwargs) + + options: TokenRequestOptions = {} + if tenant_id: + options["tenant_id"] = tenant_id + + token_info = await self._get_token_base(*scopes, options=options, **kwargs) + return AccessToken(token_info.token, token_info.expires_on) + + @log_get_token_async + async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. Applications calling this method + directly must also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scopes for the access token. This credential allows only one scope per request. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke the Azure CLI. + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked the Azure CLI but didn't + receive an access token. + """ + # only ProactorEventLoop supports subprocesses on Windows (and it isn't the default loop on Python < 3.8) + if sys.platform.startswith("win") and not isinstance(asyncio.get_event_loop(), asyncio.ProactorEventLoop): + return _SyncAzureCliCredential().get_token_info(*scopes, options=options) + return await self._get_token_base(*scopes, options=options) + + async def _get_token_base( + self, *scopes: str, options: Optional[TokenRequestOptions] = None, **kwargs: Any + ) -> AccessTokenInfo: + tenant_id = options.get("tenant_id") if options else None + if tenant_id: + validate_tenant_id(tenant_id) + for scope in scopes: + validate_scope(scope) + + resource = _scopes_to_resource(*scopes) + command = COMMAND_LINE.format(resource) + tenant = resolve_tenant( + default_tenant=self.tenant_id, + tenant_id=tenant_id, + additionally_allowed_tenants=self._additionally_allowed_tenants, + **kwargs, + ) + + if tenant: + command += " --tenant " + tenant + if self.subscription: + command += f' --subscription "{self.subscription}"' + output = await _run_command(command, self._process_timeout) + + token = parse_token(output) + if not token: + sanitized_output = sanitize_output(output) + message = ( + f"Unexpected output from Azure CLI: '{sanitized_output}'. \n" + f"To mitigate this issue, please refer to the troubleshooting guidelines here at " + f"https://aka.ms/azsdk/python/identity/azclicredential/troubleshoot." + ) + if within_dac.get(): + raise CredentialUnavailableError(message=message) + raise ClientAuthenticationError(message=message) + + return token + + async def close(self) -> None: + """Calling this method is unnecessary""" + + +async def _run_command(command: str, timeout: int) -> str: + # Ensure executable exists in PATH first. This avoids a subprocess call that would fail anyway. + if shutil.which(EXECUTABLE_NAME) is None: + raise CredentialUnavailableError(message=CLI_NOT_FOUND) + + if sys.platform.startswith("win"): + args = ("cmd", "/c " + command) + else: + args = ("/bin/sh", "-c", command) + + working_directory = get_safe_working_dir() + + try: + proc = await asyncio.create_subprocess_exec( + *args, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + stdin=asyncio.subprocess.DEVNULL, + cwd=working_directory, + env=dict(os.environ, AZURE_CORE_NO_COLOR="true"), + ) + stdout_b, stderr_b = await asyncio.wait_for(proc.communicate(), timeout) + output = stdout_b.decode() + stderr = stderr_b.decode() + except asyncio.TimeoutError as ex: + proc.kill() + raise CredentialUnavailableError(message="Timed out waiting for Azure CLI") from ex + except OSError as ex: + # failed to execute 'cmd' or '/bin/sh' + error = CredentialUnavailableError(message="Failed to execute '{}'".format(args[0])) + raise error from ex + + if proc.returncode == 0: + return output + + # Fallback check in case the executable is not found while executing subprocess. + if proc.returncode == 127 or stderr.startswith("'az' is not recognized"): + raise CredentialUnavailableError(CLI_NOT_FOUND) + + if ("az login" in stderr or "az account set" in stderr) and "AADSTS" not in stderr: + raise CredentialUnavailableError(message=NOT_LOGGED_IN) + + message = sanitize_output(stderr) if stderr else "Failed to invoke Azure CLI" + if within_dac.get(): + raise CredentialUnavailableError(message=message) + raise ClientAuthenticationError(message=message) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azure_ml.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azure_ml.py new file mode 100644 index 00000000000..88a95f94e9a --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azure_ml.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Optional, Any + +from .._internal.managed_identity_base import AsyncManagedIdentityBase +from .._internal.managed_identity_client import AsyncManagedIdentityClient +from ..._credentials.azure_ml import _get_client_args + + +class AzureMLCredential(AsyncManagedIdentityBase): + def get_client(self, **kwargs: Any) -> Optional[AsyncManagedIdentityClient]: + client_args = _get_client_args(**kwargs) + if client_args: + return AsyncManagedIdentityClient(**client_args) + return None + + def get_unavailable_message(self, desc: str = "") -> str: + return f"Azure ML managed identity configuration not found in environment. {desc}" diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azure_pipelines.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azure_pipelines.py new file mode 100644 index 00000000000..ccaa635f1da --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azure_pipelines.py @@ -0,0 +1,146 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Any, Optional + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from azure.core.rest import HttpResponse + +from .client_assertion import ClientAssertionCredential +from ..._credentials.azure_pipelines import TROUBLESHOOTING_GUIDE, build_oidc_request, validate_env_vars +from .._internal import AsyncContextManager +from ..._internal import validate_tenant_id +from ..._internal.pipeline import build_pipeline + + +class AzurePipelinesCredential(AsyncContextManager): + """Authenticates using Microsoft Entra Workload ID in Azure Pipelines. + + This credential enables authentication in Azure Pipelines using workload identity federation for Azure service + connections. + + :keyword str tenant_id: The tenant ID for the service connection. Required. + :keyword str client_id: The client ID for the service connection. Required. + :keyword str service_connection_id: The service connection ID for the service connection associated with the + pipeline. From the service connection's configuration page URL in the Azure DevOps web portal, the ID + is the value of the "resourceId" query parameter. Required. + :keyword str system_access_token: The pipeline's System.AccessToken value. It is recommended to assign the value + of System.AccessToken to a secure variable in the Azure Pipelines environment. See + https://learn.microsoft.com/azure/devops/pipelines/build/variables#systemaccesstoken for more info. Required. + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_azure_pipelines_credential_async] + :end-before: [END create_azure_pipelines_credential_async] + :language: python + :dedent: 4 + :caption: Create an AzurePipelinesCredential. + """ + + def __init__( + self, + *, + tenant_id: str, + client_id: str, + service_connection_id: str, + system_access_token: str, + **kwargs: Any, + ) -> None: + + if not system_access_token or not tenant_id or not client_id or not service_connection_id: + raise ValueError( + "'tenant_id', 'client_id','service_connection_id', and 'system_access_token' must be passed in as " + f"keyword arguments. Please refer to the troubleshooting guide at {TROUBLESHOOTING_GUIDE}." + ) + validate_tenant_id(tenant_id) + + self._system_access_token = system_access_token + self._service_connection_id = service_connection_id + self._client_assertion_credential = ClientAssertionCredential( + tenant_id=tenant_id, client_id=client_id, func=self._get_oidc_token, **kwargs + ) + self._pipeline = build_pipeline(**kwargs) + + async def get_token( + self, + *scopes: str, + claims: Optional[str] = None, + tenant_id: Optional[str] = None, + enable_cae: bool = False, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested + token. Defaults to False. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks + required data, state, or platform support + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + validate_env_vars() + return await self._client_assertion_credential.get_token( + *scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs + ) + + async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scope for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + validate_env_vars() + return await self._client_assertion_credential.get_token_info(*scopes, options=options) + + def _get_oidc_token(self) -> str: + request = build_oidc_request(self._service_connection_id, self._system_access_token) + response = self._pipeline.run(request, retry_on_methods=[request.method]) + http_response: HttpResponse = response.http_response + if http_response.status_code not in [200]: + raise ClientAuthenticationError( + message="Unexpected response from OIDC token endpoint.", response=http_response + ) + json_response = http_response.json() + if "oidcToken" not in json_response: + raise ClientAuthenticationError(message="OIDC token not found in response.") + return json_response["oidcToken"] + + async def __aenter__(self) -> "AzurePipelinesCredential": + await self._client_assertion_credential.__aenter__() + self._pipeline.__enter__() + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + await self._client_assertion_credential.close() + self._pipeline.__exit__() diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azure_powershell.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azure_powershell.py new file mode 100644 index 00000000000..f9117f2e66c --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/azure_powershell.py @@ -0,0 +1,186 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import asyncio +import sys +from typing import Any, cast, List, Optional +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions + +from .._internal import AsyncContextManager +from .._internal.decorators import log_get_token_async +from ... import CredentialUnavailableError +from ..._credentials.azure_powershell import ( + AzurePowerShellCredential as _SyncCredential, + get_command_line, + get_safe_working_dir, + raise_for_error, + parse_token, +) +from ..._internal import resolve_tenant, validate_tenant_id, validate_scope + + +class AzurePowerShellCredential(AsyncContextManager): + """Authenticates by requesting a token from Azure PowerShell. + + This requires previously logging in to Azure via "Connect-AzAccount", and will use the currently logged in identity. + + :keyword str tenant_id: Optional tenant to include in the token request. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + :keyword int process_timeout: Seconds to wait for the Azure PowerShell process to respond. Defaults to 10 seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_azure_power_shell_credential_async] + :end-before: [END create_azure_power_shell_credential_async] + :language: python + :dedent: 4 + :caption: Create an AzurePowerShellCredential. + """ + + def __init__( + self, + *, + tenant_id: str = "", + additionally_allowed_tenants: Optional[List[str]] = None, + process_timeout: int = 10, + ) -> None: + if tenant_id: + validate_tenant_id(tenant_id) + self.tenant_id = tenant_id + self._additionally_allowed_tenants = additionally_allowed_tenants or [] + self._process_timeout = process_timeout + + @log_get_token_async + async def get_token( + self, + *scopes: str, + claims: Optional[str] = None, # pylint:disable=unused-argument + tenant_id: Optional[str] = None, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. Applications calling this method directly must + also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke Azure PowerShell, or + no account is authenticated + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked Azure PowerShell but didn't + receive an access token + """ + # only ProactorEventLoop supports subprocesses on Windows (and it isn't the default loop on Python < 3.8) + if sys.platform.startswith("win") and not isinstance(asyncio.get_event_loop(), asyncio.ProactorEventLoop): + return _SyncCredential().get_token(*scopes, tenant_id=tenant_id, **kwargs) + + options: TokenRequestOptions = {} + if tenant_id: + options["tenant_id"] = tenant_id + + token_info = await self._get_token_base(*scopes, options=options, **kwargs) + return AccessToken(token_info.token, token_info.expires_on) + + @log_get_token_async + async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. Applications calling this method + directly must also handle token caching because this credential doesn't cache the tokens it acquires. + + :param str scopes: desired scopes for the access token. TThis credential allows only one scope per request. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + + :raises ~azure.identity.CredentialUnavailableError: the credential was unable to invoke Azure PowerShell, or + no account is authenticated + :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked Azure PowerShell but didn't + receive an access token + """ + if sys.platform.startswith("win") and not isinstance(asyncio.get_event_loop(), asyncio.ProactorEventLoop): + return _SyncCredential().get_token_info(*scopes, options=options) + return await self._get_token_base(*scopes, options=options) + + async def _get_token_base( + self, *scopes: str, options: Optional[TokenRequestOptions] = None, **kwargs: Any + ) -> AccessTokenInfo: + tenant_id = options.get("tenant_id") if options else None + if tenant_id: + validate_tenant_id(tenant_id) + for scope in scopes: + validate_scope(scope) + + tenant_id = resolve_tenant( + default_tenant=self.tenant_id, + tenant_id=tenant_id, + additionally_allowed_tenants=self._additionally_allowed_tenants, + **kwargs, + ) + command_line = get_command_line(scopes, tenant_id) + output = await run_command_line(command_line, self._process_timeout) + token = parse_token(output) + return token + + async def close(self) -> None: + """Calling this method is unnecessary""" + + +async def run_command_line(command_line: List[str], timeout: int) -> str: + try: + proc = await start_process(command_line) + stdout, stderr = await asyncio.wait_for(proc.communicate(), 10) + if sys.platform.startswith("win") and (b"' is not recognized" in stderr or proc.returncode == 9009): + # pwsh.exe isn't on the path; try powershell.exe + command_line[-1] = command_line[-1].replace("pwsh", "powershell", 1) + proc = await start_process(command_line) + stdout, stderr = await asyncio.wait_for(proc.communicate(), timeout) + + except asyncio.TimeoutError as ex: + proc.kill() + raise CredentialUnavailableError( + message="Timed out waiting for Azure PowerShell.\n" + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https://aka.ms/azsdk/python/identity/powershellcredential/troubleshoot." + ) from ex + except OSError as ex: + # failed to execute "cmd" or "/bin/sh"; Azure PowerShell may or may not be installed + error = CredentialUnavailableError( + message='Failed to execute "{}".\n' + "To mitigate this issue, please refer to the troubleshooting guidelines here at " + "https://aka.ms/azsdk/python/identity/powershellcredential/troubleshoot.".format(command_line[0]) + ) + raise error from ex + + decoded_stdout = stdout.decode() + + # casting because mypy infers Optional[int]; however, when proc.returncode is None, + # we handled TimeoutError above and therefore don't execute this line + raise_for_error(cast(int, proc.returncode), decoded_stdout, stderr.decode()) + return decoded_stdout + + +async def start_process(command_line): + working_directory = get_safe_working_dir() + proc = await asyncio.create_subprocess_exec( + *command_line, + cwd=working_directory, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + stdin=asyncio.subprocess.DEVNULL, + ) + return proc diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/certificate.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/certificate.py new file mode 100644 index 00000000000..8d2ad9ae12f --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/certificate.py @@ -0,0 +1,77 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Optional, Any + +from azure.core.credentials import AccessTokenInfo +from .._internal import AadClient, AsyncContextManager +from .._internal.get_token_mixin import GetTokenMixin +from ..._credentials.certificate import get_client_credential +from ..._internal import AadClientCertificate, validate_tenant_id + + +class CertificateCredential(AsyncContextManager, GetTokenMixin): + """Authenticates as a service principal using a certificate. + + The certificate must have an RSA private key, because this credential signs assertions using RS256. See + `Microsoft Entra ID documentation + `__ + for more information on configuring certificate authentication. + + :param str tenant_id: ID of the service principal's tenant. Also called its 'directory' ID. + :param str client_id: The service principal's client ID + :param str certificate_path: Path to a PEM-encoded certificate file including the private key. If not provided, + `certificate_data` is required. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example 'login.microsoftonline.com', + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword bytes certificate_data: The bytes of a certificate in PEM format, including the private key + :keyword password: The certificate's password. If a unicode string, it will be encoded as UTF-8. If the certificate + requires a different encoding, pass appropriately encoded bytes instead. + :paramtype password: str or bytes + :keyword cache_persistence_options: Configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_certificate_credential_async] + :end-before: [END create_certificate_credential_async] + :language: python + :dedent: 4 + :caption: Create a CertificateCredential. + """ + + def __init__(self, tenant_id: str, client_id: str, certificate_path: Optional[str] = None, **kwargs: Any) -> None: + validate_tenant_id(tenant_id) + + client_credential = get_client_credential(certificate_path, **kwargs) + + self._certificate = AadClientCertificate( + client_credential["private_key"], password=client_credential.get("passphrase") + ) + + self._client = AadClient(tenant_id, client_id, **kwargs) + self._client_id = client_id + super().__init__() + + async def __aenter__(self) -> "CertificateCredential": + await self._client.__aenter__() + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + + await self._client.__aexit__() + + async def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessTokenInfo]: + return self._client.get_cached_access_token(scopes, **kwargs) + + async def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + return await self._client.obtain_token_by_client_certificate(scopes, self._certificate, **kwargs) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/chained.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/chained.py new file mode 100644 index 00000000000..6f45d33b1e4 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/chained.py @@ -0,0 +1,192 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import asyncio +import logging +from typing import Any, Optional, cast + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from azure.core.credentials_async import AsyncSupportsTokenInfo, AsyncTokenCredential, AsyncTokenProvider +from .._internal import AsyncContextManager +from ... import CredentialUnavailableError +from ..._credentials.chained import _get_error_message +from ..._internal import within_credential_chain + +_LOGGER = logging.getLogger(__name__) + + +class ChainedTokenCredential(AsyncContextManager): + """A sequence of credentials that is itself a credential. + + Its :func:`get_token` method calls ``get_token`` on each credential in the sequence, in order, returning the first + valid token received. For more information, see + https://aka.ms/azsdk/python/identity/credential-chains#chainedtokencredential-overview. + + :param credentials: credential instances to form the chain + :type credentials: ~azure.core.credentials.AsyncTokenCredential + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_chained_token_credential_async] + :end-before: [END create_chained_token_credential_async] + :language: python + :dedent: 4 + :caption: Create a ChainedTokenCredential. + """ + + def __init__(self, *credentials: AsyncTokenProvider) -> None: + if not credentials: + raise ValueError("at least one credential is required") + + self._successful_credential: Optional[AsyncTokenProvider] = None + self.credentials = credentials + + async def close(self) -> None: + """Close the transport sessions of all credentials in the chain.""" + + await asyncio.gather(*(credential.close() for credential in self.credentials)) + + async def get_token( + self, + *scopes: str, + claims: Optional[str] = None, + tenant_id: Optional[str] = None, + enable_cae: bool = False, + **kwargs: Any, + ) -> AccessToken: + """Asynchronously request a token from each credential, in order, returning the first token received. + + If no credential provides a token, raises :class:`azure.core.exceptions.ClientAuthenticationError` + with an error message from each credential. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested + token. Defaults to False. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.core.exceptions.ClientAuthenticationError: no credential in the chain provided a token + """ + within_credential_chain.set(True) + history = [] + for credential in self.credentials: + try: + # Prioritize "get_token". Fall back to "get_token_info" if not available. + if hasattr(credential, "get_token"): + token = await cast(AsyncTokenCredential, credential).get_token( + *scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs + ) + else: + options: TokenRequestOptions = {} + if claims: + options["claims"] = claims + if tenant_id: + options["tenant_id"] = tenant_id + options["enable_cae"] = enable_cae + token_info = await cast(AsyncSupportsTokenInfo, credential).get_token_info(*scopes, **kwargs) + token = AccessToken(token_info.token, token_info.expires_on) + + _LOGGER.info("%s acquired a token from %s", self.__class__.__name__, credential.__class__.__name__) + self._successful_credential = credential + within_credential_chain.set(False) + return token + except CredentialUnavailableError as ex: + # credential didn't attempt authentication because it lacks required data or state -> continue + history.append((credential, ex.message)) + except Exception as ex: # pylint: disable=broad-except + # credential failed to authenticate, or something unexpectedly raised -> break + history.append((credential, str(ex))) + _LOGGER.debug( + '%s.get_token failed: %s raised unexpected error "%s"', + self.__class__.__name__, + credential.__class__.__name__, + ex, + exc_info=True, + ) + break + within_credential_chain.set(False) + attempts = _get_error_message(history) + message = ( + self.__class__.__name__ + + " failed to retrieve a token from the included credentials." + + attempts + + "\nTo mitigate this issue, please refer to the troubleshooting guidelines here at " + "https://aka.ms/azsdk/python/identity/defaultazurecredential/troubleshoot." + ) + raise ClientAuthenticationError(message=message) + + async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request a token from each chained credential, in order, returning the first token received. + + If no credential provides a token, raises :class:`azure.core.exceptions.ClientAuthenticationError` + with an error message from each credential. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + + :raises ~azure.core.exceptions.ClientAuthenticationError: no credential in the chain provided a token. + """ + within_credential_chain.set(True) + history = [] + options = options or {} + for credential in self.credentials: + try: + # Prioritize "get_token_info". Fall back to "get_token" if not available. + if hasattr(credential, "get_token_info"): + token_info = await cast(AsyncSupportsTokenInfo, credential).get_token_info(*scopes, options=options) + else: + if options.get("pop"): + raise CredentialUnavailableError( + "Proof of possession arguments are not supported for this credential." + ) + token = await cast(AsyncTokenCredential, credential).get_token(*scopes, **options) + token_info = AccessTokenInfo(token=token.token, expires_on=token.expires_on) + + _LOGGER.info("%s acquired a token from %s", self.__class__.__name__, credential.__class__.__name__) + self._successful_credential = credential + within_credential_chain.set(False) + return token_info + except CredentialUnavailableError as ex: + # credential didn't attempt authentication because it lacks required data or state -> continue + history.append((credential, ex.message)) + except Exception as ex: # pylint: disable=broad-except + # credential failed to authenticate, or something unexpectedly raised -> break + history.append((credential, str(ex))) + _LOGGER.debug( + '%s.get_token_info failed: %s raised unexpected error "%s"', + self.__class__.__name__, + credential.__class__.__name__, + ex, + exc_info=True, + ) + break + + within_credential_chain.set(False) + attempts = _get_error_message(history) + message = ( + self.__class__.__name__ + + " failed to retrieve a token from the included credentials." + + attempts + + "\nTo mitigate this issue, please refer to the troubleshooting guidelines here at " + "https://aka.ms/azsdk/python/identity/defaultazurecredential/troubleshoot." + ) + _LOGGER.warning(message) + raise ClientAuthenticationError(message=message) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/client_assertion.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/client_assertion.py new file mode 100644 index 00000000000..a316760455e --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/client_assertion.py @@ -0,0 +1,75 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Any, Callable, Optional + +from azure.core.credentials import AccessTokenInfo +from .._internal import AadClient, AsyncContextManager +from .._internal.get_token_mixin import GetTokenMixin + + +class ClientAssertionCredential(AsyncContextManager, GetTokenMixin): + """Authenticates a service principal with a JWT assertion. + + This credential is for advanced scenarios. :class:`~azure.identity.CertificateCredential` has a more + convenient API for the most common assertion scenario, authenticating a service principal with a certificate. + + :param str tenant_id: ID of the principal's tenant. Also called its "directory" ID. + :param str client_id: The principal's client ID + :param func: A callable that returns a string assertion. The credential will call this every time it + acquires a new token. + :paramtype func: Callable[[], str] + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example + "login.microsoftonline.com", the authority for Azure Public Cloud (which is the default). + :class:`~azure.identity.AzureAuthorityHosts` defines authorities for other clouds. + :keyword cache_persistence_options: configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_client_assertion_credential_async] + :end-before: [END create_client_assertion_credential_async] + :language: python + :dedent: 4 + :caption: Create a ClientAssertionCredential. + """ + + def __init__(self, tenant_id: str, client_id: str, func: Callable[[], str], **kwargs: Any) -> None: + self._func = func + authority = kwargs.pop("authority", None) + cache = kwargs.pop("cache", None) + cae_cache = kwargs.pop("cae_cache", None) + additionally_allowed_tenants = kwargs.pop("additionally_allowed_tenants", None) + self._client = AadClient( + tenant_id, + client_id, + authority=authority, + cache=cache, + cae_cache=cae_cache, + additionally_allowed_tenants=additionally_allowed_tenants, + **kwargs + ) + super().__init__() + + async def __aenter__(self) -> "ClientAssertionCredential": + await self._client.__aenter__() + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + await self._client.close() + + async def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessTokenInfo]: + return self._client.get_cached_access_token(scopes, **kwargs) + + async def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + assertion = self._func() + token = await self._client.obtain_token_by_jwt_assertion(scopes, assertion, **kwargs) + return token diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/client_secret.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/client_secret.py new file mode 100644 index 00000000000..50bbb3de931 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/client_secret.py @@ -0,0 +1,67 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Optional, Any + +from azure.core.credentials import AccessTokenInfo +from .._internal import AadClient, AsyncContextManager +from .._internal.get_token_mixin import GetTokenMixin +from ..._internal import validate_tenant_id + + +class ClientSecretCredential(AsyncContextManager, GetTokenMixin): + """Authenticates as a service principal using a client secret. + + :param str tenant_id: ID of the service principal's tenant. Also called its 'directory' ID. + :param str client_id: The service principal's client ID + :param str client_secret: One of the service principal's client secrets + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example 'login.microsoftonline.com', + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword cache_persistence_options: Configuration for persistent token caching. If unspecified, the credential + will cache tokens in memory. + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_client_secret_credential_async] + :end-before: [END create_client_secret_credential_async] + :language: python + :dedent: 4 + :caption: Create a ClientSecretCredential. + """ + + def __init__(self, tenant_id: str, client_id: str, client_secret: str, **kwargs: Any) -> None: + if not client_id: + raise ValueError("client_id should be the id of a Microsoft Entra application") + if not client_secret: + raise ValueError("secret should be a Microsoft Entra application's client secret") + if not tenant_id: + raise ValueError("tenant_id should be a Microsoft Entra tenant's id (also called its 'directory id')") + validate_tenant_id(tenant_id) + + self._client = AadClient(tenant_id, client_id, **kwargs) + self._client_id = client_id + self._secret = client_secret + super().__init__() + + async def __aenter__(self) -> "ClientSecretCredential": + await self._client.__aenter__() + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + + await self._client.__aexit__() + + async def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessTokenInfo]: + return self._client.get_cached_access_token(scopes, **kwargs) + + async def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + return await self._client.obtain_token_by_client_secret(scopes, self._secret, **kwargs) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/cloud_shell.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/cloud_shell.py new file mode 100644 index 00000000000..7c6bd862a9d --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/cloud_shell.py @@ -0,0 +1,29 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import os +from typing import Optional, Any + +from .._internal.managed_identity_base import AsyncManagedIdentityBase +from .._internal.managed_identity_client import AsyncManagedIdentityClient +from ..._constants import EnvironmentVariables +from ..._credentials.cloud_shell import _get_request, validate_client_id_and_config + + +class CloudShellCredential(AsyncManagedIdentityBase): + def get_client(self, **kwargs: Any) -> Optional[AsyncManagedIdentityClient]: + client_id = kwargs.get("client_id") + identity_config = kwargs.get("identity_config") + validate_client_id_and_config(client_id, identity_config) + + url = os.environ.get(EnvironmentVariables.MSI_ENDPOINT) + if url: + return AsyncManagedIdentityClient( + request_factory=functools.partial(_get_request, url), base_headers={"Metadata": "true"}, **kwargs + ) + return None + + def get_unavailable_message(self, desc: str = "") -> str: + return f"Cloud Shell managed identity configuration not found in environment. {desc}" diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/default.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/default.py new file mode 100644 index 00000000000..46fb0bd8b13 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/default.py @@ -0,0 +1,242 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import List, Optional, Any, cast + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from azure.core.credentials_async import AsyncTokenCredential, AsyncSupportsTokenInfo +from ..._constants import EnvironmentVariables +from ..._internal import get_default_authority, normalize_authority, within_dac +from .azure_cli import AzureCliCredential +from .azd_cli import AzureDeveloperCliCredential +from .azure_powershell import AzurePowerShellCredential +from .chained import ChainedTokenCredential +from .environment import EnvironmentCredential +from .managed_identity import ManagedIdentityCredential +from .shared_cache import SharedTokenCacheCredential +from .vscode import VisualStudioCodeCredential +from .workload_identity import WorkloadIdentityCredential + + +_LOGGER = logging.getLogger(__name__) + + +class DefaultAzureCredential(ChainedTokenCredential): + """A credential capable of handling most Azure SDK authentication scenarios. See + https://aka.ms/azsdk/python/identity/credential-chains#usage-guidance-for-defaultazurecredential. + + The identity it uses depends on the environment. When an access token is needed, it requests one using these + identities in turn, stopping when one provides a token: + + 1. A service principal configured by environment variables. See :class:`~azure.identity.aio.EnvironmentCredential` + for more details. + 2. WorkloadIdentityCredential if environment variable configuration is set by the Azure workload + identity webhook. + 3. An Azure managed identity. See :class:`~azure.identity.aio.ManagedIdentityCredential` for more details. + 4. On Windows only: a user who has signed in with a Microsoft application, such as Visual Studio. If multiple + identities are in the cache, then the value of the environment variable ``AZURE_USERNAME`` is used to select + which identity to use. See :class:`~azure.identity.aio.SharedTokenCacheCredential` for more details. + 5. The identity currently logged in to the Azure CLI. + 6. The identity currently logged in to Azure PowerShell. + 7. The identity currently logged in to the Azure Developer CLI. + + This default behavior is configurable with keyword arguments. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example 'login.microsoftonline.com', + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. Managed identities ignore this because they reside in a single cloud. + :keyword bool exclude_workload_identity_credential: Whether to exclude the workload identity from the credential. + Defaults to **False**. + :keyword bool exclude_developer_cli_credential: Whether to exclude the Azure Developer CLI + from the credential. Defaults to **False**. + :keyword bool exclude_cli_credential: Whether to exclude the Azure CLI from the credential. Defaults to **False**. + :keyword bool exclude_environment_credential: Whether to exclude a service principal configured by environment + variables from the credential. Defaults to **False**. + :keyword bool exclude_powershell_credential: Whether to exclude Azure PowerShell. Defaults to **False**. + :keyword bool exclude_visual_studio_code_credential: Whether to exclude stored credential from VS Code. + Defaults to **True**. + :keyword bool exclude_managed_identity_credential: Whether to exclude managed identity from the credential. + Defaults to **False**. + :keyword bool exclude_shared_token_cache_credential: Whether to exclude the shared token cache. Defaults to + **False**. + :keyword str managed_identity_client_id: The client ID of a user-assigned managed identity. Defaults to the value + of the environment variable AZURE_CLIENT_ID, if any. If not specified, a system-assigned identity will be used. + :keyword str workload_identity_client_id: The client ID of an identity assigned to the pod. Defaults to the value + of the environment variable AZURE_CLIENT_ID, if any. If not specified, the pod's default identity will be used. + :keyword str workload_identity_tenant_id: Preferred tenant for :class:`~azure.identity.WorkloadIdentityCredential`. + Defaults to the value of environment variable AZURE_TENANT_ID, if any. + :keyword str shared_cache_username: Preferred username for :class:`~azure.identity.aio.SharedTokenCacheCredential`. + Defaults to the value of environment variable AZURE_USERNAME, if any. + :keyword str shared_cache_tenant_id: Preferred tenant for :class:`~azure.identity.aio.SharedTokenCacheCredential`. + Defaults to the value of environment variable AZURE_TENANT_ID, if any. + :keyword str visual_studio_code_tenant_id: Tenant ID to use when authenticating with + :class:`~azure.identity.aio.VisualStudioCodeCredential`. Defaults to the "Azure: Tenant" setting in VS Code's + user settings or, when that setting has no value, the "organizations" tenant, which supports only Azure Active + Directory work or school accounts. + :keyword int process_timeout: The timeout in seconds to use for developer credentials that run + subprocesses (e.g. AzureCliCredential, AzurePowerShellCredential). Defaults to **10** seconds. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_default_credential_async] + :end-before: [END create_default_credential_async] + :language: python + :dedent: 4 + :caption: Create a DefaultAzureCredential. + """ + + def __init__(self, **kwargs: Any) -> None: # pylint: disable=too-many-statements, too-many-locals + if "tenant_id" in kwargs: + raise TypeError("'tenant_id' is not supported in DefaultAzureCredential.") + + authority = kwargs.pop("authority", None) + + vscode_tenant_id = kwargs.pop( + "visual_studio_code_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + vscode_args = dict(kwargs) + if authority: + vscode_args["authority"] = authority + if vscode_tenant_id: + vscode_args["tenant_id"] = vscode_tenant_id + + authority = normalize_authority(authority) if authority else get_default_authority() + + shared_cache_username = kwargs.pop("shared_cache_username", os.environ.get(EnvironmentVariables.AZURE_USERNAME)) + shared_cache_tenant_id = kwargs.pop( + "shared_cache_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + + managed_identity_client_id = kwargs.pop( + "managed_identity_client_id", os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + ) + workload_identity_client_id = kwargs.pop("workload_identity_client_id", managed_identity_client_id) + workload_identity_tenant_id = kwargs.pop( + "workload_identity_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + + vscode_tenant_id = kwargs.pop( + "visual_studio_code_tenant_id", os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + ) + + process_timeout = kwargs.pop("process_timeout", 10) + + exclude_workload_identity_credential = kwargs.pop("exclude_workload_identity_credential", False) + exclude_visual_studio_code_credential = kwargs.pop("exclude_visual_studio_code_credential", True) + exclude_developer_cli_credential = kwargs.pop("exclude_developer_cli_credential", False) + exclude_cli_credential = kwargs.pop("exclude_cli_credential", False) + exclude_environment_credential = kwargs.pop("exclude_environment_credential", False) + exclude_managed_identity_credential = kwargs.pop("exclude_managed_identity_credential", False) + exclude_shared_token_cache_credential = kwargs.pop("exclude_shared_token_cache_credential", False) + exclude_powershell_credential = kwargs.pop("exclude_powershell_credential", False) + + credentials: List[AsyncSupportsTokenInfo] = [] + within_dac.set(True) + if not exclude_environment_credential: + credentials.append(EnvironmentCredential(authority=authority, _within_dac=True, **kwargs)) + if not exclude_workload_identity_credential: + if all(os.environ.get(var) for var in EnvironmentVariables.WORKLOAD_IDENTITY_VARS): + client_id = workload_identity_client_id + credentials.append( + WorkloadIdentityCredential( + client_id=cast(str, client_id), + tenant_id=workload_identity_tenant_id, + token_file_path=os.environ[EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE], + **kwargs + ) + ) + if not exclude_managed_identity_credential: + credentials.append( + ManagedIdentityCredential( + client_id=managed_identity_client_id, + _exclude_workload_identity_credential=exclude_workload_identity_credential, + **kwargs + ) + ) + if not exclude_shared_token_cache_credential and SharedTokenCacheCredential.supported(): + try: + # username and/or tenant_id are only required when the cache contains tokens for multiple identities + shared_cache = SharedTokenCacheCredential( + username=shared_cache_username, tenant_id=shared_cache_tenant_id, authority=authority, **kwargs + ) + credentials.append(shared_cache) + except Exception as ex: # pylint:disable=broad-except + _LOGGER.info("Shared token cache is unavailable: '%s'", ex) + if not exclude_visual_studio_code_credential: + credentials.append(VisualStudioCodeCredential(**vscode_args)) + if not exclude_cli_credential: + credentials.append(AzureCliCredential(process_timeout=process_timeout)) + if not exclude_powershell_credential: + credentials.append(AzurePowerShellCredential(process_timeout=process_timeout)) + if not exclude_developer_cli_credential: + credentials.append(AzureDeveloperCliCredential(process_timeout=process_timeout)) + within_dac.set(False) + super().__init__(*credentials) + + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Asynchronously request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The exception has a + `message` attribute listing each authentication attempt and its error message. + """ + if self._successful_credential: + token = await cast(AsyncTokenCredential, self._successful_credential).get_token( + *scopes, claims=claims, tenant_id=tenant_id, **kwargs + ) + _LOGGER.info( + "%s acquired a token from %s", self.__class__.__name__, self._successful_credential.__class__.__name__ + ) + return token + + within_dac.set(True) + token = await super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + within_dac.set(False) + return token + + async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Asynchronously request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The exception has a + `message` attribute listing each authentication attempt and its error message. + """ + if self._successful_credential: + token_info = await cast(AsyncSupportsTokenInfo, self._successful_credential).get_token_info( + *scopes, options=options + ) + _LOGGER.info( + "%s acquired a token from %s", self.__class__.__name__, self._successful_credential.__class__.__name__ + ) + return token_info + + within_dac.set(True) + token_info = await cast(AsyncSupportsTokenInfo, super()).get_token_info(*scopes, options=options) + within_dac.set(False) + return token_info diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/environment.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/environment.py new file mode 100644 index 00000000000..bb981406d2a --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/environment.py @@ -0,0 +1,153 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import Optional, Union, Any, cast + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from azure.core.credentials_async import AsyncSupportsTokenInfo +from .._internal.decorators import log_get_token_async +from ... import CredentialUnavailableError +from ..._constants import EnvironmentVariables +from .._internal import AsyncContextManager +from .certificate import CertificateCredential +from .client_secret import ClientSecretCredential + +_LOGGER = logging.getLogger(__name__) + + +class EnvironmentCredential(AsyncContextManager): + """A credential configured by environment variables. + + This credential is capable of authenticating as a service principal using a client secret or a certificate, or as + a user with a username and password. Configuration is attempted in this order, using these environment variables: + + Service principal with secret: + - **AZURE_TENANT_ID**: ID of the service principal's tenant. Also called its 'directory' ID. + - **AZURE_CLIENT_ID**: the service principal's client ID + - **AZURE_CLIENT_SECRET**: one of the service principal's client secrets + - **AZURE_AUTHORITY_HOST**: authority of a Microsoft Entra endpoint, for example + "login.microsoftonline.com", the authority for Azure Public Cloud, which is the default + when no value is given. + + Service principal with certificate: + - **AZURE_TENANT_ID**: ID of the service principal's tenant. Also called its 'directory' ID. + - **AZURE_CLIENT_ID**: the service principal's client ID + - **AZURE_CLIENT_CERTIFICATE_PATH**: path to a PEM or PKCS12 certificate file including the private key. + - **AZURE_CLIENT_CERTIFICATE_PASSWORD**: (optional) password of the certificate file, if any. + - **AZURE_AUTHORITY_HOST**: authority of a Microsoft Entra endpoint, for example + "login.microsoftonline.com", the authority for Azure Public Cloud, which is the default + when no value is given. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_environment_credential_async] + :end-before: [END create_environment_credential_async] + :language: python + :dedent: 4 + :caption: Create an EnvironmentCredential. + """ + + def __init__(self, **kwargs: Any) -> None: + self._credential: Optional[Union[CertificateCredential, ClientSecretCredential]] = None + + if all(os.environ.get(v) is not None for v in EnvironmentVariables.CLIENT_SECRET_VARS): + self._credential = ClientSecretCredential( + client_id=os.environ[EnvironmentVariables.AZURE_CLIENT_ID], + client_secret=os.environ[EnvironmentVariables.AZURE_CLIENT_SECRET], + tenant_id=os.environ[EnvironmentVariables.AZURE_TENANT_ID], + **kwargs + ) + elif all(os.environ.get(v) is not None for v in EnvironmentVariables.CERT_VARS): + self._credential = CertificateCredential( + client_id=os.environ[EnvironmentVariables.AZURE_CLIENT_ID], + tenant_id=os.environ[EnvironmentVariables.AZURE_TENANT_ID], + certificate_path=os.environ[EnvironmentVariables.AZURE_CLIENT_CERTIFICATE_PATH], + password=os.environ.get(EnvironmentVariables.AZURE_CLIENT_CERTIFICATE_PASSWORD), + send_certificate_chain=bool( + os.environ.get(EnvironmentVariables.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN, False) + ), + **kwargs + ) + + if self._credential: + _LOGGER.info("Environment is configured for %s", self._credential.__class__.__name__) + else: + expected_variables = set(EnvironmentVariables.CERT_VARS + EnvironmentVariables.CLIENT_SECRET_VARS) + set_variables = [v for v in expected_variables if v in os.environ] + if set_variables: + _LOGGER.log( + logging.INFO if kwargs.get("_within_dac") else logging.WARNING, + "Incomplete environment configuration for EnvironmentCredential. These variables are set: %s", + ", ".join(set_variables), + ) + else: + _LOGGER.info("No environment configuration found.") + + async def __aenter__(self) -> "EnvironmentCredential": + if self._credential: + await self._credential.__aenter__() + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + + if self._credential: + await self._credential.__aexit__() + + @log_get_token_async + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Asynchronously request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: environment variable configuration is incomplete + """ + if not self._credential: + message = ( + "EnvironmentCredential authentication unavailable. Environment variables are not fully configured.\n" + "Visit https://aka.ms/azsdk/python/identity/environmentcredential/troubleshoot to troubleshoot " + "this issue." + ) + raise CredentialUnavailableError(message=message) + return await self._credential.get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + @log_get_token_async + async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scope for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + + :raises ~azure.identity.CredentialUnavailableError: environment variable configuration is incomplete. + """ + if not self._credential: + message = ( + "EnvironmentCredential authentication unavailable. Environment variables are not fully configured.\n" + "Visit https://aka.ms/azsdk/python/identity/environmentcredential/troubleshoot to troubleshoot " + "this issue." + ) + raise CredentialUnavailableError(message=message) + return await cast(AsyncSupportsTokenInfo, self._credential).get_token_info(*scopes, options=options) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/imds.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/imds.py new file mode 100644 index 00000000000..f9286c9f88f --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/imds.py @@ -0,0 +1,85 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +from typing import Optional, Any + +from azure.core.exceptions import ClientAuthenticationError, HttpResponseError +from azure.core.credentials import AccessTokenInfo +from ... import CredentialUnavailableError +from ..._constants import EnvironmentVariables +from .._internal import AsyncContextManager +from .._internal.get_token_mixin import GetTokenMixin +from .._internal.managed_identity_client import AsyncManagedIdentityClient +from ..._internal import within_credential_chain +from ..._credentials.imds import _get_request, _check_forbidden_response, PIPELINE_SETTINGS + + +class ImdsCredential(AsyncContextManager, GetTokenMixin): + def __init__(self, **kwargs: Any) -> None: + super().__init__() + + self._client = AsyncManagedIdentityClient(_get_request, **dict(PIPELINE_SETTINGS, **kwargs)) + if EnvironmentVariables.AZURE_POD_IDENTITY_AUTHORITY_HOST in os.environ: + self._endpoint_available: Optional[bool] = True + else: + self._endpoint_available = None + self._user_assigned_identity = "client_id" in kwargs or "identity_config" in kwargs + + async def __aenter__(self) -> "ImdsCredential": + await self._client.__aenter__() + return self + + async def close(self) -> None: + await self._client.close() + + async def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessTokenInfo]: + return self._client.get_cached_token(*scopes) + + async def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: # pylint:disable=unused-argument + + if within_credential_chain.get() and not self._endpoint_available: + # If within a chain (e.g. DefaultAzureCredential), we do a quick check to see if the IMDS endpoint + # is available to avoid hanging for a long time if the endpoint isn't available. + try: + await self._client.request_token(*scopes, connection_timeout=1, retry_total=0) + self._endpoint_available = True + except HttpResponseError as ex: + # IMDS responded + _check_forbidden_response(ex) + self._endpoint_available = True + except Exception as ex: # pylint:disable=broad-except + error_message = ( + "ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint." + ) + raise CredentialUnavailableError(message=error_message) from ex + + try: + token_info = await self._client.request_token(*scopes, headers={"Metadata": "true"}) + except CredentialUnavailableError: + # Response is not json, skip the IMDS credential + raise + except HttpResponseError as ex: + # 400 in response to a token request indicates managed identity is disabled, + # or the identity with the specified client_id is not available + if ex.status_code == 400: + error_message = "ManagedIdentityCredential authentication unavailable. " + if self._user_assigned_identity: + error_message += "The requested identity has not been assigned to this resource." + else: + error_message += "No identity has been assigned to this resource." + + if ex.message: + error_message += f" Error: {ex.message}" + + raise CredentialUnavailableError(message=error_message) from ex + + _check_forbidden_response(ex) + # any other error is unexpected + raise ClientAuthenticationError(message=ex.message, response=ex.response) from ex + except Exception as ex: # pylint:disable=broad-except + # if anything else was raised, assume the endpoint is unavailable + error_message = "ManagedIdentityCredential authentication unavailable, no response from the IMDS endpoint." + raise CredentialUnavailableError(error_message) from ex + return token_info diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/managed_identity.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/managed_identity.py new file mode 100644 index 00000000000..de9a73ac7ec --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/managed_identity.py @@ -0,0 +1,170 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import os +from typing import Optional, Any, Mapping, cast + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from azure.core.credentials_async import AsyncTokenCredential, AsyncSupportsTokenInfo +from .._internal import AsyncContextManager +from .._internal.decorators import log_get_token_async +from ... import CredentialUnavailableError +from ..._constants import EnvironmentVariables +from ..._credentials.managed_identity import validate_identity_config + + +_LOGGER = logging.getLogger(__name__) + + +class ManagedIdentityCredential(AsyncContextManager): + """Authenticates with an Azure managed identity in any hosting environment which supports managed identities. + + This credential defaults to using a system-assigned identity. To configure a user-assigned identity, use one of + the keyword arguments. See `Microsoft Entra ID documentation + `__ for more + information about configuring managed identity for applications. + + :keyword str client_id: a user-assigned identity's client ID or, when using Pod Identity, the client ID of a + Microsoft Entra app registration. This argument is supported in all hosting environments. + :keyword identity_config: a mapping ``{parameter_name: value}`` specifying a user-assigned identity by its object + or resource ID, for example ``{"object_id": "..."}``. Check the documentation for your hosting environment to + learn what values it expects. + :paramtype identity_config: Mapping[str, str] + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_managed_identity_credential_async] + :end-before: [END create_managed_identity_credential_async] + :language: python + :dedent: 4 + :caption: Create a ManagedIdentityCredential. + """ + + def __init__( + self, *, client_id: Optional[str] = None, identity_config: Optional[Mapping[str, str]] = None, **kwargs: Any + ) -> None: + validate_identity_config(client_id, identity_config) + self._credential: Optional[AsyncSupportsTokenInfo] = None + exclude_workload_identity = kwargs.pop("_exclude_workload_identity_credential", False) + + if os.environ.get(EnvironmentVariables.IDENTITY_ENDPOINT): + if os.environ.get(EnvironmentVariables.IDENTITY_HEADER): + if os.environ.get(EnvironmentVariables.IDENTITY_SERVER_THUMBPRINT): + _LOGGER.info("%s will use Service Fabric managed identity", self.__class__.__name__) + from .service_fabric import ServiceFabricCredential + + self._credential = ServiceFabricCredential( + client_id=client_id, identity_config=identity_config, **kwargs + ) + else: + _LOGGER.info("%s will use App Service managed identity", self.__class__.__name__) + from .app_service import AppServiceCredential + + self._credential = AppServiceCredential( + client_id=client_id, identity_config=identity_config, **kwargs + ) + elif os.environ.get(EnvironmentVariables.IMDS_ENDPOINT): + _LOGGER.info("%s will use Azure Arc managed identity", self.__class__.__name__) + from .azure_arc import AzureArcCredential + + self._credential = AzureArcCredential(client_id=client_id, identity_config=identity_config, **kwargs) + elif os.environ.get(EnvironmentVariables.MSI_ENDPOINT): + if os.environ.get(EnvironmentVariables.MSI_SECRET): + _LOGGER.info("%s will use Azure ML managed identity", self.__class__.__name__) + from .azure_ml import AzureMLCredential + + self._credential = AzureMLCredential(client_id=client_id, identity_config=identity_config, **kwargs) + else: + _LOGGER.info("%s will use Cloud Shell managed identity", self.__class__.__name__) + from .cloud_shell import CloudShellCredential + + self._credential = CloudShellCredential(client_id=client_id, identity_config=identity_config, **kwargs) + elif ( + all(os.environ.get(var) for var in EnvironmentVariables.WORKLOAD_IDENTITY_VARS) + and not exclude_workload_identity + ): + _LOGGER.info("%s will use workload identity", self.__class__.__name__) + from .workload_identity import WorkloadIdentityCredential + + workload_client_id = client_id or os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + if not workload_client_id: + raise ValueError('Configure the environment with a client ID or pass a value for "client_id" argument') + + self._credential = WorkloadIdentityCredential( + tenant_id=os.environ[EnvironmentVariables.AZURE_TENANT_ID], + client_id=workload_client_id, + token_file_path=os.environ[EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE], + **kwargs + ) + else: + from .imds import ImdsCredential + + _LOGGER.info("%s will use IMDS", self.__class__.__name__) + self._credential = ImdsCredential(client_id=client_id, identity_config=identity_config, **kwargs) + + async def __aenter__(self) -> "ManagedIdentityCredential": + if self._credential: + await self._credential.__aenter__() + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + if self._credential: + await self._credential.close() + + @log_get_token_async + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Asynchronously request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: not used by this credential; any value provided will be ignored. + :keyword str tenant_id: not used by this credential; any value provided will be ignored. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: managed identity isn't available in the hosting environment + """ + if not self._credential: + raise CredentialUnavailableError( + message="No managed identity endpoint found. \n" + "The Target Azure platform could not be determined from environment variables. " + "Visit https://aka.ms/azsdk/python/identity/managedidentitycredential/troubleshoot to " + "troubleshoot this issue." + ) + return await cast(AsyncTokenCredential, self._credential).get_token( + *scopes, claims=claims, tenant_id=tenant_id, **kwargs + ) + + @log_get_token_async + async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scope for the access token. This credential allows only one scope per request. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + :raises ~azure.identity.CredentialUnavailableError: managed identity isn't available in the hosting environment. + """ + if not self._credential: + raise CredentialUnavailableError( + message="No managed identity endpoint found. \n" + "The Target Azure platform could not be determined from environment variables. \n" + "Visit https://aka.ms/azsdk/python/identity/managedidentitycredential/troubleshoot to " + "troubleshoot this issue." + ) + return await cast(AsyncSupportsTokenInfo, self._credential).get_token_info(*scopes, options=options) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/on_behalf_of.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/on_behalf_of.py new file mode 100644 index 00000000000..102db030f63 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/on_behalf_of.py @@ -0,0 +1,135 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +from typing import Optional, Union, Any, Dict, Callable + +from azure.core.exceptions import ClientAuthenticationError +from azure.core.credentials import AccessTokenInfo +from .._internal import AadClient, AsyncContextManager +from .._internal.get_token_mixin import GetTokenMixin +from ..._credentials.certificate import get_client_credential +from ..._internal import AadClientCertificate, validate_tenant_id + +_LOGGER = logging.getLogger(__name__) + + +class OnBehalfOfCredential(AsyncContextManager, GetTokenMixin): + """Authenticates a service principal via the on-behalf-of flow. + + This flow is typically used by middle-tier services that authorize requests to other services with a delegated + user identity. Because this is not an interactive authentication flow, an application using it must have admin + consent for any delegated permissions before requesting tokens for them. See `Microsoft Entra ID documentation + `__ for a more detailed + description of the on-behalf-of flow. + + :param str tenant_id: ID of the service principal's tenant. Also called its "directory" ID. + :param str client_id: The service principal's client ID. + :keyword str client_secret: Optional. A client secret to authenticate the service principal. + One of **client_secret**, **client_certificate**, or **client_assertion_func** must be provided. + :keyword bytes client_certificate: Optional. The bytes of a certificate in PEM or PKCS12 format including + the private key to authenticate the service principal. One of **client_secret**, **client_certificate**, + or **client_assertion_func** must be provided. + :keyword client_assertion_func: Optional. Function that returns client assertions that authenticate the + application to Microsoft Entra ID. This function is called each time the credential requests a token. It must + return a valid assertion for the target resource. + :paramtype client_assertion_func: Callable[[], str] + :keyword str user_assertion: Required. The access token the credential will use as the user assertion when + requesting on-behalf-of tokens. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com", + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword password: A certificate password. Used only when **client_certificate** is provided. If this value + is a unicode string, it will be encoded as UTF-8. If the certificate requires a different encoding, pass + appropriately encoded bytes instead. + :paramtype password: str or bytes + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START create_on_behalf_of_credential_async] + :end-before: [END create_on_behalf_of_credential_async] + :language: python + :dedent: 4 + :caption: Create an OnBehalfOfCredential. + """ + + def __init__( + self, + tenant_id: str, + client_id: str, + *, + client_certificate: Optional[bytes] = None, + client_secret: Optional[str] = None, + client_assertion_func: Optional[Callable[[], str]] = None, + user_assertion: str, + password: Optional[Union[str, bytes]] = None, + **kwargs: Any + ) -> None: + super().__init__() + validate_tenant_id(tenant_id) + + self._assertion = user_assertion + if not self._assertion: + raise TypeError('"user_assertion" must not be empty.') + + if client_assertion_func: + if client_certificate or client_secret: + raise ValueError( + "It is invalid to specify more than one of the following: " + '"client_assertion_func", "client_certificate" or "client_secret".' + ) + self._client_credential: Union[str, AadClientCertificate, Dict[str, Any]] = { + "client_assertion": client_assertion_func, + } + elif client_certificate: + if client_secret: + raise ValueError('Specifying both "client_certificate" and "client_secret" is not valid.') + try: + cert = get_client_credential(None, password, client_certificate) + except ValueError as ex: + message = '"client_certificate" is not a valid certificate in PEM or PKCS12 format' + raise ValueError(message) from ex + self._client_credential = AadClientCertificate(cert["private_key"], password=cert.get("passphrase")) + elif client_secret: + self._client_credential = client_secret + else: + raise TypeError('Either "client_certificate", "client_secret", or "client_assertion_func" must be provided') + + # note AadClient handles "authority" and any pipeline kwargs + self._client = AadClient(tenant_id, client_id, **kwargs) + + async def __aenter__(self) -> "OnBehalfOfCredential": + await self._client.__aenter__() + return self + + async def close(self) -> None: + await self._client.close() + + async def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessTokenInfo]: + return self._client.get_cached_access_token(scopes, **kwargs) + + async def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + # Note we assume the cache has tokens for one user only. That's okay because each instance of this class is + # locked to a single user (assertion). This assumption will become unsafe if this class allows applications + # to change an instance's assertion. + refresh_tokens = self._client.get_cached_refresh_tokens(scopes) + if len(refresh_tokens) == 1: # there should be only one + try: + refresh_token = refresh_tokens[0]["secret"] + return await self._client.obtain_token_by_refresh_token_on_behalf_of( + scopes, self._client_credential, refresh_token, **kwargs + ) + except ClientAuthenticationError as ex: + _LOGGER.debug("silent authentication failed: %s", ex, exc_info=True) + except (IndexError, KeyError, TypeError) as ex: + # this is purely defensive, hasn't been observed in practice + _LOGGER.debug("silent authentication failed due to malformed refresh token: %s", ex, exc_info=True) + + # we don't have a refresh token, or silent auth failed: acquire a new token from the assertion + return await self._client.obtain_token_on_behalf_of(scopes, self._client_credential, self._assertion, **kwargs) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/service_fabric.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/service_fabric.py new file mode 100644 index 00000000000..dad591016f3 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/service_fabric.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Optional, Any + +from .._internal.managed_identity_base import AsyncManagedIdentityBase +from .._internal.managed_identity_client import AsyncManagedIdentityClient +from ..._credentials.service_fabric import _get_client_args + + +class ServiceFabricCredential(AsyncManagedIdentityBase): + def get_client(self, **kwargs: Any) -> Optional[AsyncManagedIdentityClient]: + client_args = _get_client_args(**kwargs) + if client_args: + return AsyncManagedIdentityClient(**client_args) + return None + + def get_unavailable_message(self, desc: str = "") -> str: + return f"Service Fabric managed identity configuration not found in environment. {desc}" diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/shared_cache.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/shared_cache.py new file mode 100644 index 00000000000..6d5f38d497f --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/shared_cache.py @@ -0,0 +1,154 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Any, Optional, cast +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from ..._internal.aad_client import AadClientBase +from ... import CredentialUnavailableError +from ..._constants import DEVELOPER_SIGN_ON_CLIENT_ID +from ..._internal.shared_token_cache import NO_TOKEN, SharedTokenCacheBase +from .._internal import AsyncContextManager +from .._internal.aad_client import AadClient +from .._internal.decorators import log_get_token_async + + +class SharedTokenCacheCredential(SharedTokenCacheBase, AsyncContextManager): + """Authenticates using tokens in the local cache shared between Microsoft applications. + + :param str username: + Username (typically an email address) of the user to authenticate as. This is required because the local cache + may contain tokens for multiple identities. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example 'login.microsoftonline.com', + the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts` + defines authorities for other clouds. + :keyword str tenant_id: a Microsoft Entra tenant ID. Used to select an account when the cache contains + tokens for multiple identities. + :keyword cache_persistence_options: configuration for persistent token caching. If not provided, the credential + will use the persistent cache shared by Microsoft development applications + :paramtype cache_persistence_options: ~azure.identity.TokenCachePersistenceOptions + """ + + async def __aenter__(self) -> "SharedTokenCacheCredential": + if self._client: + await self._client.__aenter__() # type: ignore + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + + if self._client: + await self._client.__aexit__() # type: ignore + + @log_get_token_async + async def get_token( + self, + *scopes: str, + claims: Optional[str] = None, + tenant_id: Optional[str] = None, + enable_cae: bool = False, + **kwargs: Any, + ) -> AccessToken: + """Get an access token for `scopes` from the shared cache. + + If no access token is cached, attempt to acquire one using a cached refresh token. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested + token. Defaults to False. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: the cache is unavailable or contains insufficient user + information + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. Any error response from Microsoft Entra ID is available as the error's + ``response`` attribute. + """ + options: TokenRequestOptions = {} + if claims: + options["claims"] = claims + if tenant_id: + options["tenant_id"] = tenant_id + options["enable_cae"] = enable_cae + + token_info = await self._get_token_base(*scopes, options=options, base_method_name="get_token", **kwargs) + return AccessToken(token_info.token, token_info.expires_on) + + @log_get_token_async + async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Get an access token for `scopes` from the shared cache. + + If no access token is cached, attempt to acquire one using a cached refresh token. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scope for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + :raises ~azure.identity.CredentialUnavailableError: the cache is unavailable or contains insufficient user + information + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. Any error response from Microsoft Entra ID is available as the error's + ``response`` attribute. + """ + return await self._get_token_base(*scopes, options=options, base_method_name="get_token_info") + + async def _get_token_base( + self, + *scopes: str, + options: Optional[TokenRequestOptions] = None, + base_method_name: str = "get_token_info", + **kwargs: Any, + ) -> AccessTokenInfo: + if not scopes: + raise ValueError(f"'{base_method_name}' requires at least one scope") + + if not self._client_initialized: + self._initialize_client() + + options = options or {} + claims = options.get("claims") + tenant_id = options.get("tenant_id") + is_cae = options.get("enable_cae", False) + + token_cache = self._cae_cache if is_cae else self._cache + + # Try to load the cache if it is None. + if not token_cache: + token_cache = self._initialize_cache(is_cae=is_cae) + + # If the cache is still None, raise an error. + if not token_cache: + raise CredentialUnavailableError(message="Shared token cache unavailable") + + account = self._get_account(self._username, self._tenant_id, is_cae=is_cae) + + token = self._get_cached_access_token(scopes, account, is_cae=is_cae) + if token: + return token + + # try each refresh token, returning the first access token acquired + for refresh_token in self._get_refresh_tokens(account, is_cae=is_cae): + token = await cast(AadClient, self._client).obtain_token_by_refresh_token( + scopes, refresh_token, claims=claims, tenant_id=tenant_id, enable_cae=is_cae, **kwargs + ) + return token + + raise CredentialUnavailableError(message=NO_TOKEN.format(account.get("username"))) + + def _get_auth_client(self, **kwargs: Any) -> AadClientBase: + return AadClient(client_id=DEVELOPER_SIGN_ON_CLIENT_ID, **kwargs) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/vscode.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/vscode.py new file mode 100644 index 00000000000..9451cc45f01 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/vscode.py @@ -0,0 +1,127 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import cast, Optional, Any + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from azure.core.exceptions import ClientAuthenticationError +from ..._exceptions import CredentialUnavailableError +from .._internal import AsyncContextManager +from .._internal.aad_client import AadClient +from .._internal.get_token_mixin import GetTokenMixin +from .._internal.decorators import log_get_token_async +from ..._credentials.vscode import _VSCodeCredentialBase +from ..._internal import within_dac + + +class VisualStudioCodeCredential(_VSCodeCredentialBase, AsyncContextManager, GetTokenMixin): + """Authenticates as the Azure user signed in to Visual Studio Code via the 'Azure Account' extension. + + It's a `known issue `_ that this credential doesn't + work with `Azure Account extension `_ + versions newer than **0.9.11**. A long-term fix to this problem is in progress. In the meantime, consider + authenticating with :class:`AzureCliCredential`. + + :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com". + This argument is required for a custom cloud and usually unnecessary otherwise. Defaults to the authority + matching the "Azure: Cloud" setting in VS Code's user settings or, when that setting has no value, the + authority for Azure Public Cloud. + :keyword str tenant_id: ID of the tenant the credential should authenticate in. Defaults to the "Azure: Tenant" + setting in VS Code's user settings or, when that setting has no value, the "organizations" tenant, which + supports only Microsoft Entra work or school accounts. + :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id" + for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to + acquire tokens for any tenant the application can access. + """ + + async def __aenter__(self) -> "VisualStudioCodeCredential": + if self._client: + await self._client.__aenter__() + return self + + async def close(self) -> None: + """Close the credential's transport session.""" + + if self._client: + await self._client.__aexit__() + + @log_get_token_async + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + """Request an access token for `scopes` as the user currently signed in to Visual Studio Code. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises ~azure.identity.CredentialUnavailableError: the credential cannot retrieve user details from Visual + Studio Code + """ + if self._unavailable_reason: + error_message = ( + self._unavailable_reason + "\n" + "Visit https://aka.ms/azsdk/python/identity/vscodecredential/troubleshoot" + " to troubleshoot this issue." + ) + raise CredentialUnavailableError(message=error_message) + if not self._client: + raise CredentialUnavailableError("Initialization failed") + if within_dac.get(): + try: + token = await super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + return token + except ClientAuthenticationError as ex: + raise CredentialUnavailableError(message=ex.message) from ex + return await super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes` as the user currently signed in to Visual Studio Code. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + :raises ~azure.identity.CredentialUnavailableError: the credential cannot retrieve user details from Visual + Studio Code. + """ + if self._unavailable_reason: + error_message = ( + self._unavailable_reason + "\n" + "Visit https://aka.ms/azsdk/python/identity/vscodecredential/troubleshoot" + " to troubleshoot this issue." + ) + raise CredentialUnavailableError(message=error_message) + if within_dac.get(): + try: + token = await super().get_token_info(*scopes, options=options) + return token + except ClientAuthenticationError as ex: + raise CredentialUnavailableError(message=ex.message) from ex + return await super().get_token_info(*scopes, options=options) + + async def _acquire_token_silently(self, *scopes: str, **kwargs: Any) -> Optional[AccessTokenInfo]: + self._client = cast(AadClient, self._client) + return self._client.get_cached_access_token(scopes, **kwargs) + + async def _request_token(self, *scopes: str, **kwargs: Any) -> AccessTokenInfo: + refresh_token = self._get_refresh_token() + self._client = cast(AadClient, self._client) + return await self._client.obtain_token_by_refresh_token(scopes, refresh_token, **kwargs) + + def _get_client(self, **kwargs: Any) -> AadClient: + return AadClient(**kwargs) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/workload_identity.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/workload_identity.py new file mode 100644 index 00000000000..a139f475da7 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_credentials/workload_identity.py @@ -0,0 +1,77 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import os +from typing import Any, Optional +from .client_assertion import ClientAssertionCredential +from ..._credentials.workload_identity import TokenFileMixin +from ..._constants import EnvironmentVariables + + +class WorkloadIdentityCredential(ClientAssertionCredential, TokenFileMixin): + """Authenticates using Microsoft Entra Workload ID. + + Workload identity authentication is a feature in Azure that allows applications running on virtual machines (VMs) + to access other Azure resources without the need for a service principal or managed identity. With workload + identity authentication, applications authenticate themselves using their own identity, rather than using a shared + service principal or managed identity. Under the hood, workload identity authentication uses the concept of Service + Account Credentials (SACs), which are automatically created by Azure and stored securely in the VM. By using + workload identity authentication, you can avoid the need to manage and rotate service principals or managed + identities for each application on each VM. Additionally, because SACs are created automatically and managed by + Azure, you don't need to worry about storing and securing sensitive credentials themselves. + + The WorkloadIdentityCredential supports Azure workload identity authentication on Azure Kubernetes and acquires + a token using the service account credentials available in the Azure Kubernetes environment. Refer + to `this workload identity overview `__ + for more information. + + :keyword str tenant_id: ID of the application's Microsoft Entra tenant. Also called its "directory" ID. + :keyword str client_id: The client ID of a Microsoft Entra app registration. + :keyword str token_file_path: The path to a file containing a Kubernetes service account token that authenticates + the identity. + + .. admonition:: Example: + + .. literalinclude:: ../samples/credential_creation_code_snippets.py + :start-after: [START workload_identity_credential_async] + :end-before: [END workload_identity_credential_async] + :language: python + :dedent: 4 + :caption: Create a WorkloadIdentityCredential. + """ + + def __init__( + self, + *, + tenant_id: Optional[str] = None, + client_id: Optional[str] = None, + token_file_path: Optional[str] = None, + **kwargs: Any, + ) -> None: + tenant_id = tenant_id or os.environ.get(EnvironmentVariables.AZURE_TENANT_ID) + client_id = client_id or os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID) + token_file_path = token_file_path or os.environ.get(EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE) + if not tenant_id: + raise ValueError( + "'tenant_id' is required. Please pass it in or set the " + f"{EnvironmentVariables.AZURE_TENANT_ID} environment variable" + ) + if not client_id: + raise ValueError( + "'client_id' is required. Please pass it in or set the " + f"{EnvironmentVariables.AZURE_CLIENT_ID} environment variable" + ) + if not token_file_path: + raise ValueError( + "'token_file_path' is required. Please pass it in or set the " + f"{EnvironmentVariables.AZURE_FEDERATED_TOKEN_FILE} environment variable" + ) + self._token_file_path = token_file_path + super().__init__( + tenant_id=tenant_id, + client_id=client_id, + func=self._get_service_account_token, + token_file_path=token_file_path, + **kwargs, + ) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/__init__.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/__init__.py new file mode 100644 index 00000000000..f07e04aeb19 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/__init__.py @@ -0,0 +1,32 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +from types import TracebackType +from typing import Optional, Type, TypeVar + +from .aad_client import AadClient +from .decorators import wrap_exceptions + +T = TypeVar("T", bound="AsyncContextManager") + + +class AsyncContextManager(abc.ABC): + @abc.abstractmethod + async def close(self) -> None: + pass + + async def __aenter__(self: T) -> T: + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]] = None, + exc_value: Optional[BaseException] = None, + traceback: Optional[TracebackType] = None, + ) -> None: + await self.close() + + +__all__ = ["AadClient", "AsyncContextManager", "wrap_exceptions"] diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/aad_client.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/aad_client.py new file mode 100644 index 00000000000..7b99f85ac91 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/aad_client.py @@ -0,0 +1,97 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import time +from typing import Iterable, Optional, Union, Dict, Any + +from azure.core.credentials import AccessTokenInfo +from azure.core.pipeline import AsyncPipeline +from azure.core.pipeline.policies import AsyncHTTPPolicy, SansIOHTTPPolicy +from azure.core.pipeline.transport import HttpRequest +from ..._internal import AadClientCertificate +from ..._internal import AadClientBase +from ..._internal.pipeline import build_async_pipeline + +Policy = Union[AsyncHTTPPolicy, SansIOHTTPPolicy] + + +# pylint:disable=invalid-overridden-method +class AadClient(AadClientBase): + async def __aenter__(self) -> "AadClient": + await self._pipeline.__aenter__() + return self + + async def __aexit__(self, *args): + await self.close() + + async def close(self) -> None: + """Close the client's transport session.""" + + await self._pipeline.__aexit__() + + async def obtain_token_by_authorization_code( + self, scopes: Iterable[str], code: str, redirect_uri: str, client_secret: Optional[str] = None, **kwargs + ) -> AccessTokenInfo: + request = self._get_auth_code_request( + scopes=scopes, code=code, redirect_uri=redirect_uri, client_secret=client_secret, **kwargs + ) + return await self._run_pipeline(request, **kwargs) + + async def obtain_token_by_client_certificate( + self, scopes: Iterable[str], certificate: AadClientCertificate, **kwargs + ) -> AccessTokenInfo: + request = self._get_client_certificate_request(scopes, certificate, **kwargs) + return await self._run_pipeline(request, stream=False, **kwargs) + + async def obtain_token_by_client_secret(self, scopes: Iterable[str], secret: str, **kwargs) -> AccessTokenInfo: + request = self._get_client_secret_request(scopes, secret, **kwargs) + return await self._run_pipeline(request, **kwargs) + + async def obtain_token_by_jwt_assertion(self, scopes: Iterable[str], assertion: str, **kwargs) -> AccessTokenInfo: + request = self._get_jwt_assertion_request(scopes, assertion, **kwargs) + return await self._run_pipeline(request, stream=False, **kwargs) + + async def obtain_token_by_refresh_token( + self, scopes: Iterable[str], refresh_token: str, **kwargs + ) -> AccessTokenInfo: + request = self._get_refresh_token_request(scopes, refresh_token, **kwargs) + return await self._run_pipeline(request, **kwargs) + + async def obtain_token_by_refresh_token_on_behalf_of( # pylint: disable=name-too-long + self, + scopes: Iterable[str], + client_credential: Union[str, AadClientCertificate, Dict[str, Any]], + refresh_token: str, + **kwargs + ) -> AccessTokenInfo: + request = self._get_refresh_token_on_behalf_of_request( + scopes, client_credential=client_credential, refresh_token=refresh_token, **kwargs + ) + return await self._run_pipeline(request, **kwargs) + + async def obtain_token_on_behalf_of( + self, + scopes: Iterable[str], + client_credential: Union[str, AadClientCertificate, Dict[str, Any]], + user_assertion: str, + **kwargs + ) -> AccessTokenInfo: + request = self._get_on_behalf_of_request( + scopes=scopes, client_credential=client_credential, user_assertion=user_assertion, **kwargs + ) + return await self._run_pipeline(request, **kwargs) + + def _build_pipeline(self, **kwargs) -> AsyncPipeline: + return build_async_pipeline(**kwargs) + + async def _run_pipeline(self, request: HttpRequest, **kwargs) -> AccessTokenInfo: + # remove tenant_id and claims kwarg that could have been passed from credential's get_token method + # tenant_id is already part of `request` at this point + kwargs.pop("tenant_id", None) + kwargs.pop("claims", None) + kwargs.pop("client_secret", None) + enable_cae = kwargs.pop("enable_cae", False) + now = int(time.time()) + response = await self._pipeline.run(request, retry_on_methods=self._POST, **kwargs) + return self._process_response(response, now, enable_cae=enable_cae, **kwargs) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/decorators.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/decorators.py new file mode 100644 index 00000000000..3e8f04be1bb --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/decorators.py @@ -0,0 +1,77 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import functools +import logging +import json +import base64 + +from azure.core.exceptions import ClientAuthenticationError + +from ..._internal import within_credential_chain + +_LOGGER = logging.getLogger(__name__) + + +def log_get_token_async(fn): + + @functools.wraps(fn) + async def wrapper(*args, **kwargs): + try: + token = await fn(*args, **kwargs) + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.INFO, "%s succeeded", fn.__qualname__ + ) + if _LOGGER.isEnabledFor(logging.DEBUG): + try: + base64_meta_data = token.token.split(".")[1].encode("utf-8") + b"==" + json_bytes = base64.decodebytes(base64_meta_data) + json_string = json_bytes.decode("utf-8") + json_dict = json.loads(json_string) + upn = json_dict.get("upn", "unavailableUpn") + appid = json_dict.get("appid", "") + tid = json_dict.get("tid", "") + oid = json_dict.get("oid", "") + log_string = ( + f"[Authenticated account] Client ID: {appid}. " + f"Tenant ID: {tid}. User Principal Name: {upn}. Object ID (user): {oid}" + ) + _LOGGER.debug(log_string) + except Exception as ex: # pylint: disable=broad-except + _LOGGER.debug("Failed to log the account information: %s", ex, exc_info=True) + return token + except Exception as ex: # pylint: disable=broad-except + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.WARNING, + "%s failed: %s", + fn.__qualname__, + ex, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + raise + + return wrapper + + +def wrap_exceptions(fn): + """Prevents leaking exceptions defined outside azure-core by raising ClientAuthenticationError from them. + + :param fn: The function to wrap. + :type fn: ~typing.Callable + :return: The wrapped function. + :rtype: callable + """ + + @functools.wraps(fn) + async def wrapper(*args, **kwargs): + try: + result = await fn(*args, **kwargs) + return result + except ClientAuthenticationError: + raise + except Exception as ex: # pylint:disable=broad-except + auth_error = ClientAuthenticationError(message="Authentication failed: {}".format(ex)) + raise auth_error from ex + + return wrapper diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/get_token_mixin.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/get_token_mixin.py new file mode 100644 index 00000000000..61ad01eaab7 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/get_token_mixin.py @@ -0,0 +1,165 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +import logging +import time +from typing import Any, Optional + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from ..._constants import DEFAULT_REFRESH_OFFSET, DEFAULT_TOKEN_REFRESH_RETRY_DELAY +from ..._internal import within_credential_chain + +_LOGGER = logging.getLogger(__name__) + + +class GetTokenMixin(abc.ABC): + def __init__(self, *args: Any, **kwargs: Any) -> None: + self._last_request_time = 0 + + # https://github.com/python/mypy/issues/5887 + super(GetTokenMixin, self).__init__(*args, **kwargs) # type: ignore + + @abc.abstractmethod + async def _acquire_token_silently(self, *scopes: str, **kwargs) -> Optional[AccessTokenInfo]: + """Attempt to acquire an access token from a cache or by redeeming a refresh token. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + + :return: An access token with the desired scopes if successful; otherwise, None. + :rtype: ~azure.core.credentials.AccessTokenInfo or None + """ + + @abc.abstractmethod + async def _request_token(self, *scopes: str, **kwargs) -> AccessTokenInfo: + """Request an access token from the STS. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessTokenInfo + """ + + def _should_refresh(self, token: AccessTokenInfo) -> bool: + now = int(time.time()) + if token.refresh_on is not None and now >= token.refresh_on: + return True + if token.expires_on - now > DEFAULT_REFRESH_OFFSET: + return False + if now - self._last_request_time < DEFAULT_TOKEN_REFRESH_RETRY_DELAY: + return False + return True + + async def get_token( + self, + *scopes: str, + claims: Optional[str] = None, + tenant_id: Optional[str] = None, + enable_cae: bool = False, + **kwargs: Any, + ) -> AccessToken: + """Request an access token for `scopes`. + + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see + https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword str claims: additional claims required in the token, such as those returned in a resource provider's + claims challenge following an authorization failure. + :keyword str tenant_id: optional tenant to include in the token request. + :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested + token. Defaults to False. + + :return: An access token with the desired scopes. + :rtype: ~azure.core.credentials.AccessToken + :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks + required data, state, or platform support + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + options: TokenRequestOptions = {} + if claims: + options["claims"] = claims + if tenant_id: + options["tenant_id"] = tenant_id + options["enable_cae"] = enable_cae + + token_info = await self._get_token_base(*scopes, options=options, base_method_name="get_token", **kwargs) + return AccessToken(token_info.token, token_info.expires_on) + + async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + """Request an access token for `scopes`. + + This is an alternative to `get_token` to enable certain scenarios that require additional properties + on the token. This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. This method requires at least one scope. + For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc. + :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional. + :paramtype options: ~azure.core.credentials.TokenRequestOptions + + :rtype: AccessTokenInfo + :return: An AccessTokenInfo instance containing information about the token. + :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks + required data, state, or platform support + :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message`` + attribute gives a reason. + """ + return await self._get_token_base(*scopes, options=options, base_method_name="get_token_info") + + async def _get_token_base( + self, + *scopes: str, + options: Optional[TokenRequestOptions] = None, + base_method_name: str = "get_token_info", + **kwargs: Any, + ) -> AccessTokenInfo: + if not scopes: + raise ValueError(f'"{base_method_name}" requires at least one scope') + + options = options or {} + claims = options.get("claims") + tenant_id = options.get("tenant_id") + enable_cae = options.get("enable_cae", False) + + try: + token = await self._acquire_token_silently( + *scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs + ) + if not token: + self._last_request_time = int(time.time()) + token = await self._request_token( + *scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs + ) + elif self._should_refresh(token): + try: + self._last_request_time = int(time.time()) + token = await self._request_token( + *scopes, claims=claims, tenant_id=tenant_id, enable_cae=enable_cae, **kwargs + ) + except Exception: # pylint:disable=broad-except + pass + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.INFO, + "%s.%s succeeded", + self.__class__.__name__, + base_method_name, + ) + return token + + except Exception as ex: + _LOGGER.log( + logging.DEBUG if within_credential_chain.get() else logging.WARNING, + "%s.%s failed: %s", + self.__class__.__name__, + base_method_name, + ex, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + raise diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/managed_identity_base.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/managed_identity_base.py new file mode 100644 index 00000000000..636fbbf9b2f --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/managed_identity_base.py @@ -0,0 +1,68 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import abc +from types import TracebackType +from typing import Any, cast, Optional, TypeVar, Type + +from azure.core.credentials import AccessToken, AccessTokenInfo, TokenRequestOptions +from . import AsyncContextManager +from .get_token_mixin import GetTokenMixin +from .managed_identity_client import AsyncManagedIdentityClient +from ... import CredentialUnavailableError + +T = TypeVar("T", bound="AsyncManagedIdentityBase") + + +class AsyncManagedIdentityBase(AsyncContextManager, GetTokenMixin): + """Base class for internal credentials using AsyncManagedIdentityClient""" + + def __init__(self, **kwargs) -> None: + super().__init__() + self._client = self.get_client(**kwargs) + + @abc.abstractmethod + def get_client(self, **kwargs) -> Optional[AsyncManagedIdentityClient]: + pass + + @abc.abstractmethod + def get_unavailable_message(self, desc: str = "") -> str: + pass + + async def __aenter__(self: T) -> T: + if self._client: + await self._client.__aenter__() + return self + + async def __aexit__( + self, + exc_type: Optional[Type[BaseException]] = None, + exc_value: Optional[BaseException] = None, + traceback: Optional[TracebackType] = None, + ) -> None: + if self._client: + await self._client.__aexit__(exc_type, exc_value, traceback) + + async def close(self) -> None: + await self.__aexit__() + + async def get_token( + self, *scopes: str, claims: Optional[str] = None, tenant_id: Optional[str] = None, **kwargs: Any + ) -> AccessToken: + if not self._client: + raise CredentialUnavailableError(message=self.get_unavailable_message()) + return await super().get_token(*scopes, claims=claims, tenant_id=tenant_id, **kwargs) + + async def get_token_info(self, *scopes: str, options: Optional[TokenRequestOptions] = None) -> AccessTokenInfo: + if not self._client: + raise CredentialUnavailableError(message=self.get_unavailable_message()) + return await super().get_token_info(*scopes, options=options) + + async def _acquire_token_silently(self, *scopes: str, **kwargs) -> Optional[AccessTokenInfo]: + # casting because mypy can't determine that these methods are called + # only by get_token, which raises when self._client is None + return cast(AsyncManagedIdentityClient, self._client).get_cached_token(*scopes) + + async def _request_token(self, *scopes: str, **kwargs) -> AccessTokenInfo: + return await cast(AsyncManagedIdentityClient, self._client).request_token(*scopes, **kwargs) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/managed_identity_client.py b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/managed_identity_client.py new file mode 100644 index 00000000000..340bb5a11fa --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_identity/aio/_internal/managed_identity_client.py @@ -0,0 +1,39 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import time +from typing import TypeVar + +from azure.core.credentials import AccessTokenInfo +from azure.core.pipeline import AsyncPipeline +from .._internal import AsyncContextManager +from ..._internal import _scopes_to_resource +from ..._internal.managed_identity_client import ManagedIdentityClientBase +from ..._internal.pipeline import build_async_pipeline + +T = TypeVar("T", bound="AsyncManagedIdentityClient") + + +# pylint:disable=async-client-bad-name,missing-client-constructor-parameter-credential +class AsyncManagedIdentityClient(AsyncContextManager, ManagedIdentityClientBase): + async def __aenter__(self: T) -> T: + await self._pipeline.__aenter__() + return self + + async def close(self) -> None: + await self._pipeline.__aexit__() + + async def request_token(self, *scopes: str, **kwargs) -> AccessTokenInfo: + # pylint:disable=invalid-overridden-method + resource = _scopes_to_resource(*scopes) + request = self._request_factory(resource, self._identity_config) + kwargs.pop("tenant_id", None) + kwargs.pop("claims", None) + request_time = int(time.time()) + response = await self._pipeline.run(request, retry_on_methods=[request.method], **kwargs) + token = self._process_response(response, request_time) + return token + + def _build_pipeline(self, **kwargs) -> AsyncPipeline: + return build_async_pipeline(**kwargs) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_identity/py.typed b/src/quantum/azext_quantum/vendored_sdks/azure_identity/py.typed new file mode 100644 index 00000000000..e69de29bb2d diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_authentication/__init__.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_authentication/__init__.py new file mode 100644 index 00000000000..84646caa202 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_authentication/__init__.py @@ -0,0 +1,9 @@ +# coding=utf-8 +## +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +## + +from ._chained import * +from ._default import _DefaultAzureCredential +from ._token import _TokenFileCredential diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_authentication/_chained.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_authentication/_chained.py new file mode 100644 index 00000000000..aae945fdd04 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_authentication/_chained.py @@ -0,0 +1,120 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging + +import sys +from azure.core.exceptions import ClientAuthenticationError +# from azure.identity import CredentialUnavailableError +from ...azure_identity import CredentialUnavailableError +from azure.core.credentials import AccessToken, TokenCredential + + +_LOGGER = logging.getLogger(__name__) + + + +def filter_credential_warnings(record): + """Suppress warnings from credentials other than DefaultAzureCredential""" + if record.levelno == logging.WARNING: + message = record.getMessage() + return "DefaultAzureCredential" in message + return True + + +def _get_error_message(history): + attempts = [] + for credential, error in history: + if error: + attempts.append(f"{credential.__class__.__name__}: {error}") + else: + attempts.append(credential.__class__.__name__) + return """ +Attempted credentials:\n\t{}""".format( + "\n\t".join(attempts) + ) + + +class _ChainedTokenCredential(object): + """ + Based on Azure.Identity.ChainedTokenCredential from: + https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/identity/azure-identity/azure/identity/_credentials/chained.py + + The key difference is that we don't stop attempting all credentials + if some of then failed or raised an exception. + We also don't log a warning unless all credential attempts have failed. + """ + + def __init__(self, *credentials: TokenCredential): + self._successful_credential = None + self.credentials = credentials + + def get_token(self, *scopes: str, **kwargs) -> AccessToken: # pylint:disable=unused-argument + """ + Request a token from each chained credential, in order, + returning the first token received. + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. + This method requires at least one scope. + + :raises ~azure.core.exceptions.ClientAuthenticationError: + no credential in the chain provided a token + """ + history = [] + + # Suppress warnings from credentials in Azure.Identity + azure_identity_logger = logging.getLogger("azure.identity") + handler = logging.StreamHandler(stream=sys.stdout) + handler.addFilter(filter_credential_warnings) + azure_identity_logger.addHandler(handler) + try: + for credential in self.credentials: + try: + token = credential.get_token(*scopes, **kwargs) + _LOGGER.info( + "%s acquired a token from %s", + self.__class__.__name__, + credential.__class__.__name__, + ) + self._successful_credential = credential + return token + except CredentialUnavailableError as ex: + # credential didn't attempt authentication because + # it lacks required data or state -> continue + history.append((credential, ex.message)) + _LOGGER.info( + "%s - %s is unavailable", + self.__class__.__name__, + credential.__class__.__name__, + ) + except Exception as ex: # pylint: disable=broad-except + # credential failed to authenticate, + # or something unexpectedly raised -> break + history.append((credential, str(ex))) + # instead of logging a warning, we just want to log an info + # since other credentials might succeed + _LOGGER.info( + '%s.get_token failed: %s raised unexpected error "%s"', + self.__class__.__name__, + credential.__class__.__name__, + ex, + exc_info=_LOGGER.isEnabledFor(logging.DEBUG), + ) + # here we do NOT want break and + # will continue to try other credentials + + finally: + # Re-enable warnings from credentials in Azure.Identity + azure_identity_logger.removeHandler(handler) + + # if all attempts failed, only then we log a warning and raise an error + attempts = _get_error_message(history) + message = ( + self.__class__.__name__ + + " failed to retrieve a token from the included credentials." + + attempts + ) + _LOGGER.warning(message) + raise ClientAuthenticationError(message=message) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_authentication/_default.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_authentication/_default.py new file mode 100644 index 00000000000..24fa9cb6bbb --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_authentication/_default.py @@ -0,0 +1,155 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import logging +import re +from typing import Optional +import urllib3 +from azure.core.credentials import AccessToken +# from azure.identity import ( +from ...azure_identity import ( + AzurePowerShellCredential, + EnvironmentCredential, + ManagedIdentityCredential, + AzureCliCredential, + VisualStudioCodeCredential, + InteractiveBrowserCredential, + DeviceCodeCredential, + _internal as AzureIdentityInternals, +) +from ._chained import _ChainedTokenCredential +from ._token import _TokenFileCredential +# from azure.quantum._constants import ConnectionConstants +from .._constants import ConnectionConstants + +_LOGGER = logging.getLogger(__name__) +WWW_AUTHENTICATE_REGEX = re.compile( + r""" + ^ + Bearer\sauthorization_uri=" + https://(?P[^/]*)/ + (?P[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}) + " + """, + re.VERBOSE | re.IGNORECASE) +WWW_AUTHENTICATE_HEADER_NAME = "WWW-Authenticate" + + +class _DefaultAzureCredential(_ChainedTokenCredential): + """ + Based on Azure.Identity.DefaultAzureCredential from: + https://github.com/Azure/azure-sdk-for-python/blob/master/sdk/identity/azure-identity/azure/identity/_credentials/default.py + + The three key differences are: + 1) Inherit from _ChainedTokenCredential, which has + more aggressive error handling than ChainedTokenCredential + 2) Instantiate the internal credentials the first time the get_token gets called + such that we can get the tenant_id if it was not passed by the user (but we don't + want to do that in the constructor). + We automatically identify the user's tenant_id for a given subscription + so that users with MSA accounts don't need to pass it. + This is a mitigation for bug https://github.com/Azure/azure-sdk-for-python/issues/18975 + We need the following parameters to enable auto-detection of tenant_id + - subscription_id + - arm_endpoint (defaults to the production url "https://management.azure.com/") + 3) Add custom TokenFileCredential as first method to attempt, + which will look for a local access token. + """ + def __init__( + self, + arm_endpoint: str, + subscription_id: str, + client_id: Optional[str] = None, + tenant_id: Optional[str] = None, + authority: Optional[str] = None, + ): + if arm_endpoint is None: + raise ValueError("arm_endpoint is mandatory parameter") + if subscription_id is None: + raise ValueError("subscription_id is mandatory parameter") + + self.authority = self._authority_or_default( + authority=authority, + arm_endpoint=arm_endpoint) + self.tenant_id = tenant_id + self.subscription_id = subscription_id + self.arm_endpoint = arm_endpoint + self.client_id = client_id + # credentials will be created lazy on the first call to get_token + super(_DefaultAzureCredential, self).__init__() + + def _authority_or_default(self, authority: str, arm_endpoint: str): + if authority: + return AzureIdentityInternals.normalize_authority(authority) + if arm_endpoint == ConnectionConstants.ARM_DOGFOOD_ENDPOINT: + return ConnectionConstants.DOGFOOD_AUTHORITY + return ConnectionConstants.AUTHORITY + + def _initialize_credentials(self): + self._discover_tenant_id_( + arm_endpoint=self.arm_endpoint, + subscription_id=self.subscription_id) + credentials = [] + credentials.append(_TokenFileCredential()) + credentials.append(EnvironmentCredential()) + if self.client_id: + credentials.append(ManagedIdentityCredential(client_id=self.client_id)) + if self.authority and self.tenant_id: + credentials.append(VisualStudioCodeCredential(authority=self.authority, tenant_id=self.tenant_id)) + credentials.append(AzureCliCredential(tenant_id=self.tenant_id)) + credentials.append(AzurePowerShellCredential(tenant_id=self.tenant_id)) + credentials.append(InteractiveBrowserCredential(authority=self.authority, tenant_id=self.tenant_id)) + if self.client_id: + credentials.append(DeviceCodeCredential(authority=self.authority, client_id=self.client_id, tenant_id=self.tenant_id)) + self.credentials = credentials + + def get_token(self, *scopes: str, **kwargs) -> AccessToken: + """ + Request an access token for `scopes`. + This method is called automatically by Azure SDK clients. + + :param str scopes: desired scopes for the access token. + This method requires at least one scope. + + :raises ~azure.core.exceptions.ClientAuthenticationError:authentication failed. + The exception has a `message` attribute listing each authentication + attempt and its error message. + """ + # lazy-initialize the credentials + if self.credentials is None or len(self.credentials) == 0: + self._initialize_credentials() + + return super(_DefaultAzureCredential, self).get_token(*scopes, **kwargs) + + def _discover_tenant_id_(self, arm_endpoint:str, subscription_id:str): + """ + If the tenant_id was not given, try to obtain it + by calling the management endpoint for the subscription_id, + or by applying default values. + """ + if self.tenant_id: + return + + try: + url = ( + f"{arm_endpoint.rstrip('/')}/subscriptions/" + + f"{subscription_id}?api-version=2018-01-01" + + "&discover-tenant-id" # used by the test recording infrastructure + ) + http = urllib3.PoolManager() + response = http.request( + method="GET", + url=url, + ) + if WWW_AUTHENTICATE_HEADER_NAME in response.headers: + www_authenticate = response.headers[WWW_AUTHENTICATE_HEADER_NAME] + match = re.search(WWW_AUTHENTICATE_REGEX, www_authenticate) + if match: + self.tenant_id = match.group("tenant_id") + # pylint: disable=broad-exception-caught + except Exception as ex: + _LOGGER.error(ex) + + # apply default values + self.tenant_id = self.tenant_id or ConnectionConstants.MSA_TENANT_ID diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_authentication/_token.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_authentication/_token.py new file mode 100644 index 00000000000..3b0b3a6db51 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_authentication/_token.py @@ -0,0 +1,85 @@ +## +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +## +import json +from json.decoder import JSONDecodeError +import logging +import os +import time + +# from azure.identity import CredentialUnavailableError +from ...azure_identity import CredentialUnavailableError +from azure.core.credentials import AccessToken +# from azure.quantum._constants import EnvironmentVariables +from .._constants import EnvironmentVariables + +_LOGGER = logging.getLogger(__name__) + + +class _TokenFileCredential(object): + """ + Implements a custom TokenCredential to use a local file as + the source for an AzureQuantum token. + + It will only use the local file if the AZURE_QUANTUM_TOKEN_FILE + environment variable is set, and references an existing json file + that contains the access_token and expires_on timestamp in milliseconds. + + If the environment variable is not set, the file does not exist, + or the token is invalid in any way (expired, for example), + then the credential will throw CredentialUnavailableError, + so that _ChainedTokenCredential can fallback to other methods. + """ + def __init__(self): + self.token_file = os.environ.get(EnvironmentVariables.QUANTUM_TOKEN_FILE) + if self.token_file: + _LOGGER.debug("Using provided token file location: %s", self.token_file) + else: + _LOGGER.debug("No token file location provided for %s environment variable.", + EnvironmentVariables.QUANTUM_TOKEN_FILE) + + def get_token(self, *scopes: str, **kwargs) -> AccessToken: # pylint:disable=unused-argument + """Request an access token for `scopes`. + This method is called automatically by Azure SDK clients. + This method only returns tokens for the https://quantum.microsoft.com/.default scope. + + :param str scopes: desired scopes for the access token. + + :raises ~azure.identity.CredentialUnavailableError + when failing to get the token. + The exception has a `message` attribute with the error message. + """ + if not self.token_file: + raise CredentialUnavailableError(message="Token file location not set.") + + if not os.path.isfile(self.token_file): + raise CredentialUnavailableError( + message=f"Token file at {self.token_file} does not exist.") + + try: + token = self._parse_token_file(self.token_file) + except JSONDecodeError as exception: + raise CredentialUnavailableError( + message="Failed to parse token file: Invalid JSON.") from exception + except KeyError as exception: + raise CredentialUnavailableError( + message="Failed to parse token file: Missing expected value: " + + str(exception)) from exception + except Exception as exception: + raise CredentialUnavailableError( + message="Failed to parse token file: " + str(exception)) from exception + + if token.expires_on <= time.time(): + raise CredentialUnavailableError( + message=f"Token already expired at {time.asctime(time.gmtime(token.expires_on))}") + + return token + + def _parse_token_file(self, path) -> AccessToken: + with open(path, mode="r", encoding="utf-8") as file: + data = json.load(file) + # Convert ms to seconds, since python time.time only handles epoch time in seconds + expires_on = int(data["expires_on"]) / 1000 + token = AccessToken(data["access_token"], expires_on) + return token diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/__init__.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/__init__.py new file mode 100644 index 00000000000..56503227c20 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/__init__.py @@ -0,0 +1,26 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._client import QuantumClient +from ._version import VERSION + +__version__ = VERSION + +try: + from ._patch import __all__ as _patch_all + from ._patch import * # pylint: disable=unused-wildcard-import +except ImportError: + _patch_all = [] +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "QuantumClient", +] +__all__.extend([p for p in _patch_all if p not in __all__]) + +_patch_sdk() diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_client.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_client.py new file mode 100644 index 00000000000..ad231759f33 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_client.py @@ -0,0 +1,150 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from copy import deepcopy +from typing import Any, TYPE_CHECKING + +from azure.core import PipelineClient +from azure.core.pipeline import policies +from azure.core.rest import HttpRequest, HttpResponse + +from . import models as _models +from ._configuration import QuantumClientConfiguration +from ._serialization import Deserializer, Serializer +from .operations import ( + JobsOperations, + ProvidersOperations, + QuotasOperations, + SessionsOperations, + StorageOperations, + TopLevelItemsOperations, +) + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class QuantumClient: # pylint: disable=client-accepts-api-version-keyword + """Azure Quantum REST API client. + + :ivar jobs: JobsOperations operations + :vartype jobs: azure.quantum._client.operations.JobsOperations + :ivar providers: ProvidersOperations operations + :vartype providers: azure.quantum._client.operations.ProvidersOperations + :ivar storage: StorageOperations operations + :vartype storage: azure.quantum._client.operations.StorageOperations + :ivar quotas: QuotasOperations operations + :vartype quotas: azure.quantum._client.operations.QuotasOperations + :ivar sessions: SessionsOperations operations + :vartype sessions: azure.quantum._client.operations.SessionsOperations + :ivar top_level_items: TopLevelItemsOperations operations + :vartype top_level_items: azure.quantum._client.operations.TopLevelItemsOperations + :param azure_region: Supported Azure regions for Azure Quantum Services. For example, "eastus". + Required. + :type azure_region: str + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. + 00000000-0000-0000-0000-000000000000). Required. + :type subscription_id: str + :param resource_group_name: Name of an Azure resource group. Required. + :type resource_group_name: str + :param workspace_name: Name of the workspace. Required. + :type workspace_name: str + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :keyword api_version: Api Version. Default value is "2023-11-13-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + azure_region: str, + subscription_id: str, + resource_group_name: str, + workspace_name: str, + credential: "TokenCredential", + **kwargs: Any + ) -> None: + _endpoint = kwargs.pop("endpoint", f"https://{azure_region}.quantum.azure.com") + self._config = QuantumClientConfiguration( + azure_region=azure_region, + subscription_id=subscription_id, + resource_group_name=resource_group_name, + workspace_name=workspace_name, + credential=credential, + **kwargs + ) + _policies = kwargs.pop("policies", None) + if _policies is None: + _policies = [ + policies.RequestIdPolicy(**kwargs), + self._config.headers_policy, + self._config.user_agent_policy, + self._config.proxy_policy, + policies.ContentDecodePolicy(**kwargs), + self._config.redirect_policy, + self._config.retry_policy, + self._config.authentication_policy, + self._config.custom_hook_policy, + self._config.logging_policy, + policies.DistributedTracingPolicy(**kwargs), + policies.SensitiveHeaderCleanupPolicy(**kwargs) if self._config.redirect_policy else None, + self._config.http_logging_policy, + ] + self._client: PipelineClient = PipelineClient(base_url=_endpoint, policies=_policies, **kwargs) + + client_models = {k: v for k, v in _models._models.__dict__.items() if isinstance(v, type)} + client_models.update({k: v for k, v in _models.__dict__.items() if isinstance(v, type)}) + self._serialize = Serializer(client_models) + self._deserialize = Deserializer(client_models) + self._serialize.client_side_validation = False + self.jobs = JobsOperations(self._client, self._config, self._serialize, self._deserialize) + self.providers = ProvidersOperations(self._client, self._config, self._serialize, self._deserialize) + self.storage = StorageOperations(self._client, self._config, self._serialize, self._deserialize) + self.quotas = QuotasOperations(self._client, self._config, self._serialize, self._deserialize) + self.sessions = SessionsOperations(self._client, self._config, self._serialize, self._deserialize) + self.top_level_items = TopLevelItemsOperations(self._client, self._config, self._serialize, self._deserialize) + + def send_request(self, request: HttpRequest, *, stream: bool = False, **kwargs: Any) -> HttpResponse: + """Runs the network request through the client's chained policies. + + >>> from azure.core.rest import HttpRequest + >>> request = HttpRequest("GET", "https://www.example.org/") + + >>> response = client.send_request(request) + + + For more information on this code flow, see https://aka.ms/azsdk/dpcodegen/python/send_request + + :param request: The network request you want to make. Required. + :type request: ~azure.core.rest.HttpRequest + :keyword bool stream: Whether the response payload will be streamed. Defaults to False. + :return: The response of your network call. Does not do error handling on your response. + :rtype: ~azure.core.rest.HttpResponse + """ + + request_copy = deepcopy(request) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + + request_copy.url = self._client.format_url(request_copy.url, **path_format_arguments) + return self._client.send_request(request_copy, stream=stream, **kwargs) # type: ignore + + def close(self) -> None: + self._client.close() + + def __enter__(self) -> "QuantumClient": + self._client.__enter__() + return self + + def __exit__(self, *exc_details: Any) -> None: + self._client.__exit__(*exc_details) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_configuration.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_configuration.py new file mode 100644 index 00000000000..4514ff6502c --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_configuration.py @@ -0,0 +1,89 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import Any, TYPE_CHECKING + +from azure.core.pipeline import policies + +from ._version import VERSION + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from azure.core.credentials import TokenCredential + + +class QuantumClientConfiguration: # pylint: disable=too-many-instance-attributes + """Configuration for QuantumClient. + + Note that all parameters used to create this instance are saved as instance + attributes. + + :param azure_region: Supported Azure regions for Azure Quantum Services. For example, "eastus". + Required. + :type azure_region: str + :param subscription_id: The Azure subscription ID. This is a GUID-formatted string (e.g. + 00000000-0000-0000-0000-000000000000). Required. + :type subscription_id: str + :param resource_group_name: Name of an Azure resource group. Required. + :type resource_group_name: str + :param workspace_name: Name of the workspace. Required. + :type workspace_name: str + :param credential: Credential needed for the client to connect to Azure. Required. + :type credential: ~azure.core.credentials.TokenCredential + :keyword api_version: Api Version. Default value is "2023-11-13-preview". Note that overriding + this default value may result in unsupported behavior. + :paramtype api_version: str + """ + + def __init__( + self, + azure_region: str, + subscription_id: str, + resource_group_name: str, + workspace_name: str, + credential: "TokenCredential", + **kwargs: Any + ) -> None: + api_version: str = kwargs.pop("api_version", "2022-09-12-preview") + + if azure_region is None: + raise ValueError("Parameter 'azure_region' must not be None.") + if subscription_id is None: + raise ValueError("Parameter 'subscription_id' must not be None.") + if resource_group_name is None: + raise ValueError("Parameter 'resource_group_name' must not be None.") + if workspace_name is None: + raise ValueError("Parameter 'workspace_name' must not be None.") + if credential is None: + raise ValueError("Parameter 'credential' must not be None.") + + self.azure_region = azure_region + self.subscription_id = subscription_id + self.resource_group_name = resource_group_name + self.workspace_name = workspace_name + self.credential = credential + self.api_version = api_version + self.credential_scopes = kwargs.pop("credential_scopes", ["https://quantum.microsoft.com/.default"]) + kwargs.setdefault("sdk_moniker", "quantum/{}".format(VERSION)) + self.polling_interval = kwargs.get("polling_interval", 30) + self._configure(**kwargs) + + def _configure(self, **kwargs: Any) -> None: + self.user_agent_policy = kwargs.get("user_agent_policy") or policies.UserAgentPolicy(**kwargs) + self.headers_policy = kwargs.get("headers_policy") or policies.HeadersPolicy(**kwargs) + self.proxy_policy = kwargs.get("proxy_policy") or policies.ProxyPolicy(**kwargs) + self.logging_policy = kwargs.get("logging_policy") or policies.NetworkTraceLoggingPolicy(**kwargs) + self.http_logging_policy = kwargs.get("http_logging_policy") or policies.HttpLoggingPolicy(**kwargs) + self.custom_hook_policy = kwargs.get("custom_hook_policy") or policies.CustomHookPolicy(**kwargs) + self.redirect_policy = kwargs.get("redirect_policy") or policies.RedirectPolicy(**kwargs) + self.retry_policy = kwargs.get("retry_policy") or policies.RetryPolicy(**kwargs) + self.authentication_policy = kwargs.get("authentication_policy") + if self.credential and not self.authentication_policy: + self.authentication_policy = policies.BearerTokenCredentialPolicy( + self.credential, *self.credential_scopes, **kwargs + ) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_patch.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_serialization.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_serialization.py new file mode 100644 index 00000000000..baa661cb82d --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_serialization.py @@ -0,0 +1,2005 @@ +# -------------------------------------------------------------------------- +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# +# The MIT License (MIT) +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the ""Software""), to +# deal in the Software without restriction, including without limitation the +# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +# sell copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in +# all copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED *AS IS*, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +# IN THE SOFTWARE. +# +# -------------------------------------------------------------------------- + +# pylint: skip-file +# pyright: reportUnnecessaryTypeIgnoreComment=false + +from base64 import b64decode, b64encode +import calendar +import datetime +import decimal +import email +from enum import Enum +import json +import logging +import re +import sys +import codecs +from typing import ( + Dict, + Any, + cast, + Optional, + Union, + AnyStr, + IO, + Mapping, + Callable, + TypeVar, + MutableMapping, + Type, + List, + Mapping, +) + +try: + from urllib import quote # type: ignore +except ImportError: + from urllib.parse import quote +import xml.etree.ElementTree as ET + +import isodate # type: ignore + +from azure.core.exceptions import DeserializationError, SerializationError +from azure.core.serialization import NULL as CoreNull + +_BOM = codecs.BOM_UTF8.decode(encoding="utf-8") + +ModelType = TypeVar("ModelType", bound="Model") +JSON = MutableMapping[str, Any] + + +class RawDeserializer: + + # Accept "text" because we're open minded people... + JSON_REGEXP = re.compile(r"^(application|text)/([a-z+.]+\+)?json$") + + # Name used in context + CONTEXT_NAME = "deserialized_data" + + @classmethod + def deserialize_from_text(cls, data: Optional[Union[AnyStr, IO]], content_type: Optional[str] = None) -> Any: + """Decode data according to content-type. + + Accept a stream of data as well, but will be load at once in memory for now. + + If no content-type, will return the string version (not bytes, not stream) + + :param data: Input, could be bytes or stream (will be decoded with UTF8) or text + :type data: str or bytes or IO + :param str content_type: The content type. + """ + if hasattr(data, "read"): + # Assume a stream + data = cast(IO, data).read() + + if isinstance(data, bytes): + data_as_str = data.decode(encoding="utf-8-sig") + else: + # Explain to mypy the correct type. + data_as_str = cast(str, data) + + # Remove Byte Order Mark if present in string + data_as_str = data_as_str.lstrip(_BOM) + + if content_type is None: + return data + + if cls.JSON_REGEXP.match(content_type): + try: + return json.loads(data_as_str) + except ValueError as err: + raise DeserializationError("JSON is invalid: {}".format(err), err) + elif "xml" in (content_type or []): + try: + + try: + if isinstance(data, unicode): # type: ignore + # If I'm Python 2.7 and unicode XML will scream if I try a "fromstring" on unicode string + data_as_str = data_as_str.encode(encoding="utf-8") # type: ignore + except NameError: + pass + + return ET.fromstring(data_as_str) # nosec + except ET.ParseError as err: + # It might be because the server has an issue, and returned JSON with + # content-type XML.... + # So let's try a JSON load, and if it's still broken + # let's flow the initial exception + def _json_attemp(data): + try: + return True, json.loads(data) + except ValueError: + return False, None # Don't care about this one + + success, json_result = _json_attemp(data) + if success: + return json_result + # If i'm here, it's not JSON, it's not XML, let's scream + # and raise the last context in this block (the XML exception) + # The function hack is because Py2.7 messes up with exception + # context otherwise. + _LOGGER.critical("Wasn't XML not JSON, failing") + raise DeserializationError("XML is invalid") from err + raise DeserializationError("Cannot deserialize content-type: {}".format(content_type)) + + @classmethod + def deserialize_from_http_generics(cls, body_bytes: Optional[Union[AnyStr, IO]], headers: Mapping) -> Any: + """Deserialize from HTTP response. + + Use bytes and headers to NOT use any requests/aiohttp or whatever + specific implementation. + Headers will tested for "content-type" + """ + # Try to use content-type from headers if available + content_type = None + if "content-type" in headers: + content_type = headers["content-type"].split(";")[0].strip().lower() + # Ouch, this server did not declare what it sent... + # Let's guess it's JSON... + # Also, since Autorest was considering that an empty body was a valid JSON, + # need that test as well.... + else: + content_type = "application/json" + + if body_bytes: + return cls.deserialize_from_text(body_bytes, content_type) + return None + + +try: + basestring # type: ignore + unicode_str = unicode # type: ignore +except NameError: + basestring = str + unicode_str = str + +_LOGGER = logging.getLogger(__name__) + +try: + _long_type = long # type: ignore +except NameError: + _long_type = int + + +class UTC(datetime.tzinfo): + """Time Zone info for handling UTC""" + + def utcoffset(self, dt): + """UTF offset for UTC is 0.""" + return datetime.timedelta(0) + + def tzname(self, dt): + """Timestamp representation.""" + return "Z" + + def dst(self, dt): + """No daylight saving for UTC.""" + return datetime.timedelta(hours=1) + + +try: + from datetime import timezone as _FixedOffset # type: ignore +except ImportError: # Python 2.7 + + class _FixedOffset(datetime.tzinfo): # type: ignore + """Fixed offset in minutes east from UTC. + Copy/pasted from Python doc + :param datetime.timedelta offset: offset in timedelta format + """ + + def __init__(self, offset): + self.__offset = offset + + def utcoffset(self, dt): + return self.__offset + + def tzname(self, dt): + return str(self.__offset.total_seconds() / 3600) + + def __repr__(self): + return "".format(self.tzname(None)) + + def dst(self, dt): + return datetime.timedelta(0) + + def __getinitargs__(self): + return (self.__offset,) + + +try: + from datetime import timezone + + TZ_UTC = timezone.utc +except ImportError: + TZ_UTC = UTC() # type: ignore + +_FLATTEN = re.compile(r"(? None: + self.additional_properties: Optional[Dict[str, Any]] = {} + for k in kwargs: + if k not in self._attribute_map: + _LOGGER.warning("%s is not a known attribute of class %s and will be ignored", k, self.__class__) + elif k in self._validation and self._validation[k].get("readonly", False): + _LOGGER.warning("Readonly attribute %s will be ignored in class %s", k, self.__class__) + else: + setattr(self, k, kwargs[k]) + + def __eq__(self, other: Any) -> bool: + """Compare objects by comparing all attributes.""" + if isinstance(other, self.__class__): + return self.__dict__ == other.__dict__ + return False + + def __ne__(self, other: Any) -> bool: + """Compare objects by comparing all attributes.""" + return not self.__eq__(other) + + def __str__(self) -> str: + return str(self.__dict__) + + @classmethod + def enable_additional_properties_sending(cls) -> None: + cls._attribute_map["additional_properties"] = {"key": "", "type": "{object}"} + + @classmethod + def is_xml_model(cls) -> bool: + try: + cls._xml_map # type: ignore + except AttributeError: + return False + return True + + @classmethod + def _create_xml_node(cls): + """Create XML node.""" + try: + xml_map = cls._xml_map # type: ignore + except AttributeError: + xml_map = {} + + return _create_xml_node(xml_map.get("name", cls.__name__), xml_map.get("prefix", None), xml_map.get("ns", None)) + + def serialize(self, keep_readonly: bool = False, **kwargs: Any) -> JSON: + """Return the JSON that would be sent to server from this model. + + This is an alias to `as_dict(full_restapi_key_transformer, keep_readonly=False)`. + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param bool keep_readonly: If you want to serialize the readonly attributes + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize(self, keep_readonly=keep_readonly, **kwargs) # type: ignore + + def as_dict( + self, + keep_readonly: bool = True, + key_transformer: Callable[[str, Dict[str, Any], Any], Any] = attribute_transformer, + **kwargs: Any + ) -> JSON: + """Return a dict that can be serialized using json.dump. + + Advanced usage might optionally use a callback as parameter: + + .. code::python + + def my_key_transformer(key, attr_desc, value): + return key + + Key is the attribute name used in Python. Attr_desc + is a dict of metadata. Currently contains 'type' with the + msrest type and 'key' with the RestAPI encoded key. + Value is the current value in this object. + + The string returned will be used to serialize the key. + If the return type is a list, this is considered hierarchical + result dict. + + See the three examples in this file: + + - attribute_transformer + - full_restapi_key_transformer + - last_restapi_key_transformer + + If you want XML serialization, you can pass the kwargs is_xml=True. + + :param function key_transformer: A key transformer function. + :returns: A dict JSON compatible object + :rtype: dict + """ + serializer = Serializer(self._infer_class_models()) + return serializer._serialize(self, key_transformer=key_transformer, keep_readonly=keep_readonly, **kwargs) # type: ignore + + @classmethod + def _infer_class_models(cls): + try: + str_models = cls.__module__.rsplit(".", 1)[0] + models = sys.modules[str_models] + client_models = {k: v for k, v in models.__dict__.items() if isinstance(v, type)} + if cls.__name__ not in client_models: + raise ValueError("Not Autorest generated code") + except Exception: + # Assume it's not Autorest generated (tests?). Add ourselves as dependencies. + client_models = {cls.__name__: cls} + return client_models + + @classmethod + def deserialize(cls: Type[ModelType], data: Any, content_type: Optional[str] = None) -> ModelType: + """Parse a str using the RestAPI syntax and return a model. + + :param str data: A str using RestAPI structure. JSON by default. + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises: DeserializationError if something went wrong + """ + deserializer = Deserializer(cls._infer_class_models()) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def from_dict( + cls: Type[ModelType], + data: Any, + key_extractors: Optional[Callable[[str, Dict[str, Any], Any], Any]] = None, + content_type: Optional[str] = None, + ) -> ModelType: + """Parse a dict using given key extractor return a model. + + By default consider key + extractors (rest_key_case_insensitive_extractor, attribute_key_case_insensitive_extractor + and last_rest_key_case_insensitive_extractor) + + :param dict data: A dict using RestAPI structure + :param str content_type: JSON by default, set application/xml if XML. + :returns: An instance of this model + :raises: DeserializationError if something went wrong + """ + deserializer = Deserializer(cls._infer_class_models()) + deserializer.key_extractors = ( # type: ignore + [ # type: ignore + attribute_key_case_insensitive_extractor, + rest_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + if key_extractors is None + else key_extractors + ) + return deserializer(cls.__name__, data, content_type=content_type) # type: ignore + + @classmethod + def _flatten_subtype(cls, key, objects): + if "_subtype_map" not in cls.__dict__: + return {} + result = dict(cls._subtype_map[key]) + for valuetype in cls._subtype_map[key].values(): + result.update(objects[valuetype]._flatten_subtype(key, objects)) + return result + + @classmethod + def _classify(cls, response, objects): + """Check the class _subtype_map for any child classes. + We want to ignore any inherited _subtype_maps. + Remove the polymorphic key from the initial data. + """ + for subtype_key in cls.__dict__.get("_subtype_map", {}).keys(): + subtype_value = None + + if not isinstance(response, ET.Element): + rest_api_response_key = cls._get_rest_key_parts(subtype_key)[-1] + subtype_value = response.pop(rest_api_response_key, None) or response.pop(subtype_key, None) + else: + subtype_value = xml_key_extractor(subtype_key, cls._attribute_map[subtype_key], response) + if subtype_value: + # Try to match base class. Can be class name only + # (bug to fix in Autorest to support x-ms-discriminator-name) + if cls.__name__ == subtype_value: + return cls + flatten_mapping_type = cls._flatten_subtype(subtype_key, objects) + try: + return objects[flatten_mapping_type[subtype_value]] # type: ignore + except KeyError: + _LOGGER.warning( + "Subtype value %s has no mapping, use base class %s.", + subtype_value, + cls.__name__, + ) + break + else: + _LOGGER.warning("Discriminator %s is absent or null, use base class %s.", subtype_key, cls.__name__) + break + return cls + + @classmethod + def _get_rest_key_parts(cls, attr_key): + """Get the RestAPI key of this attr, split it and decode part + :param str attr_key: Attribute key must be in attribute_map. + :returns: A list of RestAPI part + :rtype: list + """ + rest_split_key = _FLATTEN.split(cls._attribute_map[attr_key]["key"]) + return [_decode_attribute_map_key(key_part) for key_part in rest_split_key] + + +def _decode_attribute_map_key(key): + """This decode a key in an _attribute_map to the actual key we want to look at + inside the received data. + + :param str key: A key string from the generated code + """ + return key.replace("\\.", ".") + + +class Serializer(object): + """Request object model serializer.""" + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + _xml_basic_types_serializers = {"bool": lambda x: str(x).lower()} + days = {0: "Mon", 1: "Tue", 2: "Wed", 3: "Thu", 4: "Fri", 5: "Sat", 6: "Sun"} + months = { + 1: "Jan", + 2: "Feb", + 3: "Mar", + 4: "Apr", + 5: "May", + 6: "Jun", + 7: "Jul", + 8: "Aug", + 9: "Sep", + 10: "Oct", + 11: "Nov", + 12: "Dec", + } + validation = { + "min_length": lambda x, y: len(x) < y, + "max_length": lambda x, y: len(x) > y, + "minimum": lambda x, y: x < y, + "maximum": lambda x, y: x > y, + "minimum_ex": lambda x, y: x <= y, + "maximum_ex": lambda x, y: x >= y, + "min_items": lambda x, y: len(x) < y, + "max_items": lambda x, y: len(x) > y, + "pattern": lambda x, y: not re.match(y, x, re.UNICODE), + "unique": lambda x, y: len(x) != len(set(x)), + "multiple": lambda x, y: x % y != 0, + } + + def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): + self.serialize_type = { + "iso-8601": Serializer.serialize_iso, + "rfc-1123": Serializer.serialize_rfc, + "unix-time": Serializer.serialize_unix, + "duration": Serializer.serialize_duration, + "date": Serializer.serialize_date, + "time": Serializer.serialize_time, + "decimal": Serializer.serialize_decimal, + "long": Serializer.serialize_long, + "bytearray": Serializer.serialize_bytearray, + "base64": Serializer.serialize_base64, + "object": self.serialize_object, + "[]": self.serialize_iter, + "{}": self.serialize_dict, + } + self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} + self.key_transformer = full_restapi_key_transformer + self.client_side_validation = True + + def _serialize(self, target_obj, data_type=None, **kwargs): + """Serialize data into a string according to type. + + :param target_obj: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str, dict + :raises: SerializationError if serialization fails. + """ + key_transformer = kwargs.get("key_transformer", self.key_transformer) + keep_readonly = kwargs.get("keep_readonly", False) + if target_obj is None: + return None + + attr_name = None + class_name = target_obj.__class__.__name__ + + if data_type: + return self.serialize_data(target_obj, data_type, **kwargs) + + if not hasattr(target_obj, "_attribute_map"): + data_type = type(target_obj).__name__ + if data_type in self.basic_types.values(): + return self.serialize_data(target_obj, data_type, **kwargs) + + # Force "is_xml" kwargs if we detect a XML model + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + is_xml_model_serialization = kwargs.setdefault("is_xml", target_obj.is_xml_model()) + + serialized = {} + if is_xml_model_serialization: + serialized = target_obj._create_xml_node() + try: + attributes = target_obj._attribute_map + for attr, attr_desc in attributes.items(): + attr_name = attr + if not keep_readonly and target_obj._validation.get(attr_name, {}).get("readonly", False): + continue + + if attr_name == "additional_properties" and attr_desc["key"] == "": + if target_obj.additional_properties is not None: + serialized.update(target_obj.additional_properties) + continue + try: + + orig_attr = getattr(target_obj, attr) + if is_xml_model_serialization: + pass # Don't provide "transformer" for XML for now. Keep "orig_attr" + else: # JSON + keys, orig_attr = key_transformer(attr, attr_desc.copy(), orig_attr) + keys = keys if isinstance(keys, list) else [keys] + + kwargs["serialization_ctxt"] = attr_desc + new_attr = self.serialize_data(orig_attr, attr_desc["type"], **kwargs) + + if is_xml_model_serialization: + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + xml_prefix = xml_desc.get("prefix", None) + xml_ns = xml_desc.get("ns", None) + if xml_desc.get("attr", False): + if xml_ns: + ET.register_namespace(xml_prefix, xml_ns) + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + serialized.set(xml_name, new_attr) # type: ignore + continue + if xml_desc.get("text", False): + serialized.text = new_attr # type: ignore + continue + if isinstance(new_attr, list): + serialized.extend(new_attr) # type: ignore + elif isinstance(new_attr, ET.Element): + # If the down XML has no XML/Name, we MUST replace the tag with the local tag. But keeping the namespaces. + if "name" not in getattr(orig_attr, "_xml_map", {}): + splitted_tag = new_attr.tag.split("}") + if len(splitted_tag) == 2: # Namespace + new_attr.tag = "}".join([splitted_tag[0], xml_name]) + else: + new_attr.tag = xml_name + serialized.append(new_attr) # type: ignore + else: # That's a basic type + # Integrate namespace if necessary + local_node = _create_xml_node(xml_name, xml_prefix, xml_ns) + local_node.text = unicode_str(new_attr) + serialized.append(local_node) # type: ignore + else: # JSON + for k in reversed(keys): # type: ignore + new_attr = {k: new_attr} + + _new_attr = new_attr + _serialized = serialized + for k in keys: # type: ignore + if k not in _serialized: + _serialized.update(_new_attr) # type: ignore + _new_attr = _new_attr[k] # type: ignore + _serialized = _serialized[k] + except ValueError as err: + if isinstance(err, SerializationError): + raise + + except (AttributeError, KeyError, TypeError) as err: + msg = "Attribute {} in object {} cannot be serialized.\n{}".format(attr_name, class_name, str(target_obj)) + raise SerializationError(msg) from err + else: + return serialized + + def body(self, data, data_type, **kwargs): + """Serialize data intended for a request body. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: dict + :raises: SerializationError if serialization fails. + :raises: ValueError if data is None + """ + + # Just in case this is a dict + internal_data_type_str = data_type.strip("[]{}") + internal_data_type = self.dependencies.get(internal_data_type_str, None) + try: + is_xml_model_serialization = kwargs["is_xml"] + except KeyError: + if internal_data_type and issubclass(internal_data_type, Model): + is_xml_model_serialization = kwargs.setdefault("is_xml", internal_data_type.is_xml_model()) + else: + is_xml_model_serialization = False + if internal_data_type and not isinstance(internal_data_type, Enum): + try: + deserializer = Deserializer(self.dependencies) + # Since it's on serialization, it's almost sure that format is not JSON REST + # We're not able to deal with additional properties for now. + deserializer.additional_properties_detection = False + if is_xml_model_serialization: + deserializer.key_extractors = [ # type: ignore + attribute_key_case_insensitive_extractor, + ] + else: + deserializer.key_extractors = [ + rest_key_case_insensitive_extractor, + attribute_key_case_insensitive_extractor, + last_rest_key_case_insensitive_extractor, + ] + data = deserializer._deserialize(data_type, data) + except DeserializationError as err: + raise SerializationError("Unable to build a model: " + str(err)) from err + + return self._serialize(data, data_type, **kwargs) + + def url(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL path. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + + if kwargs.get("skip_quote") is True: + output = str(output) + output = output.replace("{", quote("{")).replace("}", quote("}")) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return output + + def query(self, name, data, data_type, **kwargs): + """Serialize data intended for a URL query. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :keyword bool skip_quote: Whether to skip quote the serialized result. + Defaults to False. + :rtype: str, list + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + # Treat the list aside, since we don't want to encode the div separator + if data_type.startswith("["): + internal_data_type = data_type[1:-1] + do_quote = not kwargs.get("skip_quote", False) + return self.serialize_iter(data, internal_data_type, do_quote=do_quote, **kwargs) + + # Not a list, regular serialization + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + if kwargs.get("skip_quote") is True: + output = str(output) + else: + output = quote(str(output), safe="") + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def header(self, name, data, data_type, **kwargs): + """Serialize data intended for a request header. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :rtype: str + :raises: TypeError if serialization fails. + :raises: ValueError if data is None + """ + try: + if data_type in ["[str]"]: + data = ["" if d is None else d for d in data] + + output = self.serialize_data(data, data_type, **kwargs) + if data_type == "bool": + output = json.dumps(output) + except SerializationError: + raise TypeError("{} must be type {}.".format(name, data_type)) + else: + return str(output) + + def serialize_data(self, data, data_type, **kwargs): + """Serialize generic data according to supplied data type. + + :param data: The data to be serialized. + :param str data_type: The type to be serialized from. + :param bool required: Whether it's essential that the data not be + empty or None + :raises: AttributeError if required data is None. + :raises: ValueError if data is None + :raises: SerializationError if serialization fails. + """ + if data is None: + raise ValueError("No value for given attribute") + + try: + if data is CoreNull: + return None + if data_type in self.basic_types.values(): + return self.serialize_basic(data, data_type, **kwargs) + + elif data_type in self.serialize_type: + return self.serialize_type[data_type](data, **kwargs) + + # If dependencies is empty, try with current data class + # It has to be a subclass of Enum anyway + enum_type = self.dependencies.get(data_type, data.__class__) + if issubclass(enum_type, Enum): + return Serializer.serialize_enum(data, enum_obj=enum_type) + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.serialize_type: + return self.serialize_type[iter_type](data, data_type[1:-1], **kwargs) + + except (ValueError, TypeError) as err: + msg = "Unable to serialize value: {!r} as type: {!r}." + raise SerializationError(msg.format(data, data_type)) from err + else: + return self._serialize(data, **kwargs) + + @classmethod + def _get_custom_serializers(cls, data_type, **kwargs): + custom_serializer = kwargs.get("basic_types_serializers", {}).get(data_type) + if custom_serializer: + return custom_serializer + if kwargs.get("is_xml", False): + return cls._xml_basic_types_serializers.get(data_type) + + @classmethod + def serialize_basic(cls, data, data_type, **kwargs): + """Serialize basic builting data type. + Serializes objects to str, int, float or bool. + + Possible kwargs: + - basic_types_serializers dict[str, callable] : If set, use the callable as serializer + - is_xml bool : If set, use xml_basic_types_serializers + + :param data: Object to be serialized. + :param str data_type: Type of object in the iterable. + """ + custom_serializer = cls._get_custom_serializers(data_type, **kwargs) + if custom_serializer: + return custom_serializer(data) + if data_type == "str": + return cls.serialize_unicode(data) + return eval(data_type)(data) # nosec + + @classmethod + def serialize_unicode(cls, data): + """Special handling for serializing unicode strings in Py2. + Encode to UTF-8 if unicode, otherwise handle as a str. + + :param data: Object to be serialized. + :rtype: str + """ + try: # If I received an enum, return its value + return data.value + except AttributeError: + pass + + try: + if isinstance(data, unicode): # type: ignore + # Don't change it, JSON and XML ElementTree are totally able + # to serialize correctly u'' strings + return data + except NameError: + return str(data) + else: + return str(data) + + def serialize_iter(self, data, iter_type, div=None, **kwargs): + """Serialize iterable. + + Supported kwargs: + - serialization_ctxt dict : The current entry of _attribute_map, or same format. + serialization_ctxt['type'] should be same as data_type. + - is_xml bool : If set, serialize as XML + + :param list attr: Object to be serialized. + :param str iter_type: Type of object in the iterable. + :param bool required: Whether the objects in the iterable must + not be None or empty. + :param str div: If set, this str will be used to combine the elements + in the iterable into a combined string. Default is 'None'. + :keyword bool do_quote: Whether to quote the serialized result of each iterable element. + Defaults to False. + :rtype: list, str + """ + if isinstance(data, str): + raise SerializationError("Refuse str type as a valid iter type.") + + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + is_xml = kwargs.get("is_xml", False) + + serialized = [] + for d in data: + try: + serialized.append(self.serialize_data(d, iter_type, **kwargs)) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized.append(None) + + if kwargs.get("do_quote", False): + serialized = ["" if s is None else quote(str(s), safe="") for s in serialized] + + if div: + serialized = ["" if s is None else str(s) for s in serialized] + serialized = div.join(serialized) + + if "xml" in serialization_ctxt or is_xml: + # XML serialization is more complicated + xml_desc = serialization_ctxt.get("xml", {}) + xml_name = xml_desc.get("name") + if not xml_name: + xml_name = serialization_ctxt["key"] + + # Create a wrap node if necessary (use the fact that Element and list have "append") + is_wrapped = xml_desc.get("wrapped", False) + node_name = xml_desc.get("itemsName", xml_name) + if is_wrapped: + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + else: + final_result = [] + # All list elements to "local_node" + for el in serialized: + if isinstance(el, ET.Element): + el_node = el + else: + el_node = _create_xml_node(node_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + if el is not None: # Otherwise it writes "None" :-p + el_node.text = str(el) + final_result.append(el_node) + return final_result + return serialized + + def serialize_dict(self, attr, dict_type, **kwargs): + """Serialize a dictionary of objects. + + :param dict attr: Object to be serialized. + :param str dict_type: Type of object in the dictionary. + :param bool required: Whether the objects in the dictionary must + not be None or empty. + :rtype: dict + """ + serialization_ctxt = kwargs.get("serialization_ctxt", {}) + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_data(value, dict_type, **kwargs) + except ValueError as err: + if isinstance(err, SerializationError): + raise + serialized[self.serialize_unicode(key)] = None + + if "xml" in serialization_ctxt: + # XML serialization is more complicated + xml_desc = serialization_ctxt["xml"] + xml_name = xml_desc["name"] + + final_result = _create_xml_node(xml_name, xml_desc.get("prefix", None), xml_desc.get("ns", None)) + for key, value in serialized.items(): + ET.SubElement(final_result, key).text = value + return final_result + + return serialized + + def serialize_object(self, attr, **kwargs): + """Serialize a generic object. + This will be handled as a dictionary. If object passed in is not + a basic type (str, int, float, dict, list) it will simply be + cast to str. + + :param dict attr: Object to be serialized. + :rtype: dict or str + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + return attr + obj_type = type(attr) + if obj_type in self.basic_types: + return self.serialize_basic(attr, self.basic_types[obj_type], **kwargs) + if obj_type is _long_type: + return self.serialize_long(attr) + if obj_type is unicode_str: + return self.serialize_unicode(attr) + if obj_type is datetime.datetime: + return self.serialize_iso(attr) + if obj_type is datetime.date: + return self.serialize_date(attr) + if obj_type is datetime.time: + return self.serialize_time(attr) + if obj_type is datetime.timedelta: + return self.serialize_duration(attr) + if obj_type is decimal.Decimal: + return self.serialize_decimal(attr) + + # If it's a model or I know this dependency, serialize as a Model + elif obj_type in self.dependencies.values() or isinstance(attr, Model): + return self._serialize(attr) + + if obj_type == dict: + serialized = {} + for key, value in attr.items(): + try: + serialized[self.serialize_unicode(key)] = self.serialize_object(value, **kwargs) + except ValueError: + serialized[self.serialize_unicode(key)] = None + return serialized + + if obj_type == list: + serialized = [] + for obj in attr: + try: + serialized.append(self.serialize_object(obj, **kwargs)) + except ValueError: + pass + return serialized + return str(attr) + + @staticmethod + def serialize_enum(attr, enum_obj=None): + try: + result = attr.value + except AttributeError: + result = attr + try: + enum_obj(result) # type: ignore + return result + except ValueError: + for enum_value in enum_obj: # type: ignore + if enum_value.value.lower() == str(attr).lower(): + return enum_value.value + error = "{!r} is not valid value for enum {!r}" + raise SerializationError(error.format(attr, enum_obj)) + + @staticmethod + def serialize_bytearray(attr, **kwargs): + """Serialize bytearray into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + return b64encode(attr).decode() + + @staticmethod + def serialize_base64(attr, **kwargs): + """Serialize str into base-64 string. + + :param attr: Object to be serialized. + :rtype: str + """ + encoded = b64encode(attr).decode("ascii") + return encoded.strip("=").replace("+", "-").replace("/", "_") + + @staticmethod + def serialize_decimal(attr, **kwargs): + """Serialize Decimal object to float. + + :param attr: Object to be serialized. + :rtype: float + """ + return float(attr) + + @staticmethod + def serialize_long(attr, **kwargs): + """Serialize long (Py2) or int (Py3). + + :param attr: Object to be serialized. + :rtype: int/long + """ + return _long_type(attr) + + @staticmethod + def serialize_date(attr, **kwargs): + """Serialize Date object into ISO-8601 formatted string. + + :param Date attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_date(attr) + t = "{:04}-{:02}-{:02}".format(attr.year, attr.month, attr.day) + return t + + @staticmethod + def serialize_time(attr, **kwargs): + """Serialize Time object into ISO-8601 formatted string. + + :param datetime.time attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_time(attr) + t = "{:02}:{:02}:{:02}".format(attr.hour, attr.minute, attr.second) + if attr.microsecond: + t += ".{:02}".format(attr.microsecond) + return t + + @staticmethod + def serialize_duration(attr, **kwargs): + """Serialize TimeDelta object into ISO-8601 formatted string. + + :param TimeDelta attr: Object to be serialized. + :rtype: str + """ + if isinstance(attr, str): + attr = isodate.parse_duration(attr) + return isodate.duration_isoformat(attr) + + @staticmethod + def serialize_rfc(attr, **kwargs): + """Serialize Datetime object into RFC-1123 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: TypeError if format invalid. + """ + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + except AttributeError: + raise TypeError("RFC1123 object must be valid Datetime object.") + + return "{}, {:02} {} {:04} {:02}:{:02}:{:02} GMT".format( + Serializer.days[utc.tm_wday], + utc.tm_mday, + Serializer.months[utc.tm_mon], + utc.tm_year, + utc.tm_hour, + utc.tm_min, + utc.tm_sec, + ) + + @staticmethod + def serialize_iso(attr, **kwargs): + """Serialize Datetime object into ISO-8601 formatted string. + + :param Datetime attr: Object to be serialized. + :rtype: str + :raises: SerializationError if format invalid. + """ + if isinstance(attr, str): + attr = isodate.parse_datetime(attr) + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + utc = attr.utctimetuple() + if utc.tm_year > 9999 or utc.tm_year < 1: + raise OverflowError("Hit max or min date") + + microseconds = str(attr.microsecond).rjust(6, "0").rstrip("0").ljust(3, "0") + if microseconds: + microseconds = "." + microseconds + date = "{:04}-{:02}-{:02}T{:02}:{:02}:{:02}".format( + utc.tm_year, utc.tm_mon, utc.tm_mday, utc.tm_hour, utc.tm_min, utc.tm_sec + ) + return date + microseconds + "Z" + except (ValueError, OverflowError) as err: + msg = "Unable to serialize datetime object." + raise SerializationError(msg) from err + except AttributeError as err: + msg = "ISO-8601 object must be valid Datetime object." + raise TypeError(msg) from err + + @staticmethod + def serialize_unix(attr, **kwargs): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param Datetime attr: Object to be serialized. + :rtype: int + :raises: SerializationError if format invalid + """ + if isinstance(attr, int): + return attr + try: + if not attr.tzinfo: + _LOGGER.warning("Datetime with no tzinfo will be considered UTC.") + return int(calendar.timegm(attr.utctimetuple())) + except AttributeError: + raise TypeError("Unix time object must be valid Datetime object.") + + +def rest_key_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + dict_keys = cast(List[str], _FLATTEN.split(key)) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = working_data.get(working_key, data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + return working_data.get(key) + + +def rest_key_case_insensitive_extractor(attr, attr_desc, data): + key = attr_desc["key"] + working_data = data + + while "." in key: + dict_keys = _FLATTEN.split(key) + if len(dict_keys) == 1: + key = _decode_attribute_map_key(dict_keys[0]) + break + working_key = _decode_attribute_map_key(dict_keys[0]) + working_data = attribute_key_case_insensitive_extractor(working_key, None, working_data) + if working_data is None: + # If at any point while following flatten JSON path see None, it means + # that all properties under are None as well + return None + key = ".".join(dict_keys[1:]) + + if working_data: + return attribute_key_case_insensitive_extractor(key, None, working_data) + + +def last_rest_key_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key.""" + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_extractor(dict_keys[-1], None, data) + + +def last_rest_key_case_insensitive_extractor(attr, attr_desc, data): + """Extract the attribute in "data" based on the last part of the JSON path key. + + This is the case insensitive version of "last_rest_key_extractor" + """ + key = attr_desc["key"] + dict_keys = _FLATTEN.split(key) + return attribute_key_case_insensitive_extractor(dict_keys[-1], None, data) + + +def attribute_key_extractor(attr, _, data): + return data.get(attr) + + +def attribute_key_case_insensitive_extractor(attr, _, data): + found_key = None + lower_attr = attr.lower() + for key in data: + if lower_attr == key.lower(): + found_key = key + break + + return data.get(found_key) + + +def _extract_name_from_internal_type(internal_type): + """Given an internal type XML description, extract correct XML name with namespace. + + :param dict internal_type: An model type + :rtype: tuple + :returns: A tuple XML name + namespace dict + """ + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + xml_name = internal_type_xml_map.get("name", internal_type.__name__) + xml_ns = internal_type_xml_map.get("ns", None) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + return xml_name + + +def xml_key_extractor(attr, attr_desc, data): + if isinstance(data, dict): + return None + + # Test if this model is XML ready first + if not isinstance(data, ET.Element): + return None + + xml_desc = attr_desc.get("xml", {}) + xml_name = xml_desc.get("name", attr_desc["key"]) + + # Look for a children + is_iter_type = attr_desc["type"].startswith("[") + is_wrapped = xml_desc.get("wrapped", False) + internal_type = attr_desc.get("internalType", None) + internal_type_xml_map = getattr(internal_type, "_xml_map", {}) + + # Integrate namespace if necessary + xml_ns = xml_desc.get("ns", internal_type_xml_map.get("ns", None)) + if xml_ns: + xml_name = "{{{}}}{}".format(xml_ns, xml_name) + + # If it's an attribute, that's simple + if xml_desc.get("attr", False): + return data.get(xml_name) + + # If it's x-ms-text, that's simple too + if xml_desc.get("text", False): + return data.text + + # Scenario where I take the local name: + # - Wrapped node + # - Internal type is an enum (considered basic types) + # - Internal type has no XML/Name node + if is_wrapped or (internal_type and (issubclass(internal_type, Enum) or "name" not in internal_type_xml_map)): + children = data.findall(xml_name) + # If internal type has a local name and it's not a list, I use that name + elif not is_iter_type and internal_type and "name" in internal_type_xml_map: + xml_name = _extract_name_from_internal_type(internal_type) + children = data.findall(xml_name) + # That's an array + else: + if internal_type: # Complex type, ignore itemsName and use the complex type name + items_name = _extract_name_from_internal_type(internal_type) + else: + items_name = xml_desc.get("itemsName", xml_name) + children = data.findall(items_name) + + if len(children) == 0: + if is_iter_type: + if is_wrapped: + return None # is_wrapped no node, we want None + else: + return [] # not wrapped, assume empty list + return None # Assume it's not there, maybe an optional node. + + # If is_iter_type and not wrapped, return all found children + if is_iter_type: + if not is_wrapped: + return children + else: # Iter and wrapped, should have found one node only (the wrap one) + if len(children) != 1: + raise DeserializationError( + "Tried to deserialize an array not wrapped, and found several nodes '{}'. Maybe you should declare this array as wrapped?".format( + xml_name + ) + ) + return list(children[0]) # Might be empty list and that's ok. + + # Here it's not a itertype, we should have found one element only or empty + if len(children) > 1: + raise DeserializationError("Find several XML '{}' where it was not expected".format(xml_name)) + return children[0] + + +class Deserializer(object): + """Response object model deserializer. + + :param dict classes: Class type dictionary for deserializing complex types. + :ivar list key_extractors: Ordered list of extractors to be used by this deserializer. + """ + + basic_types = {str: "str", int: "int", bool: "bool", float: "float"} + + valid_date = re.compile(r"\d{4}[-]\d{2}[-]\d{2}T\d{2}:\d{2}:\d{2}" r"\.?\d*Z?[-+]?[\d{2}]?:?[\d{2}]?") + + def __init__(self, classes: Optional[Mapping[str, Type[ModelType]]] = None): + self.deserialize_type = { + "iso-8601": Deserializer.deserialize_iso, + "rfc-1123": Deserializer.deserialize_rfc, + "unix-time": Deserializer.deserialize_unix, + "duration": Deserializer.deserialize_duration, + "date": Deserializer.deserialize_date, + "time": Deserializer.deserialize_time, + "decimal": Deserializer.deserialize_decimal, + "long": Deserializer.deserialize_long, + "bytearray": Deserializer.deserialize_bytearray, + "base64": Deserializer.deserialize_base64, + "object": self.deserialize_object, + "[]": self.deserialize_iter, + "{}": self.deserialize_dict, + } + self.deserialize_expected_types = { + "duration": (isodate.Duration, datetime.timedelta), + "iso-8601": (datetime.datetime), + } + self.dependencies: Dict[str, Type[ModelType]] = dict(classes) if classes else {} + self.key_extractors = [rest_key_extractor, xml_key_extractor] + # Additional properties only works if the "rest_key_extractor" is used to + # extract the keys. Making it to work whatever the key extractor is too much + # complicated, with no real scenario for now. + # So adding a flag to disable additional properties detection. This flag should be + # used if your expect the deserialization to NOT come from a JSON REST syntax. + # Otherwise, result are unexpected + self.additional_properties_detection = True + + def __call__(self, target_obj, response_data, content_type=None): + """Call the deserializer to process a REST response. + + :param str target_obj: Target data type to deserialize to. + :param requests.Response response_data: REST response object. + :param str content_type: Swagger "produces" if available. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + data = self._unpack_content(response_data, content_type) + return self._deserialize(target_obj, data) + + def _deserialize(self, target_obj, data): + """Call the deserializer on a model. + + Data needs to be already deserialized as JSON or XML ElementTree + + :param str target_obj: Target data type to deserialize to. + :param object data: Object to deserialize. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + # This is already a model, go recursive just in case + if hasattr(data, "_attribute_map"): + constants = [name for name, config in getattr(data, "_validation", {}).items() if config.get("constant")] + try: + for attr, mapconfig in data._attribute_map.items(): + if attr in constants: + continue + value = getattr(data, attr) + if value is None: + continue + local_type = mapconfig["type"] + internal_data_type = local_type.strip("[]{}") + if internal_data_type not in self.dependencies or isinstance(internal_data_type, Enum): + continue + setattr(data, attr, self._deserialize(local_type, value)) + return data + except AttributeError: + return + + response, class_name = self._classify_target(target_obj, data) + + if isinstance(response, basestring): + return self.deserialize_data(data, response) + elif isinstance(response, type) and issubclass(response, Enum): + return self.deserialize_enum(data, response) + + if data is None: + return data + try: + attributes = response._attribute_map # type: ignore + d_attrs = {} + for attr, attr_desc in attributes.items(): + # Check empty string. If it's not empty, someone has a real "additionalProperties"... + if attr == "additional_properties" and attr_desc["key"] == "": + continue + raw_value = None + # Enhance attr_desc with some dynamic data + attr_desc = attr_desc.copy() # Do a copy, do not change the real one + internal_data_type = attr_desc["type"].strip("[]{}") + if internal_data_type in self.dependencies: + attr_desc["internalType"] = self.dependencies[internal_data_type] + + for key_extractor in self.key_extractors: + found_value = key_extractor(attr, attr_desc, data) + if found_value is not None: + if raw_value is not None and raw_value != found_value: + msg = ( + "Ignoring extracted value '%s' from %s for key '%s'" + " (duplicate extraction, follow extractors order)" + ) + _LOGGER.warning(msg, found_value, key_extractor, attr) + continue + raw_value = found_value + + value = self.deserialize_data(raw_value, attr_desc["type"]) + d_attrs[attr] = value + except (AttributeError, TypeError, KeyError) as err: + msg = "Unable to deserialize to object: " + class_name # type: ignore + raise DeserializationError(msg) from err + else: + additional_properties = self._build_additional_properties(attributes, data) + return self._instantiate_model(response, d_attrs, additional_properties) + + def _build_additional_properties(self, attribute_map, data): + if not self.additional_properties_detection: + return None + if "additional_properties" in attribute_map and attribute_map.get("additional_properties", {}).get("key") != "": + # Check empty string. If it's not empty, someone has a real "additionalProperties" + return None + if isinstance(data, ET.Element): + data = {el.tag: el.text for el in data} + + known_keys = { + _decode_attribute_map_key(_FLATTEN.split(desc["key"])[0]) + for desc in attribute_map.values() + if desc["key"] != "" + } + present_keys = set(data.keys()) + missing_keys = present_keys - known_keys + return {key: data[key] for key in missing_keys} + + def _classify_target(self, target, data): + """Check to see whether the deserialization target object can + be classified into a subclass. + Once classification has been determined, initialize object. + + :param str target: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + """ + if target is None: + return None, None + + if isinstance(target, basestring): + try: + target = self.dependencies[target] + except KeyError: + return target, target + + try: + target = target._classify(data, self.dependencies) + except AttributeError: + pass # Target is not a Model, no classify + return target, target.__class__.__name__ # type: ignore + + def failsafe_deserialize(self, target_obj, data, content_type=None): + """Ignores any errors encountered in deserialization, + and falls back to not deserializing the object. Recommended + for use in error deserialization, as we want to return the + HttpResponseError to users, and not have them deal with + a deserialization error. + + :param str target_obj: The target object type to deserialize to. + :param str/dict data: The response data to deserialize. + :param str content_type: Swagger "produces" if available. + """ + try: + return self(target_obj, data, content_type=content_type) + except: + _LOGGER.debug( + "Ran into a deserialization error. Ignoring since this is failsafe deserialization", exc_info=True + ) + return None + + @staticmethod + def _unpack_content(raw_data, content_type=None): + """Extract the correct structure for deserialization. + + If raw_data is a PipelineResponse, try to extract the result of RawDeserializer. + if we can't, raise. Your Pipeline should have a RawDeserializer. + + If not a pipeline response and raw_data is bytes or string, use content-type + to decode it. If no content-type, try JSON. + + If raw_data is something else, bypass all logic and return it directly. + + :param raw_data: Data to be processed. + :param content_type: How to parse if raw_data is a string/bytes. + :raises JSONDecodeError: If JSON is requested and parsing is impossible. + :raises UnicodeDecodeError: If bytes is not UTF8 + """ + # Assume this is enough to detect a Pipeline Response without importing it + context = getattr(raw_data, "context", {}) + if context: + if RawDeserializer.CONTEXT_NAME in context: + return context[RawDeserializer.CONTEXT_NAME] + raise ValueError("This pipeline didn't have the RawDeserializer policy; can't deserialize") + + # Assume this is enough to recognize universal_http.ClientResponse without importing it + if hasattr(raw_data, "body"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text(), raw_data.headers) + + # Assume this enough to recognize requests.Response without importing it. + if hasattr(raw_data, "_content_consumed"): + return RawDeserializer.deserialize_from_http_generics(raw_data.text, raw_data.headers) + + if isinstance(raw_data, (basestring, bytes)) or hasattr(raw_data, "read"): + return RawDeserializer.deserialize_from_text(raw_data, content_type) # type: ignore + return raw_data + + def _instantiate_model(self, response, attrs, additional_properties=None): + """Instantiate a response model passing in deserialized args. + + :param response: The response model class. + :param d_attrs: The deserialized response attributes. + """ + if callable(response): + subtype = getattr(response, "_subtype_map", {}) + try: + readonly = [k for k, v in response._validation.items() if v.get("readonly")] + const = [k for k, v in response._validation.items() if v.get("constant")] + kwargs = {k: v for k, v in attrs.items() if k not in subtype and k not in readonly + const} + response_obj = response(**kwargs) + for attr in readonly: + setattr(response_obj, attr, attrs.get(attr)) + if additional_properties: + response_obj.additional_properties = additional_properties + return response_obj + except TypeError as err: + msg = "Unable to deserialize {} into model {}. ".format(kwargs, response) # type: ignore + raise DeserializationError(msg + str(err)) + else: + try: + for attr, value in attrs.items(): + setattr(response, attr, value) + return response + except Exception as exp: + msg = "Unable to populate response model. " + msg += "Type: {}, Error: {}".format(type(response), exp) + raise DeserializationError(msg) + + def deserialize_data(self, data, data_type): + """Process data for deserialization according to data type. + + :param str data: The response string to be deserialized. + :param str data_type: The type to deserialize to. + :raises: DeserializationError if deserialization fails. + :return: Deserialized object. + """ + if data is None: + return data + + try: + if not data_type: + return data + if data_type in self.basic_types.values(): + return self.deserialize_basic(data, data_type) + if data_type in self.deserialize_type: + if isinstance(data, self.deserialize_expected_types.get(data_type, tuple())): + return data + + is_a_text_parsing_type = lambda x: x not in ["object", "[]", r"{}"] + if isinstance(data, ET.Element) and is_a_text_parsing_type(data_type) and not data.text: + return None + data_val = self.deserialize_type[data_type](data) + return data_val + + iter_type = data_type[0] + data_type[-1] + if iter_type in self.deserialize_type: + return self.deserialize_type[iter_type](data, data_type[1:-1]) + + obj_type = self.dependencies[data_type] + if issubclass(obj_type, Enum): + if isinstance(data, ET.Element): + data = data.text + return self.deserialize_enum(data, obj_type) + + except (ValueError, TypeError, AttributeError) as err: + msg = "Unable to deserialize response data." + msg += " Data: {}, {}".format(data, data_type) + raise DeserializationError(msg) from err + else: + return self._deserialize(obj_type, data) + + def deserialize_iter(self, attr, iter_type): + """Deserialize an iterable. + + :param list attr: Iterable to be deserialized. + :param str iter_type: The type of object in the iterable. + :rtype: list + """ + if attr is None: + return None + if isinstance(attr, ET.Element): # If I receive an element here, get the children + attr = list(attr) + if not isinstance(attr, (list, set)): + raise DeserializationError("Cannot deserialize as [{}] an object of type {}".format(iter_type, type(attr))) + return [self.deserialize_data(a, iter_type) for a in attr] + + def deserialize_dict(self, attr, dict_type): + """Deserialize a dictionary. + + :param dict/list attr: Dictionary to be deserialized. Also accepts + a list of key, value pairs. + :param str dict_type: The object type of the items in the dictionary. + :rtype: dict + """ + if isinstance(attr, list): + return {x["key"]: self.deserialize_data(x["value"], dict_type) for x in attr} + + if isinstance(attr, ET.Element): + # Transform value into {"Key": "value"} + attr = {el.tag: el.text for el in attr} + return {k: self.deserialize_data(v, dict_type) for k, v in attr.items()} + + def deserialize_object(self, attr, **kwargs): + """Deserialize a generic object. + This will be handled as a dictionary. + + :param dict attr: Dictionary to be deserialized. + :rtype: dict + :raises: TypeError if non-builtin datatype encountered. + """ + if attr is None: + return None + if isinstance(attr, ET.Element): + # Do no recurse on XML, just return the tree as-is + return attr + if isinstance(attr, basestring): + return self.deserialize_basic(attr, "str") + obj_type = type(attr) + if obj_type in self.basic_types: + return self.deserialize_basic(attr, self.basic_types[obj_type]) + if obj_type is _long_type: + return self.deserialize_long(attr) + + if obj_type == dict: + deserialized = {} + for key, value in attr.items(): + try: + deserialized[key] = self.deserialize_object(value, **kwargs) + except ValueError: + deserialized[key] = None + return deserialized + + if obj_type == list: + deserialized = [] + for obj in attr: + try: + deserialized.append(self.deserialize_object(obj, **kwargs)) + except ValueError: + pass + return deserialized + + else: + error = "Cannot deserialize generic object with type: " + raise TypeError(error + str(obj_type)) + + def deserialize_basic(self, attr, data_type): + """Deserialize basic builtin data type from string. + Will attempt to convert to str, int, float and bool. + This function will also accept '1', '0', 'true' and 'false' as + valid bool values. + + :param str attr: response string to be deserialized. + :param str data_type: deserialization data type. + :rtype: str, int, float or bool + :raises: TypeError if string format is not valid. + """ + # If we're here, data is supposed to be a basic type. + # If it's still an XML node, take the text + if isinstance(attr, ET.Element): + attr = attr.text + if not attr: + if data_type == "str": + # None or '', node is empty string. + return "" + else: + # None or '', node with a strong type is None. + # Don't try to model "empty bool" or "empty int" + return None + + if data_type == "bool": + if attr in [True, False, 1, 0]: + return bool(attr) + elif isinstance(attr, basestring): + if attr.lower() in ["true", "1"]: + return True + elif attr.lower() in ["false", "0"]: + return False + raise TypeError("Invalid boolean value: {}".format(attr)) + + if data_type == "str": + return self.deserialize_unicode(attr) + return eval(data_type)(attr) # nosec + + @staticmethod + def deserialize_unicode(data): + """Preserve unicode objects in Python 2, otherwise return data + as a string. + + :param str data: response string to be deserialized. + :rtype: str or unicode + """ + # We might be here because we have an enum modeled as string, + # and we try to deserialize a partial dict with enum inside + if isinstance(data, Enum): + return data + + # Consider this is real string + try: + if isinstance(data, unicode): # type: ignore + return data + except NameError: + return str(data) + else: + return str(data) + + @staticmethod + def deserialize_enum(data, enum_obj): + """Deserialize string into enum object. + + If the string is not a valid enum value it will be returned as-is + and a warning will be logged. + + :param str data: Response string to be deserialized. If this value is + None or invalid it will be returned as-is. + :param Enum enum_obj: Enum object to deserialize to. + :rtype: Enum + """ + if isinstance(data, enum_obj) or data is None: + return data + if isinstance(data, Enum): + data = data.value + if isinstance(data, int): + # Workaround. We might consider remove it in the future. + try: + return list(enum_obj.__members__.values())[data] + except IndexError: + error = "{!r} is not a valid index for enum {!r}" + raise DeserializationError(error.format(data, enum_obj)) + try: + return enum_obj(str(data)) + except ValueError: + for enum_value in enum_obj: + if enum_value.value.lower() == str(data).lower(): + return enum_value + # We don't fail anymore for unknown value, we deserialize as a string + _LOGGER.warning("Deserializer is not able to find %s as valid enum in %s", data, enum_obj) + return Deserializer.deserialize_unicode(data) + + @staticmethod + def deserialize_bytearray(attr): + """Deserialize string into bytearray. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return bytearray(b64decode(attr)) # type: ignore + + @staticmethod + def deserialize_base64(attr): + """Deserialize base64 encoded string into string. + + :param str attr: response string to be deserialized. + :rtype: bytearray + :raises: TypeError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + padding = "=" * (3 - (len(attr) + 3) % 4) # type: ignore + attr = attr + padding # type: ignore + encoded = attr.replace("-", "+").replace("_", "/") + return b64decode(encoded) + + @staticmethod + def deserialize_decimal(attr): + """Deserialize string into Decimal object. + + :param str attr: response string to be deserialized. + :rtype: Decimal + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + return decimal.Decimal(str(attr)) # type: ignore + except decimal.DecimalException as err: + msg = "Invalid decimal {}".format(attr) + raise DeserializationError(msg) from err + + @staticmethod + def deserialize_long(attr): + """Deserialize string into long (Py2) or int (Py3). + + :param str attr: response string to be deserialized. + :rtype: long or int + :raises: ValueError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + return _long_type(attr) # type: ignore + + @staticmethod + def deserialize_duration(attr): + """Deserialize ISO-8601 formatted string into TimeDelta object. + + :param str attr: response string to be deserialized. + :rtype: TimeDelta + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + duration = isodate.parse_duration(attr) + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize duration object." + raise DeserializationError(msg) from err + else: + return duration + + @staticmethod + def deserialize_date(attr): + """Deserialize ISO-8601 formatted string into Date object. + + :param str attr: response string to be deserialized. + :rtype: Date + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + # This must NOT use defaultmonth/defaultday. Using None ensure this raises an exception. + return isodate.parse_date(attr, defaultmonth=0, defaultday=0) + + @staticmethod + def deserialize_time(attr): + """Deserialize ISO-8601 formatted string into time object. + + :param str attr: response string to be deserialized. + :rtype: datetime.time + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + if re.search(r"[^\W\d_]", attr, re.I + re.U): # type: ignore + raise DeserializationError("Date must have only digits and -. Received: %s" % attr) + return isodate.parse_time(attr) + + @staticmethod + def deserialize_rfc(attr): + """Deserialize RFC-1123 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + parsed_date = email.utils.parsedate_tz(attr) # type: ignore + date_obj = datetime.datetime( + *parsed_date[:6], tzinfo=_FixedOffset(datetime.timedelta(minutes=(parsed_date[9] or 0) / 60)) + ) + if not date_obj.tzinfo: + date_obj = date_obj.astimezone(tz=TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to rfc datetime object." + raise DeserializationError(msg) from err + else: + return date_obj + + @staticmethod + def deserialize_iso(attr): + """Deserialize ISO-8601 formatted string into Datetime object. + + :param str attr: response string to be deserialized. + :rtype: Datetime + :raises: DeserializationError if string format invalid. + """ + if isinstance(attr, ET.Element): + attr = attr.text + try: + attr = attr.upper() # type: ignore + match = Deserializer.valid_date.match(attr) + if not match: + raise ValueError("Invalid datetime string: " + attr) + + check_decimal = attr.split(".") + if len(check_decimal) > 1: + decimal_str = "" + for digit in check_decimal[1]: + if digit.isdigit(): + decimal_str += digit + else: + break + if len(decimal_str) > 6: + attr = attr.replace(decimal_str, decimal_str[0:6]) + + date_obj = isodate.parse_datetime(attr) + test_utc = date_obj.utctimetuple() + if test_utc.tm_year > 9999 or test_utc.tm_year < 1: + raise OverflowError("Hit max or min date") + except (ValueError, OverflowError, AttributeError) as err: + msg = "Cannot deserialize datetime object." + raise DeserializationError(msg) from err + else: + return date_obj + + @staticmethod + def deserialize_unix(attr): + """Serialize Datetime object into IntTime format. + This is represented as seconds. + + :param int attr: Object to be serialized. + :rtype: Datetime + :raises: DeserializationError if format invalid + """ + if isinstance(attr, ET.Element): + attr = int(attr.text) # type: ignore + try: + attr = int(attr) + date_obj = datetime.datetime.fromtimestamp(attr, TZ_UTC) + except ValueError as err: + msg = "Cannot deserialize to unix datetime object." + raise DeserializationError(msg) from err + else: + return date_obj diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_vendor.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_vendor.py new file mode 100644 index 00000000000..8598d2b7459 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_vendor.py @@ -0,0 +1,20 @@ +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from typing import List, cast + + +def _format_url_section(template, **kwargs): + components = template.split("/") + while components: + try: + return template.format(**kwargs) + except KeyError as key: + # Need the cast, as for some reasons "split" is typed as list[str | Any] + formatted_components = cast(List[str], template.split("/")) + components = [c for c in formatted_components if "{}".format(key.args[0]) not in c] + template = "/".join(components) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_version.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_version.py new file mode 100644 index 00000000000..f30401ec204 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/_version.py @@ -0,0 +1,9 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +VERSION = "2.2.0" diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/models/__init__.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/models/__init__.py new file mode 100644 index 00000000000..65301085fbc --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/models/__init__.py @@ -0,0 +1,65 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._models import BlobDetails +from ._models import CostEstimate +from ._models import ErrorData +from ._models import ItemDetails +from ._models import JobDetails +from ._models import JsonPatchDocument +from ._models import ProviderStatus +from ._models import QuantumComputingData +from ._models import Quota +from ._models import RestError +from ._models import SasUriResponse +from ._models import SessionDetails +from ._models import TargetStatus +from ._models import UsageEvent + +from ._enums import DimensionScope +from ._enums import ItemType +from ._enums import JobStatus +from ._enums import JobType +from ._enums import JsonPatchOperation +from ._enums import MeterPeriod +from ._enums import ProviderAvailability +from ._enums import SessionJobFailurePolicy +from ._enums import SessionStatus +from ._enums import TargetAvailability +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "BlobDetails", + "CostEstimate", + "ErrorData", + "ItemDetails", + "JobDetails", + "JsonPatchDocument", + "ProviderStatus", + "QuantumComputingData", + "Quota", + "RestError", + "SasUriResponse", + "SessionDetails", + "TargetStatus", + "UsageEvent", + "DimensionScope", + "ItemType", + "JobStatus", + "JobType", + "JsonPatchOperation", + "MeterPeriod", + "ProviderAvailability", + "SessionJobFailurePolicy", + "SessionStatus", + "TargetAvailability", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/models/_enums.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/models/_enums.py new file mode 100644 index 00000000000..2bd23c3f825 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/models/_enums.py @@ -0,0 +1,100 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from enum import Enum +from azure.core import CaseInsensitiveEnumMeta + + +class DimensionScope(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The scope at which the quota is applied.""" + + WORKSPACE = "Workspace" + SUBSCRIPTION = "Subscription" + + +class ItemType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of item.""" + + JOB = "Job" + """A program, problem, or application submitted for processing.""" + SESSION = "Session" + """A logical grouping of jobs.""" + + +class JobStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the job.""" + + WAITING = "Waiting" + EXECUTING = "Executing" + SUCCEEDED = "Succeeded" + FAILED = "Failed" + CANCELLED = "Cancelled" + + +class JobType(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The type of job.""" + + UNKNOWN = "Unknown" + QUANTUM_COMPUTING = "QuantumComputing" + OPTIMIZATION = "Optimization" + + +class JsonPatchOperation(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The operation to be performed.""" + + ADD = "add" + REMOVE = "remove" + REPLACE = "replace" + MOVE = "move" + COPY = "copy" + TEST = "test" + + +class MeterPeriod(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The time period in which the quota's underlying meter is accumulated. Based on calendar year. + 'None' is used for concurrent quotas. + """ + + NONE = "None" + MONTHLY = "Monthly" + + +class ProviderAvailability(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Provider availability.""" + + AVAILABLE = "Available" + DEGRADED = "Degraded" + UNAVAILABLE = "Unavailable" + + +class SessionJobFailurePolicy(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Policy controlling the behavior of the Session when a job in the session fails.""" + + ABORT = "Abort" + """New jobs submitted after a job fails will be rejected.""" + CONTINUE = "Continue" + """New jobs submitted after a job fails will be accepted.""" + + +class SessionStatus(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """The status of the session.""" + + WAITING = "Waiting" + EXECUTING = "Executing" + SUCCEEDED = "Succeeded" + FAILED = "Failed" + FAILURE_S_ = "Failure(s)" + TIMED_OUT = "TimedOut" + + +class TargetAvailability(str, Enum, metaclass=CaseInsensitiveEnumMeta): + """Target availability.""" + + AVAILABLE = "Available" + DEGRADED = "Degraded" + UNAVAILABLE = "Unavailable" diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/models/_models.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/models/_models.py new file mode 100644 index 00000000000..5579fb8e9e3 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/models/_models.py @@ -0,0 +1,1021 @@ +# coding=utf-8 +# pylint: disable=too-many-lines +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +import sys +from typing import Any, Dict, List, Optional, TYPE_CHECKING, Union + +from .. import _serialization + +if sys.version_info >= (3, 9): + from collections.abc import MutableMapping +else: + from typing import MutableMapping # type: ignore # pylint: disable=ungrouped-imports + +if TYPE_CHECKING: + # pylint: disable=unused-import,ungrouped-imports + from .. import models as _models +JSON = MutableMapping[str, Any] # pylint: disable=unsubscriptable-object + + +class BlobDetails(_serialization.Model): + """Blob details. + + All required parameters must be populated in order to send to server. + + :ivar container_name: The container name. Required. + :vartype container_name: str + :ivar blob_name: The blob name. + :vartype blob_name: str + """ + + _validation = { + "container_name": {"required": True}, + } + + _attribute_map = { + "container_name": {"key": "containerName", "type": "str"}, + "blob_name": {"key": "blobName", "type": "str"}, + } + + def __init__(self, *, container_name: str, blob_name: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword container_name: The container name. Required. + :paramtype container_name: str + :keyword blob_name: The blob name. + :paramtype blob_name: str + """ + super().__init__(**kwargs) + self.container_name = container_name + self.blob_name = blob_name + + +class CostEstimate(_serialization.Model): + """The job cost billed by the provider. The final cost on your bill might be slightly different + due to added taxes and currency conversion rates. + + :ivar currency_code: The currency code. + :vartype currency_code: str + :ivar events: List of usage events. + :vartype events: list[~azure.quantum._client.models.UsageEvent] + :ivar estimated_total: The estimated total. + :vartype estimated_total: float + """ + + _attribute_map = { + "currency_code": {"key": "currencyCode", "type": "str"}, + "events": {"key": "events", "type": "[UsageEvent]"}, + "estimated_total": {"key": "estimatedTotal", "type": "float"}, + } + + def __init__( + self, + *, + currency_code: Optional[str] = None, + events: Optional[List["_models.UsageEvent"]] = None, + estimated_total: Optional[float] = None, + **kwargs: Any + ) -> None: + """ + :keyword currency_code: The currency code. + :paramtype currency_code: str + :keyword events: List of usage events. + :paramtype events: list[~azure.quantum._client.models.UsageEvent] + :keyword estimated_total: The estimated total. + :paramtype estimated_total: float + """ + super().__init__(**kwargs) + self.currency_code = currency_code + self.events = events + self.estimated_total = estimated_total + + +class ErrorData(_serialization.Model): + """An error response from Azure. + + All required parameters must be populated in order to send to server. + + :ivar code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. Required. + :vartype code: str + :ivar message: A message describing the error, intended to be suitable for displaying in a user + interface. Required. + :vartype message: str + """ + + _validation = { + "code": {"required": True}, + "message": {"required": True}, + } + + _attribute_map = { + "code": {"key": "code", "type": "str"}, + "message": {"key": "message", "type": "str"}, + } + + def __init__(self, *, code: str, message: str, **kwargs: Any) -> None: + """ + :keyword code: An identifier for the error. Codes are invariant and are intended to be consumed + programmatically. Required. + :paramtype code: str + :keyword message: A message describing the error, intended to be suitable for displaying in a + user interface. Required. + :paramtype message: str + """ + super().__init__(**kwargs) + self.code = code + self.message = message + + +class ItemDetails(_serialization.Model): + """Item details. An item can be a job or a session. + + You probably want to use the sub-classes and not this class directly. Known sub-classes are: + JobDetails, SessionDetails + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The id of the item. Required. + :vartype id: str + :ivar name: The name of the item. It is not required for the name to be unique and it's only + used for display purposes. Required. + :vartype name: str + :ivar provider_id: The unique identifier for the provider. Required. + :vartype provider_id: str + :ivar target: The target identifier to run the job. Required. + :vartype target: str + :ivar item_type: The type of item. Required. Known values are: "Job" and "Session". + :vartype item_type: str or ~azure.quantum._client.models.ItemType + :ivar creation_time: The creation time of the item. + :vartype creation_time: ~datetime.datetime + :ivar begin_execution_time: The time when the item began execution. + :vartype begin_execution_time: ~datetime.datetime + :ivar end_execution_time: The time when the item finished execution. + :vartype end_execution_time: ~datetime.datetime + :ivar cost_estimate: The job cost billed by the provider. The final cost on your bill might be + slightly different due to added taxes and currency conversion rates. + :vartype cost_estimate: ~azure.quantum._client.models.CostEstimate + :ivar error_data: An error response from Azure. + :vartype error_data: ~azure.quantum._client.models.ErrorData + """ + + _validation = { + "id": {"required": True}, + "name": {"required": True}, + "provider_id": {"required": True}, + "target": {"required": True}, + "item_type": {"required": True}, + "creation_time": {"readonly": True}, + "begin_execution_time": {"readonly": True}, + "end_execution_time": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "provider_id": {"key": "providerId", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "item_type": {"key": "itemType", "type": "str"}, + "creation_time": {"key": "creationTime", "type": "iso-8601"}, + "begin_execution_time": {"key": "beginExecutionTime", "type": "iso-8601"}, + "end_execution_time": {"key": "endExecutionTime", "type": "iso-8601"}, + "cost_estimate": {"key": "costEstimate", "type": "CostEstimate"}, + "error_data": {"key": "errorData", "type": "ErrorData"}, + } + + _subtype_map = {"item_type": {"Job": "JobDetails", "Session": "SessionDetails"}} + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + name: str, + provider_id: str, + target: str, + cost_estimate: Optional["_models.CostEstimate"] = None, + error_data: Optional["_models.ErrorData"] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: The id of the item. Required. + :paramtype id: str + :keyword name: The name of the item. It is not required for the name to be unique and it's only + used for display purposes. Required. + :paramtype name: str + :keyword provider_id: The unique identifier for the provider. Required. + :paramtype provider_id: str + :keyword target: The target identifier to run the job. Required. + :paramtype target: str + :keyword cost_estimate: The job cost billed by the provider. The final cost on your bill might + be slightly different due to added taxes and currency conversion rates. + :paramtype cost_estimate: ~azure.quantum._client.models.CostEstimate + :keyword error_data: An error response from Azure. + :paramtype error_data: ~azure.quantum._client.models.ErrorData + """ + super().__init__(**kwargs) + self.id = id + self.name = name + self.provider_id = provider_id + self.target = target + self.item_type: Optional[str] = None + self.creation_time = None + self.begin_execution_time = None + self.end_execution_time = None + self.cost_estimate = cost_estimate + self.error_data = error_data + + +class ItemDetailsList(_serialization.Model): + """List of item details. + + All required parameters must be populated in order to send to server. + + :ivar value: Required. + :vartype value: list[~azure.quantum._client.models.ItemDetails] + :ivar next_link: Link to the next page of results. + :vartype next_link: str + """ + + _validation = { + "value": {"required": True}, + } + + _attribute_map = { + "value": {"key": "value", "type": "[ItemDetails]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__(self, *, value: List["_models.ItemDetails"], next_link: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword value: Required. + :paramtype value: list[~azure.quantum._client.models.ItemDetails] + :keyword next_link: Link to the next page of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class JobDetails(ItemDetails): # pylint: disable=too-many-instance-attributes + """Job details. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The id of the item. Required. + :vartype id: str + :ivar name: The name of the item. It is not required for the name to be unique and it's only + used for display purposes. Required. + :vartype name: str + :ivar provider_id: The unique identifier for the provider. Required. + :vartype provider_id: str + :ivar target: The target identifier to run the job. Required. + :vartype target: str + :ivar item_type: The type of item. Required. Known values are: "Job" and "Session". + :vartype item_type: str or ~azure.quantum._client.models.ItemType + :ivar creation_time: The creation time of the item. + :vartype creation_time: ~datetime.datetime + :ivar begin_execution_time: The time when the item began execution. + :vartype begin_execution_time: ~datetime.datetime + :ivar end_execution_time: The time when the item finished execution. + :vartype end_execution_time: ~datetime.datetime + :ivar cost_estimate: The job cost billed by the provider. The final cost on your bill might be + slightly different due to added taxes and currency conversion rates. + :vartype cost_estimate: ~azure.quantum._client.models.CostEstimate + :ivar error_data: An error response from Azure. + :vartype error_data: ~azure.quantum._client.models.ErrorData + :ivar job_type: The type of job. Known values are: "Unknown", "QuantumComputing", and + "Optimization". + :vartype job_type: str or ~azure.quantum._client.models.JobType + :ivar session_id: The ID of the session that the job is part of. + :vartype session_id: str + :ivar container_uri: The blob container SAS uri, the container is used to host job data. + Required. + :vartype container_uri: str + :ivar input_data_uri: The input blob SAS uri, if specified, it will override the default input + blob in the container. + :vartype input_data_uri: str + :ivar input_data_format: The format of the input data. Required. + :vartype input_data_format: str + :ivar input_params: The input parameters for the job. JSON object used by the target solver. It + is expected that the size of this object is small and only used to specify parameters for the + execution target, not the input data. + :vartype input_params: JSON + :ivar status: The status of the job. Known values are: "Waiting", "Executing", "Succeeded", + "Failed", and "Cancelled". + :vartype status: str or ~azure.quantum._client.models.JobStatus + :ivar metadata: The job metadata. Metadata provides client the ability to store client-specific + information. + :vartype metadata: dict[str, str] + :ivar output_data_uri: The output blob SAS uri. When a job finishes successfully, results will + be uploaded to this blob. + :vartype output_data_uri: str + :ivar output_data_format: The format of the output data. + :vartype output_data_format: str + :ivar cancellation_time: The time when a job was successfully cancelled. + :vartype cancellation_time: ~datetime.datetime + :ivar quantum_computing_data: Quantum computing data. + :vartype quantum_computing_data: ~azure.quantum._client.models.QuantumComputingData + :ivar tags: List of user-supplied tags associated with the job. + :vartype tags: list[str] + """ + + _validation = { + "id": {"required": True}, + "name": {"required": True}, + "provider_id": {"required": True}, + "target": {"required": True}, + "item_type": {"required": True}, + "creation_time": {"readonly": True}, + "begin_execution_time": {"readonly": True}, + "end_execution_time": {"readonly": True}, + "job_type": {"readonly": True}, + "container_uri": {"required": True}, + "input_data_format": {"required": True}, + "status": {"readonly": True}, + "cancellation_time": {"readonly": True}, + "quantum_computing_data": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "provider_id": {"key": "providerId", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "item_type": {"key": "itemType", "type": "str"}, + "creation_time": {"key": "creationTime", "type": "iso-8601"}, + "begin_execution_time": {"key": "beginExecutionTime", "type": "iso-8601"}, + "end_execution_time": {"key": "endExecutionTime", "type": "iso-8601"}, + "cost_estimate": {"key": "costEstimate", "type": "CostEstimate"}, + "error_data": {"key": "errorData", "type": "ErrorData"}, + "job_type": {"key": "jobType", "type": "str"}, + "session_id": {"key": "sessionId", "type": "str"}, + "container_uri": {"key": "containerUri", "type": "str"}, + "input_data_uri": {"key": "inputDataUri", "type": "str"}, + "input_data_format": {"key": "inputDataFormat", "type": "str"}, + "input_params": {"key": "inputParams", "type": "object"}, + "status": {"key": "status", "type": "str"}, + "metadata": {"key": "metadata", "type": "{str}"}, + "output_data_uri": {"key": "outputDataUri", "type": "str"}, + "output_data_format": {"key": "outputDataFormat", "type": "str"}, + "cancellation_time": {"key": "cancellationTime", "type": "iso-8601"}, + "quantum_computing_data": {"key": "quantumComputingData", "type": "QuantumComputingData"}, + "tags": {"key": "tags", "type": "[str]"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + name: str, + provider_id: str, + target: str, + container_uri: str, + input_data_format: str, + cost_estimate: Optional["_models.CostEstimate"] = None, + error_data: Optional["_models.ErrorData"] = None, + session_id: Optional[str] = None, + input_data_uri: Optional[str] = None, + input_params: Optional[JSON] = None, + metadata: Optional[Dict[str, str]] = None, + output_data_uri: Optional[str] = None, + output_data_format: Optional[str] = None, + tags: Optional[List[str]] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: The id of the item. Required. + :paramtype id: str + :keyword name: The name of the item. It is not required for the name to be unique and it's only + used for display purposes. Required. + :paramtype name: str + :keyword provider_id: The unique identifier for the provider. Required. + :paramtype provider_id: str + :keyword target: The target identifier to run the job. Required. + :paramtype target: str + :keyword cost_estimate: The job cost billed by the provider. The final cost on your bill might + be slightly different due to added taxes and currency conversion rates. + :paramtype cost_estimate: ~azure.quantum._client.models.CostEstimate + :keyword error_data: An error response from Azure. + :paramtype error_data: ~azure.quantum._client.models.ErrorData + :keyword session_id: The ID of the session that the job is part of. + :paramtype session_id: str + :keyword container_uri: The blob container SAS uri, the container is used to host job data. + Required. + :paramtype container_uri: str + :keyword input_data_uri: The input blob SAS uri, if specified, it will override the default + input blob in the container. + :paramtype input_data_uri: str + :keyword input_data_format: The format of the input data. Required. + :paramtype input_data_format: str + :keyword input_params: The input parameters for the job. JSON object used by the target solver. + It is expected that the size of this object is small and only used to specify parameters for + the execution target, not the input data. + :paramtype input_params: JSON + :keyword metadata: The job metadata. Metadata provides client the ability to store + client-specific information. + :paramtype metadata: dict[str, str] + :keyword output_data_uri: The output blob SAS uri. When a job finishes successfully, results + will be uploaded to this blob. + :paramtype output_data_uri: str + :keyword output_data_format: The format of the output data. + :paramtype output_data_format: str + :keyword tags: List of user-supplied tags associated with the job. + :paramtype tags: list[str] + """ + super().__init__( + id=id, + name=name, + provider_id=provider_id, + target=target, + cost_estimate=cost_estimate, + error_data=error_data, + **kwargs + ) + self.item_type: str = "Job" + self.job_type = None + self.session_id = session_id + self.container_uri = container_uri + self.input_data_uri = input_data_uri + self.input_data_format = input_data_format + self.input_params = input_params + self.status = None + self.metadata = metadata + self.output_data_uri = output_data_uri + self.output_data_format = output_data_format + self.cancellation_time = None + self.quantum_computing_data = None + self.tags = tags + + +class JobDetailsList(_serialization.Model): + """List of job details. + + :ivar value: + :vartype value: list[~azure.quantum._client.models.JobDetails] + :ivar next_link: Link to the next page of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[JobDetails]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.JobDetails"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: + :paramtype value: list[~azure.quantum._client.models.JobDetails] + :keyword next_link: Link to the next page of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class JsonPatchDocument(_serialization.Model): + """A JSONPatch document as defined by RFC 6902. + + All required parameters must be populated in order to send to server. + + :ivar op: The operation to be performed. Required. Known values are: "add", "remove", + "replace", "move", "copy", and "test". + :vartype op: str or ~azure.quantum._client.models.JsonPatchOperation + :ivar path: A JSON-Pointer. Required. + :vartype path: str + :ivar value: A value to be used in the operation on the path. + :vartype value: JSON + :ivar from_property: Optional field used in copy and move operations. + :vartype from_property: str + """ + + _validation = { + "op": {"required": True}, + "path": {"required": True}, + } + + _attribute_map = { + "op": {"key": "op", "type": "str"}, + "path": {"key": "path", "type": "str"}, + "value": {"key": "value", "type": "object"}, + "from_property": {"key": "from", "type": "str"}, + } + + def __init__( + self, + *, + op: Union[str, "_models.JsonPatchOperation"], + path: str, + value: Optional[JSON] = None, + from_property: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword op: The operation to be performed. Required. Known values are: "add", "remove", + "replace", "move", "copy", and "test". + :paramtype op: str or ~azure.quantum._client.models.JsonPatchOperation + :keyword path: A JSON-Pointer. Required. + :paramtype path: str + :keyword value: A value to be used in the operation on the path. + :paramtype value: JSON + :keyword from_property: Optional field used in copy and move operations. + :paramtype from_property: str + """ + super().__init__(**kwargs) + self.op = op + self.path = path + self.value = value + self.from_property = from_property + + +class ProviderStatus(_serialization.Model): + """Providers status. + + :ivar id: Provider id. + :vartype id: str + :ivar current_availability: Provider availability. Known values are: "Available", "Degraded", + and "Unavailable". + :vartype current_availability: str or ~azure.quantum._client.models.ProviderAvailability + :ivar targets: + :vartype targets: list[~azure.quantum._client.models.TargetStatus] + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "current_availability": {"key": "currentAvailability", "type": "str"}, + "targets": {"key": "targets", "type": "[TargetStatus]"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + current_availability: Optional[Union[str, "_models.ProviderAvailability"]] = None, + targets: Optional[List["_models.TargetStatus"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Provider id. + :paramtype id: str + :keyword current_availability: Provider availability. Known values are: "Available", + "Degraded", and "Unavailable". + :paramtype current_availability: str or ~azure.quantum._client.models.ProviderAvailability + :keyword targets: + :paramtype targets: list[~azure.quantum._client.models.TargetStatus] + """ + super().__init__(**kwargs) + self.id = id + self.current_availability = current_availability + self.targets = targets + + +class ProviderStatusList(_serialization.Model): + """Providers status. + + :ivar value: + :vartype value: list[~azure.quantum._client.models.ProviderStatus] + :ivar next_link: Link to the next page of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[ProviderStatus]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.ProviderStatus"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: + :paramtype value: list[~azure.quantum._client.models.ProviderStatus] + :keyword next_link: Link to the next page of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class QuantumComputingData(_serialization.Model): + """Quantum computing data. + + :ivar count: The number of quantum computing items in the job. + :vartype count: int + """ + + _attribute_map = { + "count": {"key": "count", "type": "int"}, + } + + def __init__(self, *, count: Optional[int] = None, **kwargs: Any) -> None: + """ + :keyword count: The number of quantum computing items in the job. + :paramtype count: int + """ + super().__init__(**kwargs) + self.count = count + + +class Quota(_serialization.Model): + """Quota information. + + :ivar dimension: The name of the dimension associated with the quota. + :vartype dimension: str + :ivar scope: The scope at which the quota is applied. Known values are: "Workspace" and + "Subscription". + :vartype scope: str or ~azure.quantum._client.models.DimensionScope + :ivar provider_id: The unique identifier for the provider. + :vartype provider_id: str + :ivar utilization: The amount of the usage that has been applied for the current period. + :vartype utilization: float + :ivar holds: The amount of the usage that has been reserved but not applied for the current + period. + :vartype holds: float + :ivar limit: The maximum amount of usage allowed for the current period. + :vartype limit: float + :ivar period: The time period in which the quota's underlying meter is accumulated. Based on + calendar year. 'None' is used for concurrent quotas. Known values are: "None" and "Monthly". + :vartype period: str or ~azure.quantum._client.models.MeterPeriod + """ + + _attribute_map = { + "dimension": {"key": "dimension", "type": "str"}, + "scope": {"key": "scope", "type": "str"}, + "provider_id": {"key": "providerId", "type": "str"}, + "utilization": {"key": "utilization", "type": "float"}, + "holds": {"key": "holds", "type": "float"}, + "limit": {"key": "limit", "type": "float"}, + "period": {"key": "period", "type": "str"}, + } + + def __init__( + self, + *, + dimension: Optional[str] = None, + scope: Optional[Union[str, "_models.DimensionScope"]] = None, + provider_id: Optional[str] = None, + utilization: Optional[float] = None, + holds: Optional[float] = None, + limit: Optional[float] = None, + period: Optional[Union[str, "_models.MeterPeriod"]] = None, + **kwargs: Any + ) -> None: + """ + :keyword dimension: The name of the dimension associated with the quota. + :paramtype dimension: str + :keyword scope: The scope at which the quota is applied. Known values are: "Workspace" and + "Subscription". + :paramtype scope: str or ~azure.quantum._client.models.DimensionScope + :keyword provider_id: The unique identifier for the provider. + :paramtype provider_id: str + :keyword utilization: The amount of the usage that has been applied for the current period. + :paramtype utilization: float + :keyword holds: The amount of the usage that has been reserved but not applied for the current + period. + :paramtype holds: float + :keyword limit: The maximum amount of usage allowed for the current period. + :paramtype limit: float + :keyword period: The time period in which the quota's underlying meter is accumulated. Based on + calendar year. 'None' is used for concurrent quotas. Known values are: "None" and "Monthly". + :paramtype period: str or ~azure.quantum._client.models.MeterPeriod + """ + super().__init__(**kwargs) + self.dimension = dimension + self.scope = scope + self.provider_id = provider_id + self.utilization = utilization + self.holds = holds + self.limit = limit + self.period = period + + +class QuotaList(_serialization.Model): + """List of quotas. + + :ivar value: + :vartype value: list[~azure.quantum._client.models.Quota] + :ivar next_link: Link to the next page of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[Quota]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.Quota"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: + :paramtype value: list[~azure.quantum._client.models.Quota] + :keyword next_link: Link to the next page of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class RestError(_serialization.Model): + """Error information returned by the API. + + All required parameters must be populated in order to send to server. + + :ivar error: An error response from Azure. Required. + :vartype error: ~azure.quantum._client.models.ErrorData + """ + + _validation = { + "error": {"required": True}, + } + + _attribute_map = { + "error": {"key": "error", "type": "ErrorData"}, + } + + def __init__(self, *, error: "_models.ErrorData", **kwargs: Any) -> None: + """ + :keyword error: An error response from Azure. Required. + :paramtype error: ~azure.quantum._client.models.ErrorData + """ + super().__init__(**kwargs) + self.error = error + + +class SasUriResponse(_serialization.Model): + """Get SAS URL operation response. + + :ivar sas_uri: A URL with a SAS token to upload a blob for execution in the given workspace. + :vartype sas_uri: str + """ + + _attribute_map = { + "sas_uri": {"key": "sasUri", "type": "str"}, + } + + def __init__(self, *, sas_uri: Optional[str] = None, **kwargs: Any) -> None: + """ + :keyword sas_uri: A URL with a SAS token to upload a blob for execution in the given workspace. + :paramtype sas_uri: str + """ + super().__init__(**kwargs) + self.sas_uri = sas_uri + + +class SessionDetails(ItemDetails): # pylint: disable=too-many-instance-attributes + """Session details. + + Variables are only populated by the server, and will be ignored when sending a request. + + All required parameters must be populated in order to send to server. + + :ivar id: The id of the item. Required. + :vartype id: str + :ivar name: The name of the item. It is not required for the name to be unique and it's only + used for display purposes. Required. + :vartype name: str + :ivar provider_id: The unique identifier for the provider. Required. + :vartype provider_id: str + :ivar target: The target identifier to run the job. Required. + :vartype target: str + :ivar item_type: The type of item. Required. Known values are: "Job" and "Session". + :vartype item_type: str or ~azure.quantum._client.models.ItemType + :ivar creation_time: The creation time of the item. + :vartype creation_time: ~datetime.datetime + :ivar begin_execution_time: The time when the item began execution. + :vartype begin_execution_time: ~datetime.datetime + :ivar end_execution_time: The time when the item finished execution. + :vartype end_execution_time: ~datetime.datetime + :ivar cost_estimate: The job cost billed by the provider. The final cost on your bill might be + slightly different due to added taxes and currency conversion rates. + :vartype cost_estimate: ~azure.quantum._client.models.CostEstimate + :ivar error_data: An error response from Azure. + :vartype error_data: ~azure.quantum._client.models.ErrorData + :ivar job_failure_policy: Policy controlling the behavior of the Session when a job in the + session fails. Known values are: "Abort" and "Continue". + :vartype job_failure_policy: str or ~azure.quantum._client.models.SessionJobFailurePolicy + :ivar status: The status of the session. Known values are: "Waiting", "Executing", "Succeeded", + "Failed", "Failure(s)", and "TimedOut". + :vartype status: str or ~azure.quantum._client.models.SessionStatus + """ + + _validation = { + "id": {"required": True}, + "name": {"required": True}, + "provider_id": {"required": True}, + "target": {"required": True}, + "item_type": {"required": True}, + "creation_time": {"readonly": True}, + "begin_execution_time": {"readonly": True}, + "end_execution_time": {"readonly": True}, + "status": {"readonly": True}, + } + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "name": {"key": "name", "type": "str"}, + "provider_id": {"key": "providerId", "type": "str"}, + "target": {"key": "target", "type": "str"}, + "item_type": {"key": "itemType", "type": "str"}, + "creation_time": {"key": "creationTime", "type": "iso-8601"}, + "begin_execution_time": {"key": "beginExecutionTime", "type": "iso-8601"}, + "end_execution_time": {"key": "endExecutionTime", "type": "iso-8601"}, + "cost_estimate": {"key": "costEstimate", "type": "CostEstimate"}, + "error_data": {"key": "errorData", "type": "ErrorData"}, + "job_failure_policy": {"key": "jobFailurePolicy", "type": "str"}, + "status": {"key": "status", "type": "str"}, + } + + def __init__( + self, + *, + id: str, # pylint: disable=redefined-builtin + name: str, + provider_id: str, + target: str, + cost_estimate: Optional["_models.CostEstimate"] = None, + error_data: Optional["_models.ErrorData"] = None, + job_failure_policy: Union[str, "_models.SessionJobFailurePolicy"] = "Abort", + **kwargs: Any + ) -> None: + """ + :keyword id: The id of the item. Required. + :paramtype id: str + :keyword name: The name of the item. It is not required for the name to be unique and it's only + used for display purposes. Required. + :paramtype name: str + :keyword provider_id: The unique identifier for the provider. Required. + :paramtype provider_id: str + :keyword target: The target identifier to run the job. Required. + :paramtype target: str + :keyword cost_estimate: The job cost billed by the provider. The final cost on your bill might + be slightly different due to added taxes and currency conversion rates. + :paramtype cost_estimate: ~azure.quantum._client.models.CostEstimate + :keyword error_data: An error response from Azure. + :paramtype error_data: ~azure.quantum._client.models.ErrorData + :keyword job_failure_policy: Policy controlling the behavior of the Session when a job in the + session fails. Known values are: "Abort" and "Continue". + :paramtype job_failure_policy: str or ~azure.quantum._client.models.SessionJobFailurePolicy + """ + super().__init__( + id=id, + name=name, + provider_id=provider_id, + target=target, + cost_estimate=cost_estimate, + error_data=error_data, + **kwargs + ) + self.item_type: str = "Session" + self.job_failure_policy = job_failure_policy + self.status = None + + +class SessionDetailsList(_serialization.Model): + """List of session details. + + :ivar value: + :vartype value: list[~azure.quantum._client.models.SessionDetails] + :ivar next_link: Link to the next page of results. + :vartype next_link: str + """ + + _attribute_map = { + "value": {"key": "value", "type": "[SessionDetails]"}, + "next_link": {"key": "nextLink", "type": "str"}, + } + + def __init__( + self, *, value: Optional[List["_models.SessionDetails"]] = None, next_link: Optional[str] = None, **kwargs: Any + ) -> None: + """ + :keyword value: + :paramtype value: list[~azure.quantum._client.models.SessionDetails] + :keyword next_link: Link to the next page of results. + :paramtype next_link: str + """ + super().__init__(**kwargs) + self.value = value + self.next_link = next_link + + +class TargetStatus(_serialization.Model): + """Target status. + + :ivar id: Target id. + :vartype id: str + :ivar current_availability: Target availability. Known values are: "Available", "Degraded", and + "Unavailable". + :vartype current_availability: str or ~azure.quantum._client.models.TargetAvailability + :ivar average_queue_time: Average queue time in seconds. + :vartype average_queue_time: int + :ivar status_page: A page with detailed status of the provider. + :vartype status_page: str + """ + + _attribute_map = { + "id": {"key": "id", "type": "str"}, + "current_availability": {"key": "currentAvailability", "type": "str"}, + "average_queue_time": {"key": "averageQueueTime", "type": "int"}, + "status_page": {"key": "statusPage", "type": "str"}, + } + + def __init__( + self, + *, + id: Optional[str] = None, # pylint: disable=redefined-builtin + current_availability: Optional[Union[str, "_models.TargetAvailability"]] = None, + average_queue_time: Optional[int] = None, + status_page: Optional[str] = None, + **kwargs: Any + ) -> None: + """ + :keyword id: Target id. + :paramtype id: str + :keyword current_availability: Target availability. Known values are: "Available", "Degraded", + and "Unavailable". + :paramtype current_availability: str or ~azure.quantum._client.models.TargetAvailability + :keyword average_queue_time: Average queue time in seconds. + :paramtype average_queue_time: int + :keyword status_page: A page with detailed status of the provider. + :paramtype status_page: str + """ + super().__init__(**kwargs) + self.id = id + self.current_availability = current_availability + self.average_queue_time = average_queue_time + self.status_page = status_page + + +class UsageEvent(_serialization.Model): + """Usage event details. + + :ivar dimension_id: The dimension id. + :vartype dimension_id: str + :ivar dimension_name: The dimension name. + :vartype dimension_name: str + :ivar measure_unit: The unit of measure. + :vartype measure_unit: str + :ivar amount_billed: The amount billed. + :vartype amount_billed: float + :ivar amount_consumed: The amount consumed. + :vartype amount_consumed: float + :ivar unit_price: The unit price. + :vartype unit_price: float + """ + + _attribute_map = { + "dimension_id": {"key": "dimensionId", "type": "str"}, + "dimension_name": {"key": "dimensionName", "type": "str"}, + "measure_unit": {"key": "measureUnit", "type": "str"}, + "amount_billed": {"key": "amountBilled", "type": "float"}, + "amount_consumed": {"key": "amountConsumed", "type": "float"}, + "unit_price": {"key": "unitPrice", "type": "float"}, + } + + def __init__( + self, + *, + dimension_id: Optional[str] = None, + dimension_name: Optional[str] = None, + measure_unit: Optional[str] = None, + amount_billed: Optional[float] = None, + amount_consumed: Optional[float] = None, + unit_price: Optional[float] = None, + **kwargs: Any + ) -> None: + """ + :keyword dimension_id: The dimension id. + :paramtype dimension_id: str + :keyword dimension_name: The dimension name. + :paramtype dimension_name: str + :keyword measure_unit: The unit of measure. + :paramtype measure_unit: str + :keyword amount_billed: The amount billed. + :paramtype amount_billed: float + :keyword amount_consumed: The amount consumed. + :paramtype amount_consumed: float + :keyword unit_price: The unit price. + :paramtype unit_price: float + """ + super().__init__(**kwargs) + self.dimension_id = dimension_id + self.dimension_name = dimension_name + self.measure_unit = measure_unit + self.amount_billed = amount_billed + self.amount_consumed = amount_consumed + self.unit_price = unit_price diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/models/_patch.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/models/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/models/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/operations/__init__.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/operations/__init__.py new file mode 100644 index 00000000000..6ee87de11fa --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/operations/__init__.py @@ -0,0 +1,29 @@ +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- + +from ._operations import JobsOperations +from ._operations import ProvidersOperations +from ._operations import StorageOperations +from ._operations import QuotasOperations +from ._operations import SessionsOperations +from ._operations import TopLevelItemsOperations + +from ._patch import __all__ as _patch_all +from ._patch import * # pylint: disable=unused-wildcard-import +from ._patch import patch_sdk as _patch_sdk + +__all__ = [ + "JobsOperations", + "ProvidersOperations", + "StorageOperations", + "QuotasOperations", + "SessionsOperations", + "TopLevelItemsOperations", +] +__all__.extend([p for p in _patch_all if p not in __all__]) +_patch_sdk() diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/operations/_operations.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/operations/_operations.py new file mode 100644 index 00000000000..cf4a97efc9e --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/operations/_operations.py @@ -0,0 +1,1866 @@ +# pylint: disable=too-many-lines,too-many-statements +# coding=utf-8 +# -------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for license information. +# Code generated by Microsoft (R) AutoRest Code Generator. +# Changes may cause incorrect behavior and will be lost if the code is regenerated. +# -------------------------------------------------------------------------- +from io import IOBase +from typing import Any, Callable, Dict, IO, Iterable, List, Optional, TypeVar, Union, overload +import urllib.parse + +from azure.core.exceptions import ( + ClientAuthenticationError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError, + ResourceNotModifiedError, + map_error, +) +from azure.core.paging import ItemPaged +from azure.core.pipeline import PipelineResponse +from azure.core.rest import HttpRequest, HttpResponse +from azure.core.tracing.decorator import distributed_trace +from azure.core.utils import case_insensitive_dict + +from .. import models as _models +from .._serialization import Serializer + +T = TypeVar("T") +ClsType = Optional[Callable[[PipelineResponse[HttpRequest, HttpResponse], T, Dict[str, Any]], Any]] + +_SERIALIZER = Serializer() +_SERIALIZER.client_side_validation = False + + +def build_jobs_list_request( + subscription_id: str, resource_group_name: str, workspace_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-13-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/jobs" # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jobs_get_request( + job_id: str, subscription_id: str, resource_group_name: str, workspace_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-13-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/jobs/{jobId}" # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str"), + "jobId": _SERIALIZER.url( + "job_id", + job_id, + "str", + max_length=36, + pattern=r"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jobs_create_request( + job_id: str, subscription_id: str, resource_group_name: str, workspace_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-13-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/jobs/{jobId}" # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str"), + "jobId": _SERIALIZER.url( + "job_id", + job_id, + "str", + max_length=36, + pattern=r"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jobs_cancel_request( + job_id: str, subscription_id: str, resource_group_name: str, workspace_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-13-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/jobs/{jobId}" # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str"), + "jobId": _SERIALIZER.url( + "job_id", + job_id, + "str", + max_length=36, + pattern=r"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="DELETE", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_jobs_patch_request( + job_id: str, subscription_id: str, resource_group_name: str, workspace_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-13-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/jobs/{jobId}" # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str"), + "jobId": _SERIALIZER.url( + "job_id", + job_id, + "str", + max_length=36, + pattern=r"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PATCH", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_providers_get_status_request( + subscription_id: str, resource_group_name: str, workspace_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-13-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/providerStatus" # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_storage_sas_uri_request( + subscription_id: str, resource_group_name: str, workspace_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-13-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/storage/sasUri" # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_quotas_list_request( + subscription_id: str, resource_group_name: str, workspace_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-13-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/quotas" # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_sessions_list_request( + subscription_id: str, resource_group_name: str, workspace_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-13-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/sessions" # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_sessions_get_request( + session_id: str, subscription_id: str, resource_group_name: str, workspace_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-13-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/sessions/{sessionId}" # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str"), + "sessionId": _SERIALIZER.url( + "session_id", + session_id, + "str", + max_length=36, + pattern=r"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_sessions_open_request( + session_id: str, subscription_id: str, resource_group_name: str, workspace_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-13-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/sessions/{sessionId}" # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str"), + "sessionId": _SERIALIZER.url( + "session_id", + session_id, + "str", + max_length=36, + pattern=r"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + if content_type is not None: + _headers["Content-Type"] = _SERIALIZER.header("content_type", content_type, "str") + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="PUT", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_sessions_close_request( + session_id: str, subscription_id: str, resource_group_name: str, workspace_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-13-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/sessions/{sessionId}:close" # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str"), + "sessionId": _SERIALIZER.url( + "session_id", + session_id, + "str", + max_length=36, + pattern=r"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="POST", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_sessions_jobs_list_request( + session_id: str, subscription_id: str, resource_group_name: str, workspace_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-13-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/sessions/{sessionId}/jobs" # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str"), + "sessionId": _SERIALIZER.url( + "session_id", + session_id, + "str", + max_length=36, + pattern=r"^[a-fA-F0-9]{8}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{4}-[a-fA-F0-9]{12}$", + ), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +def build_top_level_items_list_request( + subscription_id: str, resource_group_name: str, workspace_name: str, **kwargs: Any +) -> HttpRequest: + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = case_insensitive_dict(kwargs.pop("params", {}) or {}) + + api_version: str = kwargs.pop("api_version", _params.pop("api-version", "2023-11-13-preview")) + accept = _headers.pop("Accept", "application/json") + + # Construct URL + _url = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Quantum/workspaces/{workspaceName}/topLevelItems" # pylint: disable=line-too-long + path_format_arguments = { + "subscriptionId": _SERIALIZER.url("subscription_id", subscription_id, "str"), + "resourceGroupName": _SERIALIZER.url("resource_group_name", resource_group_name, "str"), + "workspaceName": _SERIALIZER.url("workspace_name", workspace_name, "str"), + } + + _url: str = _url.format(**path_format_arguments) # type: ignore + + # Construct parameters + _params["api-version"] = _SERIALIZER.query("api_version", api_version, "str") + + # Construct headers + _headers["Accept"] = _SERIALIZER.header("accept", accept, "str") + + return HttpRequest(method="GET", url=_url, params=_params, headers=_headers, **kwargs) + + +class JobsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.quantum._client.QuantumClient`'s + :attr:`jobs` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.JobDetails"]: + """List jobs. + + :return: An iterator like instance of JobDetails + :rtype: ~azure.core.paging.ItemPaged[~azure.quantum._client.models.JobDetails] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models._models.JobDetailsList] = kwargs.pop("cls", None) # pylint: disable=protected-access + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_jobs_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=self._config.resource_group_name, + workspace_name=self._config.workspace_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize( + _models._models.JobDetailsList, pipeline_response # pylint: disable=protected-access + ) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.RestError, pipeline_response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get(self, job_id: str, **kwargs: Any) -> _models.JobDetails: + """Get job by id. + + :param job_id: Id of the job. Required. + :type job_id: str + :return: JobDetails + :rtype: ~azure.quantum._client.models.JobDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.JobDetails] = kwargs.pop("cls", None) + + _request = build_jobs_get_request( + job_id=job_id, + subscription_id=self._config.subscription_id, + resource_group_name=self._config.resource_group_name, + workspace_name=self._config.workspace_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.RestError, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("JobDetails", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def create( + self, job_id: str, job: _models.JobDetails, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.JobDetails: + """Create a job. + + :param job_id: Id of the job. Required. + :type job_id: str + :param job: The complete metadata of the job to submit. Required. + :type job: ~azure.quantum._client.models.JobDetails + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: JobDetails + :rtype: ~azure.quantum._client.models.JobDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def create( + self, job_id: str, job: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.JobDetails: + """Create a job. + + :param job_id: Id of the job. Required. + :type job_id: str + :param job: The complete metadata of the job to submit. Required. + :type job: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: JobDetails + :rtype: ~azure.quantum._client.models.JobDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def create(self, job_id: str, job: Union[_models.JobDetails, IO[bytes]], **kwargs: Any) -> _models.JobDetails: + """Create a job. + + :param job_id: Id of the job. Required. + :type job_id: str + :param job: The complete metadata of the job to submit. Is either a JobDetails type or a + IO[bytes] type. Required. + :type job: ~azure.quantum._client.models.JobDetails or IO[bytes] + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :return: JobDetails + :rtype: ~azure.quantum._client.models.JobDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.JobDetails] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(job, (IOBase, bytes)): + _content = job + else: + _json = self._serialize.body(job, "JobDetails") + + _request = build_jobs_create_request( + job_id=job_id, + subscription_id=self._config.subscription_id, + resource_group_name=self._config.resource_group_name, + workspace_name=self._config.workspace_name, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.RestError, pipeline_response) + raise HttpResponseError(response=response, model=error) + + if response.status_code == 200: + deserialized = self._deserialize("JobDetails", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("JobDetails", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def cancel(self, job_id: str, **kwargs: Any) -> None: # pylint: disable=inconsistent-return-statements + """Cancel a job. + + :param job_id: Id of the job. Required. + :type job_id: str + :return: None + :rtype: None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[None] = kwargs.pop("cls", None) + + _request = build_jobs_cancel_request( + job_id=job_id, + subscription_id=self._config.subscription_id, + resource_group_name=self._config.resource_group_name, + workspace_name=self._config.workspace_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [204]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.RestError, pipeline_response) + raise HttpResponseError(response=response, model=error) + + if cls: + return cls(pipeline_response, None, {}) # type: ignore + + @overload + def patch( + self, + job_id: str, + patch_job: List[_models.JsonPatchDocument], + *, + content_type: str = "application/json", + **kwargs: Any + ) -> Optional[_models.JobDetails]: + """Patch a job. + + :param job_id: Id of the job. Required. + :type job_id: str + :param patch_job: The json patch document containing the patch operations. Required. + :type patch_job: list[~azure.quantum._client.models.JsonPatchDocument] + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: JobDetails or None + :rtype: ~azure.quantum._client.models.JobDetails or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def patch( + self, job_id: str, patch_job: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> Optional[_models.JobDetails]: + """Patch a job. + + :param job_id: Id of the job. Required. + :type job_id: str + :param patch_job: The json patch document containing the patch operations. Required. + :type patch_job: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: JobDetails or None + :rtype: ~azure.quantum._client.models.JobDetails or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def patch( + self, job_id: str, patch_job: Union[List[_models.JsonPatchDocument], IO[bytes]], **kwargs: Any + ) -> Optional[_models.JobDetails]: + """Patch a job. + + :param job_id: Id of the job. Required. + :type job_id: str + :param patch_job: The json patch document containing the patch operations. Is either a + [JsonPatchDocument] type or a IO[bytes] type. Required. + :type patch_job: list[~azure.quantum._client.models.JsonPatchDocument] or IO[bytes] + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :return: JobDetails or None + :rtype: ~azure.quantum._client.models.JobDetails or None + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[Optional[_models.JobDetails]] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(patch_job, (IOBase, bytes)): + _content = patch_job + else: + _json = self._serialize.body(patch_job, "[JsonPatchDocument]") + + _request = build_jobs_patch_request( + job_id=job_id, + subscription_id=self._config.subscription_id, + resource_group_name=self._config.resource_group_name, + workspace_name=self._config.workspace_name, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 204]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.RestError, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = None + if response.status_code == 200: + deserialized = self._deserialize("JobDetails", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class ProvidersOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.quantum._client.QuantumClient`'s + :attr:`providers` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def get_status(self, **kwargs: Any) -> Iterable["_models.ProviderStatus"]: + """Get provider status. + + :return: An iterator like instance of ProviderStatus + :rtype: ~azure.core.paging.ItemPaged[~azure.quantum._client.models.ProviderStatus] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models._models.ProviderStatusList] = kwargs.pop("cls", None) # pylint: disable=protected-access + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_providers_get_status_request( + subscription_id=self._config.subscription_id, + resource_group_name=self._config.resource_group_name, + workspace_name=self._config.workspace_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize( + _models._models.ProviderStatusList, pipeline_response # pylint: disable=protected-access + ) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.RestError, pipeline_response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class StorageOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.quantum._client.QuantumClient`'s + :attr:`storage` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @overload + def sas_uri( + self, blob_details: _models.BlobDetails, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.SasUriResponse: + """Gets a URL with SAS token for a container/blob in the storage account associated with the + workspace. The SAS URL can be used to upload job input and/or download job output. + + :param blob_details: The details (name and container) of the blob to store or download data. + Required. + :type blob_details: ~azure.quantum._client.models.BlobDetails + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SasUriResponse + :rtype: ~azure.quantum._client.models.SasUriResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def sas_uri( + self, blob_details: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.SasUriResponse: + """Gets a URL with SAS token for a container/blob in the storage account associated with the + workspace. The SAS URL can be used to upload job input and/or download job output. + + :param blob_details: The details (name and container) of the blob to store or download data. + Required. + :type blob_details: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SasUriResponse + :rtype: ~azure.quantum._client.models.SasUriResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def sas_uri(self, blob_details: Union[_models.BlobDetails, IO[bytes]], **kwargs: Any) -> _models.SasUriResponse: + """Gets a URL with SAS token for a container/blob in the storage account associated with the + workspace. The SAS URL can be used to upload job input and/or download job output. + + :param blob_details: The details (name and container) of the blob to store or download data. Is + either a BlobDetails type or a IO[bytes] type. Required. + :type blob_details: ~azure.quantum._client.models.BlobDetails or IO[bytes] + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :return: SasUriResponse + :rtype: ~azure.quantum._client.models.SasUriResponse + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SasUriResponse] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(blob_details, (IOBase, bytes)): + _content = blob_details + else: + _json = self._serialize.body(blob_details, "BlobDetails") + + _request = build_storage_sas_uri_request( + subscription_id=self._config.subscription_id, + resource_group_name=self._config.resource_group_name, + workspace_name=self._config.workspace_name, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.RestError, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("SasUriResponse", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + +class QuotasOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.quantum._client.QuantumClient`'s + :attr:`quotas` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.Quota"]: + """List quotas for the given workspace. + + :return: An iterator like instance of Quota + :rtype: ~azure.core.paging.ItemPaged[~azure.quantum._client.models.Quota] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models._models.QuotaList] = kwargs.pop("cls", None) # pylint: disable=protected-access + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_quotas_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=self._config.resource_group_name, + workspace_name=self._config.workspace_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize( + _models._models.QuotaList, pipeline_response # pylint: disable=protected-access + ) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.RestError, pipeline_response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class SessionsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.quantum._client.QuantumClient`'s + :attr:`sessions` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.SessionDetails"]: + """List sessions. + + :return: An iterator like instance of SessionDetails + :rtype: ~azure.core.paging.ItemPaged[~azure.quantum._client.models.SessionDetails] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models._models.SessionDetailsList] = kwargs.pop("cls", None) # pylint: disable=protected-access + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_sessions_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=self._config.resource_group_name, + workspace_name=self._config.workspace_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize( + _models._models.SessionDetailsList, pipeline_response # pylint: disable=protected-access + ) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.RestError, pipeline_response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + @distributed_trace + def get(self, session_id: str, **kwargs: Any) -> _models.SessionDetails: + """Get session by id. + + :param session_id: Id of the session. Required. + :type session_id: str + :return: SessionDetails + :rtype: ~azure.quantum._client.models.SessionDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SessionDetails] = kwargs.pop("cls", None) + + _request = build_sessions_get_request( + session_id=session_id, + subscription_id=self._config.subscription_id, + resource_group_name=self._config.resource_group_name, + workspace_name=self._config.workspace_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.RestError, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("SessionDetails", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @overload + def open( + self, session_id: str, session: _models.SessionDetails, *, content_type: str = "application/json", **kwargs: Any + ) -> _models.SessionDetails: + """Open a session. + + :param session_id: Id of the session. Required. + :type session_id: str + :param session: The complete metadata of the session to be opened. Required. + :type session: ~azure.quantum._client.models.SessionDetails + :keyword content_type: Body Parameter content-type. Content type parameter for JSON body. + Default value is "application/json". + :paramtype content_type: str + :return: SessionDetails + :rtype: ~azure.quantum._client.models.SessionDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @overload + def open( + self, session_id: str, session: IO[bytes], *, content_type: str = "application/json", **kwargs: Any + ) -> _models.SessionDetails: + """Open a session. + + :param session_id: Id of the session. Required. + :type session_id: str + :param session: The complete metadata of the session to be opened. Required. + :type session: IO[bytes] + :keyword content_type: Body Parameter content-type. Content type parameter for binary body. + Default value is "application/json". + :paramtype content_type: str + :return: SessionDetails + :rtype: ~azure.quantum._client.models.SessionDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + + @distributed_trace + def open( + self, session_id: str, session: Union[_models.SessionDetails, IO[bytes]], **kwargs: Any + ) -> _models.SessionDetails: + """Open a session. + + :param session_id: Id of the session. Required. + :type session_id: str + :param session: The complete metadata of the session to be opened. Is either a SessionDetails + type or a IO[bytes] type. Required. + :type session: ~azure.quantum._client.models.SessionDetails or IO[bytes] + :keyword content_type: Body Parameter content-type. Known values are: 'application/json'. + Default value is None. + :paramtype content_type: str + :return: SessionDetails + :rtype: ~azure.quantum._client.models.SessionDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = case_insensitive_dict(kwargs.pop("headers", {}) or {}) + _params = kwargs.pop("params", {}) or {} + + content_type: Optional[str] = kwargs.pop("content_type", _headers.pop("Content-Type", None)) + cls: ClsType[_models.SessionDetails] = kwargs.pop("cls", None) + + content_type = content_type or "application/json" + _json = None + _content = None + if isinstance(session, (IOBase, bytes)): + _content = session + else: + _json = self._serialize.body(session, "SessionDetails") + + _request = build_sessions_open_request( + session_id=session_id, + subscription_id=self._config.subscription_id, + resource_group_name=self._config.resource_group_name, + workspace_name=self._config.workspace_name, + content_type=content_type, + api_version=self._config.api_version, + json=_json, + content=_content, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200, 201]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.RestError, pipeline_response) + raise HttpResponseError(response=response, model=error) + + if response.status_code == 200: + deserialized = self._deserialize("SessionDetails", pipeline_response) + + if response.status_code == 201: + deserialized = self._deserialize("SessionDetails", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def close(self, session_id: str, **kwargs: Any) -> _models.SessionDetails: + """Close a session. + + :param session_id: Id of the session. Required. + :type session_id: str + :return: SessionDetails + :rtype: ~azure.quantum._client.models.SessionDetails + :raises ~azure.core.exceptions.HttpResponseError: + """ + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models.SessionDetails] = kwargs.pop("cls", None) + + _request = build_sessions_close_request( + session_id=session_id, + subscription_id=self._config.subscription_id, + resource_group_name=self._config.resource_group_name, + workspace_name=self._config.workspace_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.RestError, pipeline_response) + raise HttpResponseError(response=response, model=error) + + deserialized = self._deserialize("SessionDetails", pipeline_response) + + if cls: + return cls(pipeline_response, deserialized, {}) # type: ignore + + return deserialized # type: ignore + + @distributed_trace + def jobs_list(self, session_id: str, **kwargs: Any) -> Iterable["_models.JobDetails"]: + """List jobs in a session. + + :param session_id: Id of the session. Required. + :type session_id: str + :return: An iterator like instance of JobDetails + :rtype: ~azure.core.paging.ItemPaged[~azure.quantum._client.models.JobDetails] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models._models.JobDetailsList] = kwargs.pop("cls", None) # pylint: disable=protected-access + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_sessions_jobs_list_request( + session_id=session_id, + subscription_id=self._config.subscription_id, + resource_group_name=self._config.resource_group_name, + workspace_name=self._config.workspace_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize( + _models._models.JobDetailsList, pipeline_response # pylint: disable=protected-access + ) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.RestError, pipeline_response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) + + +class TopLevelItemsOperations: + """ + .. warning:: + **DO NOT** instantiate this class directly. + + Instead, you should access the following operations through + :class:`~azure.quantum._client.QuantumClient`'s + :attr:`top_level_items` attribute. + """ + + models = _models + + def __init__(self, *args, **kwargs): + input_args = list(args) + self._client = input_args.pop(0) if input_args else kwargs.pop("client") + self._config = input_args.pop(0) if input_args else kwargs.pop("config") + self._serialize = input_args.pop(0) if input_args else kwargs.pop("serializer") + self._deserialize = input_args.pop(0) if input_args else kwargs.pop("deserializer") + + @distributed_trace + def list(self, **kwargs: Any) -> Iterable["_models.ItemDetails"]: + """List top-level items. + + :return: An iterator like instance of ItemDetails + :rtype: ~azure.core.paging.ItemPaged[~azure.quantum._client.models.ItemDetails] + :raises ~azure.core.exceptions.HttpResponseError: + """ + _headers = kwargs.pop("headers", {}) or {} + _params = kwargs.pop("params", {}) or {} + + cls: ClsType[_models._models.ItemDetailsList] = kwargs.pop("cls", None) # pylint: disable=protected-access + + error_map = { + 401: ClientAuthenticationError, + 404: ResourceNotFoundError, + 409: ResourceExistsError, + 304: ResourceNotModifiedError, + } + error_map.update(kwargs.pop("error_map", {}) or {}) + + def prepare_request(next_link=None): + if not next_link: + + _request = build_top_level_items_list_request( + subscription_id=self._config.subscription_id, + resource_group_name=self._config.resource_group_name, + workspace_name=self._config.workspace_name, + api_version=self._config.api_version, + headers=_headers, + params=_params, + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + else: + # make call to next link with the client's api-version + _parsed_next_link = urllib.parse.urlparse(next_link) + _next_request_params = case_insensitive_dict( + { + key: [urllib.parse.quote(v) for v in value] + for key, value in urllib.parse.parse_qs(_parsed_next_link.query).items() + } + ) + _next_request_params["api-version"] = self._config.api_version + _request = HttpRequest( + "GET", urllib.parse.urljoin(next_link, _parsed_next_link.path), params=_next_request_params + ) + path_format_arguments = { + "azureRegion": self._serialize.url( + "self._config.azure_region", self._config.azure_region, "str", skip_quote=True + ), + } + _request.url = self._client.format_url(_request.url, **path_format_arguments) + + return _request + + def extract_data(pipeline_response): + deserialized = self._deserialize( + _models._models.ItemDetailsList, pipeline_response # pylint: disable=protected-access + ) + list_of_elem = deserialized.value + if cls: + list_of_elem = cls(list_of_elem) # type: ignore + return deserialized.next_link or None, iter(list_of_elem) + + def get_next(next_link=None): + _request = prepare_request(next_link) + + _stream = False + pipeline_response: PipelineResponse = self._client._pipeline.run( # pylint: disable=protected-access + _request, stream=_stream, **kwargs + ) + response = pipeline_response.http_response + + if response.status_code not in [200]: + if _stream: + response.read() # Load the body in memory and close the socket + map_error(status_code=response.status_code, response=response, error_map=error_map) + error = self._deserialize.failsafe_deserialize(_models.RestError, pipeline_response) + raise HttpResponseError(response=response, model=error) + + return pipeline_response + + return ItemPaged(get_next, extract_data) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/operations/_patch.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/operations/_patch.py new file mode 100644 index 00000000000..f7dd3251033 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/operations/_patch.py @@ -0,0 +1,20 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +"""Customize generated code here. + +Follow our quickstart for examples: https://aka.ms/azsdk/python/dpcodegen/python/customize +""" +from typing import List + +__all__: List[str] = [] # Add all objects you want publicly available to users at this package level + + +def patch_sdk(): + """Do not remove from this file. + + `patch_sdk` is a last resort escape hatch that allows you to do customizations + you can't accomplish using the techniques described in + https://aka.ms/azsdk/python/dpcodegen/python/customize + """ diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/py.typed b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/py.typed new file mode 100644 index 00000000000..e5aff4f83af --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_client/py.typed @@ -0,0 +1 @@ +# Marker file for PEP 561. \ No newline at end of file diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_constants.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_constants.py new file mode 100644 index 00000000000..a545480bc4d --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_constants.py @@ -0,0 +1,97 @@ +## +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +## + +from enum import Enum +# from azure.identity._constants import EnvironmentVariables as SdkEnvironmentVariables +# from azure.identity import _internal as AzureIdentityInternals +from ..azure_identity._constants import EnvironmentVariables as SdkEnvironmentVariables +from ..azure_identity import _internal as AzureIdentityInternals + + +class EnvironmentVariables: + USER_AGENT_APPID = "AZURE_QUANTUM_PYTHON_APPID" + QUANTUM_LOCATION = "AZURE_QUANTUM_WORKSPACE_LOCATION" + LOCATION = "LOCATION" + QUANTUM_RESOURCE_GROUP = "AZURE_QUANTUM_WORKSPACE_RG" + RESOURCE_GROUP = "RESOURCE_GROUP" + QUANTUM_SUBSCRIPTION_ID = "AZURE_QUANTUM_SUBSCRIPTION_ID" + SUBSCRIPTION_ID = "SUBSCRIPTION_ID" + WORKSPACE_NAME = "AZURE_QUANTUM_WORKSPACE_NAME" + QUANTUM_ENV = "AZURE_QUANTUM_ENV" + AZURE_CLIENT_ID = SdkEnvironmentVariables.AZURE_CLIENT_ID + AZURE_CLIENT_SECRET = SdkEnvironmentVariables.AZURE_CLIENT_SECRET + AZURE_CLIENT_CERTIFICATE_PATH = SdkEnvironmentVariables.AZURE_CLIENT_CERTIFICATE_PATH + AZURE_CLIENT_SEND_CERTIFICATE_CHAIN = SdkEnvironmentVariables.AZURE_CLIENT_SEND_CERTIFICATE_CHAIN + AZURE_TENANT_ID = SdkEnvironmentVariables.AZURE_TENANT_ID + QUANTUM_TOKEN_FILE = "AZURE_QUANTUM_TOKEN_FILE" + CONNECTION_STRING = "AZURE_QUANTUM_CONNECTION_STRING" + ALL = [ + USER_AGENT_APPID, + QUANTUM_LOCATION, + LOCATION, + QUANTUM_RESOURCE_GROUP, + RESOURCE_GROUP, + QUANTUM_SUBSCRIPTION_ID, + SUBSCRIPTION_ID, + WORKSPACE_NAME, + QUANTUM_ENV, + AZURE_CLIENT_ID, + AZURE_CLIENT_SECRET, + AZURE_CLIENT_CERTIFICATE_PATH, + AZURE_CLIENT_SEND_CERTIFICATE_CHAIN, + AZURE_TENANT_ID, + QUANTUM_TOKEN_FILE, + CONNECTION_STRING, + ] + + +class EnvironmentKind(Enum): + PRODUCTION = 1, + CANARY = 2, + DOGFOOD = 3 + + +class ConnectionConstants: + DATA_PLANE_CREDENTIAL_SCOPE = "https://quantum.microsoft.com/.default" + ARM_CREDENTIAL_SCOPE = "https://management.azure.com/.default" + + MSA_TENANT_ID = "9188040d-6c67-4c5b-b112-36a304b66dad" + + AUTHORITY = AzureIdentityInternals.get_default_authority() + DOGFOOD_AUTHORITY = "login.windows-ppe.net" + + # pylint: disable=unnecessary-lambda-assignment + GET_QUANTUM_PRODUCTION_ENDPOINT = \ + lambda location: f"https://{location}.quantum.azure.com/" + GET_QUANTUM_CANARY_ENDPOINT = \ + lambda location: f"https://{location or 'eastus2euap'}.quantum.azure.com/" + GET_QUANTUM_DOGFOOD_ENDPOINT = \ + lambda location: f"https://{location}.quantum-test.azure.com/" + + ARM_PRODUCTION_ENDPOINT = "https://management.azure.com/" + ARM_DOGFOOD_ENDPOINT = "https://api-dogfood.resources.windows-int.net/" + + VALID_RESOURCE_ID = ( + lambda subscription_id, resource_group, workspace_name: + f"/subscriptions/{subscription_id}" + + f"/resourceGroups/{resource_group}" + + "/providers/Microsoft.Quantum/" + + f"Workspaces/{workspace_name}" + ) + + VALID_CONNECTION_STRING = ( + lambda subscription_id, resource_group, workspace_name, api_key, quantum_endpoint: + f"SubscriptionId={subscription_id};" + + f"ResourceGroupName={resource_group};" + + f"WorkspaceName={workspace_name};" + + f"ApiKey={api_key};" + + f"QuantumEndpoint={quantum_endpoint};" + ) + + QUANTUM_API_KEY_HEADER = "x-ms-quantum-api-key" + +GUID_REGEX_PATTERN = ( + r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}" +) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_workspace_connection_params.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_workspace_connection_params.py new file mode 100644 index 00000000000..3d25ed9ec3a --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/_workspace_connection_params.py @@ -0,0 +1,547 @@ +## +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +## +from __future__ import annotations +import re +import os +from re import Match +from typing import ( + Optional, + Callable, + Union, + Any +) +from azure.core.credentials import AzureKeyCredential +from azure.core.pipeline.policies import AzureKeyCredentialPolicy +# from azure.quantum._authentication import _DefaultAzureCredential +from ._authentication import _DefaultAzureCredential +# from azure.quantum._constants import ( +from ._constants import ( + EnvironmentKind, + EnvironmentVariables, + ConnectionConstants, + GUID_REGEX_PATTERN, +) + +class WorkspaceConnectionParams: + """ + Internal Azure Quantum Python SDK class to handle logic + for the parameters needed to connect to a Workspace. + """ + + RESOURCE_ID_REGEX = re.compile( + fr""" + ^ + /subscriptions/(?P{GUID_REGEX_PATTERN}) + /resourceGroups/(?P[^\s/]+) + /providers/Microsoft\.Quantum + /Workspaces/(?P[^\s/]+) + $ + """, + re.VERBOSE | re.IGNORECASE) + + CONNECTION_STRING_REGEX = re.compile( + fr""" + ^ + SubscriptionId=(?P{GUID_REGEX_PATTERN}); + ResourceGroupName=(?P[^\s;]+); + WorkspaceName=(?P[^\s;]+); + ApiKey=(?P[^\s;]+); + QuantumEndpoint=(?Phttps://(?P[^\s\.]+).quantum(?:-test)?.azure.com/); + """, + re.VERBOSE | re.IGNORECASE) + + def __init__( + self, + subscription_id: Optional[str] = None, + resource_group: Optional[str] = None, + workspace_name: Optional[str] = None, + location: Optional[str] = None, + quantum_endpoint: Optional[str] = None, + arm_endpoint: Optional[str] = None, + environment: Union[str, EnvironmentKind, None] = None, + credential: Optional[object] = None, + resource_id: Optional[str] = None, + user_agent: Optional[str] = None, + user_agent_app_id: Optional[str] = None, + tenant_id: Optional[str] = None, + client_id: Optional[str] = None, + api_version: Optional[str] = None, + connection_string: Optional[str] = None, + on_new_client_request: Optional[Callable] = None, + ): + # fields are used for these properties since + # they have special getters/setters + self._location = None + self._environment = None + self._quantum_endpoint = None + self._arm_endpoint = None + # regular connection properties + self.subscription_id = None + self.resource_group = None + self.workspace_name = None + self.credential = None + self.user_agent = None + self.user_agent_app_id = None + self.client_id = None + self.tenant_id = None + self.api_version = None + # callback to create a new client if needed + # for example, when changing the user agent + self.on_new_client_request = on_new_client_request + # merge the connection parameters passed + # connection_string is set first as it + # should be overridden by other parameters + self.apply_connection_string(connection_string) + self.merge( + api_version=api_version, + arm_endpoint=arm_endpoint, + quantum_endpoint=quantum_endpoint, + client_id=client_id, + credential=credential, + environment=environment, + location=location, + resource_group=resource_group, + subscription_id=subscription_id, + tenant_id=tenant_id, + user_agent=user_agent, + user_agent_app_id=user_agent_app_id, + workspace_name=workspace_name, + ) + self.apply_resource_id(resource_id=resource_id) + + @property + def location(self): + """ + The Azure location. + On the setter, we normalize the value removing spaces + and converting it to lowercase. + """ + return self._location + + @location.setter + def location(self, value: str): + self._location = (value.replace(" ", "").lower() + if isinstance(value, str) + else value) + + @property + def environment(self): + """ + The environment kind, such as dogfood, canary or production. + Defaults to EnvironmentKind.PRODUCTION + """ + return self._environment or EnvironmentKind.PRODUCTION + + @environment.setter + def environment(self, value: Union[str, EnvironmentKind]): + self._environment = (EnvironmentKind[value.upper()] + if isinstance(value, str) + else value) + + @property + def quantum_endpoint(self): + """ + The Azure Quantum data plane endpoint. + Defaults to well-known endpoint based on the environment. + """ + if self._quantum_endpoint: + return self._quantum_endpoint + if not self.location: + raise ValueError("Location not specified") + if self.environment is EnvironmentKind.PRODUCTION: + return ConnectionConstants.GET_QUANTUM_PRODUCTION_ENDPOINT(self.location) + if self.environment is EnvironmentKind.CANARY: + return ConnectionConstants.GET_QUANTUM_CANARY_ENDPOINT(self.location) + if self.environment is EnvironmentKind.DOGFOOD: + return ConnectionConstants.GET_QUANTUM_DOGFOOD_ENDPOINT(self.location) + raise ValueError(f"Unknown environment `{self.environment}`.") + + @quantum_endpoint.setter + def quantum_endpoint(self, value: str): + self._quantum_endpoint = value + + @property + def arm_endpoint(self): + """ + The control plane endpoint. + Defaults to well-known arm_endpoint based on the environment. + """ + if self._arm_endpoint: + return self._arm_endpoint + if self.environment is EnvironmentKind.DOGFOOD: + return ConnectionConstants.ARM_DOGFOOD_ENDPOINT + if self.environment in [EnvironmentKind.PRODUCTION, + EnvironmentKind.CANARY]: + return ConnectionConstants.ARM_PRODUCTION_ENDPOINT + raise ValueError(f"Unknown environment `{self.environment}`.") + + @arm_endpoint.setter + def arm_endpoint(self, value: str): + self._arm_endpoint = value + + @property + def api_key(self): + """ + The api-key stored in a AzureKeyCredential. + """ + return (self.credential.key + if isinstance(self.credential, AzureKeyCredential) + else None) + + @api_key.setter + def api_key(self, value: str): + if value: + self.credential = AzureKeyCredential(value) + self._api_key = value + + def __repr__(self): + """ + Print all fields and properties. + """ + info = [] + for key in vars(self): + info.append(f" {key}: {self.__dict__[key]}") + cls = type(self) + for key in dir(self): + attr = getattr(cls, key, None) + if attr and isinstance(attr, property) and attr.fget: + info.append(f" {key}: {attr.fget(self)}") + info.sort() + info.insert(0, super().__repr__()) + return "\n".join(info) + + def apply_resource_id(self, resource_id: str): + """ + Parses the resource_id and set the connection + parameters obtained from it. + """ + if resource_id: + match = re.search( + WorkspaceConnectionParams.RESOURCE_ID_REGEX, + resource_id) + if not match: + raise ValueError("Invalid resource id") + self._merge_re_match(match) + + def apply_connection_string(self, connection_string: str): + """ + Parses the connection_string and set the connection + parameters obtained from it. + """ + if connection_string: + match = re.search( + WorkspaceConnectionParams.CONNECTION_STRING_REGEX, + connection_string) + if not match: + raise ValueError("Invalid connection string") + self._merge_re_match(match) + + def merge( + self, + subscription_id: Optional[str] = None, + resource_group: Optional[str] = None, + workspace_name: Optional[str] = None, + location: Optional[str] = None, + quantum_endpoint: Optional[str] = None, + arm_endpoint: Optional[str] = None, + environment: Union[str, EnvironmentKind, None] = None, + credential: Optional[object] = None, + user_agent: Optional[str] = None, + user_agent_app_id: Optional[str] = None, + tenant_id: Optional[str] = None, + client_id: Optional[str] = None, + api_version: Optional[str] = None, + api_key: Optional[str] = None, + ): + """ + Set all fields/properties with `not None` values + passed in the (named or key-valued) arguments + into this instance. + """ + self._merge( + api_version=api_version, + arm_endpoint=arm_endpoint, + quantum_endpoint=quantum_endpoint, + client_id=client_id, + credential=credential, + environment=environment, + location=location, + resource_group=resource_group, + subscription_id=subscription_id, + tenant_id=tenant_id, + user_agent=user_agent, + user_agent_app_id=user_agent_app_id, + workspace_name=workspace_name, + api_key=api_key, + merge_default_mode=False, + ) + return self + + def apply_defaults( + self, + subscription_id: Optional[str] = None, + resource_group: Optional[str] = None, + workspace_name: Optional[str] = None, + location: Optional[str] = None, + quantum_endpoint: Optional[str] = None, + arm_endpoint: Optional[str] = None, + environment: Union[str, EnvironmentKind, None] = None, + credential: Optional[object] = None, + user_agent: Optional[str] = None, + user_agent_app_id: Optional[str] = None, + tenant_id: Optional[str] = None, + client_id: Optional[str] = None, + api_version: Optional[str] = None, + api_key: Optional[str] = None, + ) -> WorkspaceConnectionParams: + """ + Set all fields/properties with `not None` values + passed in the (named or key-valued) arguments + into this instance IF the instance does not have + the corresponding parameter set yet. + """ + self._merge( + api_version=api_version, + arm_endpoint=arm_endpoint, + quantum_endpoint=quantum_endpoint, + client_id=client_id, + credential=credential, + environment=environment, + location=location, + resource_group=resource_group, + subscription_id=subscription_id, + tenant_id=tenant_id, + user_agent=user_agent, + user_agent_app_id=user_agent_app_id, + workspace_name=workspace_name, + api_key=api_key, + merge_default_mode=True, + ) + return self + + def _merge( + self, + merge_default_mode: bool, + subscription_id: Optional[str] = None, + resource_group: Optional[str] = None, + workspace_name: Optional[str] = None, + location: Optional[str] = None, + quantum_endpoint: Optional[str] = None, + arm_endpoint: Optional[str] = None, + environment: Union[str, EnvironmentKind, None] = None, + credential: Optional[object] = None, + user_agent: Optional[str] = None, + user_agent_app_id: Optional[str] = None, + tenant_id: Optional[str] = None, + client_id: Optional[str] = None, + api_version: Optional[str] = None, + api_key: Optional[str] = None, + ): + """ + Set all fields/properties with `not None` values + passed in the kwargs arguments + into this instance. + + If merge_default_mode is True, skip setting + the field/property if it already has a value. + """ + def _get_value_or_default(old_value, new_value): + if merge_default_mode and old_value: + return old_value + if new_value: + return new_value + return old_value + + self.subscription_id = _get_value_or_default(self.subscription_id, subscription_id) + self.resource_group = _get_value_or_default(self.resource_group, resource_group) + self.workspace_name = _get_value_or_default(self.workspace_name, workspace_name) + self.location = _get_value_or_default(self.location, location) + self.environment = _get_value_or_default(self.environment, environment) + self.credential = _get_value_or_default(self.credential, credential) + self.user_agent = _get_value_or_default(self.user_agent, user_agent) + self.user_agent_app_id = _get_value_or_default(self.user_agent_app_id, user_agent_app_id) + self.client_id = _get_value_or_default(self.client_id, client_id) + self.tenant_id = _get_value_or_default(self.tenant_id, tenant_id) + self.api_version = _get_value_or_default(self.api_version, api_version) + self.api_key = _get_value_or_default(self.api_key, api_key) + # for these properties that have a default value in the getter, we use + # the private field as the old_value + self.quantum_endpoint = _get_value_or_default(self._quantum_endpoint, quantum_endpoint) + self.arm_endpoint = _get_value_or_default(self._arm_endpoint, arm_endpoint) + return self + + def _merge_connection_params( + self, + connection_params: WorkspaceConnectionParams, + merge_default_mode: bool = False, + ) -> WorkspaceConnectionParams: + """ + Set all fields/properties with `not None` values + from the `connection_params` into this instance. + """ + self._merge( + api_version=connection_params.api_version, + client_id=connection_params.client_id, + credential=connection_params.credential, + environment=connection_params.environment, + location=connection_params.location, + resource_group=connection_params.resource_group, + subscription_id=connection_params.subscription_id, + tenant_id=connection_params.tenant_id, + user_agent=connection_params.user_agent, + user_agent_app_id=connection_params.user_agent_app_id, + workspace_name=connection_params.workspace_name, + merge_default_mode=merge_default_mode, + # for these properties that have a default value in the getter, + # so we use the private field instead + # pylint: disable=protected-access + arm_endpoint=connection_params._arm_endpoint, + quantum_endpoint=connection_params._quantum_endpoint, + ) + return self + + def get_credential_or_default(self) -> Any: + """ + Get the credential if one was set, + or defaults to a new _DefaultAzureCredential. + """ + return (self.credential + or _DefaultAzureCredential( + subscription_id=self.subscription_id, + arm_endpoint=self.arm_endpoint, + tenant_id=self.tenant_id)) + + def get_auth_policy(self) -> Any: + """ + Returns a AzureKeyCredentialPolicy if using an AzureKeyCredential. + Defaults to None. + """ + if isinstance(self.credential, AzureKeyCredential): + return AzureKeyCredentialPolicy(self.credential, + ConnectionConstants.QUANTUM_API_KEY_HEADER) + return None + + def append_user_agent(self, value: str): + """ + Append a new value to the Workspace's UserAgent and re-initialize the + QuantumClient. The values are appended using a dash. + + :param value: UserAgent value to add, e.g. "azure-quantum-" + """ + new_user_agent = None + + if ( + value + and value not in (self.user_agent or "") + ): + new_user_agent = (f"{self.user_agent}-{value}" + if self.user_agent else value) + + if new_user_agent != self.user_agent: + self.user_agent = new_user_agent + if self.on_new_client_request: + self.on_new_client_request() + + def get_full_user_agent(self): + """ + Get the full Azure Quantum Python SDK UserAgent + that is sent to the service via the header. + """ + full_user_agent = self.user_agent + app_id = self.user_agent_app_id + if self.user_agent_app_id: + full_user_agent = (f"{app_id} {full_user_agent}" + if full_user_agent else app_id) + return full_user_agent + + def is_complete(self) -> bool: + """ + Returns true if we have all necessary parameters + to connect to the Azure Quantum Workspace. + """ + return (self.location + and self.subscription_id + and self.resource_group + and self.workspace_name + and self.get_credential_or_default()) + + def assert_complete(self): + """ + Raises ValueError if we don't have all necessary parameters + to connect to the Azure Quantum Workspace. + """ + if not self.is_complete(): + raise ValueError( + """ + Azure Quantum workspace not fully specified. + Please specify one of the following: + 1) A valid combination of location and resource ID. + 2) A valid combination of location, subscription ID, + resource group name, and workspace name. + 3) A valid connection string (via Workspace.from_connection_string()). + """) + + def default_from_env_vars(self) -> WorkspaceConnectionParams: + """ + Apply default values found in the environment variables + if current parameters are not set. + """ + self.subscription_id = (self.subscription_id + or os.environ.get(EnvironmentVariables.QUANTUM_SUBSCRIPTION_ID) + or os.environ.get(EnvironmentVariables.SUBSCRIPTION_ID)) + self.resource_group = (self.resource_group + or os.environ.get(EnvironmentVariables.QUANTUM_RESOURCE_GROUP) + or os.environ.get(EnvironmentVariables.RESOURCE_GROUP)) + self.workspace_name = (self.workspace_name + or os.environ.get(EnvironmentVariables.WORKSPACE_NAME)) + self.location = (self.location + or os.environ.get(EnvironmentVariables.QUANTUM_LOCATION) + or os.environ.get(EnvironmentVariables.LOCATION)) + self.user_agent_app_id = (self.user_agent_app_id + or os.environ.get(EnvironmentVariables.USER_AGENT_APPID)) + self.tenant_id = (self.tenant_id + or os.environ.get(EnvironmentVariables.AZURE_TENANT_ID)) + self.client_id = (self.client_id + or os.environ.get(EnvironmentVariables.AZURE_CLIENT_ID)) + # for these properties we use the private field + # because the getter return default values + self.environment = (self._environment + or os.environ.get(EnvironmentVariables.QUANTUM_ENV)) + # only try to use the connection string from env var if + # we really need it + if (not self.location + or not self.subscription_id + or not self.resource_group + or not self.workspace_name + or not self.credential + ): + self._merge_connection_params( + connection_params=WorkspaceConnectionParams( + connection_string=os.environ.get(EnvironmentVariables.CONNECTION_STRING)), + merge_default_mode=True) + return self + + @classmethod + def from_env_vars( + cls, + ) -> WorkspaceConnectionParams: + """ + Initialize the WorkspaceConnectionParams from values found + in the environment variables. + """ + return WorkspaceConnectionParams().default_from_env_vars() + + def _merge_re_match(self, re_match: Match[str]): + def get_value(group_name): + return re_match.groupdict().get(group_name) + self.merge( + subscription_id=get_value('subscription_id'), + resource_group=get_value('resource_group'), + workspace_name=get_value('workspace_name'), + location=get_value('location'), + quantum_endpoint=get_value('quantum_endpoint'), + api_key=get_value('api_key'), + arm_endpoint=get_value('arm_endpoint'), + ) diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/storage.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/storage.py new file mode 100644 index 00000000000..e3675502841 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/storage.py @@ -0,0 +1,385 @@ +## +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +## +import logging +from typing import Any, Dict +from azure.core import exceptions +# from azure.storage.blob import ( +from ..azure_storage_blob import ( + BlobServiceClient, + ContainerClient, + BlobClient, + BlobSasPermissions, + ContentSettings, + generate_blob_sas, + generate_container_sas, + BlobType, + BlobProperties +) +from datetime import datetime, timedelta +from enum import Enum + +logger = logging.getLogger(__name__) + + +def create_container( + connection_string: str, container_name: str +) -> ContainerClient: + """ + Creates and initialize a container; returns the client needed to access it. + """ + blob_service_client = BlobServiceClient.from_connection_string( + connection_string + ) + logger.info( + f'{"Initializing storage client for account:"}' + + f"{blob_service_client.account_name}" + ) + + container_client = blob_service_client.get_container_client(container_name) + create_container_using_client(container_client) + return container_client + + +def create_container_using_client(container_client: ContainerClient): + """ + Creates the container if it doesn't already exist. + """ + if not container_client.exists(): + logger.debug( + f'{" - uploading to **new** container:"}' + f"{container_client.container_name}" + ) + container_client.create_container() + + +def get_container_uri(connection_string: str, container_name: str) -> str: + """ + Creates and initialize a container; + returns a URI with a SAS read/write token to access it. + """ + container = create_container(connection_string, container_name) + logger.info( + f'{"Creating SAS token for container"}' + + f"'{container_name}' on account: '{container.account_name}'" + ) + + sas_token = generate_container_sas( + container.account_name, + container.container_name, + account_key=container.credential.account_key, + permission=BlobSasPermissions( + read=True, add=True, write=True, create=True + ), + expiry=datetime.utcnow() + timedelta(days=14), + ) + + uri = container.url + "?" + sas_token + logger.debug(f" - container url: '{uri}'.") + return uri + + +def upload_blob( + container: ContainerClient, + blob_name: str, + content_type: str, + content_encoding: str, + data: Any, + return_sas_token: bool = True, +) -> str: + """ + Uploads the given data to a blob record. + If a blob with the given name already exist, it throws an error. + + Returns a uri with a SAS token to access the newly created blob. + """ + create_container_using_client(container) + logger.info( + f"Uploading blob '{blob_name}'" + + f"to container '{container.container_name}'" + + f"on account: '{container.account_name}'" + ) + + content_settings = ContentSettings( + content_type=content_type, content_encoding=content_encoding + ) + + blob = container.get_blob_client(blob_name) + + blob.upload_blob(data, content_settings=content_settings) + logger.debug(f" - blob '{blob_name}' uploaded. generating sas token.") + + if return_sas_token: + uri = get_blob_uri_with_sas_token(blob) + else: + uri = remove_sas_token(blob.url) + logger.debug(f" - blob access url: '{uri}'.") + + return uri + + +def append_blob( + container: ContainerClient, + blob_name: str, + content_type: str, + content_encoding: str, + data: Any, + return_sas_token: bool = True, + metadata: Dict[str, str] = None, +) -> str: + """ + Uploads the given data to a blob record. + If a blob with the given name already exist, it throws an error. + + Returns a uri with a SAS token to access the newly created blob. + """ + create_container_using_client(container) + logger.info( + f"Appending data to blob '{blob_name}'" + + f"in container '{container.container_name}'" + + f"on account: '{container.account_name}'" + ) + + content_settings = ContentSettings( + content_type=content_type, content_encoding=content_encoding + ) + blob = container.get_blob_client(blob_name) + try: + props = blob.get_blob_properties() + if props.blob_type != BlobType.AppendBlob: + raise Exception("blob must be an append blob") + except exceptions.ResourceNotFoundError: + props = blob.create_append_blob( + content_settings=content_settings, metadata=metadata + ) + + blob.append_block(data, len(data)) + logger.debug(f" - blob '{blob_name}' appended. generating sas token.") + + if return_sas_token: + uri = get_blob_uri_with_sas_token(blob) + else: + uri = remove_sas_token(blob.url) + + logger.debug(f" - blob access url: '{uri}'.") + + return uri + + +def get_blob_uri_with_sas_token(blob: BlobClient): + """Returns a URI for the given blob that contains a SAS Token""" + sas_token = generate_blob_sas( + blob.account_name, + blob.container_name, + blob.blob_name, + account_key=blob.credential.account_key, + permission=BlobSasPermissions(read=True), + expiry=datetime.utcnow() + timedelta(days=14), + ) + + return blob.url + "?" + sas_token + + +def download_blob(blob_url: str) -> Any: + """ + Downloads the given blob from the container. + """ + blob_client = BlobClient.from_blob_url(blob_url) + logger.info( + f"Downloading blob '{blob_client.blob_name}'" + + f"from container '{blob_client.container_name}'" + + f"on account: '{blob_client.account_name}'" + ) + + response = blob_client.download_blob().readall() + logger.debug(response) + + return response + + +def download_blob_properties(blob_url: str) -> BlobProperties: + """Downloads the blob properties from Azure for the given blob URI""" + blob_client = BlobClient.from_blob_url(blob_url) + logger.info( + f"Downloading blob properties '{blob_client.blob_name}'" + + f"from container '{blob_client.container_name}'" + + f"on account: '{blob_client.account_name}'" + ) + + response = blob_client.get_blob_properties() + logger.debug(response) + + return response + + +def download_blob_metadata(blob_url: str) -> Dict[str, str]: + """Downloads the blob metadata from the + blob properties in Azure for the given blob URI""" + return download_blob_properties(blob_url).metadata + + +def set_blob_metadata(blob_url: str, metadata: Dict[str, str]): + """Sets the provided dictionary as the metadata on the Azure blob""" + blob_client = BlobClient.from_blob_url(blob_url) + logger.info( + f"Setting blob properties '{blob_client.blob_name}'" + + f"from container '{blob_client.container_name}' on account:" + + f"'{blob_client.account_name}'" + ) + return blob_client.set_blob_metadata(metadata=metadata) + + +def remove_sas_token(sas_uri: str) -> str: + """Removes the SAS Token from the given URI if it contains one""" + index = sas_uri.find("?") + if index != -1: + sas_uri = sas_uri[0:index] + + return sas_uri + + +def init_blob_for_streaming_upload( + container: ContainerClient, + blob_name: str, + content_type: str, + content_encoding: str, + data: Any, + return_sas_token: bool = True, +) -> str: + """ + Uploads the given data to a blob record. + If a blob with the given name already exist, it throws an error. + + Returns a uri with a SAS token to access the newly created blob. + """ + create_container_using_client(container) + logger.info( + f"Streaming blob '{blob_name}'" + + f"to container '{container.container_name}' on account:" + + f"'{container.account_name}'" + ) + + content_settings = ContentSettings( + content_type=content_type, content_encoding=content_encoding + ) + blob = container.get_blob_client(blob_name) + blob.stage_block() + blob.commit_block_list() + blob.upload_blob(data, content_settings=content_settings) + logger.debug(f" - blob '{blob_name}' uploaded. generating sas token.") + + if return_sas_token: + sas_token = generate_blob_sas( + blob.account_name, + blob.container_name, + blob.blob_name, + account_key=blob.credential.account_key, + permission=BlobSasPermissions(read=True), + expiry=datetime.utcnow() + timedelta(days=14), + ) + + uri = blob.url + "?" + sas_token + else: + uri = remove_sas_token(blob.url) + + logger.debug(f" - blob access url: '{uri}'.") + + return uri + + +class StreamedBlobState(str, Enum): + not_initialized = 0 + uploading = 1 + committed = 2 + + +class StreamedBlob: + """Class that provides a state machine for writing + blobs using the Azure Block Blob API + + Internally implements a state machine for uploading blob data. + To use, start calling `upload_data()` + to add data blocks. Each call to `upload_data()` + will synchronously upload an individual block to Azure. + Once all blocks have been added, call `commit()` + to commit the blocks and make the blob available/readable. + + :param container: The container client that the blob will be uploaded to + :param blob_name: The name of the blob + (including optional path) within the blob container + :param content_type: The HTTP content type to apply to the blob metadata + :param content_encoding: The HTTP + content encoding to apply to the blob metadata + """ + + def __init__( + self, + container: ContainerClient, + blob_name: str, + content_type: str, + content_encoding: str, + ): + self.container = container + self.blob_name = blob_name + self.content_settings = ContentSettings( + content_type=content_type, content_encoding=content_encoding + ) + self.state = StreamedBlobState.not_initialized + self.blob = container.get_blob_client(blob_name) + self.blocks = [] + + def upload_data(self, data): + """Synchronously uploads a block to the given block blob in Azure + + :param data: The data to be uploaded as a block. + :type data: Union[Iterable[AnyStr], IO[AnyStr]] + """ + if self.state == StreamedBlobState.not_initialized: + create_container_using_client(self.container) + logger.info( + f"Streaming blob '{self.blob_name}' to container" + + f"'{self.container.container_name}'" + + f"on account: '{self.container.account_name}'" + ) + self.initialized = True + + self.state = StreamedBlobState.uploading + id = self._get_next_block_id() + logger.debug(f"Uploading block '{id}' to {self.blob_name}") + self.blob.stage_block(id, data, length=len(data)) + self.blocks.append(id) + + def commit(self, metadata: Dict[str, str] = None): + """Synchronously commits all previously + uploaded blobs to the block blob + + :param metadata: Optional dictionary of + metadata to be applied to the block blob + """ + if self.state == StreamedBlobState.not_initialized: + raise Exception("StreamedBlob cannot commit before uploading data") + elif self.state == StreamedBlobState.committed: + raise Exception("StreamedBlob is already committed") + + logger.debug(f"Committing {len(self.blocks)} blocks {self.blob_name}") + self.blob.commit_block_list( + self.blocks, + content_settings=self.content_settings, + metadata=metadata, + ) + self.state = StreamedBlobState.committed + logger.debug(f"Committed {self.blob_name}") + + def getUri(self, with_sas_token: bool = False): + """Gets the full Azure Storage URI for the + uploaded blob after it has been committed""" + if self.state != StreamedBlobState.committed: + raise Exception("Can only retrieve sas token for committed blob") + if with_sas_token: + return get_blob_uri_with_sas_token(self.blob) + + return remove_sas_token(self.blob.url) + + def _get_next_block_id(self): + return f"{len(self.blocks):10}" diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/version.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/version.py new file mode 100644 index 00000000000..808b6836058 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/version.py @@ -0,0 +1,8 @@ +# Auto-generated file, do not edit. +## +# version.py: Specifies the version of the azure.quantum package. +## +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +## +__version__ = "2.2.0" diff --git a/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/workspace.py b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/workspace.py new file mode 100644 index 00000000000..f43961acd58 --- /dev/null +++ b/src/quantum/azext_quantum/vendored_sdks/azure_quantum_python/workspace.py @@ -0,0 +1,698 @@ +## +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. +## +""" +Module providing the Workspace class, used to connect to +an Azure Quantum Workspace. +""" + +from __future__ import annotations +from datetime import datetime +import logging +from typing import ( + Any, + Dict, + Iterable, + List, + Optional, + TYPE_CHECKING, + Tuple, + Union, +) +# from azure.quantum._client import QuantumClient +from ._client import QuantumClient +# from azure.quantum._client.operations import ( +# JobsOperations, +# StorageOperations, +# QuotasOperations, +# SessionsOperations, +# TopLevelItemsOperations +# ) +# from azure.quantum._client.models import ( +from ._client.models import ( + BlobDetails, + # JobStatus, + # TargetStatus, +) +# from azure.quantum import Job, Session +# from azure.quantum.job.workspace_item_factory import WorkspaceItemFactory +# from azure.quantum._workspace_connection_params import ( +from ._workspace_connection_params import ( + WorkspaceConnectionParams +) +# from azure.quantum._constants import ( +from ._constants import ( + ConnectionConstants, +) +# from azure.quantum.storage import ( +from .storage import ( + create_container_using_client, + get_container_uri, + ContainerClient +) +# if TYPE_CHECKING: +# from azure.quantum.target import Target + + +logger = logging.getLogger(__name__) + +__all__ = ["Workspace"] + +# pylint: disable=line-too-long +# pylint: disable=too-many-public-methods +class Workspace: + """ + Represents an Azure Quantum workspace. + + When creating a Workspace object, callers have two options for + identifying the Azure Quantum workspace (in order of precedence): + 1. specify a valid location and resource ID; or + 2. specify a valid location, subscription ID, resource group, and workspace name. + + You can also use a connection string to specify the connection parameters + to an Azure Quantum Workspace by calling + :obj:`~ Workspace.from_connection_string() `. + + If the Azure Quantum workspace does not have linked storage, the caller + must also pass a valid Azure storage account connection string. + + :param subscription_id: + The Azure subscription ID. + Ignored if resource_id is specified. + + :param resource_group: + The Azure resource group name. + Ignored if resource_id is specified. + + :param name: + The Azure Quantum workspace name. + Ignored if resource_id is specified. + + :param storage: + The Azure storage account connection string. + Required only if the specified Azure Quantum + workspace does not have linked storage. + + :param resource_id: + The resource ID of the Azure Quantum workspace. + + :param location: + The Azure region where the Azure Quantum workspace is provisioned. + This may be specified as a region name such as + \"East US\" or a location name such as \"eastus\". + + :param credential: + The credential to use to connect to Azure services. + Normally one of the credential types from [Azure.Identity](https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes). + + Defaults to \"DefaultAzureCredential\", which will attempt multiple + forms of authentication. + + :param user_agent: + Add the specified value as a prefix to the HTTP User-Agent header + when communicating to the Azure Quantum service. + """ + def __init__( + self, + subscription_id: Optional[str] = None, + resource_group: Optional[str] = None, + name: Optional[str] = None, + storage: Optional[str] = None, + resource_id: Optional[str] = None, + location: Optional[str] = None, + credential: Optional[object] = None, + user_agent: Optional[str] = None, + **kwargs: Any, + ) -> None: + connection_params = WorkspaceConnectionParams( + location=location, + subscription_id=subscription_id, + resource_group=resource_group, + workspace_name=name, + credential=credential, + resource_id=resource_id, + user_agent=user_agent, + **kwargs + ).default_from_env_vars() + + logger.info("Using %s environment.", connection_params.environment) + + connection_params.assert_complete() + + connection_params.on_new_client_request = self._on_new_client_request + + self._connection_params = connection_params + self._storage = storage + + # Create QuantumClient + self._client = self._create_client() + + def _on_new_client_request(self) -> None: + """ + An internal callback method used by the WorkspaceConnectionParams + to ask the Workspace to recreate the underlying Azure SDK REST API client. + This is used when some value (such as the UserAgent) has changed + in the WorkspaceConnectionParams and requires the client to be + recreated. + """ + self._client = self._create_client() + + # @property + # def location(self) -> str: + # """ + # Returns the Azure location of the Quantum Workspace. + + # :return: Azure location name. + # :rtype: str + # """ + # return self._connection_params.location + + # @property + # def subscription_id(self) -> str: + # """ + # Returns the Azure Subscription ID of the Quantum Workspace. + + # :return: Azure Subscription ID. + # :rtype: str + # """ + # return self._connection_params.subscription_id + + # @property + # def resource_group(self) -> str: + # """ + # Returns the Azure Resource Group of the Quantum Workspace. + + # :return: Azure Resource Group name. + # :rtype: str + # """ + # return self._connection_params.resource_group + + # @property + # def name(self) -> str: + # """ + # Returns the Name of the Quantum Workspace. + + # :return: Azure Quantum Workspace name. + # :rtype: str + # """ + # return self._connection_params.workspace_name + + # @property + # def credential(self) -> Any: + # """ + # Returns the Credential used to connect to the Quantum Workspace. + + # :return: Azure SDK Credential from [Azure.Identity](https://learn.microsoft.com/python/api/overview/azure/identity-readme?view=azure-python#credential-classes). + # :rtype: typing.Any + # """ + # return self._connection_params.credential + + @property + def storage(self) -> str: + """ + Returns the Azure Storage account name associated with the Quantum Workspace. + + :return: Azure Storage account name. + :rtype: str + """ + return self._storage + + def _create_client(self) -> QuantumClient: + """" + An internal method to (re)create the underlying Azure SDK REST API client. + + :return: Azure SDK REST API client for Azure Quantum. + :rtype: QuantumClient + """ + connection_params = self._connection_params + kwargs = {} + if connection_params.api_version: + kwargs["api_version"] = connection_params.api_version + client = QuantumClient( + credential=connection_params.get_credential_or_default(), + subscription_id=connection_params.subscription_id, + resource_group_name=connection_params.resource_group, + workspace_name=connection_params.workspace_name, + azure_region=connection_params.location, + user_agent=connection_params.get_full_user_agent(), + credential_scopes = [ConnectionConstants.DATA_PLANE_CREDENTIAL_SCOPE], + endpoint=connection_params.quantum_endpoint, + authentication_policy=connection_params.get_auth_policy(), + **kwargs + ) + return client + + # @property + # def user_agent(self) -> str: + # """ + # Returns the Workspace's UserAgent string that is sent to + # the service via the UserAgent header. + + # :return: User Agent string. + # :rtype: str + # """ + # return self._connection_params.get_full_user_agent() + + # def append_user_agent(self, value: str) -> None: + # """ + # Append a new value to the Workspace's UserAgent. + # The values are appended using a dash. + + # :param value: + # UserAgent value to add, e.g. "azure-quantum-" + # """ + # self._connection_params.append_user_agent(value=value) + + # @classmethod + # def from_connection_string(cls, connection_string: str, **kwargs) -> Workspace: + # """ + # Creates a new Azure Quantum Workspace client from a connection string. + + # :param connection_string: + # A valid connection string, usually obtained from the + # `Quantum Workspace -> Operations -> Access Keys` blade in the Azure Portal. + + # :return: New Azure Quantum Workspace client. + # :rtype: Workspace + # """ + # connection_params = WorkspaceConnectionParams(connection_string=connection_string) + # return cls( + # subscription_id=connection_params.subscription_id, + # resource_group=connection_params.resource_group, + # name=connection_params.workspace_name, + # location=connection_params.location, + # credential=connection_params.get_credential_or_default(), + # **kwargs) + + # def _get_top_level_items_client(self) -> TopLevelItemsOperations: + # """ + # Returns the internal Azure SDK REST API client + # for the `{workspace}/topLevelItems` API. + + # :return: REST API client for the `topLevelItems` API. + # :rtype: TopLevelItemsOperations + # """ + # return self._client.top_level_items + + # def _get_sessions_client(self) -> SessionsOperations: + # """ + # Returns the internal Azure SDK REST API client + # for the `{workspace}/sessions` API. + + # :return: REST API client for the `sessions` API. + # :rtype: SessionsOperations + # """ + # return self._client.sessions + + # def _get_jobs_client(self) -> JobsOperations: + # """ + # Returns the internal Azure SDK REST API client + # for the `{workspace}/jobs` API. + + # :return: REST API client for the `jobs` API. + # :rtype: JobsOperations + # """ + # return self._client.jobs + + def _get_workspace_storage_client(self) -> StorageOperations: + """ + Returns the internal Azure SDK REST API client + for the `{workspace}/storage` API. + + :return: REST API client for the `storage` API. + :rtype: StorageOperations + """ + return self._client.storage + + # def _get_quotas_client(self) -> QuotasOperations: + # """ + # Returns the internal Azure SDK REST API client + # for the `{workspace}/quotas` API. + + # :return: REST API client for the `quotas` API. + # :rtype: QuotasOperations + # """ + # return self._client.quotas + + def _get_linked_storage_sas_uri( + self, + container_name: str, + blob_name: Optional[str] = None + ) -> str: + """ + Calls the service and returns a container/blob SAS URL + for the Storage associated with the Quantum Workspace. + + :param container_name: + The name of the storage container. + + :param blob_name: + Optional name of the blob. Defaults to `None`. + + :return: Storage Account SAS URL to a container or blob. + :rtype: str + """ + client = self._get_workspace_storage_client() + blob_details = BlobDetails( + container_name=container_name, blob_name=blob_name + ) + container_uri = client.sas_uri(blob_details=blob_details) + + logger.debug("Container URI from service: %s", container_uri) + return container_uri.sas_uri + + # def submit_job(self, job: Job) -> Job: + # """ + # Submits a job to be processed in the Workspace. + + # :param job: + # Job to submit. + + # :return: Azure Quantum Job that was submitted, with an updated status. + # :rtype: Job + # """ + # client = self._get_jobs_client() + # details = client.create( + # job.details.id, job.details + # ) + # return Job(self, details) + + # def cancel_job(self, job: Job) -> Job: + # """ + # Requests the Workspace to cancel the + # execution of a job. + + # :param job: + # Job to cancel. + + # :return: Azure Quantum Job that was requested to be cancelled, with an updated status. + # :rtype: Job + # """ + # client = self._get_jobs_client() + # client.cancel(job.details.id) + # details = client.get(job.id) + # return Job(self, details) + + # def get_job(self, job_id: str) -> Job: + # """ + # Returns the job corresponding to the given id. + + # :param job_id: + # Id of a job to fetch. + + # :return: Azure Quantum Job. + # :rtype: Job + # """ + # # pylint: disable=import-outside-toplevel + # from azure.quantum.target.target_factory import TargetFactory + # from azure.quantum.target import Target + + # client = self._get_jobs_client() + # details = client.get(job_id) + # target_factory = TargetFactory(base_cls=Target, workspace=self) + # # pylint: disable=protected-access + # target_cls = target_factory._target_cls( + # details.provider_id, + # details.target) + # job_cls = target_cls._get_job_class() + # return job_cls(self, details) + + # def list_jobs( + # self, + # name_match: Optional[str] = None, + # status: Optional[JobStatus] = None, + # created_after: Optional[datetime] = None + # ) -> List[Job]: + # """ + # Returns list of jobs that meet optional (limited) filter criteria. + + # :param name_match: + # Optional Regular Expression for job name matching. Defaults to `None`. + + # :param status: + # Optional filter by job status. Defaults to `None`. + + # :param created_after: + # Optional filter by jobs that were created after the given time. Defaults to `None`. + + # :return: Jobs that matched the search criteria. + # :rtype: typing.List[Job] + # """ + # client = self._get_jobs_client() + # jobs = client.list() + + # result = [] + # for j in jobs: + # deserialized_job = Job(self, j) + # if deserialized_job.matches_filter(name_match, status, created_after): + # result.append(deserialized_job) + + # return result + + # def _get_target_status( + # self, + # name: Optional[str] = None, + # provider_id: Optional[str] = None, + # ) -> List[Tuple[str, TargetStatus]]: + # """ + # Returns a list of tuples containing the `Provider ID` and `Target Status`, + # with the option of filtering that list by a combination of Provider ID and Target Name. + + # :param name: + # Optional name of the Target to filter for. Defaults to `None`. + + # :param provider_id: + # Optional Provider ID to filter for. Defaults to `None`. + + # :return: List of tuples containing Provider ID and TargetStatus. + # :rtype: typing.List[typing.Tuple[str, TargetStatus]] + # """ + # return [ + # (provider.id, target) + # for provider in self._client.providers.get_status() + # for target in provider.targets + # if (provider_id is None or provider.id.lower() == provider_id.lower()) + # and (name is None or target.id.lower() == name.lower()) + # ] + + # def get_targets( + # self, + # name: Optional[str] = None, + # provider_id: Optional[str] = None, + # ) -> Union[Target, Iterable[Target]]: + # """ + # Returns all available targets for this workspace filtered by Target name and Provider ID. + # If the target name is passed, a single `Target` object will be returned. + # Otherwise it returns a iterable/list of `Target` objects, optionally filtered by the Provider ID. + + # :param name: + # Optional target name to filter by, defaults to `None`. + + # :param provider_id: + # Optional provider Id to filter by, defaults to `None`. + + # :return: A single Azure Quantum Target or a iterable/list of Targets. + # :rtype: typing.Union[Target, typing.Iterable[Target]] + # """ + # # pylint: disable=import-outside-toplevel + # from azure.quantum.target.target_factory import TargetFactory + # from azure.quantum.target import Target + + # target_factory = TargetFactory( + # base_cls=Target, + # workspace=self + # ) + # return target_factory.get_targets( + # name=name, + # provider_id=provider_id + # ) + + # def get_quotas(self) -> List[Dict[str, Any]]: + # """ + # Get a list of quotas for the given workspace. + # Each quota is represented as a dictionary, containing the + # properties for that quota. + + # Common Quota properties are: + # - "dimension": The dimension that the quota is applied to. + # - "scope": The scope that the quota is applied to. + # - "provider_id": The provider that the quota is applied to. + # - "utilization": The current utilization of the quota. + # - "limit": The limit of the quota. + # - "period": The period that the quota is applied to. + + # :return: Workspace quotas. + # :rtype: typing.List[typing.Dict[str, typing.Any] + # """ + # client = self._get_quotas_client() + # return [q.as_dict() for q in client.list()] + + # def list_top_level_items( + # self + # ) -> List[Union[Job, Session]]: + # """ + # Get a list of top level items for the given workspace, + # which can be standalone Jobs (Jobs not associated with a Session) + # or Sessions (which can contain Jobs). + + # :return: List of Workspace top level Jobs or Sessions. + # :rtype: typing.List[typing.Union[Job, Session]] + # """ + # client = self._get_top_level_items_client() + # item_details_list = client.list() + # result = [WorkspaceItemFactory.__new__(workspace=self, item_details=item_details) + # for item_details in item_details_list] + # return result + + # def list_sessions( + # self + # ) -> List[Session]: + # """ + # Get the list of sessions in the given workspace. + + # :return: List of Workspace Sessions. + # :rtype: typing.List[Session] + # """ + # client = self._get_sessions_client() + # session_details_list = client.list() + # result = [Session(workspace=self,details=session_details) + # for session_details in session_details_list] + # return result + + # def open_session( + # self, + # session: Session, + # ) -> None: + # """ + # Opens/creates a session in the given workspace. + + # :param session: + # The session to be opened/created. + + # :return: A new open Azure Quantum Session. + # :rtype: Session + # """ + # client = self._get_sessions_client() + # session.details = client.open( + # session_id=session.id, + # session=session.details) + + # def close_session( + # self, + # session: Session + # ) -> None: + # """ + # Closes a session in the given workspace if the + # session is not in a terminal state. + # Otherwise, just refreshes the session details. + + # :param session: + # The session to be closed. + # """ + # client = self._get_sessions_client() + # if not session.is_in_terminal_state(): + # session.details = client.close(session_id=session.id) + # else: + # session.details = client.get(session_id=session.id) + + # if session.target: + # if (session.target.latest_session + # and session.target.latest_session.id == session.id): + # session.target.latest_session.details = session.details + + # def refresh_session( + # self, + # session: Session + # ) -> None: + # """ + # Updates the session details with the latest information + # from the workspace. + + # :param session: + # The session to be refreshed. + # """ + # session.details = self.get_session(session_id=session.id).details + + # def get_session( + # self, + # session_id: str + # ) -> Session: + # """ + # Gets a session from the workspace. + + # :param session_id: + # The id of session to be retrieved. + + # :return: Azure Quantum Session + # :rtype: Session + # """ + # client = self._get_sessions_client() + # session_details = client.get(session_id=session_id) + # result = Session(workspace=self, details=session_details) + # return result + + # def list_session_jobs( + # self, + # session_id: str + # ) -> List[Job]: + # """ + # Gets all jobs associated with a session. + + # :param session_id: + # The id of session. + + # :return: List of all jobs associated with a session. + # :rtype: typing.List[Job] + # """ + # client = self._get_sessions_client() + # job_details_list = client.jobs_list(session_id=session_id) + # result = [Job(workspace=self, job_details=job_details) + # for job_details in job_details_list] + # return result + + def get_container_uri( + self, + job_id: Optional[str] = None, + container_name: Optional[str] = None, + container_name_format: Optional[str] = "job-{job_id}" + ) -> str: + """ + Get container URI based on job ID or container name. + Creates a new container if it does not yet exist. + + :param job_id: + Job ID, defaults to `None`. + + :param container_name: + Container name, defaults to `None`. + + :param container_name_format: + Container name format, defaults to "job-{job_id}". + + :return: Container URI. + :rtype: str + """ + if container_name is None: + if job_id is not None: + container_name = container_name_format.format(job_id=job_id) + elif job_id is None: + container_name = f"{self.name}-data" + # Create container URI and get container client + if self.storage is None: + # Get linked storage account from the service, create + # a new container if it does not yet exist + container_uri = self._get_linked_storage_sas_uri( + container_name + ) + container_client = ContainerClient.from_container_url( + container_uri + ) + create_container_using_client(container_client) + else: + # Use the storage acount specified to generate container URI, + # create a new container if it does not yet exist + container_uri = get_container_uri( + self.storage, container_name + ) + return container_uri