Download tasks/AzureAD__microsoft-authentication-library-for-python__711d8a6887/spec.md from WardenOfPluto/build-spec-tasks: direct link, hf CLI and curl.
- Browser
- Download file 14.7 kB
-
https://huggingface.co/datasets/WardenOfPluto/build-spec-tasks/resolve/main/tasks/AzureAD__microsoft-authentication-library-for-python__711d8a6887/spec.md
- Command line
-
hf download hf://datasets/WardenOfPluto/build-spec-tasks/tasks/AzureAD__microsoft-authentication-library-for-python__711d8a6887/spec.md
-
curl -L -o spec.md https://huggingface.co/datasets/WardenOfPluto/build-spec-tasks/resolve/main/tasks/AzureAD__microsoft-authentication-library-for-python__711d8a6887/spec.md
Context
msal/managed_identity.py implements managed identity token acquisition for several Azure sources. msal/sku.py holds the package version:
__version__ = "1.37.0"
SKU = "MSAL.Python"
The Arc path is reached from _obtain_token(...), which dispatches on environment variables. Today the Arc branch rejects any user-assigned identity before making a request:
arc_endpoint = _get_arc_endpoint()
if arc_endpoint:
if ManagedIdentity.is_user_assigned(managed_identity):
raise ManagedIdentityError( # Note: Azure Identity for Python raised exception too
"Invalid managed_identity parameter. "
"Azure Arc supports only system-assigned managed identity, "
"See also "
"https://learn.microsoft.com/en-us/azure/service-fabric/configure-existing-cluster-enable-managed-identity-token-service")
return _obtain_token_on_arc(http_client, arc_endpoint, resource)
_obtain_token_on_arc currently takes no identity and sends no selector:
def _obtain_token_on_arc(http_client, endpoint, resource):
# https://learn.microsoft.com/en-us/azure/azure-arc/servers/managed-identity-authentication
logger.debug("Obtaining token via managed identity on Azure Arc")
resp = http_client.get(
endpoint,
params={"api-version": "2020-06-01", "resource": resource},
headers={"Metadata": "true"},
)
Its success branch is:
try:
payload = json.loads(response.text)
if payload.get("access_token") and payload.get("expires_in"):
# Example: https://learn.microsoft.com/en-us/azure/azure-arc/servers/media/managed-identity-authentication/bash-token-output-example.png
return {
"access_token": payload["access_token"],
"expires_in": int(payload["expires_in"]),
"token_type": payload.get("token_type", "Bearer"),
"resource": payload.get("resource"),
}
Helpers and names to reuse (all in msal/managed_identity.py):
_adjust_param(params, managed_identity, types_mapping=None)mutatesparamsin place, adding the wire name for the selector. With the default mapping (ManagedIdentity._types_mapping) the wire names areclient_id,msi_res_id(forResourceId) andobject_id:
def _adjust_param(params, managed_identity, types_mapping=None):
# Modify the params dict in place
id_name = (types_mapping or ManagedIdentity._types_mapping).get(
managed_identity.get(ManagedIdentity.ID_TYPE))
if id_name:
params[id_name] = managed_identity[ManagedIdentity.ID]
ManagedIdentity.is_user_assigned(unknown),ManagedIdentity.ID_TYPE,ManagedIdentity.ID, and the exceptionclass ManagedIdentityError(ValueError)._supported_arc_platforms_and_their_prefixesmapssys.platformto the directory holding the Basic-auth key file; the key filename is derived from theWWW-Authenticate: Basic realm=...challenge.
The change: Arc now accepts user-assigned identity selectors, forwards them on the token request using the IMDS spellings (msi_res_id, never mi_res_id), and fails closed by raising ManagedIdentityError when a 200 response does not echo the requested identity. The version becomes 1.38.0.
Files
- Modify:
msal/managed_identity.py(forward selectors on Arc and verify the echoed identity),msal/sku.py(version bump),tests/test_mi.py(new Arc selector and fail-closed tests). - Create: none.
- Do not touch:
msal/application.py,tests/test_mi_e2e.py,sample/managed_identity_sample.py,.Pipelines/pipeline-publish.yml.
Signatures
def _obtain_token_on_arc(
http_client, endpoint, resource, managed_identity=None,
):
"""..."""
# Returns a normalized token dict on success, or an error dict;
# raises ManagedIdentityError when a requested user-assigned identity
# is not confirmed by the response, and ArcPlatformNotSupportedError /
# ManagedIdentityError as before for challenge/platform/key-file problems.
_obtain_token(http_client, managed_identity, resource, *, access_token_sha256_to_refresh=None, client_capabilities=None) keeps its signature; only its Arc branch changes behaviour.
Design
msal/sku.py: change__version__ = "1.37.0"to__version__ = "1.38.0".msal/managed_identity.py, in_obtain_token: delete theif ManagedIdentity.is_user_assigned(managed_identity): raise ManagedIdentityError(...)block inside theif arc_endpoint:branch, and change the call toreturn _obtain_token_on_arc(http_client, arc_endpoint, resource, managed_identity).msal/managed_identity.py,_obtain_token_on_arc: add themanaged_identity=Noneparameter. Leave the first (challenge) GET exactly as it is. For the second GET, build the params through a dict so the selector can be added: createparams = {"api-version": "2020-06-01", "resource": resource}, call_adjust_param(params, managed_identity)(default mapping, so a resource-id selector becomesmsi_res_id, matching the VM/IMDS source), and passparams=paramsto the secondhttp_client.get._adjust_paramis a no-op whenmanaged_identityisNoneor system-assigned, so those requests are unchanged.- Same function, inside the success branch (
payload.get("access_token") and payload.get("expires_in")), before building the return dict: ifmanaged_identityis user-assigned (ManagedIdentity.is_user_assigned(managed_identity)), determine the requested wire name viaManagedIdentity._types_mapping.get(managed_identity.get(ManagedIdentity.ID_TYPE))and the requested value viamanaged_identity[ManagedIdentity.ID]. Read the echoed value from the payload under that wire name, falling back to"mi_res_id"when the wire name is"msi_res_id"(safety net for agents echoing the App Service spelling). If the echoed value is absent or differs from the requested value, raiseManagedIdentityErrorwith a message that names the requested identity (the module's existing exception, as every other check here uses). Otherwise return the token dict as before. System-assigned andNoneidentities skip this check entirely.
Errors use the module's existing ManagedIdentityError, as every other validation in this file does.
Behaviour and edge cases
| Input or situation | Expected result |
|---|---|
| Arc, system-assigned identity | Token dict returned; token request params contain no selector key; no echo check |
| Arc, UAMI by client_id | Second GET params include client_id equal to the id; payload echoes client_id equal to the id; token returned |
| Arc, UAMI by resource_id | Second GET params include msi_res_id (never mi_res_id); payload echoes msi_res_id (or mi_res_id) equal to the id; token returned |
| Arc, UAMI by object_id | Second GET params include object_id; payload echoes object_id equal to the id; token returned |
| Arc, UAMI requested, 200 response with no echoed identity | Raises ManagedIdentityError |
| Arc, UAMI requested, 200 response echoing a different identity | Raises ManagedIdentityError |
Arc, non-token payload (no access_token/expires_in) |
Unchanged: returns the {"error": "invalid_request", ...} dict, no echo check |
Arc, unrecognizable WWW-Authenticate, unsupported platform, oversized key file |
Unchanged: ManagedIdentityError / ArcPlatformNotSupportedError as before |
| Non-Arc sources (VM, App Service, ML, Service Fabric) | Unchanged behaviour |
msal.sku.__version__ |
"1.38.0" |
Tasks
- Tests first. Append the code below to
tests/test_mi.py(merge the import lines into the file's existing imports if any duplicate;pytest,msalandmsal.managed_identitynames used below are either standard, already exported by the package, or created here). Then runpython -m pytest tests/test_mi.py -qand confirm the new Arc selector tests fail on today's code (the system-assigned regression guard and only it may pass).
import json
import sys
import pytest
import msal
from msal.managed_identity import ManagedIdentityError
from msal.sku import __version__
class _FakeResponse:
def __init__(self, text="", headers=None):
self.text = text
self.headers = headers or {}
self.status_code = 200
class _FakeArcHttpClient:
"""Answers the Arc Basic challenge, then returns a canned token payload."""
def __init__(self, realm, payload):
self._realm = realm
self._payload = payload
self.requests = []
def get(self, endpoint, params=None, headers=None):
self.requests.append({"params": params, "headers": headers})
if len(self.requests) == 1:
return _FakeResponse(headers={
"WWW-Authenticate": "Basic realm={}".format(self._realm)})
return _FakeResponse(text=json.dumps(self._payload))
@pytest.fixture
def arc_env(monkeypatch, tmp_path):
for var in ("IDENTITY_HEADER", "IDENTITY_SERVER_THUMBPRINT",
"MSI_ENDPOINT", "MSI_SECRET"):
monkeypatch.delenv(var, raising=False)
monkeypatch.setenv(
"IDENTITY_ENDPOINT",
"http://localhost:40342/metadata/identity/oauth2/token")
monkeypatch.setenv(
"IMDS_ENDPOINT",
"http://localhost:40342/metadata/identity/oauth2/token")
realm = str(tmp_path / "challenge")
with open(str(tmp_path / "challenge.key"), "w") as f:
f.write("a secret")
monkeypatch.setitem(
msal.managed_identity._supported_arc_platforms_and_their_prefixes,
sys.platform, str(tmp_path))
return realm
def _arc_client(identity, payload, realm):
http = _FakeArcHttpClient(realm, payload)
client = msal.ManagedIdentityClient(identity, http_client=http)
return client, http
def test_arc_forwards_client_id_selector(arc_env):
# Today msal/managed_identity.py _obtain_token raises ManagedIdentityError
# for a user-assigned identity on Arc, so no token is returned.
identity = msal.UserAssignedManagedIdentity(client_id="client_id_1")
payload = {"access_token": "AT", "expires_in": 3600,
"client_id": "client_id_1"}
client, http = _arc_client(identity, payload, arc_env)
result = client.acquire_token_for_client(resource="https://resource")
assert result["access_token"] == "AT"
assert http.requests[1]["params"]["client_id"] == "client_id_1"
def test_arc_resource_id_selector_uses_msi_res_id(arc_env):
# Today _obtain_token raises for user-assigned on Arc, so no request
# carrying msi_res_id is ever made.
identity = msal.UserAssignedManagedIdentity(resource_id="resource_id_1")
payload = {"access_token": "AT", "expires_in": 3600,
"msi_res_id": "resource_id_1"}
client, http = _arc_client(identity, payload, arc_env)
result = client.acquire_token_for_client(resource="https://resource")
assert result["access_token"] == "AT"
params = http.requests[1]["params"]
assert params["msi_res_id"] == "resource_id_1"
assert "mi_res_id" not in params
def test_arc_forwards_object_id_selector(arc_env):
# Today _obtain_token raises for user-assigned on Arc.
identity = msal.UserAssignedManagedIdentity(object_id="object_id_1")
payload = {"access_token": "AT", "expires_in": 3600,
"object_id": "object_id_1"}
client, http = _arc_client(identity, payload, arc_env)
result = client.acquire_token_for_client(resource="https://resource")
assert result["access_token"] == "AT"
assert http.requests[1]["params"]["object_id"] == "object_id_1"
def test_arc_fail_closed_when_echo_missing(arc_env):
# Today _obtain_token raises before any HTTP request is made, so the
# assertion that the selector was forwarded fails.
identity = msal.UserAssignedManagedIdentity(client_id="client_id_1")
payload = {"access_token": "AT", "expires_in": 3600} # legacy agent, no echo
client, http = _arc_client(identity, payload, arc_env)
with pytest.raises(ManagedIdentityError):
client.acquire_token_for_client(resource="https://resource")
assert len(http.requests) >= 2
assert http.requests[1]["params"].get("client_id") == "client_id_1"
def test_arc_fail_closed_when_echo_mismatches(arc_env):
# Today _obtain_token raises before any HTTP request is made, so the
# assertion that the selector was forwarded fails.
identity = msal.UserAssignedManagedIdentity(client_id="client_id_1")
payload = {"access_token": "AT", "expires_in": 3600,
"client_id": "some_other_identity"}
client, http = _arc_client(identity, payload, arc_env)
with pytest.raises(ManagedIdentityError):
client.acquire_token_for_client(resource="https://resource")
assert http.requests[1]["params"].get("client_id") == "client_id_1"
def test_arc_accepts_mi_res_id_echo_as_safety_net(arc_env):
# Today _obtain_token raises for user-assigned on Arc.
identity = msal.UserAssignedManagedIdentity(resource_id="resource_id_1")
payload = {"access_token": "AT", "expires_in": 3600,
"mi_res_id": "resource_id_1"}
client, http = _arc_client(identity, payload, arc_env)
result = client.acquire_token_for_client(resource="https://resource")
assert result["access_token"] == "AT"
def test_arc_system_assigned_unaffected(arc_env):
# Regression guard for existing behaviour; passes before and after.
identity = msal.SystemAssignedManagedIdentity()
payload = {"access_token": "AT", "expires_in": 3600}
client, http = _arc_client(identity, payload, arc_env)
result = client.acquire_token_for_client(resource="https://resource")
assert result["access_token"] == "AT"
assert "client_id" not in http.requests[1]["params"]
def test_version_bumped():
# Today msal/sku.py defines __version__ = "1.37.0".
assert __version__ == "1.38.0"
msal/sku.py: apply Design step 1. Check:python -m pytest tests/test_mi.py -q(the version test now passes).msal/managed_identity.py,_obtain_token: apply Design step 2. Check:python -m pytest tests/test_mi.py -q.msal/managed_identity.py,_obtain_token_on_arc: apply Design steps 3 and 4. Check:python -m pytest tests/test_mi.py -q.- Run the full managed-identity test files and re-read the behaviour table against the code:
python -m pytest tests/test_mi.py tests/test_mi_e2e.py -q(ignore live-endpoint skips/errors that exist on the baseline if the environment lacks Azure access; the unit tests intests/test_mi.pymust all pass).