
    9i}                     j   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  ej2                  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e-   deee-      fdZ.d(dZ/d Z0d Z1d  Z2dddde-deee-      fd!Z3d"ejh                  jk                  d#      d$Z6 G d% d&e      Z7d' Z8y))    N)urlparse)UserDict)ListOptionalUnion   )
TokenCache)_IndividualCache)ThrottledHttpClientBaseRetryAfterParser)_is_running_in_cloud_shellc                       e Zd Zy)ManagedIdentityErrorN__name__
__module____qualname__     H/var/www/html/venv/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_identity0   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_assigned6   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%   UserAssignedManagedIdentityr.   r/   r0   _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__r0   r5   )self
identifierid_type	__class__s      r   r8   zManagedIdentity.__init__C   s)    ot-LL'GGZ/
 	r   )NN)r   r   r   __doc__r0   r5   	CLIENT_IDRESOURCE_ID	OBJECT_IDr1   r4   classmethodr+   r&   r'   r8   __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;   )r7   r-   r8   r1   )r9   r<   s    r   r8   z&SystemAssignedManagedIdentity.__init__V   s    +T;DDXDX;Yr   r   r   r   r=   r8   rB   rC   s   @r   r-   r-   K   s    	Z Zr   r-   c                   ,     e Zd ZdZdddd fd
Z xZS )r3   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)r7   r3   r8   r>   r?   r@   r   )r9   r    rH   r"   r<   s       r   r8   z$UserAssignedManagedIdentity.__init__c   s    [-t=9 > >{9-t=(([ > B;9-t=9 > > '45 5r   rF   rC   s   @r   r3   r3   Z   s     %)dd 5 5r   r3   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strr/   )funcargskwargsr9   s      r   <lambda>z/_ThrottledHttpClient.__init__.<locals>.<lambda>x   sM    1U1\1\Q

 

8,-FJJv4F0GGI2 r      )mapping	key_maker
expires_in)r7   rK   r8   IndividualCache_expiring_mappingr   parser/   )r9   rT   rU   r<   s   `  r   r8   z_ThrottledHttpClient.__init__t   sT    "D2DCFC
?** (*00
 hh
r   )r   r   r   r8   rB   rC   s   @r   rK   rK   s   s     r   rK   c                   |    e Zd ZdZd\  Z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 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.
    )Nmanaged_identitytoken_sourceidentity_providercacheN)token_cache
http_cacheclient_capabilitiesr`   rf   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: )re   N)	r   r+   r   _managed_identityrK   _http_clientr	   _token_cache_client_capabilities)r9   r`   http_clientrd   re   rf   s         r   r8   zManagedIdentityClient.__init__   se    ` 223CD&./?.@AC C!10 !
 (7:<$7!r   c                 d    | j                   t        j                         | _         | j                   S r$   ) _ManagedIdentityClient__instancesocketgetfqdn)r9   s    r   _get_instancez#ManagedIdentityClient._get_instance   s$    ??"$nn.DOr   )claims_challengeresourcerr   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BearerrZ   
refresh_onzutf-8access_token_sha256_to_refreshrf   i  
refresh_ini      zhttps://{}/{})r    scopetoken_endpointresponserN   rO   error)rh   r/   r   r5   timerj   searchCredentialTypeACCESS_TOKENr.   rq   _tenantintloggerdebug_TOKEN_SOURCE_TOKEN_SOURCE_CACHE_obtain_tokenri   hashlibsha256encode	hexdigestrk   addrP   _TOKEN_SOURCE_IDP)r9   rs   rr   access_token_to_refreshaccess_token_from_cacheclient_id_in_cachenowmatchesentryrZ   results              r   acquire_token_for_clientz.ManagedIdentityClient.acquire_token_for_client  s   B #'"&!3377 BDiik''..!!00== z0 $ 2 2 4,,$(	 / 	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**,dll$<#'   6)+.sVL5I/I+JF<(-1-C-Ct))*7&0:Q ;R '&		* +&&s   
DI- -I5)r   r   r   r=   rn   r   r   r   r   r   r.   r   r-   r3   r   r   rR   r8   rq   r   r   r   r   r_   r_      s    " 3J"M+! 37c8)')c8 &d3i0c8J +/	e' e' #3-	e'r   r_   c                     t        |       }|j                  r&dj                  |j                  |j                        S | S )Nz{}://{})r   schemerP   netloc)r   us     r   _scope_to_resourcer   l  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   s  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   rf   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)rl   r`   rs   r   rf   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   r4   r/   r0   r5   )rN   r`   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d	i
      }	 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-versionrs   !AZURE_POD_IDENTITY_AUTHORITY_HOSTzhttp://169.254.169.254/z/metadata/identity/oauth2/tokenMetadatatruerN   headersr}   rZ   rs   r~   r   r}   rZ   rs   r~   !IMDS emits unexpected payload: %s)r   r   r   r/   r   getenvstripjsonloadstextr   decoderJSONDecodeError)rl   r`   rs   rN   resppayloads         r   r   r     s	   
LLCD#
F &*+??
		/1I	eCj<	= V$  
D**TYY';;~&7;;|+D ' 7!',"78#KK
3%kk,A	  <<'' 8$))Ds   $A5C C ?D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}   r{   rs   r~   r   r   invalid_scopez{}, {}
statusCodemessager   error_descriptionr   )r   r   r   r   r>   r?   r@   r/   r   r   r   r   r   rP   r   r   )rl   endpointidentity_headerr`   rs   rN   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    clientidr|   r   r}   r{   rs   r~   r   r   r   z{}r   r   )r   r   r   popr/   r   r   r   r   r   rP   r   r   )rl   r   r|   r`   rs   rN   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   rs   token_sha256_to_refreshxms_ccSecretr   r}   r{   rs   r~   r   r   unauthorized_clientinvalid_clientr   )SecretHeaderNotFoundManagedIdentityNotFoundArgumentNullOrEmptycodeinvalid_requestr   r   )r   r   r/   joinitemsr   r   r   r   r   r   r   )rl   r   r   server_thumbprintrs   r   rf   kvr   r   r   error_mappings                r   r   r   I  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}   rZ   r~   r   rs   )r}   rZ   r~   rs   r   r   )r   r   r/   r   r   lowersplitlenr   rP   r   r   +_supported_arc_platforms_and_their_prefixesr   r   r   r   splitextbasenamestatst_sizeopenreadr   r   r   r   r   r   )rl   r   rs   r   www_authr   r   	challengefilenamefr|   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$   )9r   r   loggingr   ro   r   r   urllib.parser   collectionsr   typingr   r   r   rd   r	   individual_cacher
   r[   throttled_http_clientr   r   
cloudshellr   	getLoggerr   r   
ValueErrorr   r   r-   r3   rK   objectr_   r   r   r   r   r   r   r   r   r   rR   r   r   r   r   r   r   r   r   r  r   r   r   r   r   <module>r     sy  
    	  
  !   ( ( # A L 2 
		8	$	: 	,h ,^ZO Z5/ 522  f'F f'R
G hH	h8 2 59/3	2N %-SM2N "$s),	2Nj?:/bJ +//3	. %(. "$s),	.d )WW RS/ +
	#7 	1
r   