o
    i1                     @   s8  d dl m 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	m
Z
mZ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mZmZmZmZmZ dd	lmZ ee Z!d
Z"g dZ#dZ$dZ%dZ&G dd dZ'de
e fddZ(de)fddZ*de)de)fddZ+de	e) de,de)fddZ-dS )    )datetimeN)ListOptionalAnyDict)AccessTokenAccessTokenInfoTokenRequestOptions)ClientAuthenticationError   )CredentialUnavailableError)_scopes_to_resourceencode_base64resolve_tenant
within_dacvalidate_tenant_idvalidate_scopevalidate_subscription)log_get_tokenzAzure CLI not found on path)accountzget-access-tokenz--outputjsonazz*Please run 'az login' to set up an accountzThis credential doesn't support claims challenges. To authenticate with the required claims, please run the following command (requires Azure CLI version 2.76.0 or later): az login --claims-challenge {claims_value}c                   @   s   e Zd ZdZddddddedee deee  d	ed
df
ddZd ddZ	de
d
dfddZd!ddZeddddedee dee de
d
ef
ddZedddedee d
efddZdddedee de
d
efddZdS )"AzureCliCredentialaz  Authenticates by requesting a token from the Azure CLI.

    This requires previously logging in to Azure via "az login", and will use the CLI's currently logged in identity.

    :keyword str tenant_id: Optional tenant to include in the token request.
    :keyword str subscription: The name or ID of a subscription. Set this to acquire tokens for an account other
        than the Azure CLI's current account.
    :keyword List[str] additionally_allowed_tenants: Specifies tenants in addition to the specified "tenant_id"
        for which the credential may acquire tokens. Add the wildcard value "*" to allow the credential to
        acquire tokens for any tenant the application can access.
    :keyword int process_timeout: Seconds to wait for the Azure CLI process to respond. Defaults to 10 seconds.

    .. admonition:: Example:

        .. literalinclude:: ../samples/credential_creation_code_snippets.py
            :start-after: [START create_azure_cli_credential]
            :end-before: [END create_azure_cli_credential]
            :language: python
            :dedent: 4
            :caption: Create an AzureCliCredential.
     N
   )	tenant_idsubscriptionadditionally_allowed_tenantsprocess_timeoutr   r   r   r   returnc                C   s8   |rt | |rt| || _|| _|pg | _|| _d S N)r   r   r   r   _additionally_allowed_tenants_process_timeout)selfr   r   r   r    r$   \/home/app/Keep/.python/lib/python3.10/site-packages/azure/identity/_credentials/azure_cli.py__init__D   s   

zAzureCliCredential.__init__c                 C   s   | S r    r$   r#   r$   r$   r%   	__enter__V      zAzureCliCredential.__enter__argsc                 G   s   d S r    r$   )r#   r*   r$   r$   r%   __exit__Y   r)   zAzureCliCredential.__exit__c                 C   s   dS )z#Calling this method is unnecessary.Nr$   r'   r$   r$   r%   close\   s    zAzureCliCredential.close)claimsr   scopesr-   kwargsc                O   s>   i }|r||d< |r||d< | j |d|i|}t|j|jS )ar  Request an access token for `scopes`.

        This method is called automatically by Azure SDK clients. Applications calling this method directly must
        also handle token caching because this credential doesn't cache the tokens it acquires.

        :param str scopes: desired scope for the access token. This credential allows only one scope per request.
            For more information about scopes, see
            https://learn.microsoft.com/entra/identity-platform/scopes-oidc.
        :keyword str claims: additional claims required in the token. This credential does not support claims
            challenges.
        :keyword str tenant_id: optional tenant to include in the token request.

        :return: An access token with the desired scopes.
        :rtype: ~azure.core.credentials.AccessToken

        :raises ~azure.identity.CredentialUnavailableError: the credential was either unable to invoke the Azure CLI
          or a claims challenge was provided.
        :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked the Azure CLI but didn't
          receive an access token.
        r   r-   options)_get_token_baser   token
expires_on)r#   r-   r   r.   r/   r0   Z
token_infor$   r$   r%   	get_token_   s   zAzureCliCredential.get_token)r0   r0   c                G   s   | j |d|i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. Applications calling this method
        directly must also handle token caching because this credential doesn't cache the tokens it acquires.

        :param str scopes: desired scopes for the access token. This credential allows only one scope per request.
            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: ~azure.core.credentials.AccessTokenInfo
        :return: An AccessTokenInfo instance containing information about the token.

        :raises ~azure.identity.CredentialUnavailableError: the credential was either unable to invoke the Azure CLI
          or a claims challenge was provided.
        :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked the Azure CLI but didn't
          receive an access token.
        r0   )r1   )r#   r0   r.   r$   r$   r%   get_token_info   s   z!AzureCliCredential.get_token_infoc                O   s4  |r3d|v r3|d r3t jt|d d}|dr#|d|d 7 }|r.|d|d  7 }t|d|r:|dnd }|rBt| |D ]}t| qDt| }td|g }t	d| j
|| jd	|}	|	rj|d
|	g7 }| jrt|d| jg7 }t|| j}
t|
}|st|
}d| d}t rt|dt|d|S )Nr-   )Zclaims_valuer   z
 --tenant z	 --scope r   messagez
--resource)Zdefault_tenantr   r   z--tenantz--subscriptionz#Unexpected output from Azure CLI: 'z'. 
To mitigate this issue, please refer to the troubleshooting guidelines here at https://aka.ms/azsdk/python/identity/azclicredential/troubleshoot.r$   )CLAIMS_UNSUPPORTED_ERRORformatr   getr   r   r   r   COMMAND_LINEr   r   r!   r   _run_commandr"   parse_tokensanitize_outputr   r
   )r#   r0   r.   r/   error_messager   scoperesourcecommand_argsZtenantoutputr2   Zsanitized_outputr7   r$   r$   r%   r1      sF   





z"AzureCliCredential._get_token_base)r   r   )r   N)__name__
__module____qualname____doc__strr   r   intr&   r(   r   r+   r,   r   r   r4   r	   r   r5   r1   r$   r$   r$   r%   r   -   s\    



$"r   r   c              	   C   sp   z+t | }d|v rt|d t|d W S t|d d}| }t|d t|W S  ttfy7   Y dS w )a  Parse output of 'az account get-access-token' to an AccessToken.

    In particular, convert the "expiresOn" value to epoch seconds. This value is a naive local datetime as returned by
    datetime.fromtimestamp.

    :param str output: Output of 'az' command.
    :return: An AccessToken or None if the output isn't valid.
    :rtype: azure.core.credentials.AccessToken or None
    r3   ZaccessTokenZ	expiresOnz%Y-%m-%d %H:%M:%S.%fN)	r   loadsr   rI   r   strptime	timestampKeyError
ValueError)rC   r2   dtr3   r$   r$   r%   r=      s   

r=   c                  C   s.   t jdrtjd} | stdd| S dS )zInvoke 'az' from a directory controlled by the OS, not the executing program's directory.

    :return: The path to the directory.
    :rtype: str
    winZ
SYSTEMROOTz.Environment variable 'SYSTEMROOT' has no valuer6   z/bin)sysplatform
startswithosenvironr:   r   )pathr$   r$   r%   get_safe_working_dir   s   
rW   rC   c                 C   s   t dd| S )zRedact access tokens from CLI output to prevent error messages revealing them.

    :param str output: The output of the Azure CLI.
    :return: The output with access tokens redacted.
    :rtype: str
    z\"accessToken\": \"(.*?)(\"|$)z****)resub)rC   r$   r$   r%   r>      s   r>   rB   timeoutc           	   
   C   s  t jdrttd ptt}ntt}|sttd|g|  }z#t }t	j
t	j|d|ttjddd}td| t	j|fi |W S  t	jy } zK|jd	ks`|jd urf|jd
rfttd||jd urd|jv sud|jv rd|jvrttd||jrt|j}nd}t rt|d|t|d|d }~w ty } ztd|d d}||d }~w ty } ztdd}||d }~ww )NrP   z.cmdr6   Ttrue)ZAZURE_CORE_NO_COLOR)stderrstdincwduniversal_newlinesrZ   envz4Executing subprocess with the following arguments %s   z'az' is not recognizedzaz loginzaz account setZAADSTSzFailed to invoke Azure CLIzFailed to execute '{}'r   zFailed to invoke the Azure CLI)rQ   rR   rS   shutilwhichEXECUTABLE_NAMEr   CLI_NOT_FOUNDrW   
subprocessPIPEDEVNULLdictrT   rU   _LOGGERdebugcheck_outputCalledProcessError
returncoder\   NOT_LOGGED_INr>   r   r:   r
   OSErrorr9   	Exception)	rB   rZ   Zaz_pathr*   Zworking_directoryr/   exr7   errorr$   r$   r%   r<     sN   


 

r<   ).r   r   rT   rX   loggingrb   rf   rQ   typingr   r   r   r   Zazure.core.credentialsr   r   r	   Zazure.core.exceptionsr
   r   r   	_internalr   r   r   r   r   r   r   Z_internal.decoratorsr   	getLoggerrD   rj   re   r;   rd   ro   r8   r   r=   rH   rW   r>   rI   r<   r$   r$   r$   r%   <module>   s6   $	
 $
