
    #	hv                        S SK r S SKrS SKrS SKrS SKrS SKrS SKJr  S SKJ	r	  S SK
JrJr  SSKJr  SSKJr  SSKJrJr  SS	KJr  \R.                  " \5      r " S
 S\5      r " S S\	5      r " S S\5      r " S S\5      r " S S\5      r " S S\ 5      r!S r"S r#\ " 5       r$\ " 5       r%\ " 5       r&\ " 5       r'\ " 5       r(\ " 5       r)S r*S r+S%S jr,S r-S r.S r/S r0S\Rb                  Re                  S 5      S!.r3 " S" S#\5      r4S$ r5g)&    N)urlparse)UserDict)OptionalUnion   )
TokenCache)_IndividualCache)ThrottledHttpClientBaseRetryAfterParser)_is_running_in_cloud_shellc                       \ rS rSrSrg)ManagedIdentityError    N__name__
__module____qualname____firstlineno____static_attributes__r       G/var/www/html/env/lib/python3.13/site-packages/msal/managed_identity.pyr   r          r   r   c                      ^  \ rS rSrSrSrSrSrSrSr	Sr
\S	\S
\	S0r\S 5       r\S 5       r\S 5       rSU 4S jjrSrU =r$ )ManagedIdentity   z{Feed 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                     [        U[        5      =(       d)    U R                  U5      =(       d    U R                  U5      $ N)
isinstancer   is_system_assignedis_user_assignedclsunknowns     r   is_managed_identity#ManagedIdentity.is_managed_identity/   s7    7O4 -%%g.-##G,	.r   c                     [        U[        5      =(       d?    [        U[        5      =(       a(    UR                  U R                  5      U R
                  :H  $ r'   )r(   SystemAssignedManagedIdentitydictgetID_TYPESYSTEM_ASSIGNEDr+   s     r   r)   "ManagedIdentity.is_system_assigned5   sD    '#@A Aw% @CKK(C,?,??	Ar   c                     [        U[        5      =(       da    [        U[        5      =(       aJ    UR                  U R                  5      U R
                  ;   =(       a    UR                  U R                  5      $ r'   )r(   UserAssignedManagedIdentityr2   r3   r4   _types_mappingIDr+   s     r   r*    ManagedIdentity.is_user_assigned;   sV    '#>? %w% $CKK(C,>,>>$CFF#	%r   c                 \   > [         [        U ]  U R                  UU R                  U05        g r'   )superr   __init__r4   r:   )self
identifierid_type	__class__s      r   r>   ManagedIdentity.__init__B   s)    ot-LL'GGZ/
 	r   r   )NN)r   r   r   r   __doc__r4   r:   	CLIENT_IDRESOURCE_ID	OBJECT_IDr5   r9   classmethodr.   r)   r*   r>   r   __classcell__rB   s   @r   r   r      s     &G	B IKI&O 	;\;N . .
 A A
 % % r   r   c                   ,   ^  \ rS rSrSrU 4S jrSrU =r$ )r1   J   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                 <   > [         [        U ]  U R                  S9  g )N)rA   )r=   r1   r>   r5   )r?   rB   s    r   r>   &SystemAssignedManagedIdentity.__init__U   s    +T;DDXDX;Yr   r   r   r   r   r   rD   r>   r   rI   rJ   s   @r   r1   r1   J   s    	Z Zr   r1   c                   8   ^  \ rS rSrSrSSSS.U 4S jjrSrU =r$ )r8   Y   a%  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                F  > U(       a+  U(       d$  U(       d  [         [        U ]  U R                  US9  g U(       d+  U(       a$  U(       d  [         [        U ]  U R                  US9  g U(       d+  U(       d$  U(       a  [         [        U ]  U R
                  US9  g [        S5      e)N)rA   r@   zPYou shall specify one of the three parameters: client_id, resource_id, object_id)r=   r8   r>   rE   rF   rG   r   )r?   r#   rR   r%   rB   s       r   r>   $UserAssignedManagedIdentity.__init__b   s    [-t=9 > >{9-t=(([ > B;9-t=9 > > '45 5r   r   rO   rJ   s   @r   r8   r8   Y   s     %)dd 5 5r   r8   c                   (   ^  \ rS rSrU 4S jrSrU =r$ )_ThrottledHttpClientr   c                    >^  [         [        T ]
  " U40 UD6  [        T R                  U 4S j[        S5      R                  S9" UR                  5      T l        g )Nc                    > SR                  US   TR                  [        UR                  S5      5      [        UR                  S5      5      -   5      5      $ )Nz"REQ {} hash={} 429/5xx/Retry-Afterr   paramsdata)format_hashstrr3   )funcargskwargsr?   s      r   <lambda>/_ThrottledHttpClient.__init__.<locals>.<lambda>w   sK    1U1\1\Q

 

8,-FJJv4F0GGI2r      )mapping	key_maker
expires_in)r=   rV   r>   IndividualCache_expiring_mappingr   parser3   )r?   http_clientra   rB   s   `  r   r>   _ThrottledHttpClient.__init__s   sP    "D2;I&I"** (*00
 oo
r   )r3   )r   r   r   r   r>   r   rI   rJ   s   @r   rV   rV   r   s     r   rV   c                   z    \ rS rSrSrSu  rrSrSrSr	SSS.S	\
\\\\4   4S
 jjrS rSS.S\S\\   4S jjrSrg)ManagedIdentityClient   a  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_cacherp   c                    [         R                  U5      (       d  [        SU 35      eXl        [	        [        U[        5      (       a  UR                  OUUS9U l        U=(       d
    [        5       U l
        g)am  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`.

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: )ru   N)r   r.   r   _managed_identityrV   r(   r
   rk   _http_clientr   _token_cache)r?   rp   rk   rt   ru   s        r   r>   ManagedIdentityClient.__init__   sw    H 223CDD&./?.@AC C!10 k+BCC ##IT!
 (7:<r   c                 h    U R                   c  [        R                  " 5       U l         U R                   $ r'   ) _ManagedIdentityClient__instancesocketgetfqdn)r?   s    r   _get_instance#ManagedIdentityClient._get_instance   s$    ??"$nn.DOr   )claims_challengeresourcer   c                   SnU R                   R                  [        R                  S5      n[        R                  " 5       nU(       d  U R
                  R                  U R
                  R                  R                  U/[        UU R                  5       U R                  SS9S9nU H  n[        US   5      U-
  nUS:  a  M  [        R                  S5        SUS	   S
UR                  S
S5      S[        U5      U R                  U R                   0nSU;   a%  [        US   5      US'   [        US   5      U:  a    OUs  $     [#        U R$                  U R                   U5      n	SU	;   a  U	R                  SS5      nSU	;  a  US:  a  [        US-  5      U	S'   U R
                  R'                  [        UU/SR)                  U R                  5       U R                  5      U	0 0 S95        SU	;   a  [        XYS   -   5      U	S'   U R*                  XR                  '   U	(       a  SU	;  d  U(       d  U	$  U$ !   U(       d  e  U$ = f)a  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 skip a token cache read,
    and 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,  zCache hit an ATaccess_tokensecret
token_typeBearerrg   
refresh_oni  
refresh_ini      zhttps://{}/{})r#   scopetoken_endpointresponserZ   r[   error)rw   r3   r   r:   timery   findCredentialTypeACCESS_TOKENr2   r   _tenantintloggerdebug_TOKEN_SOURCE_TOKEN_SOURCE_CACHE_obtain_tokenrx   addr\   _TOKEN_SOURCE_IDP)
r?   r   r   access_token_from_cacheclient_id_in_cachenowmatchesentryrg   results
             r   acquire_token_for_client.ManagedIdentityClient.acquire_token_for_client   sR   D #'!3377 BDiik'',,!!00== z0 $ 2 2 4,,$(	 - 	G ! |!45;
$./"E(O %))L("C #j/&&(@(@	+'  5(<?l@S<T+L95./#5.. ! 	"4#4#4d6L6LhWF'#ZZd;
v-*2D+.zA~+>F<(!!%%d0#*#2#9#9**,dll$<#'   6)+.sL5I/I+JF<(-1-C-C))*7&0:Q ;R '&		* +&&s   C,H4 4
I)
__instancerx   rw   ry   )r   r   r   r   rD   r|   r   r   r   r   r   r2   r   r1   r8   r>   r   r^   r   r   r   r   r   r   rn   rn      s    " 3J"M+! W8)')W8r +/	Y' Y' #3-	Y' Y'r   rn   c                     [        U 5      nUR                  (       a&  SR                  UR                  UR                  5      $ U $ )Nz{}://{})r   schemer\   netloc)r   us     r   _scope_to_resourcer   S  s2    Axx!((33Lr   c                     S[         R                  ;   a'  S[         R                  ;   a  [         R                  S   $ [        R                  S:X  a$  [         R                  R                  S5      (       dU  [        R                  S:X  aC  [         R                  R                  [         R                  R                  S5      5      (       a  gg g )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   Z  s    bjj(_

-Jzz-..BGGNN3M$N$N<<7"rww~~bgg6H6HC7
 ( (
 G("r   c                     S[         R                  ;   a.  S[         R                  ;   a  S[         R                  ;   a  [        $ S[         R                  ;   a  S[         R                  ;   a  [        $ S[         R                  ;   a  S[         R                  ;   a  [        $ [        5       (       a  [        $ [        5       (       a  [        $ [        $ )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   n  s     	rzz).?2::.M,

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

(B!##r   c                 6   S[         R                  ;   a  S[         R                  ;   ar  S[         R                  ;   a^  U(       a  [        R                  S5        [	        U [         R                  S   [         R                  S   [         R                  S   U5      $ S[         R                  ;   aE  S[         R                  ;   a1  [        U [         R                  S   [         R                  S   UU5      $ S[         R                  ;   aE  S[         R                  ;   a1  [        U [         R                  S   [         R                  S   UU5      $ [        5       nU(       a1  [        R                  U5      (       a  [        S5      e[        XU5      $ [        XU5      $ )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   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)rk   rp   r   arc_endpoints       r   r   r     sY   rzz).?2::.M,

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

(B0JJ~&JJ|$
 	
 %&L++,<==&JK K
 $KxHH$[HMMr   c                     U=(       d    [         R                  R                  UR                  [         R                  5      5      nU(       a  U[         R                     X'   g g r'   )r   r9   r3   r4   r:   )rZ   rp   types_mappingid_names       r   _adjust_paramr     sK    > > >CC_4457G*?+=+=> r   c                 N   [         R                  S5        SUS.n[        X15        U R                  [        R
                  " SS5      R                  S5      S-   USS	0S
9n [        R                  " UR                  5      nUR                  S5      (       aK  UR                  S5      (       a5  US   [        US   5      UR                  S5      UR                  SS5      S.$ U$ ! [        R                  R                   a"    [         R                  SUR                  5        e f = f)Nz0Obtaining token via managed identity on Azure VMz
2018-02-01api-versionr   !AZURE_POD_IDENTITY_AUTHORITY_HOSTzhttp://169.254.169.254/z/metadata/identity/oauth2/tokenMetadatatruerZ   headersr   rg   r   r   r   r   rg   r   r   !IMDS emits unexpected payload: %s)r   r   r   r3   r   getenvstripjsonloadstextr   decoderJSONDecodeError)rk   rp   r   rZ   resppayloads         r   r   r     s   
LLCD#
F &+??
		/1I	eCj<	= V$  
D**TYY';;~&&7;;|+D+D ' 7!',"78#KK
3%kk,A	  <<'' 8$))Ds   !B C$ "C$ $A D$c           
          [         R                  S5        SUS.n[        XS[        R                  S[        R
                  S[        R                  S0S9  U R                  UUUSS	.S
9n [        R                  " UR                  5      nUR                  S5      (       aj  UR                  S5      (       aT  US   [        US   5      [        [        R                  " 5       5      -
  UR                  S5      UR                  SS5      S.$ SSR                  UR                  S5      UR                  S5      5      S.$ ! [        R                  R                   a"    [         R                  SUR                  5        e f = f)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   r   r   r   r   invalid_scopez{}, {}
statusCodemessager   error_descriptionr   )r   r   r   r   rE   rF   rG   r3   r   r   r   r   r   r\   r   r   )rk   endpointidentity_headerrp   r   rZ   r   r   s           r   r   r     sW    LLLM#
F &!!;##[!!;;  ??!0  	
D**TYY';;~&&7;;|+D+D ' 7!',"783tyy{;KK#KK
3%kk,A	  %!)L)7;;y+A"C 	
 <<'' 8$))Ds   *BD= 
2D= =A E=c                    [         R                  S5        SUS.n[        XS5        US   S:X  a  SU;   a  UR                  S5      US'   U R	                  UUSU0S9n [
        R                  " UR                  5      nUR	                  S	5      (       aj  UR	                  S
5      (       aT  US	   [        US
   5      [        [        R                  " 5       5      -
  UR	                  S5      UR	                  SS5      S.$ SSR                  U5      S.$ ! [
        R                  R                   a"    [         R                  SUR                  5        e f = f)Nz>Obtaining token via managed identity on Azure Machine Learningz
2017-09-01r   r   r#   clientidr   r   r   r   r   r   r   r   r   z{}r   r   )r   r   r   popr3   r   r   r   r   r   r\   r   r   )rk   r   r   rp   r   rZ   r   r   s           r   r   r     s4   
 LLQR)x@F&+m,1F#ZZ4z??6"  
D
**TYY';;~&&7;;|+D+D ' 7!',"783tyy{;KK#KK
3%kk,A	  %!%W!5 	 <<'' 8$))Ds   BD =D A Ec                    [         R                  S5        U R                  USUS.SU0S9n [        R                  " UR
                  5      nUR                  S5      (       a]  UR                  S5      (       aG  US   [        US   5      [        [        R                  " 5       5      -
  UR                  S5      US	   S
.$ UR                  S0 5      nSSSS.nUR                  US   S   S5      UR
                  S.$ ! [        R                  R                   a"    [         R                  SUR
                  5        e f = f)z^Obtains 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-previewr   Secretr   r   r   r   r   r   r   unauthorized_clientinvalid_clientr   )SecretHeaderNotFoundManagedIdentityNotFoundArgumentNullOrEmptycodeinvalid_requestr   r   )
r   r   r3   r   r   r   r   r   r   r   )	rk   r   r   server_thumbprintr   r   r   r   error_mappings	            r   r   r   *  s7    LLOP??3J?+  
D
**TYY';;~&&7;;|+D+D ' 7!L)DIIK() $KK
3%l3  GR($9'7#2 #&&ww'7'?ARS!% 	 <<'' 8$))Ds   BC=  <C= =A D=z/var/opt/azcmagent/tokensz/%ProgramData%\AzureConnectedMachineAgent\Tokens)r   r   c                       \ rS rSrSrg)ArcPlatformNotSupportedErroriX  r   Nr   r   r   r   r  r  X  r   r   r  c           	         [         R                  S5        U R                  USUS.SS0S9nSnUR                  R	                  5        VVs0 s H,  u  pVUR                  5       U:X  d  M  UR                  5       U_M.     snnR                  US5      R                  S	5      n[        U5      S
:X  a  US   R                  5       S:X  d$  [        SR                  UR                  5      5      e[        R                  [        ;  a  [        S[        R                   S35      e[        R                  R!                  [        [        R                     [        R                  R#                  [        R                  R%                  US   5      5      S   S-   5      n[        R&                  " U5      R(                  S:  a  [        S5      e[+        U5       n	U	R-                  5       n
S S S 5        U R                  USUS.SSR                  W
5      S.S9n [.        R0                  " UR2                  5      nUR                  S5      (       aK  UR                  S5      (       a5  US   [5        US   5      UR                  SS5      UR                  S5      S.$ SUR2                  S.$ s  snnf ! , (       d  f       N= f! [.        R6                  R8                   a     NFf = f)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   rg   r   r   r   )r   rg   r   r   r   r   )r   r   r3   r   itemslowersplitlenr   r\   r   r   +_supported_arc_platforms_and_their_prefixesr  r   r   joinsplitextbasenamestatst_sizeopenreadr   r   r   r   r   r   )rk   r   r   r   www_authkv	challengefilenamefr   r   r   s                r   r   r   [  sx   
LLDE??+BV$  
D
 "H "&!3!3!5
 "6h9N	1!5
 #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+D !( 7!',"78%kk,A#KK
3	  #%]]
 
K
$ 
" <<'' s+   J")J"J(B J9 (
J69KKr'   )6r   loggingr   r}   r   r   urllib.parser   collectionsr   typingr   r   rt   r   individual_cacher	   rh   throttled_http_clientr
   r   
cloudshellr   	getLoggerr   r   
ValueErrorr   r   r1   r8   rV   objectrn   r   r   r   r   r   r   r   r   r   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  N'F N'b
G hH	h8 ,,N^?:/bD&T )WW RS/ +
	#7 	1
r   