Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.10/site-packages/msal/managed_identity.py: 25%

Shortcuts on this page

r m x   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

444 statements  

1# Copyright (c) Microsoft Corporation. 

2# All rights reserved. 

3# 

4# This code is licensed under the MIT License. 

5import copy 

6import hashlib 

7import ipaddress 

8import json 

9import logging 

10import math 

11import os 

12import re 

13import ssl 

14import sys 

15import time 

16import uuid 

17from urllib.parse import urlparse, urlsplit # Python 3+ 

18from collections import UserDict # Python 3+ 

19from typing import Dict, List, Optional, Tuple, TypedDict, Union 

20import requests 

21from requests.adapters import HTTPAdapter 

22from urllib3.connection import HTTPSConnection 

23from urllib3.connectionpool import HTTPSConnectionPool 

24from urllib3.exceptions import MaxRetryError 

25from urllib3.util import parse_url 

26from urllib3.util import ssl_ as urllib3_ssl 

27from urllib3.util.retry import Retry 

28from .token_cache import TokenCache 

29from .individual_cache import _IndividualCache as IndividualCache 

30from .throttled_http_client import ThrottledHttpClientBase, RetryAfterParser 

31from .cloudshell import _is_running_in_cloud_shell 

32from .sku import SKU, __version__ 

33 

34 

35logger = logging.getLogger(__name__) 

36 

37 

38class ManagedIdentityError(ValueError): 

39 pass 

40 

41 

42class ServiceFabricHttpOptions(TypedDict, total=False): 

43 """Optional settings for MSAL's owned, certificate-pinned Service Fabric client. 

44 

45 See :class:`ManagedIdentityClient` for validation, defaults, and ownership. 

46 No setting can disable endpoint certificate pinning or enable redirects. 

47 """ 

48 headers: Dict[str, str] 

49 proxies: Dict[str, str] 

50 trust_env: bool 

51 timeout: Union[int, float, Tuple[Union[int, float], Union[int, float]]] 

52 max_retries: int 

53 

54 

55class _ServiceFabricOptionsError(ManagedIdentityError): 

56 """A configuration error must not be hidden by proactive-refresh fallback.""" 

57 

58 

59def _snapshot_service_fabric_options(options): 

60 if not isinstance(options, dict): 

61 return options 

62 snapshot = dict(options) 

63 for field in ("headers", "proxies"): 

64 if isinstance(snapshot.get(field), dict): 

65 snapshot[field] = dict(snapshot[field]) 

66 return snapshot 

67 

68 

69def _valid_proxy_host(host): 

70 if not host: 

71 return False 

72 try: 

73 ipaddress.ip_address(host) 

74 return True 

75 except ValueError: 

76 return all(re.fullmatch( 

77 r"[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?", label) 

78 for label in host.encode("idna").decode("ascii").rstrip(".").split(".")) 

79 

80 

81def _valid_service_fabric_proxy(value, *, selection_key=False, allow_default_scheme=False): 

82 if not isinstance(value, str) or not value or any( 

83 character.isspace() or ord(character) < 32 for character in value): 

84 return False 

85 try: 

86 if selection_key: 

87 if value in ("http", "https", "all"): 

88 return True 

89 scheme, separator, host = value.partition("://") 

90 # Requests selection uses urlparse(endpoint).hostname, including 

91 # unbracketed IPv6 literals, rather than a proxy URL's authority. 

92 return bool(separator and scheme in ("http", "https", "all") 

93 and _valid_proxy_host(host)) 

94 if allow_default_scheme: 

95 value = requests.utils.prepend_scheme_if_needed(value, "http") 

96 parsed = urlsplit(value) 

97 if (parsed.scheme not in ("http", "https") 

98 or not _valid_proxy_host(parsed.hostname) 

99 or parsed.query or parsed.fragment or "?" in value or "#" in value 

100 or parsed.path not in ("", "/")): 

101 return False 

102 # The transport's IDNA parser is stricter than Python's builtin codec. 

103 # Consume its potentially credential-bearing errors only in this helper. 

104 parse_url(value) 

105 username, password = requests.utils.get_auth_from_url(value) 

106 if username: # Requests only sends proxy authentication for nonempty usernames. 

107 username.encode("latin-1") 

108 password.encode("latin-1") 

109 # Azure Identity Python's default synchronous transport also uses 

110 # Requests' Latin-1 encoding for Basic proxy authentication. 

111 return (not parsed.netloc.endswith(":") 

112 and (parsed.port is None or 0 < parsed.port <= 65535)) 

113 except (ValueError, UnicodeError): 

114 return False 

115 

116 

117def _validate_service_fabric_options(options): 

118 if not isinstance(options, dict): 

119 raise _ServiceFabricOptionsError("Service Fabric HTTP options must be a dict.") 

120 if options.keys() - ServiceFabricHttpOptions.__annotations__.keys(): 

121 raise _ServiceFabricOptionsError("Unknown Service Fabric HTTP option.") 

122 result = dict(headers={}, proxies={}, trust_env=False, timeout=(5, 30), max_retries=0) 

123 result.update(options) 

124 for field in ("headers", "proxies"): 

125 if not isinstance(result[field], dict) or any( 

126 not isinstance(key, str) or not isinstance(value, str) 

127 for key, value in result[field].items()): 

128 raise _ServiceFabricOptionsError( 

129 "Service Fabric {} must be a dict of strings.".format(field)) 

130 for name, value in result["headers"].items(): 

131 if (not re.fullmatch(r"[!#$%&'*+\-.^_`|~0-9A-Za-z]+", name) 

132 or name.lower() in ("secret", "host") 

133 or (value and value[0].isspace()) 

134 or any(ord(character) < 32 and character != "\t" 

135 or ord(character) == 127 or ord(character) > 255 

136 for character in value)): 

137 raise _ServiceFabricOptionsError("Invalid or reserved Service Fabric header.") 

138 for key, value in result["proxies"].items(): 

139 if (not _valid_service_fabric_proxy(key, selection_key=True) 

140 or not _valid_service_fabric_proxy(value)): 

141 raise _ServiceFabricOptionsError("Invalid Service Fabric proxies configuration.") 

142 if not isinstance(result["trust_env"], bool): 

143 raise _ServiceFabricOptionsError("Service Fabric trust_env must be a bool.") 

144 retries = result["max_retries"] 

145 if isinstance(retries, bool) or not isinstance(retries, int) or retries < 0: 

146 raise _ServiceFabricOptionsError("Service Fabric max_retries must be a non-negative int.") 

147 timeout = result["timeout"] 

148 waits = timeout if isinstance(timeout, tuple) else (timeout, timeout) 

149 try: 

150 valid_timeout = len(waits) == 2 and all( 

151 isinstance(wait, (int, float)) and not isinstance(wait, bool) 

152 and wait > 0 and math.isfinite(wait) for wait in waits) 

153 except OverflowError: 

154 valid_timeout = False 

155 if not valid_timeout: 

156 raise _ServiceFabricOptionsError( 

157 "Service Fabric timeout must contain positive finite numbers.") 

158 return result 

159 

160 

161class ManagedIdentity(UserDict): 

162 """Feed an instance of this class to :class:`msal.ManagedIdentityClient` 

163 to acquire token for the specified managed identity. 

164 """ 

165 # The key names used in config dict 

166 ID_TYPE = "ManagedIdentityIdType" # Contains keyword ManagedIdentity so its json equivalent will be more readable 

167 ID = "Id" 

168 

169 # Valid values for key ID_TYPE 

170 CLIENT_ID = "ClientId" 

171 RESOURCE_ID = "ResourceId" 

172 OBJECT_ID = "ObjectId" 

173 SYSTEM_ASSIGNED = "SystemAssigned" 

174 

175 _types_mapping = { # Maps type name in configuration to type name on wire 

176 CLIENT_ID: "client_id", 

177 RESOURCE_ID: "msi_res_id", # VM's IMDS prefers msi_res_id https://github.com/Azure/azure-rest-api-specs/blob/dba6ed1f03bda88ac6884c0a883246446cc72495/specification/imds/data-plane/Microsoft.InstanceMetadataService/stable/2018-10-01/imds.json#L233-L239 

178 OBJECT_ID: "object_id", 

179 } 

180 

181 @classmethod 

182 def is_managed_identity(cls, unknown): 

183 return (isinstance(unknown, ManagedIdentity) 

184 or cls.is_system_assigned(unknown) 

185 or cls.is_user_assigned(unknown)) 

186 

187 @classmethod 

188 def is_system_assigned(cls, unknown): 

189 return isinstance(unknown, SystemAssignedManagedIdentity) or ( 

190 isinstance(unknown, dict) 

191 and unknown.get(cls.ID_TYPE) == cls.SYSTEM_ASSIGNED) 

192 

193 @classmethod 

194 def is_user_assigned(cls, unknown): 

195 return isinstance(unknown, UserAssignedManagedIdentity) or ( 

196 isinstance(unknown, dict) 

197 and unknown.get(cls.ID_TYPE) in cls._types_mapping 

198 and unknown.get(cls.ID)) 

199 

200 def __init__(self, identifier=None, id_type=None): 

201 # Undocumented. Use subclasses instead. 

202 super(ManagedIdentity, self).__init__({ 

203 self.ID_TYPE: id_type, 

204 self.ID: identifier, 

205 }) 

206 

207 

208class SystemAssignedManagedIdentity(ManagedIdentity): 

209 """Represent a system-assigned managed identity. 

210 

211 It is equivalent to a Python dict of:: 

212 

213 {"ManagedIdentityIdType": "SystemAssigned", "Id": None} 

214 

215 or a JSON blob of:: 

216 

217 {"ManagedIdentityIdType": "SystemAssigned", "Id": null} 

218 """ 

219 def __init__(self): 

220 super(SystemAssignedManagedIdentity, self).__init__(id_type=self.SYSTEM_ASSIGNED) 

221 

222 

223class UserAssignedManagedIdentity(ManagedIdentity): 

224 """Represent a user-assigned managed identity. 

225 

226 Depends on the id you provided, the outcome is equivalent to one of the below:: 

227 

228 {"ManagedIdentityIdType": "ClientId", "Id": "foo"} 

229 {"ManagedIdentityIdType": "ResourceId", "Id": "foo"} 

230 {"ManagedIdentityIdType": "ObjectId", "Id": "foo"} 

231 """ 

232 def __init__(self, *, client_id=None, resource_id=None, object_id=None): 

233 if client_id and not resource_id and not object_id: 

234 super(UserAssignedManagedIdentity, self).__init__( 

235 id_type=self.CLIENT_ID, identifier=client_id) 

236 elif not client_id and resource_id and not object_id: 

237 super(UserAssignedManagedIdentity, self).__init__( 

238 id_type=self.RESOURCE_ID, identifier=resource_id) 

239 elif not client_id and not resource_id and object_id: 

240 super(UserAssignedManagedIdentity, self).__init__( 

241 id_type=self.OBJECT_ID, identifier=object_id) 

242 else: 

243 raise ManagedIdentityError( 

244 "You shall specify one of the three parameters: " 

245 "client_id, resource_id, object_id") 

246 

247 

248class _ThrottledHttpClient(ThrottledHttpClientBase): 

249 def __init__(self, *args, **kwargs): 

250 super(_ThrottledHttpClient, self).__init__(*args, **kwargs) 

251 self.get = IndividualCache( # All MIs (except Cloud Shell) use GETs 

252 mapping=self._expiring_mapping, 

253 key_maker=lambda func, args, kwargs: "REQ {} hash={} 429/5xx/Retry-After".format( 

254 args[0], # It is the endpoint, typically a constant per MI type 

255 self._hash( 

256 # Managed Identity flavors have inconsistent parameters. 

257 # We simply choose to hash them all. 

258 str(kwargs.get("params")) + str(kwargs.get("data"))), 

259 ), 

260 expires_in=RetryAfterParser(5).parse, # 5 seconds default for non-PCA 

261 )(self.get) # Note: Decorate the parent get(), not the http_client.get() 

262 

263 

264class ManagedIdentityClient(object): 

265 """This API encapsulates multiple managed identity back-ends: 

266 VM, App Service, Azure Automation (Runbooks), Azure Function, Service Fabric, 

267 and Azure Arc. 

268 

269 It also provides token cache support. 

270 

271 .. note:: 

272 

273 Cloud Shell support is NOT implemented in this class. 

274 Since MSAL Python 1.18 in May 2022, it has been implemented in 

275 :func:`PublicClientApplication.acquire_token_interactive` via calling pattern 

276 ``PublicClientApplication(...).acquire_token_interactive(scopes=[...], prompt="none")``. 

277 That is appropriate, because Cloud Shell yields a token with 

278 delegated permissions for the end user who has signed in to the Azure Portal 

279 (like what a ``PublicClientApplication`` does), 

280 not a token with application permissions for an app. 

281 """ 

282 __instance = "localhost" # We used to get this value from socket.getfqdn() 

283 # but it is unreliable because getfqdn() either hangs or returns empty value 

284 # on some misconfigured machines 

285 _tenant = "managed_identity" 

286 _TOKEN_SOURCE = "token_source" 

287 _TOKEN_SOURCE_IDP = "identity_provider" 

288 _TOKEN_SOURCE_CACHE = "cache" 

289 

290 def __init__( 

291 self, 

292 managed_identity: Union[ 

293 dict, 

294 ManagedIdentity, # Could use Type[ManagedIdentity] but it is deprecated in Python 3.9+ 

295 SystemAssignedManagedIdentity, 

296 UserAssignedManagedIdentity, 

297 ], 

298 *, 

299 http_client, 

300 token_cache=None, 

301 http_cache=None, 

302 client_capabilities: Optional[List[str]] = None, 

303 service_fabric_http_options: Optional[ServiceFabricHttpOptions] = None, 

304 ): 

305 """Create a managed identity client. 

306 

307 :param managed_identity: 

308 It accepts an instance of :class:`SystemAssignedManagedIdentity` 

309 or :class:`UserAssignedManagedIdentity`. 

310 They are equivalent to a dict with a certain shape, 

311 which may be loaded from a JSON configuration file or an env var. 

312 

313 :param http_client: 

314 An http client object. For example, you can use ``requests.Session()``, 

315 optionally with exponential backoff behavior demonstrated in this recipe:: 

316 

317 import msal, requests 

318 from requests.adapters import HTTPAdapter, Retry 

319 s = requests.Session() 

320 retries = Retry(total=3, backoff_factor=0.1, status_forcelist=[ 

321 429, 500, 501, 502, 503, 504]) 

322 s.mount('https://', HTTPAdapter(max_retries=retries)) 

323 managed_identity = ... 

324 client = msal.ManagedIdentityClient(managed_identity, http_client=s) 

325 

326 Unless ``service_fabric_http_options`` is supplied, for Service Fabric 

327 managed identity, ``http_client`` must be a 

328 ``requests.Session`` using ``requests.adapters.HTTPAdapter`` or a 

329 subclass for the Service Fabric endpoint. 

330 MSAL derives a separate session for the Service Fabric endpoint so that 

331 its certificate thumbprint can be validated before the Secret header is sent. 

332 Standard session, retry, and connection-pool settings are preserved, 

333 but custom adapter behavior is not used. 

334 

335 :param service_fabric_http_options: 

336 Optional :class:`msal.ServiceFabricHttpOptions` dictionary. Any dict, 

337 including ``{}``, selects an isolated MSAL-owned Service Fabric 

338 session without inspecting or using ``http_client``. Omission or 

339 ``None`` retains the legacy behavior described above. Other managed 

340 identity providers still use the required ``http_client``. 

341 

342 Supported dictionaries are snapshotted at construction. Validation 

343 is deferred until Service Fabric needs a network acquisition, not 

344 performed on token-cache hits or in other environments. Invalid 

345 options raise :class:`ManagedIdentityError`, even when a proactive 

346 refresh could otherwise fall back to a cached token. See 

347 :ref:`service-fabric-http-options` for all settings and defaults. 

348 

349 :param token_cache: 

350 Optional. It accepts a :class:`msal.TokenCache` instance to store tokens. 

351 It will use an in-memory token cache by default. 

352 

353 :param http_cache: 

354 Optional. It has the same characteristics as the 

355 :paramref:`msal.ClientApplication.http_cache`. 

356 

357 :param list[str] client_capabilities: (optional) 

358 Allows configuration of one or more client capabilities, e.g. ["CP1"]. 

359 

360 Client capability is meant to inform the Microsoft identity platform 

361 (STS) what this client is capable for, 

362 so STS can decide to turn on certain features. 

363 

364 Implementation details: 

365 Client capability in Managed Identity is relayed as-is 

366 via ``xms_cc`` parameter on the wire. 

367 

368 Recipe 1: Hard code a managed identity for your app:: 

369 

370 import msal, requests 

371 client = msal.ManagedIdentityClient( 

372 msal.UserAssignedManagedIdentity(client_id="foo"), 

373 http_client=requests.Session(), 

374 ) 

375 token = client.acquire_token_for_client("resource") 

376 

377 Recipe 2: Write once, run everywhere. 

378 If you use different managed identity on different deployment, 

379 you may use an environment variable (such as MY_MANAGED_IDENTITY_CONFIG) 

380 to store a json blob like 

381 ``{"ManagedIdentityIdType": "ClientId", "Id": "foo"}`` or 

382 ``{"ManagedIdentityIdType": "SystemAssigned", "Id": null}``. 

383 The following app can load managed identity configuration dynamically:: 

384 

385 import json, os, msal, requests 

386 config = os.getenv("MY_MANAGED_IDENTITY_CONFIG") 

387 assert config, "An ENV VAR with value should exist" 

388 client = msal.ManagedIdentityClient( 

389 json.loads(config), 

390 http_client=requests.Session(), 

391 ) 

392 token = client.acquire_token_for_client("resource") 

393 """ 

394 if not ManagedIdentity.is_managed_identity(managed_identity): 

395 raise ManagedIdentityError( 

396 f"Incorrect managed_identity: {managed_identity}") 

397 self._managed_identity = managed_identity 

398 self._http_client = _ThrottledHttpClient( 

399 # This class only throttles excess token acquisition requests. 

400 # It does not provide retry. 

401 # Retry is the http_client or caller's responsibility, not MSAL's. 

402 # 

403 # FWIW, here is the inconsistent retry recommendation. 

404 # 1. Only MI on VM defines exotic 404 and 410 retry recommendations 

405 # ( https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/how-to-use-vm-token#error-handling ) 

406 # (especially for 410 which was supposed to be a permanent failure). 

407 # 2. MI on Service Fabric specifically suggests to not retry on 404. 

408 # ( https://learn.microsoft.com/en-us/azure/service-fabric/how-to-managed-cluster-managed-identity-service-fabric-app-code#error-handling ) 

409 http_client, 

410 http_cache=http_cache, 

411 ) 

412 self._token_cache = token_cache or TokenCache() 

413 self._client_capabilities = client_capabilities 

414 self._service_fabric_http_options = _snapshot_service_fabric_options( 

415 service_fabric_http_options) 

416 

417 def acquire_token_for_client( 

418 self, 

419 *, 

420 resource: str, # If/when we support scope, resource will become optional 

421 claims_challenge: Optional[str] = None, 

422 ): 

423 """Acquire token for the managed identity. 

424 

425 The result will be automatically cached. 

426 Subsequent calls will automatically search from cache first. 

427 

428 :param resource: The resource for which the token is acquired. 

429 

430 :param claims_challenge: 

431 Optional. 

432 It is a string representation of a JSON object 

433 (which contains lists of claims being requested). 

434 

435 The tenant admin may choose to revoke all Managed Identity tokens, 

436 and then a *claims challenge* will be returned by the target resource, 

437 as a `claims_challenge` directive in the `www-authenticate` header, 

438 even if the app developer did not opt in for the "CP1" client capability. 

439 Upon receiving a `claims_challenge`, MSAL will attempt to acquire a new token. 

440 

441 .. note:: 

442 

443 Known issue: When an Azure VM has only one user-assigned managed identity, 

444 and your app specifies to use system-assigned managed identity, 

445 Azure VM may still return a token for your user-assigned identity. 

446 

447 This is a service-side behavior that cannot be changed by this library. 

448 `Azure VM docs <https://learn.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token#get-a-token-using-http>`_ 

449 """ 

450 access_token_to_refresh = None # This could become a public parameter in the future 

451 access_token_from_cache = None 

452 client_id_in_cache = self._managed_identity.get( 

453 ManagedIdentity.ID, "SYSTEM_ASSIGNED_MANAGED_IDENTITY") 

454 now = time.time() 

455 if True: # Attempt cache search even if receiving claims_challenge, 

456 # because we want to locate the existing token (if any) and refresh it 

457 matches = self._token_cache.search( 

458 self._token_cache.CredentialType.ACCESS_TOKEN, 

459 target=[resource], 

460 query=dict( 

461 client_id=client_id_in_cache, 

462 environment=self.__instance, 

463 realm=self._tenant, 

464 home_account_id=None, 

465 ), 

466 ) 

467 for entry in matches: 

468 expires_in = int(entry["expires_on"]) - now 

469 if expires_in < 5*60: # Then consider it expired 

470 continue # Removal is not necessary, it will be overwritten 

471 if claims_challenge and not access_token_to_refresh: 

472 # Since caller did not pinpoint the token causing claims challenge, 

473 # we have to assume it is the first token we found in cache. 

474 access_token_to_refresh = entry["secret"] 

475 break 

476 logger.debug("Cache hit an AT") 

477 access_token_from_cache = { # Mimic a real response 

478 "access_token": entry["secret"], 

479 "token_type": entry.get("token_type", "Bearer"), 

480 "expires_in": int(expires_in), # OAuth2 specs defines it as int 

481 self._TOKEN_SOURCE: self._TOKEN_SOURCE_CACHE, 

482 } 

483 if "refresh_on" in entry: 

484 access_token_from_cache["refresh_on"] = int(entry["refresh_on"]) 

485 if int(entry["refresh_on"]) < now: # aging 

486 break # With a fallback in hand, we break here to go refresh 

487 return access_token_from_cache # It is still good as new 

488 try: 

489 result = _obtain_token( 

490 self._http_client, self._managed_identity, resource, 

491 access_token_sha256_to_refresh=hashlib.sha256( 

492 access_token_to_refresh.encode("utf-8")).hexdigest() 

493 if access_token_to_refresh else None, 

494 client_capabilities=self._client_capabilities, 

495 service_fabric_http_options=self._service_fabric_http_options, 

496 ) 

497 if "access_token" in result: 

498 expires_in = result.get("expires_in", 3600) 

499 if "refresh_in" not in result and expires_in >= 7200: 

500 result["refresh_in"] = int(expires_in / 2) 

501 self._token_cache.add(dict( 

502 client_id=client_id_in_cache, 

503 scope=[resource], 

504 token_endpoint="https://{}/{}".format( 

505 self.__instance, self._tenant), 

506 response=result, 

507 params={}, 

508 data={}, 

509 )) 

510 if "refresh_in" in result: 

511 result["refresh_on"] = int(now + result["refresh_in"]) 

512 result[self._TOKEN_SOURCE] = self._TOKEN_SOURCE_IDP 

513 if (result and "error" not in result) or (not access_token_from_cache): 

514 return result 

515 except _ServiceFabricOptionsError: 

516 raise 

517 except: # The exact HTTP exception is transportation-layer dependent 

518 # Typically network error. Potential AAD outage? 

519 if not access_token_from_cache: # It means there is no fall back option 

520 raise # We choose to bubble up the exception 

521 return access_token_from_cache 

522 

523 

524def _scope_to_resource(scope): # This is an experimental reasonable-effort approach 

525 u = urlparse(scope) 

526 if u.scheme: 

527 return "{}://{}".format(u.scheme, u.netloc) 

528 return scope # There is no much else we can do here 

529 

530 

531def _get_arc_endpoint(): 

532 if "IDENTITY_ENDPOINT" in os.environ and "IMDS_ENDPOINT" in os.environ: 

533 return os.environ["IDENTITY_ENDPOINT"] 

534 if ( # Defined in https://eng.ms/docs/cloud-ai-platform/azure-core/azure-management-and-platforms/control-plane-bburns/hybrid-resource-provider/azure-arc-for-servers/specs/extension_authoring 

535 sys.platform == "linux" and os.path.exists("/opt/azcmagent/bin/himds") 

536 or sys.platform == "win32" and os.path.exists(os.path.expandvars( 

537 # Avoid Windows-only "%EnvVar%" syntax so that tests can be run on Linux 

538 r"${ProgramFiles}\AzureConnectedMachineAgent\himds.exe" 

539 )) 

540 ): 

541 return "http://localhost:40342/metadata/identity/oauth2/token" 

542 

543 

544APP_SERVICE = object() 

545AZURE_ARC = object() 

546CLOUD_SHELL = object() # In MSAL Python, token acquisition was done by 

547 # PublicClientApplication(...).acquire_token_interactive(..., prompt="none") 

548MACHINE_LEARNING = object() 

549SERVICE_FABRIC = object() 

550DEFAULT_TO_VM = object() # Unknown environment; default to VM; you may want to probe 

551def get_managed_identity_source(): 

552 """Detect the current environment and return the likely identity source. 

553 

554 When this function returns ``CLOUD_SHELL``, you should use 

555 :func:`msal.PublicClientApplication.acquire_token_interactive` with ``prompt="none"`` 

556 to obtain a token. 

557 """ 

558 if ("IDENTITY_ENDPOINT" in os.environ and "IDENTITY_HEADER" in os.environ 

559 and "IDENTITY_SERVER_THUMBPRINT" in os.environ 

560 ): 

561 return SERVICE_FABRIC 

562 if "IDENTITY_ENDPOINT" in os.environ and "IDENTITY_HEADER" in os.environ: 

563 return APP_SERVICE 

564 if "MSI_ENDPOINT" in os.environ and "MSI_SECRET" in os.environ: 

565 return MACHINE_LEARNING 

566 if _get_arc_endpoint(): 

567 return AZURE_ARC 

568 if _is_running_in_cloud_shell(): 

569 return CLOUD_SHELL 

570 return DEFAULT_TO_VM 

571 

572 

573def _obtain_token( 

574 http_client, managed_identity, resource, 

575 *, 

576 access_token_sha256_to_refresh: Optional[str] = None, 

577 client_capabilities: Optional[List[str]] = None, 

578 service_fabric_http_options=None, 

579): 

580 if ("IDENTITY_ENDPOINT" in os.environ and "IDENTITY_HEADER" in os.environ 

581 and "IDENTITY_SERVER_THUMBPRINT" in os.environ 

582 ): 

583 if managed_identity: 

584 logger.debug( 

585 "Ignoring managed_identity parameter. " 

586 "Managed Identity in Service Fabric is configured in the cluster, " 

587 "not during runtime. See also " 

588 "https://learn.microsoft.com/en-us/azure/service-fabric/configure-existing-cluster-enable-managed-identity-token-service") 

589 return _obtain_token_on_service_fabric( 

590 http_client, 

591 os.environ["IDENTITY_ENDPOINT"], 

592 os.environ["IDENTITY_HEADER"], 

593 os.environ["IDENTITY_SERVER_THUMBPRINT"], 

594 resource, 

595 access_token_sha256_to_refresh=access_token_sha256_to_refresh, 

596 client_capabilities=client_capabilities, 

597 service_fabric_http_options=service_fabric_http_options, 

598 ) 

599 if "IDENTITY_ENDPOINT" in os.environ and "IDENTITY_HEADER" in os.environ: 

600 return _obtain_token_on_app_service( 

601 http_client, 

602 os.environ["IDENTITY_ENDPOINT"], 

603 os.environ["IDENTITY_HEADER"], 

604 managed_identity, 

605 resource, 

606 ) 

607 if "MSI_ENDPOINT" in os.environ and "MSI_SECRET" in os.environ: 

608 # Back ported from https://github.com/Azure/azure-sdk-for-python/blob/azure-identity_1.15.0/sdk/identity/azure-identity/azure/identity/_credentials/azure_ml.py 

609 return _obtain_token_on_machine_learning( 

610 http_client, 

611 os.environ["MSI_ENDPOINT"], 

612 os.environ["MSI_SECRET"], 

613 managed_identity, 

614 resource, 

615 ) 

616 arc_endpoint = _get_arc_endpoint() 

617 if arc_endpoint: 

618 return _obtain_token_on_arc( 

619 http_client, arc_endpoint, resource, managed_identity) 

620 return _obtain_token_on_azure_vm(http_client, managed_identity, resource) 

621 

622 

623def _adjust_param(params, managed_identity, types_mapping=None): 

624 # Modify the params dict in place 

625 id_name = (types_mapping or ManagedIdentity._types_mapping).get( 

626 managed_identity.get(ManagedIdentity.ID_TYPE)) 

627 if id_name: 

628 params[id_name] = managed_identity[ManagedIdentity.ID] 

629 

630def _obtain_token_on_azure_vm(http_client, managed_identity, resource): 

631 # Based on https://docs.microsoft.com/en-us/azure/active-directory/managed-identities-azure-resources/how-to-use-vm-token#get-a-token-using-http 

632 logger.debug("Obtaining token via managed identity on Azure VM") 

633 params = { 

634 "api-version": "2018-02-01", 

635 "resource": resource, 

636 } 

637 _adjust_param(params, managed_identity) 

638 resp = http_client.get( 

639 os.getenv( 

640 "AZURE_POD_IDENTITY_AUTHORITY_HOST", "http://169.254.169.254" 

641 ).strip("/") + "/metadata/identity/oauth2/token", 

642 params=params, 

643 headers={ 

644 "Metadata": "true", 

645 "x-client-SKU": SKU, 

646 "x-client-Ver": __version__, 

647 "x-ms-client-request-id": str(uuid.uuid4()), 

648 }, 

649 ) 

650 try: 

651 payload = json.loads(resp.text) 

652 if payload.get("access_token") and payload.get("expires_in"): 

653 return { # Normalizing the payload into OAuth2 format 

654 "access_token": payload["access_token"], 

655 "expires_in": int(payload["expires_in"]), 

656 "resource": payload.get("resource"), 

657 "token_type": payload.get("token_type", "Bearer"), 

658 } 

659 return payload # It would be {"error": ..., "error_description": ...} according to https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/how-to-use-vm-token#error-handling 

660 except json.decoder.JSONDecodeError: 

661 logger.debug("IMDS emits unexpected payload: %s", resp.text) 

662 raise 

663 

664def _obtain_token_on_app_service( 

665 http_client, endpoint, identity_header, managed_identity, resource, 

666): 

667 """Obtains token for 

668 `App Service <https://learn.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=portal%2Chttp#rest-endpoint-reference>`_, 

669 Azure Functions, and Azure Automation. 

670 """ 

671 # Prerequisite: Create your app service https://docs.microsoft.com/en-us/azure/app-service/quickstart-python 

672 # Assign it a managed identity https://docs.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=portal%2Chttp 

673 # SSH into your container for testing https://docs.microsoft.com/en-us/azure/app-service/configure-linux-open-ssh-session 

674 logger.debug("Obtaining token via managed identity on Azure App Service") 

675 params = { 

676 "api-version": "2019-08-01", 

677 "resource": resource, 

678 } 

679 _adjust_param(params, managed_identity, types_mapping={ 

680 ManagedIdentity.CLIENT_ID: "client_id", 

681 ManagedIdentity.RESOURCE_ID: "mi_res_id", # App Service's resource id uses "mi_res_id" 

682 ManagedIdentity.OBJECT_ID: "object_id", 

683 }) 

684 

685 resp = http_client.get( 

686 endpoint, 

687 params=params, 

688 headers={ 

689 "X-IDENTITY-HEADER": identity_header, 

690 "Metadata": "true", # Unnecessary yet harmless for App Service, 

691 # It will be needed by Azure Automation 

692 # https://docs.microsoft.com/en-us/azure/automation/enable-managed-identity-for-automation#get-access-token-for-system-assigned-managed-identity-using-http-get 

693 }, 

694 ) 

695 try: 

696 payload = json.loads(resp.text) 

697 if payload.get("access_token") and payload.get("expires_on"): 

698 return { # Normalizing the payload into OAuth2 format 

699 "access_token": payload["access_token"], 

700 "expires_in": int(payload["expires_on"]) - int(time.time()), 

701 "resource": payload.get("resource"), 

702 "token_type": payload.get("token_type", "Bearer"), 

703 } 

704 return { 

705 "error": "invalid_scope", # Empirically, wrong resource ends up with a vague statusCode=500 

706 "error_description": "{}, {}".format( 

707 payload.get("statusCode"), payload.get("message")), 

708 } 

709 except json.decoder.JSONDecodeError: 

710 logger.debug("IMDS emits unexpected payload: %s", resp.text) 

711 raise 

712 

713def _obtain_token_on_machine_learning( 

714 http_client, endpoint, secret, managed_identity, resource, 

715): 

716 # Could not find protocol docs from https://docs.microsoft.com/en-us/azure/machine-learning 

717 # The following implementation is back ported from Azure Identity 1.15.0 

718 logger.debug("Obtaining token via managed identity on Azure Machine Learning") 

719 params = {"api-version": "2017-09-01", "resource": resource} 

720 _adjust_param(params, managed_identity) 

721 if params["api-version"] == "2017-09-01" and "client_id" in params: 

722 # Workaround for a known bug in Azure ML 2017 API 

723 params["clientid"] = params.pop("client_id") 

724 resp = http_client.get( 

725 endpoint, 

726 params=params, 

727 headers={"secret": secret}, 

728 ) 

729 try: 

730 payload = json.loads(resp.text) 

731 if payload.get("access_token") and payload.get("expires_on"): 

732 return { # Normalizing the payload into OAuth2 format 

733 "access_token": payload["access_token"], 

734 "expires_in": int(payload["expires_on"]) - int(time.time()), 

735 "resource": payload.get("resource"), 

736 "token_type": payload.get("token_type", "Bearer"), 

737 } 

738 return { 

739 "error": "invalid_scope", # TODO: To be tested 

740 "error_description": "{}".format(payload), 

741 } 

742 except json.decoder.JSONDecodeError: 

743 logger.debug("IMDS emits unexpected payload: %s", resp.text) 

744 raise 

745 

746 

747def _obtain_token_on_service_fabric( 

748 http_client, endpoint, identity_header, server_thumbprint, resource, 

749 *, 

750 access_token_sha256_to_refresh: str = None, 

751 client_capabilities: Optional[List[str]] = None, 

752 service_fabric_http_options=None, 

753): 

754 """Obtains token for 

755 `Service Fabric <https://learn.microsoft.com/en-us/azure/service-fabric/>`_ 

756 """ 

757 # Deployment https://learn.microsoft.com/en-us/azure/service-fabric/service-fabric-get-started-containers-linux 

758 # See also https://github.com/Azure/azure-sdk-for-python/blob/main/sdk/identity/azure-identity/tests/managed-identity-live/service-fabric/service_fabric.md 

759 # Protocol https://learn.microsoft.com/en-us/azure/service-fabric/how-to-managed-identity-service-fabric-app-code#acquiring-an-access-token-using-rest-api 

760 logger.debug("Obtaining token via managed identity on Azure Service Fabric") 

761 options = (_validate_service_fabric_options(service_fabric_http_options) 

762 if service_fabric_http_options is not None else None) 

763 parsed_endpoint = urlparse(endpoint) 

764 if parsed_endpoint.scheme.lower() != "https" or not parsed_endpoint.hostname: 

765 raise ManagedIdentityError( 

766 "Service Fabric managed identity endpoint must use HTTPS.") 

767 thumbprint = _normalize_service_fabric_thumbprint(server_thumbprint) 

768 params = {k: v for k, v in { 

769 "api-version": "2019-07-01-preview", 

770 "resource": resource, 

771 "token_sha256_to_refresh": access_token_sha256_to_refresh, 

772 "xms_cc": ",".join(client_capabilities) if client_capabilities else None, 

773 }.items() if v is not None} 

774 if options is None: 

775 service_fabric_http_client = _create_service_fabric_http_client( 

776 http_client, endpoint, thumbprint) 

777 return _parse_service_fabric_response(service_fabric_http_client.get( 

778 endpoint, params=params, headers={"Secret": identity_header})) 

779 

780 service_fabric_http_client = _create_owned_service_fabric_http_client(options, thumbprint) 

781 response = None 

782 

783 def receive_response(raw_response, **ignored): 

784 nonlocal response 

785 # Capture ownership before Requests processes redirects or reads content. 

786 response = raw_response 

787 if 300 <= response.status_code < 400: 

788 raise ManagedIdentityError( 

789 "Service Fabric returned a redirect (HTTP {}).".format(response.status_code)) 

790 

791 try: 

792 service_fabric_http_client.get( 

793 endpoint, params=params, headers={"Secret": identity_header}, 

794 timeout=options["timeout"], allow_redirects=False, stream=True, 

795 hooks={"response": receive_response}) 

796 return _parse_service_fabric_response(response) 

797 finally: 

798 try: 

799 if response is not None: 

800 response.close() 

801 finally: 

802 service_fabric_http_client.close() 

803 

804 

805def _parse_service_fabric_response(resp): 

806 try: 

807 payload = json.loads(resp.text) 

808 if payload.get("access_token") and payload.get("expires_on"): 

809 return { # Normalizing the payload into OAuth2 format 

810 "access_token": payload["access_token"], 

811 "expires_in": int( # Despite the example in docs shows an integer, 

812 payload["expires_on"] # Azure SDK team's test obtained a string. 

813 ) - int(time.time()), 

814 "resource": payload.get("resource"), 

815 "token_type": payload["token_type"], 

816 } 

817 error = payload.get("error", {}) # https://learn.microsoft.com/en-us/azure/service-fabric/how-to-managed-identity-service-fabric-app-code#error-handling 

818 error_mapping = { # Map Service Fabric errors into OAuth2 errors https://www.rfc-editor.org/rfc/rfc6749#section-5.2 

819 "SecretHeaderNotFound": "unauthorized_client", 

820 "ManagedIdentityNotFound": "invalid_client", 

821 "ArgumentNullOrEmpty": "invalid_scope", 

822 } 

823 return { 

824 "error": error_mapping.get(error.get("code"), "invalid_request"), 

825 "error_description": resp.text, 

826 } 

827 except json.decoder.JSONDecodeError: 

828 logger.debug("IMDS emits unexpected payload: %s", resp.text) 

829 raise 

830 

831 

832def _normalize_service_fabric_thumbprint(server_thumbprint): 

833 normalized = "".join( 

834 character for character in str(server_thumbprint) 

835 if character not in " \t\r\n:") 

836 if len(normalized) != 40 or any( 

837 character not in "0123456789abcdefABCDEF" 

838 for character in normalized): 

839 raise ManagedIdentityError( 

840 "IDENTITY_SERVER_THUMBPRINT must be a SHA-1 certificate thumbprint.") 

841 return normalized.lower() 

842 

843 

844class _ServiceFabricAuthenticatedProxyConnection(HTTPSConnection): 

845 _proxy_ssl_context = None 

846 _proxy_hostname = None 

847 

848 def _connect_tls_proxy(self, hostname, sock): 

849 # This hook runs before CONNECT. The endpoint's CERT_NONE must never 

850 # configure the outer TLS handshake, which authenticates proxy credentials. 

851 hostname = self._proxy_hostname.strip("[]").split("%", 1)[0].rstrip(".") 

852 proxy_socket = self._proxy_ssl_context.wrap_socket(sock, server_hostname=hostname) 

853 self.proxy_is_verified = True 

854 return proxy_socket 

855 

856 

857class _ServiceFabricConnectionRetry(Retry): 

858 """Exclude non-connection retries even on urllib3 without an 'other' limit.""" 

859 

860 def increment(self, method=None, url=None, response=None, error=None, 

861 _pool=None, _stacktrace=None): 

862 if (error is not None and not self._is_connection_error(error) 

863 and not self._is_read_error(error)): 

864 raise MaxRetryError(_pool, url, error) from error 

865 return super(_ServiceFabricConnectionRetry, self).increment( 

866 method=method, url=url, response=response, error=error, 

867 _pool=_pool, _stacktrace=_stacktrace) 

868 

869 

870class _ServiceFabricHTTPAdapter(HTTPAdapter): 

871 """Use certificate-thumbprint authentication for the Service Fabric endpoint.""" 

872 

873 def __init__(self, server_thumbprint, *args, _restrict_proxies=False, **kwargs): 

874 self._server_thumbprint = server_thumbprint 

875 self._restrict_proxies = _restrict_proxies 

876 super(_ServiceFabricHTTPAdapter, self).__init__(*args, **kwargs) 

877 

878 def init_poolmanager(self, connections, maxsize, block=False, **pool_kwargs): 

879 pool_kwargs["assert_fingerprint"] = self._server_thumbprint 

880 super(_ServiceFabricHTTPAdapter, self).init_poolmanager( 

881 connections, maxsize, block=block, **pool_kwargs) 

882 

883 def proxy_manager_for(self, proxy, **proxy_kwargs): 

884 if self._restrict_proxies and not _valid_service_fabric_proxy(proxy): 

885 raise ManagedIdentityError("Unsupported Service Fabric proxy configuration.") 

886 if proxy_kwargs.get("use_forwarding_for_https"): 

887 raise requests.exceptions.SSLError( 

888 "Cannot validate the Service Fabric endpoint certificate through " 

889 "a forwarding proxy.") 

890 proxy_kwargs["assert_fingerprint"] = self._server_thumbprint 

891 new_manager = proxy not in self.proxy_manager 

892 pool_manager = super(_ServiceFabricHTTPAdapter, self).proxy_manager_for( 

893 proxy, **proxy_kwargs) 

894 if new_manager and self._restrict_proxies and urlsplit(proxy).scheme.lower() == "https": 

895 connection_class = type( 

896 "_ServiceFabricProxyConnection", 

897 (_ServiceFabricAuthenticatedProxyConnection,), 

898 {"_proxy_hostname": parse_url(proxy).host}, 

899 ) 

900 # Isolate outer-proxy trust without changing direct or HTTP CONNECT pools. 

901 pool_manager.pool_classes_by_scheme = pool_manager.pool_classes_by_scheme.copy() 

902 pool_manager.pool_classes_by_scheme["https"] = type( 

903 "_ServiceFabricProxyConnectionPool", 

904 (HTTPSConnectionPool,), 

905 {"ConnectionCls": connection_class}, 

906 ) 

907 return pool_manager 

908 

909 def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None): 

910 if self._restrict_proxies: 

911 proxy = requests.utils.select_proxy(request.url, proxies) 

912 # Requests parses selected proxies before calling proxy_manager_for. 

913 if proxy and not _valid_service_fabric_proxy(proxy, allow_default_scheme=True): 

914 raise ManagedIdentityError("Unsupported Service Fabric proxy configuration.") 

915 if proxy and urlsplit(proxy).scheme.lower() == "https": 

916 # Older urllib3 accepts arbitrary pool kwargs without supporting 

917 # HTTPS tunneling. Require the actual pre-CONNECT TLS hook and 

918 # TLS-in-TLS implementation instead of passing ignored options. 

919 if (not callable(getattr(HTTPSConnection, "_connect_tls_proxy", None)) 

920 or not callable(getattr(urllib3_ssl, "SSLTransport", None)) 

921 or not callable(getattr(urllib3_ssl.SSLContext, "wrap_bio", None))): 

922 raise ManagedIdentityError( 

923 "Installed urllib3 does not support authenticated HTTPS proxy tunneling.") 

924 ca_bundle = verify if isinstance(verify, str) else ( 

925 requests.utils.extract_zipped_paths(requests.adapters.DEFAULT_CA_BUNDLE_PATH)) 

926 context = ssl.create_default_context( 

927 capath=ca_bundle if os.path.isdir(ca_bundle) else None, 

928 cafile=None if os.path.isdir(ca_bundle) else ca_bundle) 

929 proxy = requests.utils.prepend_scheme_if_needed(proxy, "http") 

930 pool_manager = self.proxy_manager_for(proxy) 

931 pool_manager.pool_classes_by_scheme["https"].ConnectionCls._proxy_ssl_context = context 

932 # Select pin-only pools before Requests can attach its shared CA context. 

933 # The original verify value above applies only to the outer proxy TLS. 

934 return super(_ServiceFabricHTTPAdapter, self).send( 

935 request, stream=stream, timeout=timeout, verify=False, cert=cert, proxies=proxies) 

936 

937 

938def _create_owned_service_fabric_http_client(options, server_thumbprint): 

939 session = requests.Session() 

940 try: 

941 session.headers.update(options["headers"]) 

942 session.proxies.update(options["proxies"]) 

943 session.trust_env = options["trust_env"] 

944 adapter = _ServiceFabricHTTPAdapter( 

945 server_thumbprint, _restrict_proxies=True, 

946 max_retries=_ServiceFabricConnectionRetry( 

947 total=options["max_retries"], connect=options["max_retries"], 

948 read=False, redirect=0, status=0, 

949 backoff_factor=0, respect_retry_after_header=False)) 

950 default_adapter = session.adapters["https://"] 

951 session.mount("https://", adapter) 

952 default_adapter.close() 

953 except BaseException: 

954 session.close() 

955 raise 

956 return session 

957 

958 

959def _create_service_fabric_http_client(http_client, endpoint, server_thumbprint): 

960 """Derive a Requests session with a pinning-only HTTPS transport. 

961 

962 HTTPAdapter subclasses are accepted as sources of retry and pool settings, 

963 but the derived session always uses MSAL's certificate-pinning adapter. 

964 Other HTTP clients and adapters are unsupported. 

965 """ 

966 if isinstance(http_client, ThrottledHttpClientBase): 

967 http_client = http_client.http_client 

968 if not isinstance(http_client, requests.Session): 

969 raise ManagedIdentityError( 

970 "Service Fabric managed identity requires a requests.Session " 

971 "with an HTTPAdapter or subclass.") 

972 source_adapter = http_client.get_adapter(endpoint) 

973 if not isinstance(source_adapter, HTTPAdapter): 

974 raise ManagedIdentityError( 

975 "Service Fabric managed identity requires an HTTPAdapter or subclass.") 

976 

977 service_fabric_client = requests.Session() 

978 service_fabric_client.headers = http_client.headers.copy() 

979 service_fabric_client.cookies = http_client.cookies.copy() 

980 service_fabric_client.auth = http_client.auth 

981 service_fabric_client.params = copy.copy(http_client.params) 

982 service_fabric_client.hooks = { 

983 event: handlers[:] for event, handlers in http_client.hooks.items()} 

984 service_fabric_client.proxies = http_client.proxies.copy() 

985 service_fabric_client.stream = http_client.stream 

986 service_fabric_client.trust_env = http_client.trust_env 

987 service_fabric_client.max_redirects = http_client.max_redirects 

988 service_fabric_client.cert = http_client.cert 

989 service_fabric_client.verify = True 

990 service_fabric_client.adapters.clear() 

991 service_fabric_client.mount("https://", _ServiceFabricHTTPAdapter( 

992 server_thumbprint, 

993 max_retries=copy.deepcopy(source_adapter.max_retries), 

994 pool_connections=source_adapter._pool_connections, 

995 pool_maxsize=source_adapter._pool_maxsize, 

996 pool_block=source_adapter._pool_block, 

997 )) 

998 return service_fabric_client 

999 

1000 

1001_supported_arc_platforms_and_their_prefixes = { 

1002 "linux": "/var/opt/azcmagent/tokens", 

1003 "win32": os.path.expandvars(r"%ProgramData%\AzureConnectedMachineAgent\Tokens"), 

1004} 

1005 

1006class ArcPlatformNotSupportedError(ManagedIdentityError): 

1007 pass 

1008 

1009def _raise_if_arc_did_not_honor_user_assigned_identity(managed_identity, payload): 

1010 """Fail closed when a user-assigned identity was requested but Azure Arc did not confirm it. 

1011 

1012 A legacy Azure Arc agent ignores the client_id / object_id / msi_res_id selector and silently 

1013 returns the machine's system-assigned identity. An agent that supports user-assigned managed 

1014 identity echoes the identity it used in the token response. When that echo is missing or does 

1015 not match the requested selector, MSAL must not hand back a token for a different identity than 

1016 the one that was requested. 

1017 """ 

1018 if not ManagedIdentity.is_user_assigned(managed_identity): 

1019 return # System-assigned: there is no requested identity to confirm 

1020 requested = managed_identity.get(ManagedIdentity.ID) 

1021 echoed = { 

1022 ManagedIdentity.CLIENT_ID: payload.get("client_id"), 

1023 ManagedIdentity.OBJECT_ID: payload.get("object_id"), 

1024 # Azure Arc echoes msi_res_id; accept the mi_res_id spelling too as a safety net 

1025 ManagedIdentity.RESOURCE_ID: payload.get("msi_res_id") or payload.get("mi_res_id"), 

1026 }.get(managed_identity.get(ManagedIdentity.ID_TYPE)) 

1027 # Compare case-insensitively: client_id / object_id are GUIDs, and an ARM resource id 

1028 # (msi_res_id) can legitimately differ in segment casing. 

1029 if not echoed or str(echoed).lower() != str(requested).lower(): 

1030 raise ManagedIdentityError( 

1031 "Azure Arc did not confirm the requested user-assigned managed identity " 

1032 "in the token response. The agent likely does not support user-assigned " 

1033 "managed identities and returned the system-assigned identity.") 

1034 

1035def _obtain_token_on_arc(http_client, endpoint, resource, managed_identity=None): 

1036 # https://learn.microsoft.com/en-us/azure/azure-arc/servers/managed-identity-authentication 

1037 logger.debug("Obtaining token via managed identity on Azure Arc") 

1038 params = {"api-version": "2020-06-01", "resource": resource} 

1039 if managed_identity: 

1040 _adjust_param(params, managed_identity, types_mapping={ 

1041 ManagedIdentity.CLIENT_ID: "client_id", 

1042 ManagedIdentity.RESOURCE_ID: "msi_res_id", # Azure Arc honors the IMDS msi_res_id spelling; mi_res_id is ignored and returns the system-assigned identity 

1043 ManagedIdentity.OBJECT_ID: "object_id", 

1044 }) 

1045 resp = http_client.get( 

1046 endpoint, 

1047 params=params.copy(), 

1048 headers={"Metadata": "true"}, 

1049 ) 

1050 if resp.status_code != 401: 

1051 return { 

1052 "error": "invalid_request", 

1053 "error_description": resp.text, 

1054 } 

1055 www_auth = "www-authenticate" # Header in lower case 

1056 challenge = { 

1057 # Normalized to lowercase, because header names are case-insensitive 

1058 # https://datatracker.ietf.org/doc/html/rfc7230#section-3.2 

1059 k.lower(): v for k, v in resp.headers.items() if k.lower() == www_auth 

1060 }.get(www_auth, "").split("=") # Output will be ["Basic realm", "content"] 

1061 if not ( # https://datatracker.ietf.org/doc/html/rfc7617#section-2 

1062 len(challenge) == 2 and challenge[0].lower() == "basic realm"): 

1063 raise ManagedIdentityError( 

1064 "Unrecognizable WWW-Authenticate header: {}".format(resp.headers)) 

1065 if sys.platform not in _supported_arc_platforms_and_their_prefixes: 

1066 raise ArcPlatformNotSupportedError( 

1067 f"Platform {sys.platform} was undefined and unsupported") 

1068 filename = os.path.join( 

1069 # This algorithm is documented in an internal doc https://msazure.visualstudio.com/One/_wiki/wikis/One.wiki/233012/VM-Extension-Authoring-for-Arc?anchor=2.-obtaining-tokens 

1070 _supported_arc_platforms_and_their_prefixes[sys.platform], 

1071 os.path.splitext(os.path.basename(challenge[1]))[0] + ".key") 

1072 if os.stat(filename).st_size > 4096: # Check size BEFORE loading its content 

1073 raise ManagedIdentityError("Local key file shall not be larger than 4KB") 

1074 with open(filename) as f: 

1075 secret = f.read() 

1076 response = http_client.get( 

1077 endpoint, 

1078 params=params.copy(), 

1079 headers={"Metadata": "true", "Authorization": "Basic {}".format(secret)}, 

1080 ) 

1081 try: 

1082 payload = json.loads(response.text) 

1083 if payload.get("access_token") and payload.get("expires_in"): 

1084 # Example: https://learn.microsoft.com/en-us/azure/azure-arc/servers/media/managed-identity-authentication/bash-token-output-example.png 

1085 _raise_if_arc_did_not_honor_user_assigned_identity( 

1086 managed_identity, payload) 

1087 return { 

1088 "access_token": payload["access_token"], 

1089 "expires_in": int(payload["expires_in"]), 

1090 "token_type": payload.get("token_type", "Bearer"), 

1091 "resource": payload.get("resource"), 

1092 } 

1093 except json.decoder.JSONDecodeError: 

1094 pass 

1095 return { 

1096 "error": "invalid_request", 

1097 "error_description": response.text, 

1098 }