ace-pluto's picture
build-spec-tasks: the training tasks of Kerberos 35B-A3B
845996e verified
|
Raw History Blame Contribute Delete
14.7 kB

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) mutates params in place, adding the wire name for the selector. With the default mapping (ManagedIdentity._types_mapping) the wire names are client_id, msi_res_id (for ResourceId) and object_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 exception class ManagedIdentityError(ValueError).
  • _supported_arc_platforms_and_their_prefixes maps sys.platform to the directory holding the Basic-auth key file; the key filename is derived from the WWW-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

  1. msal/sku.py: change __version__ = "1.37.0" to __version__ = "1.38.0".
  2. msal/managed_identity.py, in _obtain_token: delete the if ManagedIdentity.is_user_assigned(managed_identity): raise ManagedIdentityError(...) block inside the if arc_endpoint: branch, and change the call to return _obtain_token_on_arc(http_client, arc_endpoint, resource, managed_identity).
  3. msal/managed_identity.py, _obtain_token_on_arc: add the managed_identity=None parameter. 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: create params = {"api-version": "2020-06-01", "resource": resource}, call _adjust_param(params, managed_identity) (default mapping, so a resource-id selector becomes msi_res_id, matching the VM/IMDS source), and pass params=params to the second http_client.get. _adjust_param is a no-op when managed_identity is None or system-assigned, so those requests are unchanged.
  4. Same function, inside the success branch (payload.get("access_token") and payload.get("expires_in")), before building the return dict: if managed_identity is user-assigned (ManagedIdentity.is_user_assigned(managed_identity)), determine the requested wire name via ManagedIdentity._types_mapping.get(managed_identity.get(ManagedIdentity.ID_TYPE)) and the requested value via managed_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, raise ManagedIdentityError with 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 and None identities 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

  1. 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, msal and msal.managed_identity names used below are either standard, already exported by the package, or created here). Then run python -m pytest tests/test_mi.py -q and 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"
  1. msal/sku.py: apply Design step 1. Check: python -m pytest tests/test_mi.py -q (the version test now passes).
  2. msal/managed_identity.py, _obtain_token: apply Design step 2. Check: python -m pytest tests/test_mi.py -q.
  3. msal/managed_identity.py, _obtain_token_on_arc: apply Design steps 3 and 4. Check: python -m pytest tests/test_mi.py -q.
  4. 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 in tests/test_mi.py must all pass).