diff --git a/docs/managed-identity-v2.rst b/docs/managed-identity-v2.rst index 567272d5..c5eba04b 100644 --- a/docs/managed-identity-v2.rst +++ b/docs/managed-identity-v2.rst @@ -48,7 +48,8 @@ including cache hits. Bearer-over-mTLS results carry an explicit bearer type and ``binding_certificate=None``. Private key bytes never cross the CNG boundary. Tokens remain opaque in product code. -The public sample supports both modes and bounded worker-backed async requests:: +The public sample supports both modes and bounded worker-backed async +acquisition and resource requests:: python sample\managed_identity_v2.py pop --resource https://vault.azure.net --url https://YOUR-VAULT.vault.azure.net/secrets/NAME?api-version=7.5 python sample\managed_identity_v2.py async-pop --resource https://vault.azure.net --url https://YOUR-VAULT.vault.azure.net/secrets/NAME?api-version=7.5 @@ -70,6 +71,111 @@ It is not an aiohttp integration. Cancellation stops waiting, not the native transaction: worker slots, buffers, the exact binding and cleanup ownership remain held until native work exits. Sessions stay on one event loop. +Async acquisition +----------------- + +``client.open_async_session(max_concurrency=4)`` exposes awaitable +``acquire_token_for_client`` and ``get_managed_identity_capabilities`` methods, +with ``aclose`` and async context management. Only explicit +``mtls_proof_of_possession`` or ``request_over_mtls`` acquisition is supported; +ordinary managed identity routing and existing synchronous API signatures are +unchanged. The v2 refresh behavior below applies to both sync and async calls. +For example, with an existing ``ManagedIdentityClient`` and an approved resource +origin:: + + async def acquire_and_send(client, resource, url): + async with client.open_async_session() as acquisition: + result = await acquisition.acquire_token_for_client( + resource=resource, mtls_proof_of_possession=True) + async with result["binding_certificate"].open_async_session( + resource_origin=url) as transport: + return await transport.get(url, headers={ + "Authorization": result["token_type"] + " " + result["access_token"], + "x-ms-tokenboundauth": "true", + }) + +The acquisition session owns only its worker executor. It shares the original +client's token cache, certificate policy and attestation cache; there is no +separate async token partition. Results, claims challenges, force-refresh +semantics and typed failures are the same as synchronous acquisition. +Returned bindings remain usable after the acquisition session closes. +Keep the caller-supplied synchronous HTTP client open until acquisition work +has drained. The resource session has its own independent concurrency bound. +Both limits accept integers from 1 through 32 and apply per session, not +process-wide. + +Cancellation immediately stops the caller's wait and signals its acquisition +worker. A worker waiting for the v2 policy or attestation lock abandons the +wait; acquisition stages and token retry delays also observe cancellation. +An already-running synchronous HTTP or native call cannot be interrupted. +Its worker slot, native handles and buffers remain occupied until it returns, +then cancellation prevents the next stage from starting. A result already +committed before cancellation may remain cached. Cancellation of one +acquisition does not cancel other callers. Callers cancelled while waiting +for worker capacity never start work. ``aclose`` +rejects further work and drains submitted operations without blocking the +event loop. Cancelling ``aclose`` does not cancel those operations; await it +again before closing the HTTP client or event loop. Failures after caller +cancellation are logged by category without token or error-body details; +cooperative cancellation itself is not logged as a background failure. +Capability-discovery timeouts include waiting for worker capacity. + +To attach response handling, schedule ``acquire_and_send`` with +``asyncio.create_task`` and use ``task.add_done_callback(handler)``. The handler +must account for cancellation and exceptions before accessing ``task.result()``. +Other async work can continue; await the task before closing its surrounding +resources. No separate MSAL callback API is required. + +This is an asyncio adapter over blocking native operations, not native +nonblocking I/O or an aiohttp SSL context. It does not by itself implement an +``azure.identity.aio`` credential, Azure Core response adapter, PoP authentication +policy or service-specific challenge handling. + +Concurrent refresh +------------------ + +MSAL owns token-cache lookup and refresh coordination. The existing token +cache implementation, persistence format and partition dimensions are +unchanged; there is no separate async cache or error cache. The v2 acquisition +logic is shared by synchronous and asynchronous callers. Ordinary managed +identity routing and the rest of MSAL are not converted to async. + +Cold acquisitions, expired tokens and tokens at or within the five-minute reuse +boundary serialize certificate selection, renewal and exchange by binding +policy. A caller rechecks its own token cache after entering the policy lock: +one successful exchange populates a shared cache and matching waiters reuse it. +If an acquisition fails, it releases the lock and each queued caller can make +its own attempt. Failures are not shared across a group or stored with a TTL. +There is no outage-wide cooldown or circuit breaker. + +A token at or past ``refresh_on`` but still outside the five-minute expiry boundary +can be proactively refreshed. One caller attempts refresh without waiting for +the policy lock; concurrent callers return the still-usable cached token rather +than queueing behind that refresh. If proactive refresh fails, the owner +revalidates the token and its original binding before falling back, with a +category-only warning. An expired token, unusable binding, changed key generation +or rejected/replaced certificate cannot be used as a fallback. A later call may +retry immediately; no proactive retry cooldown is added. + +This refresh behavior follows MSAL Go's IMDSv2 feature +(``e06994c7f557580e2e379aa602c445d70884959a``), not Azure Core Go's separate +temporal-resource cache and its 30-second proactive backoff. Python retains its +existing per-policy locks rather than adding Go's process-wide endpoint gate. +All coordination is process-local. + +Certificate renewal selects the replacement binding before looking up its +token. An LRU eviction does not invalidate a binding already held by a caller, +and an in-flight resource request retains its exact generation during rotation. +``force_refresh=True`` bypasses the token cache and remints the certificate, +matching .NET's MSI v2 delegation path +(``3e78a47d7fb9308c68403b6f82b085f4ce3de342``); Go differs on this point. +Nonempty ``claims_challenge`` requests also bypass cached tokens. Both explicit +paths remain separate exchanges and never use proactive-refresh fallback. +Requests to the resource service itself are not deduplicated. + +Discovery, retries and persistence +---------------------------------- + ``client.get_managed_identity_capabilities(timeout=seconds)`` returns a dict with ``source``, ``error_reason``, ``max_supported_binding_strength`` and ``is_mtls_pop_supported_by_host``. The default total budget is 90 seconds; diff --git a/msal/_managed_identity_async.py b/msal/_managed_identity_async.py new file mode 100644 index 00000000..1683ff3c --- /dev/null +++ b/msal/_managed_identity_async.py @@ -0,0 +1,132 @@ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License. + +"""Bounded asyncio adapters for blocking managed identity v2 operations.""" + +import asyncio +import logging +import threading +from concurrent.futures import CancelledError, ThreadPoolExecutor +from typing import Optional + +from ._managed_identity_v2 import _Deadline, _V2Error, _acquisition_cancellation +from .managed_identity import ManagedIdentityError + + +logger = logging.getLogger(__name__) + + +class _AsyncWorker: + _closed_error_code = "session_closed" + + def __init__(self, concurrency): + if isinstance(concurrency, bool) or not isinstance(concurrency, int) or not 1 <= concurrency <= 32: + raise _V2Error("Async concurrency must be an integer in [1, 32].", + stage="binding", error_code="unsupported_transport_option") + self._executor = ThreadPoolExecutor(max_workers=concurrency, thread_name_prefix="msal-mi-v2") + self._slots = asyncio.Semaphore(concurrency) + self._loop, self._closed, self._inflight = None, False, set() + + def _check_loop(self): + loop = asyncio.get_running_loop() + if self._loop is not None and self._loop is not loop: + raise _V2Error("An async managed identity session must stay on its original event loop.", + stage="binding", error_code="unsupported_transport_option") + self._loop = loop + return loop + + def _require_open(self): + if self._closed: + raise _V2Error("The async managed identity session is closed.", + stage="binding", error_code=self._closed_error_code) + + async def _run(self, operation): + loop = self._check_loop() + self._require_open() + await self._slots.acquire() + try: + self._require_open() + future = loop.run_in_executor(self._executor, operation) + except BaseException: + self._slots.release() + raise + self._inflight.add(future) + future.add_done_callback(self._completed) + try: + # Cancelling a waiter must not release capacity still owned by native work. + return await asyncio.shield(future) + except asyncio.CancelledError: + future.add_done_callback(self._abandoned) + raise + + def _completed(self, future): + self._inflight.discard(future) + self._slots.release() + if not future.cancelled(): + future.exception() + + @staticmethod + def _abandoned(future): + if (not future.cancelled() and future.exception() is not None + and not isinstance(future.exception(), (CancelledError, asyncio.CancelledError))): + logger.warning("Cancelled managed identity work failed in the background (%s).", + type(future.exception()).__name__) + + async def aclose(self): + self._check_loop() + self._closed = True + self._executor.shutdown(wait=False) + if self._inflight: + await asyncio.shield(asyncio.gather(*self._inflight, return_exceptions=True)) + + async def __aenter__(self): + self._check_loop() + self._require_open() + return self + + async def __aexit__(self, *_exception): + await self.aclose() + + +class _AsyncManagedIdentityClient(_AsyncWorker): + def __init__(self, client, concurrency): + super().__init__(concurrency) + self._client = client + + async def acquire_token_for_client( + self, *, resource: str, claims_challenge: Optional[str] = None, + mtls_proof_of_possession: bool = False, request_over_mtls: bool = False, + with_attestation_support: bool = False, minimum_binding_strength: Optional[int] = None, + force_refresh: bool = False, + ): + """Acquire an explicit v2 token using the owning client's cache and binding policy.""" + if not mtls_proof_of_possession and not request_over_mtls: + raise ManagedIdentityError("Async acquisition requires an explicit mTLS token mode.") + cancellation = threading.Event() + + def acquire(): + with _acquisition_cancellation(cancellation): + return self._client.acquire_token_for_client( + resource=resource, claims_challenge=claims_challenge, + mtls_proof_of_possession=mtls_proof_of_possession, request_over_mtls=request_over_mtls, + with_attestation_support=with_attestation_support, minimum_binding_strength=minimum_binding_strength, + force_refresh=force_refresh) + + try: + return await self._run(acquire) + except asyncio.CancelledError: + cancellation.set() + raise + + async def get_managed_identity_capabilities(self, *, timeout=None): + """Discover capabilities without blocking the loop; the budget includes worker admission.""" + budget = _Deadline(90 if timeout is None else timeout) + + def discover(): + return self._client.get_managed_identity_capabilities(timeout=budget.remaining()) + + try: + return await asyncio.wait_for(self._run(discover), timeout=budget.remaining()) + except asyncio.TimeoutError: + raise _V2Error("The managed identity discovery deadline expired.", + stage="discovery", error_code="timeout") from None diff --git a/msal/_managed_identity_binding.py b/msal/_managed_identity_binding.py index 4c0b3658..823c1187 100644 --- a/msal/_managed_identity_binding.py +++ b/msal/_managed_identity_binding.py @@ -4,7 +4,6 @@ """Generation-specific requests transport for the blocking Rust transaction ABI.""" import base64 -import asyncio import ctypes import hashlib import logging @@ -13,14 +12,13 @@ import tempfile import threading from contextlib import contextmanager -from concurrent.futures import ThreadPoolExecutor -from functools import partial from urllib.parse import urlencode import requests from requests.adapters import BaseAdapter from ._managed_identity_v2 import _V2Error +from ._managed_identity_async import _AsyncWorker from ._native_mtls import _NativeMtlsError, _https_origin @@ -215,72 +213,28 @@ def send(self, request, **kwargs): return super().send(request, **kwargs) -class _AsyncBoundSession: +class _AsyncBoundSession(_AsyncWorker): + _closed_error_code = "binding_closed" + def __init__(self, binding, concurrency, *, resource_origin=None): - if isinstance(concurrency, bool) or not isinstance(concurrency, int) or not 1 <= concurrency <= 32: - raise _V2Error("Async binding concurrency must be an integer in [1, 32].", - stage="binding", error_code="unsupported_transport_option") + super().__init__(concurrency) self._binding = binding self._adapter = _BoundAdapter(binding, resource_origin=resource_origin) - self._executor = ThreadPoolExecutor(max_workers=concurrency, thread_name_prefix="msal-mi-mtls") - self._slots = asyncio.Semaphore(concurrency) - self._loop, self._closed, self._inflight = None, False, set() - - def _check_loop(self): - loop = asyncio.get_running_loop() - if self._loop is not None and self._loop is not loop: - raise _V2Error("An async binding session must stay on its original event loop.", - stage="binding", error_code="unsupported_transport_option") - self._loop = loop - return loop async def request(self, method, url, *, headers=None, data=None, json=None, params=None, timeout=10, allow_redirects=False): - loop = self._check_loop() if allow_redirects: raise _V2Error("Bound async requests cannot follow redirects.", stage="binding", error_code="unsupported_transport_option") - await self._slots.acquire() - if self._closed: - self._slots.release() - raise _V2Error("The async binding session is closed.", - stage="binding", error_code="binding_closed") - try: + def send(): prepared = requests.Request(method, url, headers=headers, data=data, json=json, params=params).prepare() - operation = partial(self._adapter.send, prepared, timeout=timeout, - verify=self._binding._ca_bundle_path) - future = loop.run_in_executor(self._executor, operation) - except BaseException: - self._slots.release() - raise - self._inflight.add(future) - future.add_done_callback(self._completed) - # Cancellation must not release the native call's slot, buffers or binding. - return await asyncio.shield(future) - - def _completed(self, future): - self._inflight.discard(future) - self._slots.release() - if not future.cancelled(): - future.exception() + return self._adapter.send(prepared, timeout=timeout, verify=self._binding._ca_bundle_path) + + return await self._run(send) async def get(self, url, **kwargs): return await self.request("GET", url, **kwargs) async def post(self, url, **kwargs): return await self.request("POST", url, **kwargs) - - async def aclose(self): - self._check_loop() - self._closed = True - self._executor.shutdown(wait=False) - if self._inflight: - await asyncio.shield(asyncio.gather(*self._inflight, return_exceptions=True)) - - async def __aenter__(self): - self._check_loop() - return self - - async def __aexit__(self, *_exception): - await self.aclose() diff --git a/msal/_managed_identity_v2.py b/msal/_managed_identity_v2.py index 86340430..d37f61d1 100644 --- a/msal/_managed_identity_v2.py +++ b/msal/_managed_identity_v2.py @@ -17,7 +17,8 @@ import uuid import weakref from collections import OrderedDict -from concurrent.futures import ThreadPoolExecutor, TimeoutError as FutureTimeout +from concurrent.futures import CancelledError, ThreadPoolExecutor, TimeoutError as FutureTimeout +from contextlib import contextmanager from datetime import timezone from urllib.parse import urlsplit from pathlib import Path @@ -47,6 +48,7 @@ "azurebleucloud": "attestation.sovcloud-identity.fr", } _BINDINGS, _POLICY_LOCKS = OrderedDict(), weakref.WeakValueDictionary() +_ACQUISITION_CONTEXT = threading.local() # Failed store deletion must stay invalid across clients until replacement persists. _FORCE_MINT = set() _CACHE_LOCK = threading.Lock() @@ -59,6 +61,22 @@ def __init__(self, message, *, stage, error_code, status_code=None): self.stage, self.error_code, self.status_code = stage, error_code, status_code +@contextmanager +def _acquisition_cancellation(event): + previous = getattr(_ACQUISITION_CONTEXT, "cancellation", None) + _ACQUISITION_CONTEXT.cancellation = event + try: + yield + finally: + _ACQUISITION_CONTEXT.cancellation = previous + + +def _check_cancellation(): + event = getattr(_ACQUISITION_CONTEXT, "cancellation", None) + if event is not None and event.is_set(): + raise CancelledError() + + class _Deadline: def __init__(self, timeout, *, clock=time.monotonic, sleep=time.sleep): if (isinstance(timeout, bool) or not isinstance(timeout, (int, float)) @@ -68,6 +86,7 @@ def __init__(self, timeout, *, clock=time.monotonic, sleep=time.sleep): self._end = clock() + timeout def remaining(self): + _check_cancellation() remaining = self._end - self._clock() if remaining <= 0: raise _V2Error("The managed identity operation deadline expired.", @@ -76,7 +95,11 @@ def remaining(self): def wait(self, seconds): remaining = self.remaining() - self._sleep(min(seconds, remaining)) + cancellation = getattr(_ACQUISITION_CONTEXT, "cancellation", None) + if cancellation is None: + self._sleep(min(seconds, remaining)) + else: + cancellation.wait(min(seconds, remaining)) self.remaining() @@ -310,7 +333,10 @@ def __init__(self, *, clock=time.time): def get_or_attest(self, endpoint, generation, operation): cache_key = (_endpoint(endpoint, stage="attestation"), generation) - with self._lock: + while not self._lock.acquire(timeout=0.05): + _check_cancellation() + try: + _check_cancellation() for name in list(self._entries): if self._entries[name][1] <= self._clock() + 300: del self._entries[name] @@ -338,6 +364,8 @@ def get_or_attest(self, endpoint, generation, operation): while len(self._entries) > 128: self._entries.popitem(last=False) return jwt + finally: + self._lock.release() _MAA_CACHE = _MaaTokenCache() @@ -580,7 +608,7 @@ def __init__(self, owner): self._runtime = self._key = self._attestation = None self._store = _CertificateStore() - def _binding(self, policy, resource, attested, ca_bundle, *, force=False): + def _binding(self, policy, resource, attested, ca_bundle, *, force=False, cached_only=False): from ._managed_identity_binding import _BindingCertificate from ._managed_identity_store import _store_alias alias = _store_alias(policy) @@ -589,6 +617,8 @@ def _binding(self, policy, resource, attested, ca_bundle, *, force=False): if binding and (force or binding._closed or binding.expires_on <= time.time() + 86400): del _BINDINGS[policy] binding = None + if cached_only and binding is None: + return None if force: _FORCE_MINT.add(policy) self._store.remove(alias) @@ -615,8 +645,12 @@ def _binding(self, policy, resource, attested, ca_bundle, *, force=False): if reusable: key.close() with _CACHE_LOCK: - _BINDINGS.move_to_end(policy) + if _BINDINGS.get(policy) is binding: + _BINDINGS.move_to_end(policy) return binding + if cached_only: + key.close() + return None if binding: with _CACHE_LOCK: if _BINDINGS.get(policy) is binding: @@ -730,6 +764,7 @@ def post(url, **kwargs): return result def acquire(self, resource, *, pop, attested, floor, force, claims_challenge): + _check_cancellation() _resource_scope(resource) ca_bundle = _trust_bundle(self.http) claims = _claims(self.owner._client_capabilities, claims_challenge) @@ -743,9 +778,13 @@ def acquire(self, resource, *, pop, attested, floor, force, claims_challenge): origin = _https_origin(resource)[1] if pop else None policy = (client_id, tuple(sorted(policy_data.items())), origin, ca_bundle, os.getenv("MSAL_NATIVE_PRIMITIVES_DIR", "installed")) - with _policy_lock(policy): + cache = self.owner._token_cache + lock = _policy_lock(policy) + use_cache = not force and not claims_challenge + + def select_binding(**options): try: - binding = self._binding(policy, resource if pop else None, attested, ca_bundle, force=force) + return self._binding(policy, resource if pop else None, attested, ca_bundle, **options) except _NativeMtlsError as error: if floor != 3: raise @@ -753,21 +792,46 @@ def acquire(self, resource, *, pop, attested, floor, force, claims_challenge): stage="keyguard", error_code="minimum_binding_strength_not_met") failure.native_code, failure.system_error = error.native_code, error.system_error raise failure from error + + def cached_result(binding): + if binding is None: + return None, False data = dict(policy_data, mi_v2_binding_id=binding.key_id if pop else "") - cache = self.owner._token_cache - if not force and not claims_challenge: - for entry in cache.search(cache.CredentialType.ACCESS_TOKEN, target=[resource], query=dict( - client_id=client_id, environment="localhost", realm="managed_identity", - home_account_id=None, ext_cache_key=_compute_ext_cache_key(data))): - now = time.time() - if (isinstance(entry.get("token_type"), str) - and entry["token_type"].lower() == mode - and int(entry["expires_on"]) > now + 300 - and int(entry.get("refresh_on", entry["expires_on"])) > now): - return dict(access_token=entry["secret"], token_type=entry["token_type"], - expires_in=int(int(entry["expires_on"]) - now), token_source="cache", - binding_certificate=binding if pop else None) + for entry in cache.search(cache.CredentialType.ACCESS_TOKEN, target=[resource], query=dict( + client_id=client_id, environment="localhost", realm="managed_identity", + home_account_id=None, ext_cache_key=_compute_ext_cache_key(data))): + now = time.time() + if (isinstance(entry.get("token_type"), str) + and entry["token_type"].lower() == mode + and int(entry["expires_on"]) > now + 300): + return (dict(access_token=entry["secret"], token_type=entry["token_type"], + expires_in=int(int(entry["expires_on"]) - now), token_source="cache", + binding_certificate=binding if pop else None), + int(entry.get("refresh_on", entry["expires_on"])) <= now) + return None, False + + cached_binding = select_binding(cached_only=True) if use_cache else None + cached, refresh_due = cached_result(cached_binding) + _check_cancellation() + if cached and not refresh_due: + return cached + if cached: + # Proactive work must not queue a caller that already has a usable token. + if not lock.acquire(blocking=False): + return cached + else: + while not lock.acquire(timeout=0.05): + _check_cancellation() + try: + _check_cancellation() + binding = select_binding(force=force) + data = dict(policy_data, mi_v2_binding_id=binding.key_id if pop else "") + if use_cache: + current, still_due = cached_result(binding) + if current and (not cached or not still_due): + return current for attempt in range(2): + _check_cancellation() try: result = self._exchange(binding, mode, resource, claims) break @@ -784,13 +848,24 @@ def acquire(self, resource, *, pop, attested, floor, force, claims_challenge): _FORCE_MINT.add(policy) if attempt: raise - binding = self._binding(policy, resource if pop else None, attested, ca_bundle) + binding = select_binding() data["mi_v2_binding_id"] = binding.key_id if pop else "" cache.add(dict( client_id=client_id, scope=[resource], token_endpoint="https://localhost/managed_identity", response=result, params={}, data=data)) result.update(token_source="identity_provider", binding_certificate=binding if pop else None) return result + except (_V2Error, _NativeMtlsError, requests.RequestException, ConnectionResetError) as error: + if cached: + fallback_binding = select_binding(cached_only=True) + fallback, _ = cached_result(fallback_binding) if fallback_binding is cached_binding else (None, False) + if fallback: + logger.warning("Managed identity proactive refresh failed; using a valid cached token (%s).", + type(error).__name__) + return fallback + raise + finally: + lock.release() def _der(tag, contents): diff --git a/msal/managed_identity.py b/msal/managed_identity.py index 29cf8e54..b26b6db1 100644 --- a/msal/managed_identity.py +++ b/msal/managed_identity.py @@ -418,6 +418,32 @@ def __init__( self._v2_lock = threading.Lock() self._capability_discovery = None + def open_async_session(self, *, max_concurrency=4): + """Create a bounded, worker-backed asyncio session for managed identity v2. + + The session offers awaitable ``acquire_token_for_client`` and + ``get_managed_identity_capabilities`` methods, plus ``aclose`` and + async context management. Acquisition requires an explicit + ``mtls_proof_of_possession`` or ``request_over_mtls`` mode and + otherwise preserves this client's arguments, results and errors. + Existing synchronous managed identity routing is unchanged. + + :param int max_concurrency: + Maximum submitted worker operations, from 1 to 32; default 4. + Additional callers wait without occupying another worker. + + The session shares this client's token cache and binding policy; + it does not own the supplied HTTP client or returned bindings. + Keep the HTTP client open until ``aclose`` has drained submitted work. + Cancelling acquisition stops waiting and cooperatively cancels lock + waits and subsequent stages. It cannot interrupt synchronous HTTP or + native work already in progress; the session drains that work before + releasing its resources. Use and close the session on one event loop. + This is not an aiohttp or Azure Identity credential adapter. + """ + from ._managed_identity_async import _AsyncManagedIdentityClient + return _AsyncManagedIdentityClient(self, max_concurrency) + def get_managed_identity_capabilities(self, *, timeout=None): """Discover the host source and maximum binding strength. diff --git a/sample/managed_identity_v2.py b/sample/managed_identity_v2.py index 11a101a5..8dd6685b 100644 --- a/sample/managed_identity_v2.py +++ b/sample/managed_identity_v2.py @@ -7,6 +7,17 @@ import requests +async def async_pop(client, resource, url): + async with client.open_async_session() as acquisition: + result = await acquisition.acquire_token_for_client( + resource=resource, mtls_proof_of_possession=True, with_attestation_support=True) + async with result["binding_certificate"].open_async_session(resource_origin=url) as session: + return await session.get(url, timeout=30, headers={ + "Authorization": result["token_type"] + " " + result["access_token"], + "x-ms-tokenboundauth": "true", + }) + + def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("mode", choices=("pop", "async-pop", "bearer")) @@ -18,25 +29,21 @@ def main(): msal.SystemAssignedManagedIdentity()) with requests.Session() as metadata: client = msal.ManagedIdentityClient(identity, http_client=metadata) - result = client.acquire_token_for_client( - resource=args.resource, with_attestation_support=True, - **({"request_over_mtls": True} if args.mode == "bearer" else - {"mtls_proof_of_possession": True})) - headers = {"Authorization": result["token_type"] + " " + result["access_token"]} - if args.mode != "bearer": - headers["x-ms-tokenboundauth"] = "true" - if args.mode == "bearer": - with requests.Session() as ordinary: - response = ordinary.get(args.url, headers=headers, timeout=30, allow_redirects=False) - elif args.mode == "pop": - with result["binding_certificate"].open_session(resource_origin=args.url) as session: - response = session.get(args.url, headers=headers, timeout=30) + if args.mode == "async-pop": + response = asyncio.run(async_pop(client, args.resource, args.url)) else: - async def send(): - async with result["binding_certificate"].open_async_session( - resource_origin=args.url, max_concurrency=4) as session: - return await session.get(args.url, headers=headers, timeout=30) - response = asyncio.run(send()) + result = client.acquire_token_for_client( + resource=args.resource, with_attestation_support=True, + **({"request_over_mtls": True} if args.mode == "bearer" else + {"mtls_proof_of_possession": True})) + headers = {"Authorization": result["token_type"] + " " + result["access_token"]} + if args.mode == "bearer": + with requests.Session() as ordinary: + response = ordinary.get(args.url, headers=headers, timeout=30, allow_redirects=False) + else: + headers["x-ms-tokenboundauth"] = "true" + with result["binding_certificate"].open_session(resource_origin=args.url) as session: + response = session.get(args.url, headers=headers, timeout=30) if not 200 <= response.status_code < 300: raise RuntimeError("The resource operation failed (HTTP {}).".format(response.status_code)) print("Resource request succeeded using " + args.mode + ".") diff --git a/tests/test_managed_identity_v2.py b/tests/test_managed_identity_v2.py index 8ec351fb..88e967de 100644 --- a/tests/test_managed_identity_v2.py +++ b/tests/test_managed_identity_v2.py @@ -8,7 +8,7 @@ import sys import uuid import unittest -from contextlib import contextmanager +from contextlib import asynccontextmanager, contextmanager from collections import OrderedDict from concurrent.futures import ThreadPoolExecutor from datetime import datetime, timedelta, timezone @@ -287,7 +287,7 @@ def locked_fixture_chain(path, digest): yield -class PublicProtectedFlowTests(unittest.TestCase): +class _ProtectedFlowFixture: """Public SDK wiring with software/mocked native boundaries, not live MSI v2.""" def setUp(self): from msal.managed_identity import DEFAULT_TO_VM @@ -343,6 +343,8 @@ def _native_request(self, **kwargs): def _acquire(self, **kwargs): return self.client.acquire_token_for_client(resource="https://vault.example", **kwargs) + +class PublicProtectedFlowTests(_ProtectedFlowFixture, unittest.TestCase): def test_public_pop_exchange_uses_canonical_fields_claims_and_live_binding_on_cache_hit(self): result = self._acquire(mtls_proof_of_possession=True, claims_challenge='{"access_token":{"custom":{"essential":true}}}') @@ -697,6 +699,1270 @@ def test_v1_only_explicit_request_reports_unsupported_before_loading_native(self load.assert_not_called() +class AsyncProtectedFlowTests(_ProtectedFlowFixture, unittest.IsolatedAsyncioTestCase): + def setUp(self): + super().setUp() + from msal._managed_identity_binding import _BindingCertificate + + def binding(*args, **kwargs): + result = _BindingCertificate(*args, **kwargs) + self.addCleanup(result.close) + return result + + constructor = patch("msal._managed_identity_binding._BindingCertificate", side_effect=binding) + constructor.start() + self.addCleanup(constructor.stop) + + @asynccontextmanager + async def _blocked(self, target, attribute): + original = getattr(target, attribute) + entered, release = asyncio.Event(), threading.Event() + loop = asyncio.get_running_loop() + + def blocked(*args, **kwargs): + loop.call_soon_threadsafe(entered.set) + if not release.wait(5): + raise RuntimeError("The unit async-operation gate timed out.") + return original(*args, **kwargs) + + with patch.object(target, attribute, side_effect=blocked): + try: + yield entered, release + finally: + release.set() + + @asynccontextmanager + async def _policy_waiters(self, expected): + from msal._managed_identity_v2 import _policy_lock + loop, joined, count_lock = asyncio.get_running_loop(), asyncio.Event(), threading.Lock() + callers = 0 + + def join(policy): + nonlocal callers + with count_lock: + callers += 1 + if callers == expected: + loop.call_soon_threadsafe(joined.set) + return _policy_lock(policy) + + with patch("msal._managed_identity_v2._policy_lock", side_effect=join): + yield joined + + def _expire_token(self, **updates): + entries = json.loads(self.cache.serialize())[self.cache.CredentialType.ACCESS_TOKEN] + self.assertEqual(len(entries), 1) + entry = next(iter(entries.values())) + self.cache.modify(self.cache.CredentialType.ACCESS_TOKEN, entry, updates) + + async def test_sync_and_async_calls_share_cache_and_exact_binding(self): + first = self._acquire(mtls_proof_of_possession=True) + async with self.client.open_async_session() as client: + second = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + second["access_token"] = "caller-edited-result" + third = self._acquire(mtls_proof_of_possession=True) + self.assertEqual(second["token_source"], "cache") + self.assertEqual(third["access_token"], first["access_token"]) + self.assertIs(second["binding_certificate"], first["binding_certificate"]) + self.assertIs(third["binding_certificate"], first["binding_certificate"]) + self.assertEqual(len(self.token_requests), 1) + + async def test_exact_expiry_and_refresh_boundaries_in_both_modes(self): + now = int(time.time()) + async with self.client.open_async_session() as client: + for mode, option in (("mtls_pop", "mtls_proof_of_possession"), ("bearer", "request_over_mtls")): + self.cache.deserialize("{}") + options = dict(resource="https://vault.example", **{option: True}) + first = await client.acquire_token_for_client(force_refresh=True, **options) + certificates = self.http.post.call_count + for lifetime, refresh_delta, exchange in ( + (301, 1, False), (300, 1, True), (299, 1, True), + (3600, 1, False), (3600, 0, True), (3600, -1, True)): + with self.subTest(mode=mode, lifetime=lifetime, refresh_delta=refresh_delta): + self._expire_token(secret="cached", expires_on=str(now + lifetime), + refresh_on=str(now + refresh_delta)) + self.next_tokens = [dict(access_token="refreshed", token_type=mode, expires_in=3600)] + before = len(self.token_requests) + with patch("msal._managed_identity_v2.time.time", return_value=now): + result = await client.acquire_token_for_client(**options) + self.assertEqual(result["access_token"], "refreshed" if exchange else "cached") + self.assertEqual(result["token_source"], "identity_provider" if exchange else "cache") + self.assertEqual(len(self.token_requests), before + int(exchange)) + self.assertIs(result["binding_certificate"], first["binding_certificate"]) + self.assertEqual(self.http.post.call_count, certificates) + + async def test_independent_caches_do_not_reuse_each_others_successful_token(self): + other_cache = SerializableTokenCache() + other = ManagedIdentityClient( + SystemAssignedManagedIdentity(), http_client=self.http, + token_cache=other_cache, client_capabilities=["CP1"]) + self.next_tokens = [ + dict(access_token=token, token_type="mtls_pop", expires_in=3600) + for token in ("first-cache-token", "second-cache-token")] + options = dict(resource="https://vault.example", mtls_proof_of_possession=True) + async with self.client.open_async_session() as first, other.open_async_session() as second: + async with self._blocked(self.runtime, "request") as (entered, release): + async with self._policy_waiters(2) as joined: + pending = asyncio.create_task(first.acquire_token_for_client(**options)) + await asyncio.wait_for(entered.wait(), 2) + independent = asyncio.create_task(second.acquire_token_for_client(**options)) + await asyncio.wait_for(joined.wait(), 2) + release.set() + results = await asyncio.gather(pending, independent) + cached = [await client.acquire_token_for_client(**options) for client in (first, second)] + self.assertEqual([result["access_token"] for result in results], + ["first-cache-token", "second-cache-token"]) + self.assertEqual([result["access_token"] for result in cached], + ["first-cache-token", "second-cache-token"]) + self.assertTrue(all(result["token_source"] == "cache" for result in cached)) + self.assertIs(results[0]["binding_certificate"], results[1]["binding_certificate"]) + self.assertNotIn("second-cache-token", self.cache.serialize()) + self.assertNotIn("first-cache-token", other_cache.serialize()) + self.assertEqual(len(self.token_requests), 2) + self.http.post.assert_called_once() + + async def test_resources_sharing_an_origin_reuse_binding_but_not_tokens(self): + for mode, option in (("mtls_pop", "mtls_proof_of_possession"), ("bearer", "request_over_mtls")): + with self.subTest(mode=mode): + self.cache.deserialize("{}") + resources = ("https://vault.example/one", "https://vault.example/two") + self.next_tokens = [ + dict(access_token=resource, token_type=mode, expires_in=3600) for resource in resources] + tokens_before, certs_before = len(self.token_requests), self.http.post.call_count + async with self.client.open_async_session() as client: + results = await asyncio.gather(*(client.acquire_token_for_client( + resource=resource, **{option: True}) for resource in resources)) + cached = await asyncio.gather(*(client.acquire_token_for_client( + resource=resource, **{option: True}) for resource in resources)) + self.assertEqual([result["access_token"] for result in results], list(resources)) + self.assertEqual([result["access_token"] for result in cached], list(resources)) + self.assertTrue(all(result["token_source"] == "cache" for result in cached)) + self.assertIs(results[0]["binding_certificate"], results[1]["binding_certificate"]) + self.assertEqual(len(self.token_requests), tokens_before + 2) + self.assertEqual(self.http.post.call_count, certs_before + 1) + + async def test_concurrent_cold_calls_across_sessions_share_one_acquisition(self): + async with self.client.open_async_session() as first, self.client.open_async_session() as second: + async with self._blocked(self.http, "post") as (entered, release): + async with self._policy_waiters(8) as joined: + tasks = [asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True, + with_attestation_support=True)) + for client in (first, second) for _ in range(4)] + await asyncio.wait_for(entered.wait(), 2) + await asyncio.wait_for(joined.wait(), 2) + release.set() + results = await asyncio.gather(*tasks) + self.assertEqual(self.http.post.call_count, 1) + self.assertEqual(len(self.token_requests), 1) + self.attestation.attest.assert_called_once() + self.assertEqual(sum(r["token_source"] == "identity_provider" for r in results), 1) + self.assertTrue(all(r["binding_certificate"] is results[0]["binding_certificate"] for r in results)) + + async def test_concurrent_expiry_and_renewal_refresh_once_across_sync_and_async_clients(self): + other = ManagedIdentityClient( + SystemAssignedManagedIdentity(), http_client=self.http, + token_cache=self.cache, client_capabilities=["CP1"]) + for reason in ("expired", "near_expiry", "certificate"): + with self.subTest(reason=reason): + self.cache.deserialize("{}") + options = dict(resource="https://vault.example", mtls_proof_of_possession=True, + with_attestation_support=True) + self.next_tokens = [dict(access_token="old-" + reason, token_type="mtls_pop", expires_in=3600)] + initial = await asyncio.to_thread( + self.client.acquire_token_for_client, force_refresh=True, **options) + if reason == "certificate": + initial["binding_certificate"].expires_on = time.time() + 86400 + else: + self._expire_token(expires_on=str(int(time.time()) + ( + 300 if reason == "near_expiry" else -1))) + self.next_tokens = [dict( + access_token="fresh-" + reason, token_type="mtls_pop", expires_in=3600)] + tokens_before, certs_before = len(self.token_requests), self.http.post.call_count + attestations_before = self.attestation.attest.call_count + async with self.client.open_async_session() as first, other.open_async_session() as second: + async with self._blocked(self.runtime, "request") as (entered, release): + async with self._policy_waiters(8) as joined: + tasks = [asyncio.create_task(client.acquire_token_for_client(**options)) + for client, count in ((first, 4), (second, 3)) for _ in range(count)] + tasks.append(asyncio.create_task(asyncio.to_thread( + self.client.acquire_token_for_client, **options))) + await asyncio.wait_for(entered.wait(), 2) + await asyncio.wait_for(joined.wait(), 2) + self.runtime.request.assert_called_once() + release.set() + results = await asyncio.gather(*tasks) + self.assertEqual(len(self.token_requests), tokens_before + 1) + self.assertEqual(sum(r["token_source"] == "identity_provider" for r in results), 1) + self.assertTrue(all(r["access_token"] == "fresh-" + reason for r in results)) + self.assertTrue(all( + r["binding_certificate"] is results[0]["binding_certificate"] for r in results)) + self.assertEqual(self.http.post.call_count, certs_before + int(reason == "certificate")) + self.assertEqual(self.attestation.attest.call_count, attestations_before) + self.assertEqual(results[0]["binding_certificate"] is initial["binding_certificate"], + reason != "certificate") + + async def test_cancelled_refresh_owner_and_waiter_do_not_cancel_other_acquisition(self): + initial = self._acquire(mtls_proof_of_possession=True) + self._expire_token(expires_on=str(int(time.time()) - 1)) + async with self.client.open_async_session(max_concurrency=3) as client: + async with self._blocked(self.runtime, "request") as (entered, release): + async with self._policy_waiters(3) as joined: + owner = asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + await asyncio.wait_for(entered.wait(), 2) + waiters = [asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) for _ in range(2)] + await asyncio.wait_for(joined.wait(), 2) + for task in (owner, waiters[0]): + task.cancel() + with self.assertRaises(asyncio.CancelledError): + await task + release.set() + result = await waiters[1] + self.assertEqual(result["token_source"], "identity_provider") + self.assertIs(result["binding_certificate"], initial["binding_certificate"]) + self.assertEqual(len(self.token_requests), 3) + + async def test_cancelled_policy_waiter_releases_its_worker_without_waiting_for_owner(self): + self._acquire(mtls_proof_of_possession=True) + self._expire_token(expires_on="1") + async with self.client.open_async_session(max_concurrency=2) as client: + async with self._blocked(self.runtime, "request") as (entered, release): + async with self._policy_waiters(2) as joined: + owner = asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + await asyncio.wait_for(entered.wait(), 2) + owner_workers = set(client._inflight) + waiter = asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True, force_refresh=True)) + await asyncio.wait_for(joined.wait(), 2) + waiter_workers = client._inflight - owner_workers + self.assertEqual(len(waiter_workers), 1) + waiter.cancel() + with self.assertRaises(asyncio.CancelledError): + await waiter + await asyncio.wait_for(asyncio.gather(*waiter_workers, return_exceptions=True), 2) + self.assertFalse(owner.done()) + self.assertEqual(self.http.post.call_count, 1) + self.runtime.request.assert_called_once() + release.set() + result = await owner + cached = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertEqual(cached["access_token"], result["access_token"]) + self.assertEqual(cached["token_source"], "cache") + self.assertEqual(len(self.token_requests), 2) + + async def test_cancellation_after_native_attestation_stops_before_certificate_issuance(self): + async with self.client.open_async_session() as client: + async with self._blocked(self.attestation, "attest") as (entered, release): + pending = asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True, + with_attestation_support=True)) + await asyncio.wait_for(entered.wait(), 2) + pending.cancel() + with self.assertRaises(asyncio.CancelledError): + await pending + self.assertEqual(len(client._inflight), 1) + release.set() + await asyncio.wait_for(client.aclose(), 2) + self.http.post.assert_not_called() + self.runtime.request.assert_not_called() + + async def test_cancellation_after_metadata_stops_before_protected_key_creation(self): + async with self.client.open_async_session() as client: + with patch("msal._managed_identity_v2._NativeKey", return_value=self.signer) as create: + async with self._blocked(self.http, "get") as (entered, release): + pending = asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + await asyncio.wait_for(entered.wait(), 2) + pending.cancel() + with self.assertRaises(asyncio.CancelledError): + await pending + release.set() + await asyncio.wait_for(client.aclose(), 2) + create.assert_not_called() + self.http.post.assert_not_called() + self.runtime.request.assert_not_called() + + async def test_cancelled_attestation_waiter_does_not_wait_for_other_native_call(self): + from msal._managed_identity_v2 import _MAA_CACHE + entered_cache, loop = asyncio.Event(), asyncio.get_running_loop() + original, count_lock, calls = _MAA_CACHE.get_or_attest, threading.Lock(), 0 + + def attest(*args, **kwargs): + nonlocal calls + with count_lock: + calls += 1 + if calls == 2: + loop.call_soon_threadsafe(entered_cache.set) + return original(*args, **kwargs) + + async with self.client.open_async_session(max_concurrency=2) as client: + with patch.object(_MAA_CACHE, "get_or_attest", side_effect=attest): + async with self._blocked(self.attestation, "attest") as (entered, release): + owner = asyncio.create_task(client.acquire_token_for_client( + resource="https://first.example", mtls_proof_of_possession=True, + with_attestation_support=True)) + await asyncio.wait_for(entered.wait(), 2) + owner_workers = set(client._inflight) + waiter = asyncio.create_task(client.acquire_token_for_client( + resource="https://second.example", mtls_proof_of_possession=True, + with_attestation_support=True)) + await asyncio.wait_for(entered_cache.wait(), 2) + waiter_workers = client._inflight - owner_workers + self.assertEqual(len(waiter_workers), 1) + waiter.cancel() + with self.assertRaises(asyncio.CancelledError): + await waiter + await asyncio.wait_for(asyncio.gather(*waiter_workers, return_exceptions=True), 2) + self.assertFalse(owner.done()) + self.attestation.attest.assert_called_once() + self.http.post.assert_not_called() + release.set() + await owner + await client.acquire_token_for_client( + resource="https://second.example", mtls_proof_of_possession=True, + with_attestation_support=True) + self.attestation.attest.assert_called_once() + self.assertEqual(len(self.token_requests), 2) + + async def test_cancellation_interrupts_token_retry_delay_without_another_attempt(self): + retrying, loop = asyncio.Event(), asyncio.get_running_loop() + unavailable = response({}, status=503) + unavailable.headers["Retry-After"] = "90" + self.runtime.request.side_effect = None + self.runtime.request.return_value = unavailable + original_wait = _Deadline.wait + + def wait(budget, seconds): + loop.call_soon_threadsafe(retrying.set) + return original_wait(budget, seconds) + + async with self.client.open_async_session() as client: + with patch.object(_Deadline, "wait", wait): + pending = asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + await asyncio.wait_for(retrying.wait(), 2) + pending.cancel() + with self.assertRaises(asyncio.CancelledError): + await pending + await asyncio.wait_for(client.aclose(), 2) + self.runtime.request.assert_called_once() + + async def test_concurrent_failed_refreshes_retry_serially_and_later_call_can_recover(self): + self._acquire(mtls_proof_of_possession=True) + self._expire_token(expires_on="1") + before = len(self.token_requests) + + def denied(**kwargs): + self.token_requests.append(kwargs) + return response(dict(error="unauthorized_client"), status=400) + + self.runtime.request.side_effect = denied + async with self.client.open_async_session() as first, self.client.open_async_session() as second: + async with self._blocked(self.runtime, "request") as (entered, release): + async with self._policy_waiters(8) as joined: + tasks = [asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + for client in (first, second) for _ in range(4)] + await asyncio.wait_for(entered.wait(), 2) + await asyncio.wait_for(joined.wait(), 2) + self.runtime.request.assert_called_once() + release.set() + results = await asyncio.gather(*tasks, return_exceptions=True) + self.assertTrue(all(isinstance(result, _V2Error) for result in results)) + self.assertTrue(all(result.error_code == "unauthorized_client" for result in results)) + self.assertEqual(len(self.token_requests), before + 8) + self.assertEqual(json.loads(self.cache.serialize()).get(self.cache.CredentialType.ACCESS_TOKEN, {}), {}) + self.runtime.request.side_effect = self._native_request + recovered = await first.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertEqual(recovered["token_source"], "identity_provider") + self.assertEqual(len(self.token_requests), before + 9) + + async def test_cancelled_failed_refresh_owner_does_not_prevent_waiter_retry(self): + self._acquire(mtls_proof_of_possession=True) + self._expire_token(expires_on="1") + + def denied(**kwargs): + self.token_requests.append(kwargs) + return response(dict(error="unauthorized_client"), status=400) + + self.runtime.request.side_effect = denied + async with self.client.open_async_session(max_concurrency=2) as client: + async with self._blocked(self.runtime, "request") as (entered, release): + async with self._policy_waiters(2) as joined: + owner = asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + await asyncio.wait_for(entered.wait(), 2) + waiter = asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + await asyncio.wait_for(joined.wait(), 2) + owner.cancel() + with self.assertRaises(asyncio.CancelledError): + await owner + release.set() + with self.assertRaises(_V2Error) as caught: + await waiter + await client.aclose() + self.assertEqual(caught.exception.error_code, "unauthorized_client") + self.assertEqual(len(self.token_requests), 3) + + async def test_failure_does_not_cross_resource_or_cache_instance(self): + for separate in ("resource", "cache"): + with self.subTest(separate=separate): + self.cache.deserialize("{}") + other_cache = self.cache if separate == "resource" else SerializableTokenCache() + other_resource = "https://other.example" if separate == "resource" else "https://vault.example" + other = ManagedIdentityClient( + SystemAssignedManagedIdentity(), http_client=self.http, + token_cache=other_cache, client_capabilities=["CP1"]) + entered, release = asyncio.Event(), threading.Event() + loop, exchanges = asyncio.get_running_loop(), [] + + def exchange(**kwargs): + exchanges.append(kwargs) + if len(exchanges) == 1: + loop.call_soon_threadsafe(entered.set) + if not release.wait(5): + raise RuntimeError("The unit failure-isolation gate timed out.") + return response(dict(error="unauthorized_client"), status=400) + return response(dict(access_token="independent", token_type="bearer", expires_in=3600)) + + self.runtime.request.side_effect = exchange + async with self.client.open_async_session() as first, other.open_async_session() as second: + async with self._policy_waiters(2) as joined: + failed = asyncio.create_task(first.acquire_token_for_client( + resource="https://vault.example", request_over_mtls=True)) + independent = None + try: + await asyncio.wait_for(entered.wait(), 2) + independent = asyncio.create_task(second.acquire_token_for_client( + resource=other_resource, request_over_mtls=True)) + await asyncio.wait_for(joined.wait(), 2) + finally: + release.set() + with self.assertRaises(_V2Error): + await failed + result = await independent + self.assertEqual(result["access_token"], "independent") + self.assertIsNone(result["binding_certificate"]) + self.assertEqual(len(exchanges), 2) + + async def test_reentrant_acquisition_does_not_wait_on_its_own_policy_lock(self): + nested = [] + + def exchange(**kwargs): + if not nested: + nested.append(None) + nested[0] = self._acquire(mtls_proof_of_possession=True) + return self._native_request(**kwargs) + + self.runtime.request.side_effect = exchange + async with self.client.open_async_session() as client: + result = await asyncio.wait_for(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True), 2) + self.assertIs(result["binding_certificate"], nested[0]["binding_certificate"]) + self.assertEqual(len(self.token_requests), 2) + + async def test_concurrent_explicit_refresh_and_challenge_keep_bypass_contract(self): + challenge = '{"access_token":{"custom":{"essential":true}}}' + async with self.client.open_async_session() as client: + for options, certificates in ((dict(force_refresh=True), 4), (dict(claims_challenge=challenge), 1)): + with self.subTest(options=options): + before = len(self.token_requests) + async with self._blocked(self.runtime, "request") as (entered, release): + async with self._policy_waiters(4) as joined: + tasks = [asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True, **options)) + for _ in range(4)] + await asyncio.wait_for(entered.wait(), 2) + await asyncio.wait_for(joined.wait(), 2) + release.set() + results = await asyncio.gather(*tasks) + self.assertEqual(len(self.token_requests), before + 4) + self.assertTrue(all(result["token_source"] == "identity_provider" for result in results)) + self.assertEqual(len({result["binding_certificate"].key_id for result in results}), certificates) + + async def test_proactive_refresh_waiters_use_valid_token_and_failure_falls_back(self): + initial = self._acquire(mtls_proof_of_possession=True) + self._expire_token(refresh_on="1") + + def denied(**kwargs): + self.token_requests.append(kwargs) + return response(dict(error="unauthorized_client"), status=400) + + self.runtime.request.side_effect = denied + async with self.client.open_async_session(max_concurrency=2) as client: + async with self._blocked(self.runtime, "request") as (entered, release): + first = asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + await asyncio.wait_for(entered.wait(), 2) + second = await asyncio.wait_for(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True), 2) + self.assertFalse(first.done()) + self.assertEqual(second["access_token"], initial["access_token"]) + with self.assertLogs("msal._managed_identity_v2", level="WARNING"): + release.set() + result = await first + self.assertEqual(result["access_token"], initial["access_token"]) + self.assertIs(result["binding_certificate"], initial["binding_certificate"]) + self.assertEqual(result["token_source"], "cache") + # The Go MSI v2 feature has no failure TTL: the next call may retry. + self.runtime.request.side_effect = self._native_request + recovered = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertEqual(recovered["token_source"], "identity_provider") + self.assertEqual(len(self.token_requests), 3) + + async def test_proactive_refresh_success_updates_cache_without_blocking_other_callers(self): + self.next_tokens = [dict(access_token="old", token_type="mtls_pop", expires_in=3600)] + initial = self._acquire(mtls_proof_of_possession=True) + self._expire_token(refresh_on="1") + self.next_tokens = [dict(access_token="new", token_type="mtls_pop", expires_in=3600)] + async with self.client.open_async_session() as first, self.client.open_async_session() as second: + async with self._blocked(self.runtime, "request") as (entered, release): + owner = asyncio.create_task(first.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + await asyncio.wait_for(entered.wait(), 2) + waiters = [asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + for client, count in ((first, 3), (second, 3)) for _ in range(count)] + waiters.append(asyncio.create_task(asyncio.to_thread( + self.client.acquire_token_for_client, + resource="https://vault.example", mtls_proof_of_possession=True))) + results = await asyncio.wait_for(asyncio.gather(*waiters), 2) + self.assertFalse(owner.done()) + self.assertTrue(all(result["access_token"] == "old" for result in results)) + self.assertTrue(all(result["token_source"] == "cache" for result in results)) + self.runtime.request.assert_called_once() + release.set() + refreshed = await owner + cached = await second.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertEqual(refreshed["access_token"], "new") + self.assertEqual(refreshed["token_source"], "identity_provider") + self.assertEqual(cached["access_token"], "new") + self.assertEqual(cached["token_source"], "cache") + self.assertIs(refreshed["binding_certificate"], initial["binding_certificate"]) + self.assertEqual(len(self.token_requests), 2) + self.http.post.assert_called_once() + + async def test_proactive_refresh_never_returns_token_that_expired_during_failure(self): + self._acquire(mtls_proof_of_possession=True) + self._expire_token(refresh_on="1") + + def denied(**kwargs): + self._expire_token(expires_on="1") + return response(dict(error="unauthorized_client"), status=400) + + self.runtime.request.side_effect = denied + async with self.client.open_async_session() as client: + with self.assertRaises(_V2Error) as caught: + await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertEqual(caught.exception.error_code, "unauthorized_client") + + async def test_proactive_fallback_rejects_lost_cache_or_unusable_binding(self): + from msal._managed_identity_v2 import _BINDINGS + for invalidate in ("token_boundary", "certificate_boundary", "closed", "key_generation", "cache_removed"): + with self.subTest(invalidate=invalidate): + _BINDINGS.clear() + self.cache.deserialize("{}") + self.runtime.request.side_effect = self._native_request + old = self._acquire(mtls_proof_of_possession=True) + self._expire_token(refresh_on="1") + original_signer = self.signer + replacement = SoftwareSignerFixture() if invalidate == "key_generation" else None + + def denied(**kwargs): + if invalidate == "token_boundary": + self._expire_token(expires_on=str(int(time.time()) + 300)) + elif invalidate == "certificate_boundary": + old["binding_certificate"].expires_on = time.time() + 86400 + elif invalidate == "closed": + old["binding_certificate"].close() + elif invalidate == "key_generation": + self.signer = replacement + else: + self.cache.deserialize("{}") + return response(dict(error="unauthorized_client"), status=400) + + self.runtime.request.side_effect = denied + try: + with patch("msal._managed_identity_v2._NativeKey", side_effect=lambda *args: self.signer): + async with self.client.open_async_session() as client: + with self.assertRaises(_V2Error) as caught: + await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + finally: + self.signer = original_signer + self.assertEqual(caught.exception.error_code, "unauthorized_client") + + async def test_proactive_transport_failures_fall_back_without_exposing_error_details(self): + for option in ("mtls_proof_of_possession", "request_over_mtls"): + for error in (requests.ConnectionError("private-transport-detail"), + _NativeMtlsError("private-native-detail", native_code=8)): + with self.subTest(option=option, error=type(error).__name__): + self.cache.deserialize("{}") + self.runtime.request.side_effect = self._native_request + old = self._acquire(**{option: True}) + self._expire_token(refresh_on="1") + self.runtime.request.side_effect = error + async with self.client.open_async_session() as client: + with self.assertLogs("msal._managed_identity_v2", level="WARNING") as captured: + result = await client.acquire_token_for_client( + resource="https://vault.example", **{option: True}) + self.assertEqual(result["access_token"], old["access_token"]) + self.assertEqual(result["token_source"], "cache") + self.assertIs(result["binding_certificate"], old["binding_certificate"]) + self.assertNotIn("private-", "\n".join(captured.output)) + + async def test_explicit_refresh_errors_never_use_proactive_fallback(self): + challenge = '{"access_token":{"custom":{"essential":true}}}' + async with self.client.open_async_session() as client: + for option in ("mtls_proof_of_possession", "request_over_mtls"): + for bypass in (dict(force_refresh=True), dict(claims_challenge=challenge)): + with self.subTest(option=option, bypass=bypass): + self.cache.deserialize("{}") + self.runtime.request.side_effect = self._native_request + options = dict(resource="https://vault.example", **{option: True}, **bypass) + await client.acquire_token_for_client(**options) + self._expire_token(refresh_on="1") + self.runtime.request.side_effect = lambda **kwargs: response( + dict(error="unauthorized_client"), status=400) + with self.assertRaises(_V2Error) as caught: + await client.acquire_token_for_client(**options) + self.assertEqual(caught.exception.error_code, "unauthorized_client") + self.assertNotIn("unauthorized_client", self.cache.serialize()) + + async def test_unexpected_proactive_error_propagates_and_releases_policy_lock(self): + self._acquire(mtls_proof_of_possession=True) + self._expire_token(refresh_on="1") + error = RuntimeError("unit unexpected transport failure") + self.runtime.request.side_effect = error + async with self.client.open_async_session(max_concurrency=1) as client: + with self.assertRaises(RuntimeError) as caught: + await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertIs(caught.exception, error) + self.runtime.request.side_effect = self._native_request + result = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertEqual(result["token_source"], "identity_provider") + self.assertEqual(len(self.token_requests), 2) + + async def test_proactive_binding_rejection_does_not_fall_back_to_rejected_pair(self): + old = self._acquire(mtls_proof_of_possession=True) + self._expire_token(refresh_on="1") + self.next_tokens = [dict(error="invalid_client"), dict(error="unauthorized_client")] + async with self.client.open_async_session() as client: + with self.assertRaises(_V2Error) as caught: + await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertEqual(caught.exception.error_code, "unauthorized_client") + self.assertEqual(len(self.token_requests), 3) + self.assertEqual(self.http.post.call_count, 2) + self.assertFalse(old["binding_certificate"]._closed) + + async def test_cached_strength_floor_preserves_structured_key_failure(self): + async with self.client.open_async_session() as client: + await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True, + minimum_binding_strength=3) + denied = _NativeMtlsError("Unit protected key unavailable", native_code=7, system_error=123) + with patch("msal._managed_identity_v2._NativeKey", side_effect=denied): + with self.assertRaises(_V2Error) as caught: + await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True, + minimum_binding_strength=3) + self.assertEqual(caught.exception.error_code, "minimum_binding_strength_not_met") + self.assertEqual(caught.exception.stage, "keyguard") + self.assertEqual(caught.exception.native_code, 7) + self.assertEqual(caught.exception.system_error, 123) + self.assertEqual(len(self.token_requests), 1) + + async def test_unrelated_resource_policy_progresses_while_another_exchange_waits(self): + entered, release = asyncio.Event(), threading.Event() + loop = asyncio.get_running_loop() + + def exchange(**kwargs): + self.token_requests.append(kwargs) + scope = parse_qs(kwargs["body"].decode("ascii"))["scope"][0] + if scope == "https://first.example/.default": + loop.call_soon_threadsafe(entered.set) + if not release.wait(5): + raise RuntimeError("The unit unrelated-policy gate timed out.") + return response(dict(access_token=scope, token_type="mtls_pop", expires_in=3600)) + + self.runtime.request.side_effect = exchange + async with self.client.open_async_session(max_concurrency=2) as client: + pending = asyncio.create_task(client.acquire_token_for_client( + resource="https://first.example", mtls_proof_of_possession=True)) + try: + await asyncio.wait_for(entered.wait(), 2) + other = await asyncio.wait_for(client.acquire_token_for_client( + resource="https://second.example", mtls_proof_of_possession=True), 2) + self.assertFalse(pending.done()) + self.assertEqual(other["access_token"], "https://second.example/.default") + finally: + release.set() + first = await pending + self.assertEqual(first["access_token"], "https://first.example/.default") + self.assertIsNot(first["binding_certificate"], other["binding_certificate"]) + self.assertEqual(len(self.token_requests), 2) + + async def test_lru_eviction_during_key_revalidation_preserves_inflight_cached_binding(self): + from msal._managed_identity_v2 import _BINDINGS + first = self._acquire(mtls_proof_of_possession=True) + + def fill(): + for index in range(127): + self.client.acquire_token_for_client( + resource="https://cache{}.example".format(index), mtls_proof_of_possession=True) + + await asyncio.to_thread(fill) + self.assertEqual(len(_BINDINGS), 128) + entered, release = asyncio.Event(), threading.Event() + loop, first_reopen, gate_lock = asyncio.get_running_loop(), True, threading.Lock() + + def reopen(*args): + nonlocal first_reopen + with gate_lock: + block, first_reopen = first_reopen, False + if block: + loop.call_soon_threadsafe(entered.set) + if not release.wait(5): + raise RuntimeError("The unit binding-eviction gate timed out.") + return self.signer + + async with self.client.open_async_session(max_concurrency=2) as client: + with patch("msal._managed_identity_v2._NativeKey", side_effect=reopen): + pending = asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + try: + await asyncio.wait_for(entered.wait(), 2) + await client.acquire_token_for_client( + resource="https://new-entry.example", mtls_proof_of_possession=True) + self.assertNotIn(first["binding_certificate"], _BINDINGS.values()) + finally: + release.set() + result = await pending + self.assertEqual(result["token_source"], "cache") + self.assertIs(result["binding_certificate"], first["binding_certificate"]) + self.assertEqual(len(self.token_requests), 129) + self.assertEqual(len(_BINDINGS), 128) + async with result["binding_certificate"].open_async_session() as transport: + self.assertEqual((await transport.get("https://vault.example/secret")).status_code, 200) + + async def test_expired_and_proactively_refreshable_tokens_reuse_healthy_binding(self): + for lifetime, advance, refresh_in in ((3600, 3601, None), (3600, 3300, None), (7200, 3601, 3600)): + with self.subTest(lifetime=lifetime, advance=advance, refresh_in=refresh_in): + self.cache.deserialize("{}") + token = dict(access_token="before-refresh", token_type="mtls_pop", expires_in=lifetime) + if refresh_in is not None: + token["refresh_in"] = refresh_in + self.next_tokens = [token] + async with self.client.open_async_session() as client: + first = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + before = len(self.token_requests) + with patch("msal._managed_identity_v2.time.time", return_value=time.time() + advance): + refreshed = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + cached = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertEqual(refreshed["token_source"], "identity_provider") + self.assertEqual(cached["token_source"], "cache") + self.assertIs(refreshed["binding_certificate"], first["binding_certificate"]) + self.assertEqual(len(self.token_requests), before + 1) + + async def test_certificate_renewal_and_closure_never_reuse_old_bound_token(self): + async with self.client.open_async_session() as client: + for invalidate in ("renewal", "closed"): + with self.subTest(invalidate=invalidate): + self.next_tokens = [dict( + access_token="before-" + invalidate, token_type="mtls_pop", expires_in=3600)] + first = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True, force_refresh=True) + binding = first["binding_certificate"] + if invalidate == "renewal": + binding.expires_on = time.time() + 86400 + else: + binding.close() + before = len(self.token_requests) + renewed = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertIsNot(renewed["binding_certificate"], binding) + self.assertNotEqual(renewed["binding_certificate"].key_id, binding.key_id) + self.assertNotEqual(renewed["access_token"], first["access_token"]) + self.assertEqual(renewed["token_source"], "identity_provider") + self.assertEqual(len(self.token_requests), before + 1) + + async def test_changed_key_generation_invalidates_cached_pop_token(self): + async with self.client.open_async_session() as client: + first = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.signer = SoftwareSignerFixture() + with patch("msal._managed_identity_v2._NativeKey", return_value=self.signer): + second = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + cached = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertNotEqual(first["binding_certificate"]._key.generation_id, + second["binding_certificate"]._key.generation_id) + self.assertEqual(second["token_source"], "identity_provider") + self.assertIs(second["binding_certificate"], cached["binding_certificate"]) + self.assertEqual(cached["token_source"], "cache") + self.assertEqual(len(self.token_requests), 2) + + async def test_modes_claims_and_attestation_remain_partitioned(self): + challenge = '{"access_token":{"custom":{"essential":true}}}' + async with self.client.open_async_session() as client: + options = ( + dict(mtls_proof_of_possession=True), + dict(request_over_mtls=True), + dict(mtls_proof_of_possession=True, with_attestation_support=True), + dict(mtls_proof_of_possession=True, claims_challenge=challenge), + ) + results = [await client.acquire_token_for_client( + resource="https://vault.example", **option) for option in options] + self.assertTrue(all(r["token_source"] == "identity_provider" for r in results)) + self.assertIsNone(results[1]["binding_certificate"]) + self.assertTrue(results[2]["binding_certificate"].attested) + for option in options[:3]: + cached = await client.acquire_token_for_client( + resource="https://vault.example", **option) + self.assertEqual(cached["token_source"], "cache") + await client.acquire_token_for_client( + resource="https://vault.example", **options[3]) + self.assertEqual(len(self.token_requests), 5) + + async def test_different_identities_sharing_cache_never_share_token_or_binding(self): + other_id = "66666666-7777-8888-9999-000000000000" + + def metadata(url, **kwargs): + return response(dict(platform(), clientId=kwargs["params"]["client_id"]), url=url) + + def issue(url, **kwargs): + return response(dict( + client_id=kwargs["params"]["client_id"], tenant_id=TENANT, identity_type="UAMI", + certificate=self.signer.certificate(), + mtls_authentication_endpoint="https://region.login.example"), url=url) + + def exchange(**kwargs): + self.token_requests.append(kwargs) + form = parse_qs(kwargs["body"].decode("ascii")) + return response(dict(access_token=form["client_id"][0], token_type="mtls_pop", expires_in=3600)) + + self.http.get.side_effect, self.http.post.side_effect = metadata, issue + self.runtime.request.side_effect = exchange + owners = [ManagedIdentityClient( + UserAssignedManagedIdentity(client_id=identifier), http_client=self.http, token_cache=self.cache) + for identifier in (CLIENT, other_id)] + async with owners[0].open_async_session() as first, owners[1].open_async_session() as second: + results = await asyncio.gather(*(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + for client in (first, second))) + cached = await asyncio.gather(*(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + for client in (first, second))) + self.assertEqual([r["access_token"] for r in results], [CLIENT, other_id]) + self.assertEqual([r["access_token"] for r in cached], [CLIENT, other_id]) + self.assertTrue(all(r["token_source"] == "cache" for r in cached)) + self.assertIsNot(results[0]["binding_certificate"], results[1]["binding_certificate"]) + self.assertEqual(len(self.token_requests), 2) + + async def test_refresh_does_not_replace_binding_of_inflight_resource_request(self): + self.next_tokens = [ + dict(access_token=token, token_type="mtls_pop", expires_in=3600) + for token in ("old-token", "new-token")] + async with self.client.open_async_session() as client: + old = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + binding = old["binding_certificate"] + async with binding.open_async_session() as resource: + async with self._blocked(self.runtime, "request") as (entered, release): + pending = asyncio.create_task(resource.get( + "https://vault.example/secret", headers={"Authorization": "mtls_pop old-token"})) + await asyncio.wait_for(entered.wait(), 2) + # The gate applies to resource work only; allow renewal to proceed. + self.runtime.request.side_effect = self._native_request + new = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True, force_refresh=True) + self.assertIsNot(binding, new["binding_certificate"]) + self.assertTrue(binding._chain_path.exists()) + release.set() + self.assertEqual((await pending).json(), {"value": "unit-resource"}) + cached = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + async with new["binding_certificate"].open_async_session() as current: + await current.get("https://vault.example/secret", headers={ + "Authorization": "mtls_pop " + cached["access_token"]}) + resource_calls = [call.kwargs for call in self.runtime.request.call_args_list + if call.kwargs["url"].endswith("/secret")] + self.assertEqual(resource_calls[0]["certificate_path"], binding._chain_path) + self.assertEqual(resource_calls[0]["headers"]["Authorization"], "mtls_pop old-token") + self.assertIs(cached["binding_certificate"], new["binding_certificate"]) + self.assertEqual(resource_calls[-1]["certificate_path"], new["binding_certificate"]._chain_path) + self.assertEqual(resource_calls[-1]["headers"]["Authorization"], "mtls_pop new-token") + + async def test_failure_is_not_cached_and_retry_can_recover(self): + denial = _V2Error("Unit denial", stage="ests", error_code="unauthorized_client") + self.runtime.request.side_effect = denial + async with self.client.open_async_session() as client: + with self.assertRaises(_V2Error) as caught: + await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertIs(caught.exception, denial) + self.assertEqual(json.loads(self.cache.serialize()).get(self.cache.CredentialType.ACCESS_TOKEN, {}), {}) + self.runtime.request.side_effect = self._native_request + result = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertEqual(result["token_source"], "identity_provider") + self.assertEqual(self.http.post.call_count, 1) + + async def test_cancelled_submitted_call_drains_without_starting_acquisition(self): + session = self.client.open_async_session(max_concurrency=1) + async with session: + async with self._blocked(self.client, "acquire_token_for_client") as (entered, release): + first = asyncio.create_task(session.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + await asyncio.wait_for(entered.wait(), 2) + first.cancel() + with self.assertRaises(asyncio.CancelledError): + await first + queued = asyncio.create_task(session.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + await asyncio.sleep(0) + self.client.acquire_token_for_client.assert_called_once() + closing = asyncio.create_task(session.aclose()) + await asyncio.sleep(0) + self.assertFalse(closing.done()) + release.set() + await asyncio.wait_for(closing, 2) + with self.assertRaises(_V2Error) as caught: + await queued + self.assertEqual(caught.exception.error_code, "session_closed") + self.client.acquire_token_for_client.assert_called_once() + async with self.client.open_async_session() as reopened: + cached = await reopened.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertEqual(cached["token_source"], "identity_provider") + self.assertEqual(len(self.token_requests), 1) + + async def test_cancelled_queued_call_never_starts_or_leaks_capacity(self): + async with self.client.open_async_session(max_concurrency=1) as client: + async with self._blocked(self.client, "acquire_token_for_client") as (entered, release): + first = asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + await asyncio.wait_for(entered.wait(), 2) + queued = asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True, force_refresh=True)) + await asyncio.sleep(0) + queued.cancel() + with self.assertRaises(asyncio.CancelledError): + await queued + release.set() + result = await first + self.client.acquire_token_for_client.assert_called_once() + cached = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertIs(cached["binding_certificate"], result["binding_certificate"]) + self.assertEqual(self.http.post.call_count, 1) + + async def test_timeout_during_proactive_refresh_does_not_poison_reused_worker(self): + old = self._acquire(mtls_proof_of_possession=True) + self._expire_token(refresh_on="1") + self.next_tokens = [ + dict(access_token=token, token_type="mtls_pop", expires_in=3600) + for token in ("discarded-after-timeout", "recovered-on-same-worker")] + async with self.client.open_async_session(max_concurrency=1) as client: + async with self._blocked(self.runtime, "request") as (entered, release): + pending = asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + await asyncio.wait_for(entered.wait(), 2) + submitted = list(client._inflight) + with self.assertRaises(asyncio.TimeoutError): + await asyncio.wait_for(pending, 0.02) + self.assertEqual(len(client._inflight), 1) + release.set() + await asyncio.wait_for(asyncio.gather(*submitted, return_exceptions=True), 2) + self.assertNotIn("discarded-after-timeout", self.cache.serialize()) + cached_entry = next(iter(json.loads(self.cache.serialize())[ + self.cache.CredentialType.ACCESS_TOKEN].values())) + self.assertEqual(cached_entry["secret"], old["access_token"]) + recovered = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertEqual(recovered["access_token"], "recovered-on-same-worker") + self.assertEqual(recovered["token_source"], "identity_provider") + self.assertIs(recovered["binding_certificate"], old["binding_certificate"]) + self.assertEqual(len(self.token_requests), 3) + self.http.post.assert_called_once() + + async def test_cancelling_all_policy_waiters_leaves_same_session_usable(self): + options = dict(resource="https://vault.example", mtls_proof_of_possession=True) + async with self.client.open_async_session(max_concurrency=4) as client: + async with self._blocked(self.runtime, "request") as (entered, release): + async with self._policy_waiters(4) as joined: + owner = asyncio.create_task(client.acquire_token_for_client(**options)) + await asyncio.wait_for(entered.wait(), 2) + waiters = [asyncio.create_task(client.acquire_token_for_client(**options)) for _ in range(3)] + await asyncio.wait_for(joined.wait(), 2) + submitted = list(client._inflight) + for task in [owner] + waiters: + task.cancel() + cancelled = await asyncio.gather(owner, *waiters, return_exceptions=True) + self.assertTrue(all(isinstance(result, asyncio.CancelledError) for result in cancelled)) + release.set() + await asyncio.wait_for(asyncio.gather(*submitted, return_exceptions=True), 2) + self.runtime.request.assert_called_once() + self.assertFalse(json.loads(self.cache.serialize()).get(self.cache.CredentialType.ACCESS_TOKEN)) + recovered = await client.acquire_token_for_client(**options) + cached = await client.acquire_token_for_client(**options) + self.assertEqual(recovered["token_source"], "identity_provider") + self.assertEqual(cached["token_source"], "cache") + self.assertIs(cached["binding_certificate"], recovered["binding_certificate"]) + self.assertEqual(len(self.token_requests), 2) + self.http.post.assert_called_once() + + async def test_executor_submission_failure_releases_capacity_for_next_request(self): + async with self.client.open_async_session(max_concurrency=1) as client: + with patch.object(client._executor, "submit", side_effect=RuntimeError("unit submit failure")): + with self.assertRaisesRegex(RuntimeError, "unit submit failure"): + await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.http.get.assert_not_called() + self.http.post.assert_not_called() + self.runtime.request.assert_not_called() + recovered = await asyncio.wait_for(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True), 2) + self.assertEqual(recovered["token_source"], "identity_provider") + self.assertEqual(len(self.token_requests), 1) + + async def test_cache_write_failure_propagates_and_next_request_recovers(self): + async with self.client.open_async_session(max_concurrency=1) as client: + with patch.object(self.cache, "add", side_effect=RuntimeError("unit cache write failure")): + with self.assertRaisesRegex(RuntimeError, "unit cache write failure"): + await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertFalse(json.loads(self.cache.serialize()).get(self.cache.CredentialType.ACCESS_TOKEN)) + recovered = await asyncio.wait_for(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True), 2) + self.assertEqual(recovered["token_source"], "identity_provider") + self.assertEqual(len(self.token_requests), 2) + self.http.post.assert_called_once() + + async def test_resource_capacity_and_shutdown_with_many_waiters(self): + result = self._acquire(mtls_proof_of_possession=True) + binding = result["binding_certificate"] + for action in ("cancel_waiters", "close"): + with self.subTest(action=action): + entered, release = asyncio.Event(), threading.Event() + loop, count_lock, calls = asyncio.get_running_loop(), threading.Lock(), 0 + + def blocked(**kwargs): + nonlocal calls + with count_lock: + calls += 1 + if calls == 2: + loop.call_soon_threadsafe(entered.set) + if not release.wait(5): + raise RuntimeError("The unit resource-capacity gate timed out.") + return self._native_request(**kwargs) + + async with binding.open_async_session(max_concurrency=2) as session: + with patch.object(self.runtime, "request", side_effect=blocked): + pending = [asyncio.create_task(session.get("https://vault.example/secret")) + for _ in range(8)] + closing = None + try: + await asyncio.wait_for(entered.wait(), 2) + self.assertEqual(calls, 2) + if action == "cancel_waiters": + for task in pending[2:]: + task.cancel() + cancelled = await asyncio.gather(*pending[2:], return_exceptions=True) + self.assertTrue(all(isinstance(item, asyncio.CancelledError) + for item in cancelled)) + self.assertEqual(len(session._inflight), 2) + else: + closing = asyncio.create_task(session.aclose()) + await asyncio.sleep(0) + self.assertTrue(session._closed) + self.assertFalse(closing.done()) + self.assertEqual(calls, 2) + finally: + release.set() + results = await asyncio.wait_for( + asyncio.gather(*pending, return_exceptions=True), 2) + if closing is not None: + await asyncio.wait_for(closing, 2) + self.assertTrue(all(item.status_code == 200 for item in results[:2])) + if action == "close": + self.assertTrue(all(isinstance(item, _V2Error) + and item.error_code == "binding_closed" for item in results[2:])) + self.assertEqual(calls, 2) + self.assertFalse(binding._closed) + async with binding.open_async_session() as session: + self.assertEqual((await session.get("https://vault.example/secret")).status_code, 200) + + async def test_resource_errors_release_capacity_and_preserve_borrowed_binding(self): + async with self.client.open_async_session() as client: + result = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + binding = result["binding_certificate"] + session = binding.open_async_session(max_concurrency=1) + async with session: + for url, data, error_code in ( + ("https://other.example/secret", None, "origin_mismatch"), + ("https://vault.example/secret", iter([b"body"]), "unsupported_transport_option")): + with self.subTest(error_code=error_code), self.assertRaises(_V2Error) as caught: + await session.post(url, data=data) + self.assertEqual(caught.exception.error_code, error_code) + self.assertEqual(self.runtime.request.call_count, 1) # Only the token exchange. + answer = await session.get("https://vault.example/secret") + self.assertEqual(answer.json(), {"value": "unit-resource"}) + with self.assertRaises(_V2Error) as caught: + await session.get("https://vault.example/secret") + self.assertEqual(caught.exception.error_code, "binding_closed") + async with binding.open_async_session() as another: + self.assertEqual((await another.get("https://vault.example/secret")).status_code, 200) + + async def test_callback_and_other_work_run_without_waiting_for_native_completion(self): + from sample.managed_identity_v2 import async_pop + handled = asyncio.Event() + responses = [] + + def on_response(completed): + responses.append(completed.result().json()) + handled.set() + + with patch.object(self.http, "close", wraps=self.http.close) as close: + async with self._blocked(self.http, "post") as (entered, release): + task = asyncio.create_task(async_pop( + self.client, "https://vault.example", "https://vault.example/secret")) + task.add_done_callback(on_response) + await asyncio.wait_for(entered.wait(), 2) + self.assertFalse(task.done()) + self.assertFalse(handled.is_set()) + release.set() + await task + await asyncio.wait_for(handled.wait(), 2) + self.assertEqual(responses, [{"value": "unit-resource"}]) + close.assert_not_called() + call = self.runtime.request.call_args.kwargs + self.assertEqual(call["url"], "https://vault.example/secret") + self.assertEqual(call["headers"]["Authorization"], "mtls_pop opaque-unit-token") + self.assertEqual(call["headers"]["x-ms-tokenboundauth"], "true") + self.attestation.attest.assert_called_once() + + async def test_closed_session_and_invalid_modes_do_not_start_work(self): + session = self.client.open_async_session() + await session.aclose() + with self.assertRaises(_V2Error): + await session.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + with self.assertRaises(_V2Error): + await session.__aenter__() + async with self.client.open_async_session() as client: + for options in ({}, dict(mtls_proof_of_possession=True, request_over_mtls=True), + dict(mtls_proof_of_possession=True, minimum_binding_strength=2)): + with self.subTest(options=options), self.assertRaises(ManagedIdentityError): + await client.acquire_token_for_client(resource="https://vault.example", **options) + self.http.get.assert_not_called() + self.http.post.assert_not_called() + self.runtime.request.assert_not_called() + + async def test_discovery_uses_existing_cache_and_preserves_returned_value_isolation(self): + self.http.get.side_effect = None + self.http.get.return_value = response({}, status=400) + async with self.client.open_async_session() as client: + result = await client.get_managed_identity_capabilities(timeout=2) + self.assertEqual(result["max_supported_binding_strength"], 3) + result["max_supported_binding_strength"] = 99 + cached = await client.get_managed_identity_capabilities(timeout=2) + self.assertEqual(cached["max_supported_binding_strength"], 3) + self.http.get.assert_called_once() + self.http.post.assert_not_called() + + async def test_discovery_deadline_includes_waiting_for_worker_capacity(self): + async with self.client.open_async_session(max_concurrency=1) as client: + async with self._blocked(self.client, "acquire_token_for_client") as (entered, release): + first = asyncio.create_task(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + await asyncio.wait_for(entered.wait(), 2) + with self.assertRaises(_V2Error) as caught: + await client.get_managed_identity_capabilities(timeout=0.02) + self.assertEqual(caught.exception.error_code, "timeout") + self.http.get.assert_not_called() + release.set() + await first + self.http.get.side_effect = None + self.http.get.return_value = response({}, status=400) + result = await client.get_managed_identity_capabilities(timeout=2) + self.assertEqual(result["max_supported_binding_strength"], 3) + + async def test_cancelling_close_does_not_cancel_acquisition_or_allow_new_work(self): + session = self.client.open_async_session() + async with session: + async with self._blocked(self.client, "acquire_token_for_client") as (entered, release): + pending = asyncio.create_task(session.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + await asyncio.wait_for(entered.wait(), 2) + closing = asyncio.create_task(session.aclose()) + await asyncio.sleep(0) + closing.cancel() + with self.assertRaises(asyncio.CancelledError): + await closing + self.assertFalse(pending.done()) + with self.assertRaises(_V2Error) as caught: + await session.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertEqual(caught.exception.error_code, "session_closed") + release.set() + await session.aclose() + self.assertEqual((await pending)["token_type"], "mtls_pop") + + async def test_failure_after_cancellation_is_diagnosed_without_logging_error_details(self): + failure = _V2Error("private-error-detail", stage="ests", error_code="unauthorized_client") + self.runtime.request.side_effect = failure + async with self.client.open_async_session() as session: + async with self._blocked(self.runtime, "request") as (entered, release): + task = asyncio.create_task(session.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True)) + await asyncio.wait_for(entered.wait(), 2) + task.cancel() + with self.assertRaises(asyncio.CancelledError): + await task + with self.assertLogs("msal._managed_identity_async", level="WARNING") as captured: + release.set() + await session.aclose() + self.assertIn("_V2Error", "\n".join(captured.output)) + self.assertNotIn("private-error-detail", "\n".join(captured.output)) + self.assertEqual(json.loads(self.cache.serialize()).get(self.cache.CredentialType.ACCESS_TOKEN, {}), {}) + + async def test_cross_loop_use_is_rejected_without_poisoning_original_loop(self): + async with self.client.open_async_session() as client: + with self.assertRaises(_V2Error) as caught: + await asyncio.to_thread(lambda: asyncio.run(client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True))) + self.assertEqual(caught.exception.error_code, "unsupported_transport_option") + self.http.get.assert_not_called() + result = await client.acquire_token_for_client( + resource="https://vault.example", mtls_proof_of_possession=True) + self.assertEqual(result["token_type"], "mtls_pop") + + async def test_invalid_concurrency_is_rejected_before_any_work(self): + for concurrency in (True, 0, -1, 33, 1.5, None): + with self.subTest(concurrency=concurrency), self.assertRaises(_V2Error): + self.client.open_async_session(max_concurrency=concurrency) + self.http.get.assert_not_called() + self.runtime.request.assert_not_called() + + class CapabilityDiscoveryTests(unittest.TestCase): def setUp(self): from msal.managed_identity import DEFAULT_TO_VM