diff --git a/eng/.docsettings.yml b/eng/.docsettings.yml index 3326fd1725b3..eb2a71c2cced 100644 --- a/eng/.docsettings.yml +++ b/eng/.docsettings.yml @@ -153,6 +153,7 @@ known_content_issues: - ['sdk/appconfiguration/azure-appconfiguration/swagger/README.md', '#4554'] - ['sdk/core/azure-core/tests/testserver_tests/coretestserver/README.md', '#4554'] - ['sdk/core/azure-core-experimental/README.md', '#4554'] + - ['sdk/identity/azure-identity-broker/README.md', '#4554'] package_indexing_exclusion_list: - 'azure-sdk-tools' - 'azure-template' diff --git a/sdk/identity/azure-identity-broker/CHANGELOG.md b/sdk/identity/azure-identity-broker/CHANGELOG.md new file mode 100644 index 000000000000..3b59ec910a83 --- /dev/null +++ b/sdk/identity/azure-identity-broker/CHANGELOG.md @@ -0,0 +1,14 @@ +# Release History + +## 1.0.0b1 (Unreleased) + +### Features Added + +- Added `azure.identity.broker.InteractiveBrowserBrokerCredential` + and `azure.identity.broker.UsernamePasswordBrokerCredential` which have broker support. + +### Breaking Changes + +### Bugs Fixed + +### Other Changes diff --git a/sdk/identity/azure-identity-broker/LICENSE b/sdk/identity/azure-identity-broker/LICENSE new file mode 100644 index 000000000000..63447fd8bbbf --- /dev/null +++ b/sdk/identity/azure-identity-broker/LICENSE @@ -0,0 +1,21 @@ +Copyright (c) Microsoft Corporation. + +MIT License + +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. \ No newline at end of file diff --git a/sdk/identity/azure-identity-broker/MANIFEST.in b/sdk/identity/azure-identity-broker/MANIFEST.in new file mode 100644 index 000000000000..e75c8caa6879 --- /dev/null +++ b/sdk/identity/azure-identity-broker/MANIFEST.in @@ -0,0 +1,6 @@ +recursive-include samples *.py +recursive-include tests *.py +include *.md +include LICENSE +include azure/__init__.py +include azure/identity/broker/py.typed diff --git a/sdk/identity/azure-identity-broker/README.md b/sdk/identity/azure-identity-broker/README.md new file mode 100644 index 000000000000..13224c5c4d4b --- /dev/null +++ b/sdk/identity/azure-identity-broker/README.md @@ -0,0 +1,43 @@ + + +# Azure Identity Broker plugin for Python + +## Getting started + +### Install the package + +Install the Azure Identity Broker plugin for Python with [pip](https://pypi.org/project/pip/): + +```bash +pip install azure-identity-broker +``` + + +## Examples + +Now you can create `azure.identity.broker.InteractiveBrowserCredential` and `azure.identity.broker.UsernamePasswordCredential` with broker support. + +```python + +import win32gui +from azure.identity.broker import InteractiveBrowserCredential + +# Get the handle of the current window +current_window_handle = win32gui.GetForegroundWindow() + +credential = InteractiveBrowserCredential(allow_broker=True, parent_window_handle=current_window_handle) +``` + + +## Troubleshooting + +This client raises exceptions defined in [Azure Core](https://learn.microsoft.com/python/api/azure-core/azure.core.exceptions?view=azure-python). + + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us the rights to use your contribution. For details, visit https://cla.microsoft.com. + +When you submit a pull request, a CLA-bot will automatically determine whether you need to provide a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions provided by the bot. You will only need to do this once across all repos using our CLA. + +This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. diff --git a/sdk/identity/azure-identity-broker/azure/__init__.py b/sdk/identity/azure-identity-broker/azure/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/identity/azure-identity-broker/azure/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/identity/azure-identity-broker/azure/identity/__init__.py b/sdk/identity/azure-identity-broker/azure/identity/__init__.py new file mode 100644 index 000000000000..d55ccad1f573 --- /dev/null +++ b/sdk/identity/azure-identity-broker/azure/identity/__init__.py @@ -0,0 +1 @@ +__path__ = __import__("pkgutil").extend_path(__path__, __name__) # type: ignore diff --git a/sdk/identity/azure-identity-broker/azure/identity/broker/__init__.py b/sdk/identity/azure-identity-broker/azure/identity/broker/__init__.py new file mode 100644 index 000000000000..8ac5cf563c93 --- /dev/null +++ b/sdk/identity/azure-identity-broker/azure/identity/broker/__init__.py @@ -0,0 +1,12 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from ._browser import InteractiveBrowserBrokerCredential +from ._user_password import UsernamePasswordBrokerCredential + + +__all__ = [ + "InteractiveBrowserBrokerCredential", + "UsernamePasswordBrokerCredential", +] diff --git a/sdk/identity/azure-identity-broker/azure/identity/broker/_browser.py b/sdk/identity/azure-identity-broker/azure/identity/broker/_browser.py new file mode 100644 index 000000000000..da9969441d81 --- /dev/null +++ b/sdk/identity/azure-identity-broker/azure/identity/broker/_browser.py @@ -0,0 +1,135 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +import socket +from typing import Dict, Any +import msal + +from azure.core.exceptions import ClientAuthenticationError +from azure.identity._credentials import ( + InteractiveBrowserCredential as _InteractiveBrowserCredential, +) # pylint:disable=protected-access +from azure.identity._exceptions import CredentialUnavailableError # pylint:disable=protected-access +from azure.identity._internal.utils import within_dac # pylint:disable=protected-access +from ._utils import wrap_exceptions, resolve_tenant + + +class InteractiveBrowserBrokerCredential(_InteractiveBrowserCredential): + """Opens a browser to interactively authenticate a user. + + :func:`~get_token` opens a browser to a login URL provided by Azure Active Directory 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 an Azure Active Directory 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: an Azure Active Directory tenant ID. Defaults to the "organizations" tenant, which can + authenticate work or school accounts. + :keyword str client_id: Client ID of the Azure Active Directory application users will sign in to. If + unspecified, users will authenticate to an Azure development application. + :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 allow_broker: An authentication broker is an application that runs on a user's machine that manages + the authentication handshakes and token maintenance for connected accounts. The Windows operating system uses + the Web Account Manager (WAM) as its authentication broker. If this parameter is set to True, the broker will + be used when possible. Defaults to False. + Check https://learn.microsoft.com/azure/active-directory/develop/scenario-desktop-acquire-token-wam for more + information about WAM. + :keyword int parent_window_handle: If your app is a GUI app running on a modern Windows system, + and your app opts in to use broker via `allow_broker`, you are required to also provide its window handle, + so that the sign in UI window will properly pop up on top of your window. + :keyword bool enable_msa_passthrough: Determines whether Microsoft Account (MSA) passthrough is enabled. Note, this + is only needed for select legacy first-party applications. 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. + :raises ValueError: invalid **redirect_uri** + """ + + def __init__(self, **kwargs: Any) -> None: + self._allow_broker = kwargs.pop("allow_broker", None) + self._parent_window_handle = kwargs.pop("parent_window_handle", None) + self._enable_msa_passthrough = kwargs.pop("enable_msa_passthrough", False) + super().__init__(**kwargs) + + @wrap_exceptions + def _request_token(self, *scopes: str, **kwargs: Any) -> Dict: + scopes = list(scopes) # type: ignore + claims = kwargs.get("claims") + app = self._get_app(**kwargs) + port = self._parsed_url.port if self._parsed_url else None + + try: + result = app.acquire_token_interactive( + scopes=scopes, + login_hint=self._login_hint, + claims_challenge=claims, + timeout=self._timeout, + prompt="select_account", + port=port, + parent_window_handle=self._parent_window_handle, + enable_msa_passthrough=self._enable_msa_passthrough, + ) + except socket.error as ex: + raise CredentialUnavailableError(message="Couldn't start an HTTP server.") from ex + if "access_token" not in result and "error_description" in result: + if within_dac.get(): + raise CredentialUnavailableError(message=result["error_description"]) + raise ClientAuthenticationError(message=result.get("error_description")) + if "access_token" not in result: + if within_dac.get(): + raise CredentialUnavailableError(message="Failed to authenticate user") + raise ClientAuthenticationError(message="Failed to authenticate user") + + # base class will raise for other errors + return result + + 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: + 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, + allow_broker=self._allow_broker, + ) + + return client_applications_map[tenant_id] diff --git a/sdk/identity/azure-identity-broker/azure/identity/broker/_user_password.py b/sdk/identity/azure-identity-broker/azure/identity/broker/_user_password.py new file mode 100644 index 000000000000..b159c61b13ca --- /dev/null +++ b/sdk/identity/azure-identity-broker/azure/identity/broker/_user_password.py @@ -0,0 +1,100 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import Any +import msal +from azure.identity._credentials import ( + UsernamePasswordCredential as _UsernamePasswordCredential, +) # pylint:disable=protected-access +from ._utils import resolve_tenant + + +class UsernamePasswordBrokerCredential(_UsernamePasswordCredential): + """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 `Azure Active Directory 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 an Azure Active Directory 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 Azure Active Directory 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 bool allow_broker: An authentication broker is an application that runs on a user's machine that manages + the authentication handshakes and token maintenance for connected accounts. The Windows operating system uses + the Web Account Manager (WAM) as its authentication broker. If this parameter is set to True, the broker will + be used when possible. Defaults to False. + Check https://learn.microsoft.com/azure/active-directory/develop/scenario-desktop-acquire-token-wam for more + information about WAM. + :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 __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. + self._allow_broker = kwargs.pop("allow_broker", None) + super(UsernamePasswordBrokerCredential, self).__init__( + client_id=client_id, username=username, password=password, **kwargs + ) + + 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: + 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, + allow_broker=self._allow_broker, + ) + + return client_applications_map[tenant_id] diff --git a/sdk/identity/azure-identity-broker/azure/identity/broker/_utils.py b/sdk/identity/azure-identity-broker/azure/identity/broker/_utils.py new file mode 100644 index 000000000000..861cf94a65d3 --- /dev/null +++ b/sdk/identity/azure-identity-broker/azure/identity/broker/_utils.py @@ -0,0 +1,76 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from typing import List, Optional +import os +import functools +import logging +from azure.core.exceptions import ClientAuthenticationError + + +_LOGGER = logging.getLogger(__name__) + + +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 + + +def resolve_tenant( + default_tenant: str, tenant_id: Optional[str] = None, *, additionally_allowed_tenants: List[str] = [], **_ +) -> 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("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 "*" 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/sdk/identity/azure-identity-broker/azure/identity/broker/_version.py b/sdk/identity/azure-identity-broker/azure/identity/broker/_version.py new file mode 100644 index 000000000000..a4040f093c86 --- /dev/null +++ b/sdk/identity/azure-identity-broker/azure/identity/broker/_version.py @@ -0,0 +1,5 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +VERSION = "1.0.0b1" diff --git a/sdk/identity/azure-identity-broker/azure/identity/broker/py.typed b/sdk/identity/azure-identity-broker/azure/identity/broker/py.typed new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/sdk/identity/azure-identity-broker/dev_requirements.txt b/sdk/identity/azure-identity-broker/dev_requirements.txt new file mode 100644 index 000000000000..bf7aa75ff55e --- /dev/null +++ b/sdk/identity/azure-identity-broker/dev_requirements.txt @@ -0,0 +1,6 @@ +../../core/azure-core +aiohttp>=3.0 +typing_extensions>=3.7.2 +-e ../../../tools/azure-sdk-tools +-e ../../../tools/azure-devtools +cryptography<=40.0.2 \ No newline at end of file diff --git a/sdk/identity/azure-identity-broker/pyproject.toml b/sdk/identity/azure-identity-broker/pyproject.toml new file mode 100644 index 000000000000..e68e9286f132 --- /dev/null +++ b/sdk/identity/azure-identity-broker/pyproject.toml @@ -0,0 +1,4 @@ +[tool.azure-sdk-build] +type_check_samples = false +verifytypes = false +pyright = false diff --git a/sdk/identity/azure-identity-broker/sdk_packaging.toml b/sdk/identity/azure-identity-broker/sdk_packaging.toml new file mode 100644 index 000000000000..e7687fdae93b --- /dev/null +++ b/sdk/identity/azure-identity-broker/sdk_packaging.toml @@ -0,0 +1,2 @@ +[packaging] +auto_update = false \ No newline at end of file diff --git a/sdk/identity/azure-identity-broker/setup.py b/sdk/identity/azure-identity-broker/setup.py new file mode 100644 index 000000000000..8969353fe819 --- /dev/null +++ b/sdk/identity/azure-identity-broker/setup.py @@ -0,0 +1,68 @@ +#!/usr/bin/env python + +# ------------------------------------------------------------------------- +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. See License.txt in the project root for +# license information. +# -------------------------------------------------------------------------- + +import re +import os.path +from io import open +from setuptools import find_packages, setup # type: ignore + +# Change the PACKAGE_NAME only to change folder and different name +PACKAGE_NAME = "azure-identity-broker" +PACKAGE_PPRINT_NAME = "Identity Broker plugin" + +package_folder_path = "azure/identity/broker" + +# Version extraction inspired from 'requests' +with open(os.path.join(package_folder_path, "_version.py"), "r") as fd: + version = re.search(r'^VERSION\s*=\s*[\'"]([^\'"]*)[\'"]', fd.read(), re.MULTILINE).group(1) # type: ignore + +if not version: + raise RuntimeError("Cannot find version information") + +with open("README.md", encoding="utf-8") as f: + readme = f.read() +with open("CHANGELOG.md", encoding="utf-8") as f: + changelog = f.read() + +setup( + name=PACKAGE_NAME, + version=version, + description="Microsoft Azure {} for Python".format(PACKAGE_PPRINT_NAME), + long_description=readme + "\n\n" + changelog, + long_description_content_type="text/markdown", + license="MIT License", + author="Microsoft Corporation", + author_email="azpysdkhelp@microsoft.com", + url="https://github.com/Azure/azure-sdk-for-python/tree/main/sdk/identity/azure-identity-broker", + keywords="azure, azure sdk", + classifiers=[ + "Development Status :: 4 - Beta", + "Programming Language :: Python", + "Programming Language :: Python :: 3 :: Only", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.7", + "Programming Language :: Python :: 3.8", + "Programming Language :: Python :: 3.9", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "License :: OSI Approved :: MIT License", + ], + zip_safe=False, + packages=[ + "azure.identity.broker", + ], + include_package_data=True, + package_data={ + "pytyped": ["py.typed"], + }, + python_requires=">=3.7", + install_requires=[ + "azure-identity<2.0.0,>=1.14.0", + "msal[broker]>=1.20,<2", + ], +) diff --git a/sdk/identity/azure-identity-broker/tests/conftest.py b/sdk/identity/azure-identity-broker/tests/conftest.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/sdk/identity/azure-identity-broker/tests/test_broker.py b/sdk/identity/azure-identity-broker/tests/test_broker.py new file mode 100644 index 000000000000..07ad81c2022e --- /dev/null +++ b/sdk/identity/azure-identity-broker/tests/test_broker.py @@ -0,0 +1,31 @@ +# ------------------------------------ +# Copyright (c) Microsoft Corporation. +# Licensed under the MIT License. +# ------------------------------------ +from azure.identity.broker import InteractiveBrowserBrokerCredential, UsernamePasswordBrokerCredential + + +def test_interactive_browser_cred_with_broker(): + cred = InteractiveBrowserBrokerCredential(allow_broker=True) + assert cred._allow_broker + + +def test_interactive_browser_cred_without_broker(): + cred = InteractiveBrowserBrokerCredential() + assert not cred._allow_broker + + cred = InteractiveBrowserBrokerCredential(allow_broker=False) + assert not cred._allow_broker + + +def test_username_password_cred_with_broker(): + cred = UsernamePasswordBrokerCredential("client-id", "username", "password", allow_broker=True) + assert cred._allow_broker + + +def test_username_password_cred_without_broker(): + cred = UsernamePasswordBrokerCredential("client-id", "username", "password") + assert not cred._allow_broker + + cred = UsernamePasswordBrokerCredential("client-id", "username", "password", allow_broker=False) + assert not cred._allow_broker