Skip to content
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
108 commits
Select commit Hold shift + click to select a range
41d2254
Update models.py
cemateia May 20, 2025
2ff1cb7
Update models.py
cemateia May 20, 2025
16baeaf
Update models.py
cemateia May 20, 2025
35c1138
Update phone number identifier
cemateia May 21, 2025
fbb7f25
add tests
cemateia May 21, 2025
94509ef
small updates
cemateia May 22, 2025
2e38ae9
Update test_identifier_raw_id.py
cemateia May 22, 2025
f25083c
Update test_identifier_raw_id.py
cemateia May 22, 2025
b273592
Update test_identifier_raw_id.py
cemateia May 22, 2025
8364393
Create entra_user_credential_async.py
cemateia May 22, 2025
5486112
add entra token cred
cemateia May 22, 2025
0c3dbd7
add async exchange
cemateia May 22, 2025
8a3e58c
Update models.py
cemateia May 23, 2025
a2db6c1
Update test_identifier_raw_id.py
cemateia May 23, 2025
40eaff6
Update test_identifier_raw_id.py
cemateia May 26, 2025
295005b
update credential
cemateia May 26, 2025
72ff99e
Update entra_user_credential_async.py
cemateia May 26, 2025
7325a46
Update entra_user_credential_async.py
cemateia May 26, 2025
bd8de3e
Update entra_user_credential_async.py
cemateia May 26, 2025
5c612ef
Update entra_user_credential_async.py
cemateia May 26, 2025
cc7158a
Create pipeline_utils.py
cemateia May 27, 2025
d84645b
Create entra_token_guard_policy.py
cemateia May 28, 2025
0fc8830
Create entra_token_credential_options.py
cemateia May 28, 2025
61f39c5
Create token_exchange.py
cemateia May 28, 2025
5bf5d3e
Update token_exchange.py
cemateia May 28, 2025
58c938f
updates
cemateia May 28, 2025
5e5f0ae
Update token_exchange.py
cemateia May 28, 2025
1b31ec0
Update token_exchange.py
cemateia May 28, 2025
409de87
cleanup old files
cemateia May 28, 2025
7cb15d5
Update token_exchange.py
cemateia May 28, 2025
d05f146
Update entra_token_guard_policy.py
cemateia May 28, 2025
bd6d110
updated credential classes
cemateia May 28, 2025
158e856
updates
cemateia May 28, 2025
b8d7f73
Delete manual_test.py
cemateia May 28, 2025
cc2060f
Update user_credential.py
cemateia Jun 2, 2025
81fe42e
Copy to all _shared in all sdks
cemateia Jun 2, 2025
8446332
Update sdk/communication/azure-communication-callautomation/azure/com…
cemateia Jun 2, 2025
c118907
Update token_exchange.py
cemateia Jun 2, 2025
4080755
Merge branch 'py-ops-updates' of https://github.com/Azure/azure-sdk-f…
cemateia Jun 2, 2025
018c4e5
update version
cemateia Jun 2, 2025
df1d4a7
Fix imports
cemateia Jun 2, 2025
4e3f980
Fix imports in all folders
cemateia Jun 2, 2025
4541dde
Fix test
cemateia Jun 2, 2025
0b580b8
Update test_identifier_raw_id.py
cemateia Jun 2, 2025
25d5da8
Update dev_requirements.txt
cemateia Jun 2, 2025
6d97f10
try to fix conflict in pipeline
cemateia Jun 2, 2025
ddf5b15
try to fix conflict in pipeline 2
cemateia Jun 2, 2025
d43ad33
Update setup.py
cemateia Jun 2, 2025
e19c09d
try to fix call automation
cemateia Jun 3, 2025
7c27078
remove references
cemateia Jun 3, 2025
d04ef18
expose the identifiers
cemateia Jun 3, 2025
e7bb955
Update documentation for credential to include the optional params
cemateia Jun 3, 2025
87c79eb
Delete manual_test.py
cemateia Jun 3, 2025
8304e74
Update _version.py
cemateia Jun 3, 2025
3d122ea
fix comment to default the cloud
cemateia Jun 3, 2025
d6b9405
fix comments for phone number properties
cemateia Jun 3, 2025
66321e2
fix path
cemateia Jun 3, 2025
a2e8550
Update CHANGELOG.md
cemateia Jun 3, 2025
c53b9e5
fix cloud param
cemateia Jun 4, 2025
6d6341b
fix comment
cemateia Jun 4, 2025
7323cc8
Create test_entra_token_guard_policy.py
cemateia Jun 4, 2025
adec6c7
fix for cloud param
cemateia Jun 4, 2025
5258c20
Add tests for token exchange
cemateia Jun 4, 2025
7c8fd0a
add tests for credential
cemateia Jun 4, 2025
c50ea4b
update test
cemateia Jun 4, 2025
4fbb8b3
Update test_user_credential_async.py
cemateia Jun 4, 2025
65443e3
add check in async cred
cemateia Jun 4, 2025
578f980
fix cloud
cemateia Jun 5, 2025
832d7de
update not required
cemateia Jun 6, 2025
55f6698
Update test_identifier_raw_id.py
cemateia Jun 6, 2025
5fe60a7
fix passing scopes
cemateia Jun 10, 2025
35e4853
copy paste from identity
cemateia Jun 10, 2025
7d2afff
fix space
cemateia Jun 10, 2025
70ccb7f
fix sending scopes
cemateia Jun 10, 2025
a11f401
Update test_token_exchange.py
cemateia Jun 10, 2025
56b5d45
fix spaces for doc
cemateia Jun 10, 2025
f319c69
fix pylint errors
cemateia Jun 10, 2025
197ff99
fix pylint error in model
cemateia Jun 10, 2025
56a0fd2
fix props in phone number
cemateia Jun 10, 2025
4543764
fix dateutil import
cemateia Jun 10, 2025
174edd7
update init of asserted_id
cemateia Jun 10, 2025
6bfbcb6
replace none with ""
cemateia Jun 10, 2025
9b2c46b
update models phone number
cemateia Jun 11, 2025
4d4aa29
fix some pylint errors: format
cemateia Jun 11, 2025
05f635e
split files
cemateia Jun 11, 2025
9539b94
pylint fixes
cemateia Jun 11, 2025
6425438
pylint call automation
cemateia Jun 11, 2025
dafbd3b
pylint for all
cemateia Jun 11, 2025
964f4b2
fix some pylint warnings
cemateia Jun 11, 2025
6b9c117
fix last warnings in identity
cemateia Jun 11, 2025
30c21b8
update all
cemateia Jun 11, 2025
ebab4bd
update token exchange
cemateia Jun 13, 2025
eecd4ec
update credential for all sdks
cemateia Jun 13, 2025
cfdc33c
fix comments
cemateia Jun 16, 2025
a534f28
add some tests
cemateia Jun 16, 2025
5043cf1
fix tests
cemateia Jun 16, 2025
bb32643
fix some comments
cemateia Jun 17, 2025
5d9b73f
fix comments
cemateia Jun 17, 2025
134fb54
copy in all sdks
cemateia Jun 17, 2025
343fcf6
fix include
cemateia Jun 17, 2025
b80bcb7
fix import
cemateia Jun 18, 2025
dc50027
fix tests
cemateia Jun 18, 2025
0076a93
fix comments
cemateia Jun 18, 2025
dc0684a
fix analysis warnings
cemateia Jun 18, 2025
71a6b8b
fix mypy
cemateia Jun 18, 2025
b6b4f3a
fix pylint
cemateia Jun 18, 2025
9179ccb
fix mypy
cemateia Jun 18, 2025
1a045af
fix optional scopes
cemateia Jun 19, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,8 @@
PhoneNumberIdentifier,
PhoneNumberProperties,
UnknownIdentifier,
TeamsExtensionUserIdentifier,
TeamsExtensionUserProperties,
)

__all__ = [
Expand All @@ -40,4 +42,6 @@
"PhoneNumberIdentifier",
"PhoneNumberProperties",
"UnknownIdentifier",
"TeamsExtensionUserIdentifier",
"TeamsExtensionUserProperties",
]
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"])
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"])
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)

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()
Loading
Loading