Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
108 changes: 107 additions & 1 deletion docs/managed-identity-v2.rst
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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;
Expand Down
132 changes: 132 additions & 0 deletions msal/_managed_identity_async.py
Original file line number Diff line number Diff line change
@@ -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
64 changes: 9 additions & 55 deletions msal/_managed_identity_binding.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
"""Generation-specific requests transport for the blocking Rust transaction ABI."""

import base64
import asyncio
import ctypes
import hashlib
import logging
Expand All @@ -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


Expand Down Expand Up @@ -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()
Loading
Loading