--- a/msal/managed_identity.py +++ b/msal/managed_identity.py @@ -452,13 +452,7 @@ ) 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) + return _obtain_token_on_arc(http_client, arc_endpoint, resource, managed_identity) return _obtain_token_on_azure_vm(http_client, managed_identity, resource) @@ -643,7 +637,7 @@ class ArcPlatformNotSupportedError(ManagedIdentityError): pass -def _obtain_token_on_arc(http_client, endpoint, resource): +def _obtain_token_on_arc(http_client, endpoint, resource, managed_identity=None): # 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( @@ -672,14 +666,27 @@ raise ManagedIdentityError("Local key file shall not be larger than 4KB") with open(filename) as f: secret = f.read() + params = {"api-version": "2020-06-01", "resource": resource} + _adjust_param(params, managed_identity) response = http_client.get( endpoint, - params={"api-version": "2020-06-01", "resource": resource}, + params=params, headers={"Metadata": "true", "Authorization": "Basic {}".format(secret)}, ) try: payload = json.loads(response.text) if payload.get("access_token") and payload.get("expires_in"): + # Fail-closed: verify echoed user-assigned identity + if ManagedIdentity.is_user_assigned(managed_identity): + wire_name = ManagedIdentity._types_mapping.get( + managed_identity.get(ManagedIdentity.ID_TYPE)) + requested_value = managed_identity[ManagedIdentity.ID] + # Safety net: agents may echo mi_res_id instead of msi_res_id + echo_value = payload.get(wire_name, payload.get("mi_res_id")) + if echo_value is None or echo_value != requested_value: + raise ManagedIdentityError( + "Managed identity not echoed by Arc endpoint. " + "Expected {}={}".format(wire_name, requested_value)) # 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"], --- a/msal/sku.py +++ b/msal/sku.py @@ -2,5 +2,5 @@ """ # The __init__.py will import this. Not the other way around. -__version__ = "1.37.0" +__version__ = "1.38.0" SKU = "MSAL.Python" --- a/tests/test_mi.py +++ b/tests/test_mi.py @@ -532,3 +532,133 @@ def test_default_to_vm(self): self.assertEqual(get_managed_identity_source(), DEFAULT_TO_VM) + + +# --- Arc selector tests (SPEC.md) --- +import pytest +import msal +from msal.managed_identity import ManagedIdentityError as _MIError +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): + 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): + 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): + 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): + identity = msal.UserAssignedManagedIdentity(client_id="client_id_1") + payload = {"access_token": "AT", "expires_in": 3600} + 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): + 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): + 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): + 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(): + assert __version__ == "1.38.0"