-
Notifications
You must be signed in to change notification settings - Fork 3.3k
[OPS Common SDK] Update Communication Common SDK for Teams Phone Extensibility GA #41219
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 16 commits
Commits
Show all changes
108 commits
Select commit
Hold shift + click to select a range
41d2254
Update models.py
cemateia 2ff1cb7
Update models.py
cemateia 16baeaf
Update models.py
cemateia 35c1138
Update phone number identifier
cemateia fbb7f25
add tests
cemateia 94509ef
small updates
cemateia 2e38ae9
Update test_identifier_raw_id.py
cemateia f25083c
Update test_identifier_raw_id.py
cemateia b273592
Update test_identifier_raw_id.py
cemateia 8364393
Create entra_user_credential_async.py
cemateia 5486112
add entra token cred
cemateia 0c3dbd7
add async exchange
cemateia 8a3e58c
Update models.py
cemateia a2db6c1
Update test_identifier_raw_id.py
cemateia 40eaff6
Update test_identifier_raw_id.py
cemateia 295005b
update credential
cemateia 72ff99e
Update entra_user_credential_async.py
cemateia 7325a46
Update entra_user_credential_async.py
cemateia bd8de3e
Update entra_user_credential_async.py
cemateia 5c612ef
Update entra_user_credential_async.py
cemateia cc7158a
Create pipeline_utils.py
cemateia d84645b
Create entra_token_guard_policy.py
cemateia 0fc8830
Create entra_token_credential_options.py
cemateia 61f39c5
Create token_exchange.py
cemateia 5bf5d3e
Update token_exchange.py
cemateia 58c938f
updates
cemateia 5e5f0ae
Update token_exchange.py
cemateia 1b31ec0
Update token_exchange.py
cemateia 409de87
cleanup old files
cemateia 7cb15d5
Update token_exchange.py
cemateia d05f146
Update entra_token_guard_policy.py
cemateia bd6d110
updated credential classes
cemateia 158e856
updates
cemateia b8d7f73
Delete manual_test.py
cemateia cc2060f
Update user_credential.py
cemateia 81fe42e
Copy to all _shared in all sdks
cemateia 8446332
Update sdk/communication/azure-communication-callautomation/azure/com…
cemateia c118907
Update token_exchange.py
cemateia 4080755
Merge branch 'py-ops-updates' of https://github.com/Azure/azure-sdk-f…
cemateia 018c4e5
update version
cemateia df1d4a7
Fix imports
cemateia 4e3f980
Fix imports in all folders
cemateia 4541dde
Fix test
cemateia 0b580b8
Update test_identifier_raw_id.py
cemateia 25d5da8
Update dev_requirements.txt
cemateia 6d97f10
try to fix conflict in pipeline
cemateia ddf5b15
try to fix conflict in pipeline 2
cemateia d43ad33
Update setup.py
cemateia e19c09d
try to fix call automation
cemateia 7c27078
remove references
cemateia d04ef18
expose the identifiers
cemateia e7bb955
Update documentation for credential to include the optional params
cemateia 87c79eb
Delete manual_test.py
cemateia 8304e74
Update _version.py
cemateia 3d122ea
fix comment to default the cloud
cemateia d6b9405
fix comments for phone number properties
cemateia 66321e2
fix path
cemateia a2e8550
Update CHANGELOG.md
cemateia c53b9e5
fix cloud param
cemateia 6d6341b
fix comment
cemateia 7323cc8
Create test_entra_token_guard_policy.py
cemateia adec6c7
fix for cloud param
cemateia 5258c20
Add tests for token exchange
cemateia 7c8fd0a
add tests for credential
cemateia c50ea4b
update test
cemateia 4fbb8b3
Update test_user_credential_async.py
cemateia 65443e3
add check in async cred
cemateia 578f980
fix cloud
cemateia 832d7de
update not required
cemateia 55f6698
Update test_identifier_raw_id.py
cemateia 5fe60a7
fix passing scopes
cemateia 35e4853
copy paste from identity
cemateia 7d2afff
fix space
cemateia 70ccb7f
fix sending scopes
cemateia a11f401
Update test_token_exchange.py
cemateia 56b5d45
fix spaces for doc
cemateia f319c69
fix pylint errors
cemateia 197ff99
fix pylint error in model
cemateia 56a0fd2
fix props in phone number
cemateia 4543764
fix dateutil import
cemateia 174edd7
update init of asserted_id
cemateia 6bfbcb6
replace none with ""
cemateia 9b2c46b
update models phone number
cemateia 4d4aa29
fix some pylint errors: format
cemateia 05f635e
split files
cemateia 9539b94
pylint fixes
cemateia 6425438
pylint call automation
cemateia dafbd3b
pylint for all
cemateia 964f4b2
fix some pylint warnings
cemateia 6b9c117
fix last warnings in identity
cemateia 30c21b8
update all
cemateia ebab4bd
update token exchange
cemateia eecd4ec
update credential for all sdks
cemateia cfdc33c
fix comments
cemateia a534f28
add some tests
cemateia 5043cf1
fix tests
cemateia bb32643
fix some comments
cemateia 5d9b73f
fix comments
cemateia 134fb54
copy in all sdks
cemateia 343fcf6
fix include
cemateia b80bcb7
fix import
cemateia dc50027
fix tests
cemateia 0076a93
fix comments
cemateia dc0684a
fix analysis warnings
cemateia 71a6b8b
fix mypy
cemateia b6b4f3a
fix pylint
cemateia 9179ccb
fix mypy
cemateia 1a045af
fix optional scopes
cemateia File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
48 changes: 48 additions & 0 deletions
48
...azure-communication-identity/azure/communication/identity/_shared/entra_token_exchange.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| # coding=utf-8 | ||
| # ------------------------------------ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
| # ------------------------------------ | ||
|
|
||
| from typing import Any, Optional | ||
| from azure.core.credentials import AccessToken | ||
| import requests | ||
| import threading | ||
|
|
||
|
|
||
| class EntraTokenExchangeClient(object): | ||
| """Client for exchanging a customer-provided Entra ID token for a new user access token via the TeamsExtension token exchange endpoint. | ||
|
|
||
| :param str endpoint: The endpoint URL for the token exchange service. | ||
| :param str customer_token: The Entra ID token provided by the customer, used for authentication. | ||
| """ | ||
|
|
||
| def __init__(self, endpoint: str, customer_token: str, **kwargs: Any) -> None: | ||
| if not isinstance(endpoint, str) or not endpoint: | ||
| raise ValueError("Endpoint must be a non-empty string.") | ||
| if not isinstance(customer_token, str) or not customer_token: | ||
| raise ValueError("Customer token must be a non-empty string.") | ||
| self._endpoint = endpoint | ||
| self._customer_token = customer_token | ||
| self._lock = threading.Lock() # Add a lock for thread safety | ||
|
|
||
| def exchange_token(self, **kwargs: Any) -> AccessToken: | ||
| """Exchanges the customer-provided Entra ID token for a new user access token. | ||
|
|
||
| :return: An AccessToken instance containing the new user access token and its expiration. | ||
| :rtype: ~azure.core.credentials.AccessToken | ||
| """ | ||
| with self._lock: | ||
| response = requests.post( | ||
| self._endpoint, | ||
| headers={ | ||
| "Authorization": f"Bearer {self._customer_token}", | ||
| "Content-Type": "application/json", | ||
| "Accept": "application/json", | ||
| }, | ||
| json=kwargs.get("payload", {}), | ||
| timeout=30, | ||
| ) | ||
| response.raise_for_status() | ||
| token_data = response.json() | ||
| return AccessToken(token_data["accessToken"]["token"], token_data["accessToken"]["expiresOn"]) |
49 changes: 49 additions & 0 deletions
49
...communication-identity/azure/communication/identity/_shared/entra_token_exchange_async.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| # coding=utf-8 | ||
| # ------------------------------------ | ||
| # Copyright (c) Microsoft Corporation. | ||
| # Licensed under the MIT License. | ||
| # ------------------------------------ | ||
|
|
||
| from typing import Any | ||
| from azure.core.credentials import AccessToken | ||
| import aiohttp | ||
| import asyncio | ||
|
|
||
|
|
||
| class EntraTokenExchangeClientAsync(object): | ||
| """Async client for exchanging a customer-provided Entra ID token for a new user access token via the TeamsExtension token exchange endpoint. | ||
|
|
||
| :param str endpoint: The endpoint URL for the token exchange service. | ||
| :param str customer_token: The Entra ID token provided by the customer, used for authentication. | ||
| """ | ||
|
|
||
| def __init__(self, endpoint: str, customer_token: str, **kwargs: Any) -> None: | ||
| if not isinstance(endpoint, str) or not endpoint: | ||
| raise ValueError("Endpoint must be a non-empty string.") | ||
| if not isinstance(customer_token, str) or not customer_token: | ||
| raise ValueError("Customer token must be a non-empty string.") | ||
| self._endpoint = endpoint | ||
| self._customer_token = customer_token | ||
| self._lock = asyncio.Lock() # Async lock for thread safety | ||
|
|
||
| async def exchange_token(self, **kwargs: Any) -> AccessToken: | ||
| """Asynchronously exchanges the customer-provided Entra ID token for a new user access token. | ||
|
|
||
| :return: An AccessToken instance containing the new user access token and its expiration. | ||
| :rtype: ~azure.core.credentials.AccessToken | ||
| """ | ||
| async with self._lock: | ||
| async with aiohttp.ClientSession() as session: | ||
| async with session.post( | ||
| self._endpoint, | ||
| headers={ | ||
| "Authorization": f"Bearer {self._customer_token}", | ||
| "Content-Type": "application/json", | ||
| "Accept": "application/json", | ||
| }, | ||
| json=kwargs.get("payload", {}), | ||
| timeout=30, | ||
| ) as response: | ||
| response.raise_for_status() | ||
| token_data = await response.json() | ||
| return AccessToken(token_data["accessToken"]["token"], token_data["accessToken"]["expiresOn"]) |
192 changes: 192 additions & 0 deletions
192
...ommunication-identity/azure/communication/identity/_shared/entra_user_credential_async.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,192 @@ | ||
| # ------------------------------------------------------------------------- | ||
| # Copyright (c) Microsoft Corporation. All rights reserved. | ||
| # Licensed under the MIT License. See License.txt in the project root for | ||
| # license information. | ||
| # -------------------------------------------------------------------------- | ||
| # pylint: disable=C4763 | ||
| from asyncio import Condition, Lock, Event | ||
| from datetime import timedelta | ||
| from typing import Any, Optional | ||
| import sys | ||
|
|
||
| from .utils import get_current_utc_as_int | ||
| from .utils import create_access_token | ||
| from .utils_async import AsyncTimer | ||
| from azure.core.credentials import AccessToken | ||
| from entra_token_exchange_async import EntraTokenExchangeClientAsync | ||
| from entra_communication_token_credential_options import EntraCommunicationTokenCredentialOptions | ||
| from typing import List, Optional | ||
| from azure.core.credentials import TokenCredential | ||
|
|
||
| class EntraCommunicationTokenCredentialOptions: | ||
| """Options for EntraCommunicationTokenCredential. | ||
|
|
||
| :param str resource_endpoint: The Azure Communication Service resource endpoint URL, | ||
| e.g. https://myResource.communication.azure.com. | ||
| :param ~azure.core.credentials.AsyncTokenCredential token_credential: The Entra ID token credential. | ||
| :param list[str] scopes: The scopes for retrieving the Entra ID access token. | ||
| """ | ||
|
|
||
| def __init__( | ||
| self, | ||
| resource_endpoint: str, | ||
| token_credential: AsyncTokenCredential, | ||
| scopes: Optional[List[str]] = None, | ||
| ) -> None: | ||
|
|
||
| if not resource_endpoint: | ||
| raise ValueError("resource_endpoint cannot be empty") | ||
| if not token_credential: | ||
| raise ValueError("token_credential cannot be None") | ||
|
|
||
| self.resource_endpoint = resource_endpoint | ||
| self.token_credential = token_credential | ||
| self.scopes = scopes or ["https://communication.azure.com/clients/.default"] | ||
|
|
||
| class EntraTokenCredential(object): | ||
| """Credential type used for authenticating to an Azure Communication service via Entra ID. | ||
| The provided token will be exchanged for another token used for authentication. | ||
| :param str token: The token to be exchanged. | ||
| :keyword token_refresher: The async token refresher to provide capacity to fetch a fresh token. | ||
| :paramtype token_refresher: Callable[[], Awaitable[AccessToken]] | ||
| :keyword bool proactive_refresh: Whether to refresh the token proactively or not. | ||
| """ | ||
|
|
||
| _ON_DEMAND_REFRESHING_INTERVAL_MINUTES = 2 | ||
| _DEFAULT_AUTOREFRESH_INTERVAL_MINUTES = 10 | ||
|
|
||
| def __init__(self, options: EntraCommunicationTokenCredentialOptions, **kwargs: Any): | ||
| if options is None: | ||
| raise ValueError("Options must be provided.") | ||
| self._token_refresher = kwargs.pop("token_refresher", None) | ||
| self._proactive_refresh = kwargs.pop("proactive_refresh", False) | ||
| if self._proactive_refresh and self._token_refresher is None: | ||
| raise ValueError("When 'proactive_refresh' is True, 'token_refresher' must not be None.") | ||
| self._timer = None | ||
| self._async_mutex = Lock() | ||
| if sys.version_info[:3] == (3, 10, 0): | ||
| # Workaround for Python 3.10 bug(https://bugs.python.org/issue45416): | ||
| getattr(self._async_mutex, "_get_loop", lambda: None)() | ||
| self._lock = Condition(self._async_mutex) | ||
| self._some_thread_refreshing = False | ||
| self._is_closed = Event() | ||
| self._token: AccessToken # This will be set after exchange | ||
| self._original_token: str = None | ||
|
|
||
| async def get_token(self, *scopes, **kwargs): # pylint: disable=unused-argument | ||
| """Returns the exchanged token.""" | ||
| if self._proactive_refresh and self._is_closed.is_set(): | ||
| raise RuntimeError("An instance of EntraTokenCredential cannot be reused once it has been closed.") | ||
|
|
||
| if self._token is None: | ||
| self._original_token = await self._get_entra_token(options.token_credential, options.scopes) | ||
| self._token = await self._exchange_token(self._original_token) | ||
|
|
||
| if not self._token_refresher or not self._is_token_expiring_soon(self._token): | ||
| return self._token | ||
| await self._update_token_and_reschedule() | ||
| return self._token | ||
|
|
||
| async def _get_entra_token(self, token_credential, scopes): | ||
| """ | ||
| Helper method to get a token from the provided token_credential and scopes. | ||
| """ | ||
| token = await token_credential.get_token(*scopes) | ||
| return token.token | ||
|
|
||
| async def _exchange_token(self, original_token): | ||
| """Exchanges the original token for a new token using EntraTokenExchangeClientAsync.""" | ||
|
|
||
| # Instantiate the async client with the endpoint and original token | ||
| endpoint = "" # TO BE DONE | ||
|
|
||
| client = EntraTokenExchangeClientAsync(endpoint, original_token) | ||
| # Optionally, you can pass additional payload via kwargs if needed | ||
| token = await client.exchange_token() | ||
| return AccessToken(token.token, token.expires_on) | ||
|
|
||
| async def _update_token_and_reschedule(self): | ||
| should_this_thread_refresh = False | ||
| async with self._lock: | ||
| while self._is_token_expiring_soon(self._token): | ||
| if self._some_thread_refreshing: | ||
| if self._is_token_valid(self._token): | ||
| return self._token | ||
| await self._wait_till_lock_owner_finishes_refreshing() | ||
| else: | ||
| should_this_thread_refresh = True | ||
| self._some_thread_refreshing = True | ||
| break | ||
|
|
||
| if should_this_thread_refresh: | ||
| try: | ||
| new_options = await self._token_refresher() | ||
| new_entra_token = await self._get_entra_token(new_options.token_credential, new_options.scopes) | ||
| new_token = await self._exchange_token(new_entra_token) | ||
|
|
||
cemateia marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if not self._is_token_valid(new_token): | ||
| raise ValueError("The token returned from the token_refresher is expired.") | ||
| async with self._lock: | ||
| self._original_token = new_entra_token | ||
| self._token = new_token | ||
| self._some_thread_refreshing = False | ||
| self._lock.notify_all() | ||
| except: | ||
| async with self._lock: | ||
| self._some_thread_refreshing = False | ||
| self._lock.notify_all() | ||
| raise | ||
| if self._proactive_refresh: | ||
| self._schedule_refresh() | ||
| return self._token | ||
|
|
||
| def _schedule_refresh(self): | ||
| if self._is_closed.is_set(): | ||
| return | ||
| if self._timer is not None: | ||
| self._timer.cancel() | ||
|
|
||
| token_ttl = self._token.expires_on - get_current_utc_as_int() | ||
|
|
||
| if self._is_token_expiring_soon(self._token): | ||
| # Schedule the next refresh for when it reaches a certain percentage of the remaining lifetime. | ||
| timespan = token_ttl // 2 | ||
| else: | ||
| # Schedule the next refresh for when it gets in to the soon-to-expire window. | ||
| timespan = token_ttl - timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES).total_seconds() | ||
|
|
||
| self._timer = AsyncTimer(timespan, self._update_token_and_reschedule) | ||
| self._timer.start() | ||
|
|
||
| async def _wait_till_lock_owner_finishes_refreshing(self): | ||
| self._lock.release() | ||
| await self._lock.acquire() | ||
|
|
||
| def _is_token_expiring_soon(self, token): | ||
| if self._proactive_refresh: | ||
| interval = timedelta(minutes=self._DEFAULT_AUTOREFRESH_INTERVAL_MINUTES) | ||
| else: | ||
| interval = timedelta(minutes=self._ON_DEMAND_REFRESHING_INTERVAL_MINUTES) | ||
| return (token.expires_on - get_current_utc_as_int()) < interval.total_seconds() | ||
|
|
||
| @classmethod | ||
| def _is_token_valid(cls, token): | ||
| return get_current_utc_as_int() < token.expires_on | ||
|
|
||
| async def __aenter__(self): | ||
| if self._proactive_refresh: | ||
| if self._is_closed.is_set(): | ||
| raise RuntimeError( | ||
| "An instance of EntraTokenCredential cannot be reused once it has been closed." | ||
| ) | ||
| self._schedule_refresh() | ||
| return self | ||
|
|
||
| async def __aexit__(self, *args): | ||
| await self.close() | ||
|
|
||
| async def close(self) -> None: | ||
| if self._timer is not None: | ||
| self._timer.cancel() | ||
| self._timer = None | ||
| self._is_closed.set() | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.