
    j8                     x   d 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mZm	Z	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 d	dlmZ d	dlmZmZ d	dlmZ ej<                  Z ej>                  e       Z!dejD                  z   ddejF                  z   ddejH                  z   diZ%de&fdZ'd Z( G d dee      Z)y)zIBase class for credentials using MSAL for interactive user authentication    N)AnyOptionalIterableDict)urlparse)AccessTokenAccessTokenInfoTokenRequestOptions)ClientAuthenticationError   )MsalCredential   )AuthenticationRecord)KnownAuthorities)AuthenticationRequiredErrorCredentialUnavailableError)wrap_exceptionszhttps://)z2https://management.core.chinacloudapi.cn//.default)z3https://management.core.usgovcloudapi.net//.default)z-https://management.core.windows.net//.defaultreturnc                     | dt        |        dz  z  z  } t        |       } t        j                  |       j	                  d      S )zDecode client info. Taken from msal.oauth2cli.oidc.

    :param str raw: base64-encoded client info
    :return: decoded client info
    :rtype: str
    =   zutf-8)lenstrbase64urlsafe_b64decodedecode)raws    e/root/aria/tools/markitdown-venv/lib/python3.12/site-packages/azure/identity/_internal/interactive.py_decode_client_infor   #   sB     33s8)a-  C
c(C##C(//88    c                    	 | d   }d| v r4t        j                  t        | d               } dj                  di |}n|d   }t	        |d         }|j                  d      xs |j                  j                  d      }|j                  d      xs |d	   }t        |j                  |d
   |||      S # t        t        f$ r}t        d      }||d}~ww xY w)a~  Build an AuthenticationRecord from the result of an MSAL ClientApplication token request.

    :param response: The result of a token request
    :type response: dict[str, typing.Any]
    :return: An AuthenticationRecord
    :rtype: ~azure.identity.AuthenticationRecord
    :raises ~azure.core.exceptions.ClientAuthenticationError: If the response doesn't contain expected data
    id_token_claimsclient_infoz{uid}.{utid}subisstid/preferred_usernameupnaud)	authority	client_idhome_account_id	tenant_idusernamezCFailed to build AuthenticationRecord from unexpected identity tokenmessageN )jsonloadsr   formatr   getpathstripr   netlocKeyError
ValueErrorr   )	responseid_tokenr#   r-   issuerr.   r/   ex
auth_errors	            r   _build_auth_recordrA   0   s    !-.H$**%8-9P%QRK3n33BkBO 'uoO (5/* LL'A6;;+<+<S+A	 << 45H%#mmuo+
 	
 j! !.Y

 b 	!s   B2B5 5CCCc                   J    e Zd Zddddee   dededdf fdZdddd	d
edee   dee   dedede	fdZ
ddd
edee   defdZdddd
edee   dededef
dZdddddd
eee      dee   dee   dededefdZed
ededefd       Zej(                  defd       Z xZS )InteractiveCredentialNF)authentication_record disable_automatic_authenticationrD   rE   kwargsr   c                X   || _         || _        | j                  r||j                  dd        |j                  dd       xs | j                  j                  }t	        t
        |   d| j                  j                  | j                  j                  |d| y t	        t
        |   di | y )Nr,   r.   )r,   r+   r.   r2   )	!_disable_automatic_authentication_auth_recordpopr.   superrC   __init__r,   r+   )selfrD   rE   rF   r.   	__class__s        r   rL   zInteractiveCredential.__init__\   s     2R.1JJ{D)

;5T9J9J9T9TI'7 ++55++55# 	 '7A&Ar    claimsr.   
enable_caescopesrP   r.   rQ   c                    i }|r||d<   |r||d<   ||d<    | j                   ||dd|}t        |j                  |j                        S )a  Request an access token for `scopes`.

        This method is called automatically by Azure SDK clients.

        :param str scopes: desired scopes for the access token. This method requires at least one scope.
            For more information about scopes, see
            https://learn.microsoft.com/entra/identity-platform/scopes-oidc.
        :keyword str claims: additional claims required in the token, such as those returned in a resource provider's
            claims challenge following an authorization failure
        :keyword str tenant_id: optional tenant to include in the token request.
        :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested
            token. Defaults to False.
        :return: An access token with the desired scopes.
        :rtype: ~azure.core.credentials.AccessToken
        :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks
            required data, state, or platform support
        :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message``
            attribute gives a reason.
        :raises AuthenticationRequiredError: user interaction is necessary to acquire a token, and the credential is
            configured not to begin this automatically. Call :func:`authenticate` to begin interactive authentication.
        rP   r.   rQ   	get_tokenoptionsbase_method_name)_get_token_baser   token
expires_on)rM   rP   r.   rQ   rR   rF   rV   
token_infos           r   rT   zInteractiveCredential.get_tokenq   sc    : (* &GH#,GK  *)T))67U`kdjk
:++Z-B-BCCr    )rV   rV   c                (     | j                   ||ddS )a&  Request an access token for `scopes`.

        This is an alternative to `get_token` to enable certain scenarios that require additional properties
        on the token. This method is called automatically by Azure SDK clients.

        :param str scopes: desired scopes for the access token. This method requires at least one scope.
            For more information about scopes, see https://learn.microsoft.com/entra/identity-platform/scopes-oidc.
        :keyword options: A dictionary of options for the token request. Unknown options will be ignored. Optional.
        :paramtype options: ~azure.core.credentials.TokenRequestOptions

        :rtype: AccessTokenInfo
        :return: An AccessTokenInfo instance containing information about the token.

        :raises CredentialUnavailableError: the credential is unable to attempt authentication because it lacks
            required data, state, or platform support
        :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message``
            attribute gives a reason.
        :raises AuthenticationRequiredError: user interaction is necessary to acquire a token, and the credential is
            configured not to begin this automatically. Call :func:`authenticate` to begin interactive authentication.
        get_token_inforU   )rX   )rM   rV   rR   s      r   r]   z$InteractiveCredential.get_token_info   s    * $t##VWO_``r    r]   rU   rW   c          
         |s=d| d}t         j                  d| j                  j                  ||       t	        |      |j                  d| j                         }|xs i }|j                  d      }|j                  d      }|j                  dd      }	|D ]*  }
|
t        j                  vs|j                  |
||
          , 	  | j                  ||||	d	|}t         j                  d
| j                  j                  |       |S # t        $ rl}t        |t              r|sPt         j                  d| j                  j                  ||t         j!                  t"        j$                                Y d }~nd }~ww xY wt'        t)        j(                               }	  | j*                  ||||	d	|}d|vr[dj-                  |j                  d      xs |j                  d            }| j.                  j1                  |      }t3        ||      t5        |      | _        na# t        $ rU}t         j                  d| j                  j                  ||t         j!                  t"        j$                                d }~ww xY wt         j                  d
| j                  j                  |       d|v rt'        |d         nd }t9        |d   |t'        |d         z   |j                  dd      |      S )N'z' requires at least one scopez%s.%s failed: %s_allow_promptrP   r.   rQ   FrO   z%s.%s succeeded)exc_infoaccess_tokenzAuthentication failed: {}error_descriptionerror)r1   r<   
refresh_on
expires_in
token_typeBearerrg   re   )_LOGGERwarningrN   __name__r;   rJ   rH   r6   r
   __annotations__
setdefault_acquire_token_silentinfo	Exception
isinstancer   isEnabledForloggingDEBUGinttime_request_tokenr5   _clientget_error_responser   rA   rI   r	   )rM   rV   rW   rR   rF   r1   allow_promptrP   r.   rQ   keyrY   r?   nowresultr<   re   s                    r   rX   z%InteractiveCredential._get_token_base   s    *++HIGOO.0G0GIY[bcW%%zz/t7]7]3]^-RX&KK,	[[u5
  	5C-===!!#ws|4	5	.D..)
V\E LL*DNN,C,CEUVL 		r#>?L&NN++$$11'--@     EQ		 $))+	(T((&9akvouvFV+5<<VZZH[=\=s`f`j`jkr`st<<::6B/(SS !36 :D 	OO"''  --gmm<   	 	&(?(?AQR2>&2HS-.d
>"#f\*++zz,9!	
 	
s4   AD
 
	E?A"E::E? BH& &	J/AI??J)rR   rP   r.   rQ   c                    |s1| j                   t        vrt        d      t        | j                      } | j                  |d|||d|}| j                  S )ai  Interactively authenticate a user. This method will always generate a challenge to the user.

        :keyword Iterable[str] scopes: scopes to request during authentication, such as those provided by
          :func:`AuthenticationRequiredError.scopes`. If provided, successful authentication will cache an access token
          for these scopes.
        :keyword str claims: additional claims required in the token, such as those provided by
          :func:`AuthenticationRequiredError.claims`
        :keyword str tenant_id: optional tenant to include in the token request.
        :keyword bool enable_cae: indicates whether to enable Continuous Access Evaluation (CAE) for the requested
            token. Access tokens retrieved with CAE enabled will be cached separately from other tokens.
            Defaults to False.
        :return: An AuthenticationRecord containing the authenticated user's information.
        :rtype: ~azure.identity.AuthenticationRecord
        :raises ~azure.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message``
          attribute gives a reason.
        zVAuthenticating in this environment requires a value for the 'scopes' keyword argument.r0   T)r`   rP   r.   rQ   )
_authority_DEFAULT_AUTHENTICATE_SCOPESr   rT   rI   )rM   rR   rP   r.   rQ   rF   _s          r   authenticatez"InteractiveCredential.authenticate   sf    4 &BB0t  2$//BFDNN4)Xb
fl
    r    c           	         d }|j                  d      }| j                  r | j                  di |}|j                  | j                  j                        D ]  }|j                  d      | j                  j
                  k7  r,t        t        j                               }|j                  t        |      ||      }|sid|v snd|v ssd|v rt        |d         nd }t        |d   |t        |d         z   |j                  dd	      |
      c S  |r)| j                  j                  |      }	t        |||	      t        ||      )NrP   )r/   r-   )accountclaims_challengerb   rf   re   rg   rh   ri   )rP   r<   )rP   r2   )r6   rI   _get_appget_accountsr/   r-   rv   rw   acquire_token_silent_with_errorlistr	   ry   rz   r   )
rM   rR   rF   r~   rP   appr   r}   re   r<   s
             r   ro   z+InteractiveCredential._acquire_token_silent  s?   H%$--)&)C++T5F5F5O5O+P ;;01T5F5F5V5VV$))+&<<T&\SZms<tn6<6;Q>Jf>TVL%9!:Z^J*~.c&"677#)::lH#E#-	   ||66v>H-fVhWW)&@@r    c                      y )Nr2   )rM   rR   rF   s      r   rx   z$InteractiveCredential._request_token9  s    r    )rl   
__module____qualname__r   r   boolr   rL   r   r   rT   r
   r	   r]   rX   r   r   r   ro   abcabstractmethodr   rx   __classcell__)rN   s   @r   rC   rC   [   s    AE16	B  ((<=B +/	B
 B 
B0 !%#' %D%D %D C=	%D
 %D %D 
%DN UY ac aH=P4Q a]l a4 26 0	E
E
 -.E
 	E

 E
 
E
T +/ $#' &! #'&! 	&!
 C=&! &! &! 
&!P AS AC AO A A4 	4  r    rC   )*__doc__r   r   r3   rt   rw   typingr   r   r   r   urllib.parser   azure.core.credentialsr   r	   r
   azure.core.exceptionsr   msal_credentialsr   rI   r   
_constantsr   _exceptionsr   r   	_internalr   ABC	getLoggerrl   rj   AZURE_CHINAAZURE_GOVERNMENTAZURE_PUBLIC_CLOUDr   r   r   rA   rC   r2   r    r   <module>r      s   
 P 
     0 0 ! T T ; , / ) Q '	gg
'

H
% !---/f!2224l!4446h  
9 
9(!V`NC `r    