
    AHj}~                     z   d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlmZ d dl	m
Z
 d dlmZmZmZ ddlmZ ddlmZ ddlmZmZ dd	lmZ dd
lmZmZ  ej8                  e      Z G d de      Z  G d de
      Z! G d de!      Z" G d de!      Z# G d de      Z$ G d de%      Z&d Z'd Z( e%       Z) e%       Z* e%       Z+ e%       Z, e%       Z- e%       Z.d Z/ddddee0   deee0      fdZ1d)dZ2d Z3d  Z4d! Z5dddde0deee0      fd"Z6d#ejn                  jq                  d$      d%Z9 G d& d'e       Z:d( Z;y)*    N)urlparse)UserDict)ListOptionalUnion   )
TokenCache)_IndividualCache)ThrottledHttpClientBaseRetryAfterParser)_is_running_in_cloud_shell)SKU__version__c                       e Zd Zy)ManagedIdentityErrorN__name__
__module____qualname__     M/root/tools/cai/cai_env/lib/python3.12/site-packages/msal/managed_identity.pyr   r          r   r   c                   |     e Zd ZdZdZdZdZdZdZdZ	eded	ed
iZ
ed        Zed        Zed        Zd fd	Z xZS )ManagedIdentityzFeed an instance of this class to :class:`msal.ManagedIdentityClient`
    to acquire token for the specified managed identity.
    ManagedIdentityIdTypeIdClientId
ResourceIdObjectIdSystemAssigned	client_id
msi_res_id	object_idc                 n    t        |t              xs$ | j                  |      xs | j                  |      S N)
isinstancer   is_system_assignedis_user_assignedclsunknowns     r   is_managed_identityz#ManagedIdentity.is_managed_identity1   s7    7O4 -%%g.-##G,	.r   c                     t        |t              xs: t        |t              xr( |j                  | j                        | j
                  k(  S r&   )r'   SystemAssignedManagedIdentitydictgetID_TYPESYSTEM_ASSIGNEDr*   s     r   r(   z"ManagedIdentity.is_system_assigned7   sD    '#@A Aw% @CKK(C,?,??	Ar   c                     t        |t              xsV t        |t              xrD |j                  | j                        | j
                  v xr |j                  | j                        S r&   )r'   UserAssignedManagedIdentityr0   r1   r2   _types_mappingIDr*   s     r   r)   z ManagedIdentity.is_user_assigned=   sV    '#>? %w% $CKK(C,>,>>$CFF#	%r   c                 \    t         t        |   | j                  || j                  |i       y r&   )superr   __init__r2   r7   )self
identifierid_type	__class__s      r   r:   zManagedIdentity.__init__D   s)    ot-LL'GGZ/
 	r   )NN)r   r   r   __doc__r2   r7   	CLIENT_IDRESOURCE_ID	OBJECT_IDr3   r6   classmethodr-   r(   r)   r:   __classcell__r>   s   @r   r   r      s     &G	B IKI&O 	;\;N . .
 A A
 % % r   r   c                   "     e Zd ZdZ fdZ xZS )r/   zRepresent a system-assigned managed identity.

    It is equivalent to a Python dict of::

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

    or a JSON blob of::

        {"ManagedIdentityIdType": "SystemAssigned", "Id": null}
    c                 B    t         t        |   | j                         y )N)r=   )r9   r/   r:   r3   )r;   r>   s    r   r:   z&SystemAssignedManagedIdentity.__init__W   s    +T;DDXDX;Yr   r   r   r   r?   r:   rD   rE   s   @r   r/   r/   L   s    	Z Zr   r/   c                   ,     e Zd ZdZdddd fd
Z xZS )r5   a9  Represent a user-assigned managed identity.

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

        {"ManagedIdentityIdType": "ClientId", "Id": "foo"}
        {"ManagedIdentityIdType": "ResourceId", "Id": "foo"}
        {"ManagedIdentityIdType": "ObjectId", "Id": "foo"}
    N)r"   resource_idr$   c                    |r$|s"|s t         t        |   | j                  |       y |s$|r"|s t         t        |   | j                  |       y |s$|s"|r t         t        |   | j
                  |       y t        d      )N)r=   r<   zPYou shall specify one of the three parameters: client_id, resource_id, object_id)r9   r5   r:   r@   rA   rB   r   )r;   r"   rJ   r$   r>   s       r   r:   z$UserAssignedManagedIdentity.__init__d   s    [-t=9 > >{9-t=(([ > B;9-t=9 > > '45 5r   rH   rE   s   @r   r5   r5   [   s     %)dd 5 5r   r5   c                        e Zd Z fdZ xZS )_ThrottledHttpClientc                      t        t         
  |i |  t         j                   fdt        d      j                         j                         _        y )Nc                     dj                  |d   j                  t        |j                  d            t        |j                  d            z               S )Nz"REQ {} hash={} 429/5xx/Retry-Afterr   paramsdata)format_hashstrr1   )funcargskwargsr;   s      r   <lambda>z/_ThrottledHttpClient.__init__.<locals>.<lambda>y   sM    1U1\1\Q

 

8,-FJJv4F0GGI2 r      )mapping	key_maker
expires_in)r9   rM   r:   IndividualCache_expiring_mappingr   parser1   )r;   rV   rW   r>   s   `  r   r:   z_ThrottledHttpClient.__init__u   sT    "D2DCFC
?** (*00
 hh
r   )r   r   r   r:   rD   rE   s   @r   rM   rM   t   s     r   rM   c                   t    e Zd ZdZdZdZdZdZdZddddde	e
eeef   d	eee      fd
Zdddedee   fdZy)ManagedIdentityClienta*  This API encapsulates multiple managed identity back-ends:
    VM, App Service, Azure Automation (Runbooks), Azure Function, Service Fabric,
    and Azure Arc.

    It also provides token cache support.

    .. note::

        Cloud Shell support is NOT implemented in this class.
        Since MSAL Python 1.18 in May 2022, it has been implemented in
        :func:`PublicClientApplication.acquire_token_interactive` via calling pattern
        ``PublicClientApplication(...).acquire_token_interactive(scopes=[...], prompt="none")``.
        That is appropriate, because Cloud Shell yields a token with
        delegated permissions for the end user who has signed in to the Azure Portal
        (like what a ``PublicClientApplication`` does),
        not a token with application permissions for an app.
    	localhostmanaged_identitytoken_sourceidentity_providercacheN)token_cache
http_cacheclient_capabilitiesri   c                    t         j                  |      st        d|       || _        t	        ||      | _        |xs
 t               | _        || _        y)a  Create a managed identity client.

        :param managed_identity:
            It accepts an instance of :class:`SystemAssignedManagedIdentity`
            or :class:`UserAssignedManagedIdentity`.
            They are equivalent to a dict with a certain shape,
            which may be loaded from a JSON configuration file or an env var.

        :param http_client:
            An http client object. For example, you can use ``requests.Session()``,
            optionally with exponential backoff behavior demonstrated in this recipe::

                import msal, requests
                from requests.adapters import HTTPAdapter, Retry
                s = requests.Session()
                retries = Retry(total=3, backoff_factor=0.1, status_forcelist=[
                    429, 500, 501, 502, 503, 504])
                s.mount('https://', HTTPAdapter(max_retries=retries))
                managed_identity = ...
                client = msal.ManagedIdentityClient(managed_identity, http_client=s)

        :param token_cache:
            Optional. It accepts a :class:`msal.TokenCache` instance to store tokens.
            It will use an in-memory token cache by default.

        :param http_cache:
            Optional. It has the same characteristics as the
            :paramref:`msal.ClientApplication.http_cache`.

        :param list[str] client_capabilities: (optional)
            Allows configuration of one or more client capabilities, e.g. ["CP1"].

            Client capability is meant to inform the Microsoft identity platform
            (STS) what this client is capable for,
            so STS can decide to turn on certain features.

            Implementation details:
            Client capability in Managed Identity is relayed as-is
            via ``xms_cc`` parameter on the wire.

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

            import msal, requests
            client = msal.ManagedIdentityClient(
                msal.UserAssignedManagedIdentity(client_id="foo"),
                http_client=requests.Session(),
                )
            token = client.acquire_token_for_client("resource")

        Recipe 2: Write once, run everywhere.
        If you use different managed identity on different deployment,
        you may use an environment variable (such as MY_MANAGED_IDENTITY_CONFIG)
        to store a json blob like
        ``{"ManagedIdentityIdType": "ClientId", "Id": "foo"}`` or
        ``{"ManagedIdentityIdType": "SystemAssigned", "Id": null}``.
        The following app can load managed identity configuration dynamically::

            import json, os, msal, requests
            config = os.getenv("MY_MANAGED_IDENTITY_CONFIG")
            assert config, "An ENV VAR with value should exist"
            client = msal.ManagedIdentityClient(
                json.loads(config),
                http_client=requests.Session(),
                )
            token = client.acquire_token_for_client("resource")
        zIncorrect managed_identity: )rh   N)	r   r-   r   _managed_identityrM   _http_clientr	   _token_cache_client_capabilities)r;   rc   http_clientrg   rh   ri   s         r   r:   zManagedIdentityClient.__init__   se    ` 223CD&./?.@AC C!10 !
 (7:<$7!r   )claims_challengeresourcerp   c          
         d}d}| j                   j                  t        j                  d      }t	        j                         }	 | j
                  j                  | j
                  j                  j                  |gt        || j                  | j                  d            }|D ]  }t        |d         |z
  }	|	dk  r|r	|s|d   } n|t        j                  d       d	|d   d
|j                  d
d      dt        |	      | j                  | j                   i}d|v r$t        |d         |d<   t        |d         |k  r n|c S  	 t#        | j$                  | j                   ||r2t'        j(                  |j+                  d            j-                         nd| j.                        }
d	|
v r|
j                  dd      }	d|
vr|	dk\  rt        |	dz        |
d<   | j
                  j1                  t        ||gdj3                  | j                  | j                        |
i i              d|
v rt        ||
d   z         |
d<   | j4                  |
| j                  <   |
rd|
vs|s|
S 	 |S #  |s Y |S xY w)aE  Acquire token for the managed identity.

        The result will be automatically cached.
        Subsequent calls will automatically search from cache first.

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

        :param claims_challenge:
            Optional.
            It is a string representation of a JSON object
            (which contains lists of claims being requested).

            The tenant admin may choose to revoke all Managed Identity tokens,
            and then a *claims challenge* will be returned by the target resource,
            as a `claims_challenge` directive in the `www-authenticate` header,
            even if the app developer did not opt in for the "CP1" client capability.
            Upon receiving a `claims_challenge`, MSAL will attempt to acquire a new token.

        .. note::

            Known issue: When an Azure VM has only one user-assigned managed identity,
            and your app specifies to use system-assigned managed identity,
            Azure VM may still return a token for your user-assigned identity.

            This is a service-side behavior that cannot be changed by this library.
            `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>`_
        N SYSTEM_ASSIGNED_MANAGED_IDENTITY)r"   environmentrealmhome_account_id)targetquery
expires_oni,  secretzCache hit an ATaccess_token
token_typeBearerr\   
refresh_onzutf-8access_token_sha256_to_refreshri   i  
refresh_ini      zhttps://{}/{})r"   scopetoken_endpointresponserP   rQ   error)rk   r1   r   r7   timerm   searchCredentialTypeACCESS_TOKENr0    _ManagedIdentityClient__instance_tenantintloggerdebug_TOKEN_SOURCE_TOKEN_SOURCE_CACHE_obtain_tokenrl   hashlibsha256encode	hexdigestrn   addrR   _TOKEN_SOURCE_IDP)r;   rq   rp   access_token_to_refreshaccess_token_from_cacheclient_id_in_cachenowmatchesentryr\   results              r   acquire_token_for_clientz.ManagedIdentityClient.acquire_token_for_client  s   B #'"&!3377 BDiik''..!!00== z0 $,,$(	 / 	G ! / |!45;
$#,C /4Ho+./"E(O %))L("C #j/&&(@(@	+'  5(<?l@S<T+L95./#5..)/*	"!!4#9#98 / 07~~+227;0==FY[48$($=$=F '#ZZd;
v-*2D+.zA~+>F<(!!%%d0#*#2#9#9$7#'   6)+.sVL5I/I+JF<(-1-C-Ct))*7&0:Q ;R '&		* +&&s   DI% %I-)r   r   r   r?   r   r   r   r   r   r   r0   r   r/   r5   r   r   rT   r:   r   r   r   r   ra   ra      s    " J !G"M+! 37c8)')c8 &d3i0c8R +/	e' e' #3-	e'r   ra   c                     t        |       }|j                  r&dj                  |j                  |j                        S | S )Nz{}://{})r   schemerR   netloc)r   us     r   _scope_to_resourcer   k  s2    Axx!((33Lr   c                  x   dt         j                  v r%dt         j                  v rt         j                  d   S t        j                  dk(  rt         j                  j                  d      sOt        j                  dk(  r>t         j                  j                  t         j                  j                  d            ryy y )NIDENTITY_ENDPOINTIMDS_ENDPOINTlinuxz/opt/azcmagent/bin/himdswin32z4${ProgramFiles}\AzureConnectedMachineAgent\himds.exez5http://localhost:40342/metadata/identity/oauth2/token)osenvironsysplatformpathexists
expandvarsr   r   r   _get_arc_endpointr   r  s    bjj(_

-Jzz-..BGGNN3M$N<<7"rww~~bgg6H6HC7
 (
 G("r   c                  n   dt         j                  v r*dt         j                  v rdt         j                  v rt        S dt         j                  v rdt         j                  v rt        S dt         j                  v rdt         j                  v rt        S t               rt        S t               rt        S t        S )zDetect the current environment and return the likely identity source.

    When this function returns ``CLOUD_SHELL``, you should use
    :func:`msal.PublicClientApplication.acquire_token_interactive` with ``prompt="none"``
    to obtain a token.
    r   IDENTITY_HEADERIDENTITY_SERVER_THUMBPRINTMSI_ENDPOINT
MSI_SECRET)
r   r   SERVICE_FABRICAPP_SERVICEMACHINE_LEARNINGr   	AZURE_ARCr   CLOUD_SHELLDEFAULT_TO_VMr   r   r   get_managed_identity_sourcer     s     	rzz).?2::.M,

:bjj(->"**-L#

(B!#r   r   r   ri   c          	         dt         j                  v rdt         j                  v rndt         j                  v r\|rt        j                  d       t	        | t         j                  d   t         j                  d   t         j                  d   |||      S dt         j                  v rCdt         j                  v r1t        | t         j                  d   t         j                  d   ||      S dt         j                  v rCdt         j                  v r1t        | t         j                  d   t         j                  d   ||      S t               }|r-t        j                  |      rt        d      t        | ||      S t        | ||      S )	Nr   r   r   zIgnoring managed_identity parameter. Managed Identity in Service Fabric is configured in the cluster, not during runtime. See also https://learn.microsoft.com/en-us/azure/service-fabric/configure-existing-cluster-enable-managed-identity-token-servicer   r   r   zInvalid 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)r   r   r   r   _obtain_token_on_service_fabric_obtain_token_on_app_service!_obtain_token_on_machine_learningr   r   r)   r   _obtain_token_on_arc_obtain_token_on_azure_vm)ro   rc   rq   r   ri   arc_endpoints         r   r   r     sc    	rzz).?2::.M,

:LLJK
 /JJ*+JJ()JJ34+I 3
 	
 bjj(->"**-L+JJ*+JJ()
 	
 #

(B0JJ~&JJ|$
 	
 %&L++,<=&JK K
 $KxHH$[2BHMMr   c                     |xs t         j                  j                  |j                  t         j                              }|r|t         j                     | |<   y y r&   )r   r6   r1   r2   r7   )rP   rc   types_mappingid_names       r   _adjust_paramr     sM    > > >CC_4457G*?+=+=>w r   c                    t         j                  d       d|d}t        ||       | j                  t	        j
                  dd      j                  d      dz   |dt        t        t        t        j                               d	
      }	 t        j                  |j                        }|j                  d      rF|j                  d      r5|d   t        |d         |j                  d      |j                  dd      dS |S # t        j                   j"                  $ r" t         j                  d|j                          w xY w)Nz0Obtaining token via managed identity on Azure VMz
2018-02-01api-versionrq   !AZURE_POD_IDENTITY_AUTHORITY_HOSTzhttp://169.254.169.254/z/metadata/identity/oauth2/tokentrue)Metadatazx-client-SKUzx-client-Verzx-ms-client-request-idrP   headersr{   r\   rq   r|   r}   r{   r\   rq   r|   !IMDS emits unexpected payload: %s)r   r   r   r1   r   getenvstripr   r   rT   uuiduuid4jsonloadstextr   decoderJSONDecodeError)ro   rc   rq   rP   resppayloads         r   r   r     s   
LLCD#
F &*+??
		/1I	eCj<	= '&)$**,&7	  
D**TYY';;~&7;;|+D ' 7!',"78#KK
3%kk,A	  <<'' 8$))Ds   
A5D  D ?Ec           
         t         j                  d       d|d}t        ||t        j                  dt        j
                  dt        j                  di       | j                  |||dd	
      }	 t        j                  |j                        }|j                  d      rd|j                  d      rS|d   t        |d         t        t        j                               z
  |j                  d      |j                  dd      dS ddj                  |j                  d      |j                  d            dS # t        j                  j                  $ r" t         j                  d|j                          w xY w)zObtains token for
    `App Service <https://learn.microsoft.com/en-us/azure/app-service/overview-managed-identity?tabs=portal%2Chttp#rest-endpoint-reference>`_,
    Azure Functions, and Azure Automation.
    z9Obtaining token via managed identity on Azure App Servicez
2019-08-01r   r"   	mi_res_idr$   )r   r   )zX-IDENTITY-HEADERr   r   r{   ry   rq   r|   r}   r   invalid_scopez{}, {}
statusCodemessager   error_descriptionr   )r   r   r   r   r@   rA   rB   r1   r   r   r   r   r   rR   r   r   )ro   endpointidentity_headerrc   rq   rP   r   r   s           r   r   r     sT    LLLM#
F &*!!;##[!!;;  ??!0  	
D**TYY';;~&7;;|+D ' 7!',"783tyy{;KK#KK
3%kk,A	  %!)L)7;;y+A"C 	
 <<'' 8$))Ds   1BD8 2D8 8?E7c                    t         j                  d       d|d}t        ||       |d   dk(  rd|v r|j                  d      |d<   | j	                  ||d|i      }	 t        j                  |j                        }|j	                  d	      rd|j	                  d
      rS|d	   t        |d
         t        t        j                               z
  |j	                  d      |j	                  dd      dS ddj                  |      dS # t
        j                  j                  $ r" t         j                  d|j                          w xY w)Nz>Obtaining token via managed identity on Azure Machine Learningz
2017-09-01r   r   r"   clientidrz   r   r{   ry   rq   r|   r}   r   r   z{}r   r   )r   r   r   popr1   r   r   r   r   r   rR   r   r   )ro   r   rz   rc   rq   rP   r   r   s           r   r   r   +  s1   
 LLQR)x@F&*+m,1F#ZZ4z??6"  
D
**TYY';;~&7;;|+D ' 7!',"783tyy{;KK#KK
3%kk,A	  %!%W!5 	 <<'' 8$))Ds   BD 2D ?Ec          	         t         j                  d       | j                  |d|||rdj                  |      nddj	                         D ci c]
  \  }}||| c}}d|i      }		 t        j                  |	j                        }
|
j                  d      rW|
j                  d	      rF|
d   t        |
d	         t        t        j                               z
  |
j                  d
      |
d   dS |
j                  di       }dddd}|j                  |j                  d      d      |	j                  dS c c}}w # t
        j                  j                  $ r" t         j                  d|	j                          w xY w)zfObtains token for
    `Service Fabric <https://learn.microsoft.com/en-us/azure/service-fabric/>`_
    z<Obtaining token via managed identity on Azure Service Fabricz2019-07-01-preview,N)r   rq   token_sha256_to_refreshxms_ccSecretr   r{   ry   rq   r|   r   r   unauthorized_clientinvalid_clientr   )SecretHeaderNotFoundManagedIdentityNotFoundArgumentNullOrEmptycodeinvalid_requestr   r   )r   r   r1   joinitemsr   r   r   r   r   r   r   )ro   r   r   server_thumbprintrq   r   ri   kvr   r   r   error_mappings                r   r   r   M  sy    LLOP??/ 'E7Jchh23PT	"
 eg(A
  1 ( ?+  	
D**TYY';;~&7;;|+D ' 7!L)DIIK() $KK
3%l3  GR($9'7#2 #&&uyy'8:KL!% 	3(: <<'' 8$))Ds   D6)BD< 0AD< <?E;z/var/opt/azcmagent/tokensz/%ProgramData%\AzureConnectedMachineAgent\Tokens)r   r   c                       e Zd Zy)ArcPlatformNotSupportedErrorNr   r   r   r   r   r     r   r   r   c           	         t         j                  d       | j                  |d|dddi      }d}|j                  j	                         D ci c]*  \  }}|j                         |k(  s|j                         |, c}}j                  |d      j                  d	      }t        |      d
k(  r|d   j                         dk(  s$t        dj                  |j                              t        j                  t        vrt        dt        j                   d      t        j                  j!                  t        t        j                     t        j                  j#                  t        j                  j%                  |d               d   dz         }t        j&                  |      j(                  dkD  rt        d      t+        |      5 }	|	j-                         }
d d d        | j                  |d|dddj                  
      d      }	 t/        j0                  |j2                        }|j                  d      rF|j                  d      r5|d   t5        |d         |j                  dd      |j                  d      dS d|j2                  dS c c}}w # 1 sw Y   xY w# t.        j6                  j8                  $ r Y @w xY w)Nz1Obtaining token via managed identity on Azure Arcz
2020-06-01r   r   r   r   zwww-authenticate =r   r   zbasic realmz*Unrecognizable WWW-Authenticate header: {}z	Platform z was undefined and unsupportedr   z.keyi   z+Local key file shall not be larger than 4KBzBasic {})r   Authorizationr{   r\   r|   r}   rq   )r{   r\   r|   rq   r   r   )r   r   r1   r   r   lowersplitlenr   rR   r   r   +_supported_arc_platforms_and_their_prefixesr   r   r   r   splitextbasenamestatst_sizeopenreadr   r   r   r   r   r   )ro   r   rq   r   www_authr   r   	challengefilenamefrz   r   r   s                r   r   r     su   
LLDE??+BV$  
D
 "H "&!3!3!5
 Ah9N	1
 #h
EE#J	  	NaIaL$6$6$8M$I"8??MO 	O
||FF*~%CDF 	Fww||3CLLA
)))A,78;fDFH 
wwx  4'"#PQQ	h 1+B#j6G6G6OP  
H
**X]]+;;~&7;;|+D !( 7!',"78%kk,A#KK
3	  #%]]
 
K
$ " <<'' s+   J*JJA5J% J"%KKr&   )<r   r   loggingr   r   r   r   urllib.parser   collectionsr   typingr   r   r   rg   r	   individual_cacher
   r]   throttled_http_clientr   r   
cloudshellr   skur   r   	getLoggerr   r   
ValueErrorr   r   r/   r5   rM   objectra   r   r   r   r   r   r   r   r   r   rT   r   r   r   r   r   r   r   r   r  r   r   r   r   r   <module>r     s}  
    	 
   !   ( ( # A L 2 ! 
		8	$	: 	,h ,^ZO Z5/ 522  d'F d'N
G hH	h8 2 59/3	2N %-SM2N "$s),	2Nj? D/bJ +//3	. %(. "$s),	.d )WW RS/ +
	#7 	1
r   