o
    i/                     @   sR  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 dd	lmZmZmZmZmZmZ dd
lmZ eeZdZdZ dZ!dZ"dZ#dZ$dZ%G dd dZ&dee' de(de'fddZ)dee' ddfddZ*de'defddZ+d ee'd!f d"e'dee' fd#d$Z,d%e(d&e'd'e'ddfd(d)Z-dS )*    N)AnyListTupleOptional)AccessTokenAccessTokenInfoTokenRequestOptions)ClientAuthenticationError   )get_safe_working_dir   )CredentialUnavailableError)_scopes_to_resourceencode_base64resolve_tenant
within_dacvalidate_tenant_idvalidate_scope)log_get_tokenz+Az.Account module >= 2.2.0 is not installedz4Execution policy prevented invoking Azure PowerShellNO_AZ_ACCOUNT_MODULEzPowerShell is not installedz0Please run "Connect-AzAccount" to set up accountzThis credential doesn't support claims challenges. To authenticate with the required claims, please run the following command (requires Az.Accounts module version 5.2.0 or later): Connect-AzAccount -ClaimsChallenge {claims_value}a  $ErrorActionPreference = 'Stop'
[version]$minimumVersion = '2.2.0'

$m = Import-Module Az.Accounts -MinimumVersion $minimumVersion -PassThru -ErrorAction SilentlyContinue

if (! $m) {{
    Write-Output {}
    exit
}}

$params = @{{ 'ResourceUrl' = '{}'; 'WarningAction' = 'Ignore' }}

$tenantId = '{}'
if ($tenantId.Length -gt 0) {{
    $params['TenantId'] = $tenantId
}}

if ($m.Version -ge [version]'2.17.0' -and $m.Version -lt [version]'5.0.0') {{
    $params['AsSecureString'] = $true
}}

$token = Get-AzAccessToken @params
$tokenValue = $token.Token
if ($tokenValue -is [System.Security.SecureString]) {{
    if ($PSVersionTable.PSVersion.Major -lt 7) {{
        $ssPtr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($tokenValue)
        try {{
            $tokenValue = [System.Runtime.InteropServices.Marshal]::PtrToStringBSTR($ssPtr)
        }}
        finally {{
            [System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($ssPtr)
        }}
    }}
    else {{
        $tokenValue = $tokenValue | ConvertFrom-SecureString -AsPlainText
    }}
}}
Write-Output "`nazsdk%$($tokenValue)%$($token.ExpiresOn.ToUnixTimeSeconds())`n"
c                   @   s   e Zd ZdZddddd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 )!AzurePowerShellCredentiala  Authenticates by requesting a token from Azure PowerShell.

    This requires previously logging in to Azure via "Connect-AzAccount", and will use the currently logged in identity.

    :keyword str tenant_id: Optional tenant to include in the token request.
    :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 PowerShell process to respond. Defaults to 10 seconds.

    .. admonition:: Example:

        .. literalinclude:: ../samples/credential_creation_code_snippets.py
            :start-after: [START create_azure_power_shell_credential]
            :end-before: [END create_azure_power_shell_credential]
            :language: python
            :dedent: 4
            :caption: Create an AzurePowerShellCredential.
     N
   )	tenant_idadditionally_allowed_tenantsprocess_timeoutr   r   r   returnc                C   s&   |rt | || _|pg | _|| _d S N)r   r   _additionally_allowed_tenants_process_timeout)selfr   r   r    r!   c/home/app/Keep/.python/lib/python3.10/site-packages/azure/identity/_credentials/azure_powershell.py__init__e   s
   

z"AzurePowerShellCredential.__init__c                 C   s   | S r   r!   r    r!   r!   r"   	__enter__r      z#AzurePowerShellCredential.__enter__argsc                 G   s   d S r   r!   )r    r'   r!   r!   r"   __exit__u   r&   z"AzurePowerShellCredential.__exit__c                 C   s   dS )z#Calling this method is unnecessary.Nr!   r$   r!   r!   r"   closex   s    zAzurePowerShellCredential.close)claimsr   scopesr*   kwargsc                O   s>   i }|r||d< |r||d< | j |d|i|}t|j|jS )aD  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: not used by this credential; any value provided will be ignored.
        :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 unable to invoke Azure PowerShell, or
          no account is authenticated
        :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked Azure PowerShell but didn't
          receive an access token
        r   r*   options)_get_token_baser   token
expires_on)r    r*   r   r+   r,   r-   Z
token_infor!   r!   r"   	get_token{   s   z#AzurePowerShellCredential.get_token)r-   r-   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. TThis 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 unable to invoke Azure PowerShell, or
          no account is authenticated
        :raises ~azure.core.exceptions.ClientAuthenticationError: the credential invoked Azure PowerShell but didn't
          receive an access token
        r-   )r.   )r    r-   r+   r!   r!   r"   get_token_info   s   z(AzurePowerShellCredential.get_token_infoc          
      O   s   |r(d|v r(|d r(t jt|d d}|dr#|d|d 7 }t|d|r/|dnd }|r7t| |D ]}t| q9td| j|| j	d|}t
||}t|| j}t|}	|	S )Nr*   )Zclaims_valuer   z	 -Tenant message)Zdefault_tenantr   r   r!   )CLAIMS_UNSUPPORTED_ERRORformatr   getr   r   r   r   r   r   get_command_linerun_command_liner   parse_token)
r    r-   r+   r,   error_messager   scopecommand_lineoutputr/   r!   r!   r"   r.      s*   



z)AzurePowerShellCredential._get_token_base)r   r   )r   N)__name__
__module____qualname____doc__strr   r   intr#   r%   r   r(   r)   r   r   r1   r   r   r2   r.   r!   r!   r!   r"   r   P   sV    



#"r   r=   timeoutr   c              
   C   s   d }}d }d|i}z8t | }|jdi |\}}tjdrAd|v s(|jdkrA| d ddd	| d< t | }|jdi |\}}W n ty_ } z|rS|jsS|  t	d
d}||d }~ww t
|j|| |S )Nr   rE   win' is not recognizedi1#  pwsh
powershellr
   zFailed to invoke PowerShell.
To mitigate this issue, please refer to the troubleshooting guidelines here at https://aka.ms/azsdk/python/identity/powershellcredential/troubleshoot.r3   r!   )start_processcommunicatesysplatform
startswith
returncodereplace	Exceptionkillr   raise_for_error)r=   rE   stdoutstderrprocr,   exerrorr!   r!   r"   r9      s,   
r9   r'   zsubprocess.Popenc                 C   s&   t  }tj| |tjtjtjdd}|S )NT)cwdrU   rV   stdinuniversal_newlines)r   
subprocessPopenPIPEDEVNULL)r'   Zworking_directoryrW   r!   r!   r"   rK      s   rK   r>   c                 C   sb   |   D ]}|dr| d\}}}t|t|  S qt r)td| dtd| d)Nzazsdk%%z.Unexpected output from Get-AzAccessToken: "{}"r3   )	splitrO   r   rD   r   r7   r   r6   r	   )r>   line_r/   r0   r!   r!   r"   r:      s   
r:   r+   .r   c                 C   sb   |r|nd}t |  }tt||}t|d }d| }tj	
dr,dd|d gS dd	|gS )
Nr   z	utf-16-lez0pwsh -NoProfile -NonInteractive -EncodedCommand rF   cmdz/cz & exitz/bin/shz-c)r   SCRIPTr6   r   base64	b64encodeencodedecoderM   rN   rO   )r+   r   Ztenant_argumentresourcescriptZencoded_scriptcommandr!   r!   r"   r8   	  s   
r8   return_coderU   rV   c                 C   sx   | dkrt |v rttd S | dksd|v rttdd|v r$ttdd|v r-ttd|r7tdtj	| tdd)	Nr      rG   r3   zRun Connect-AzAccount to loginz!AuthorizationManager check failedz0%s received an error from Azure PowerShell: "%s"zMFailed to invoke PowerShell. Enable debug logging for additional information.)
r   r   AZ_ACCOUNT_NOT_INSTALLEDPOWERSHELL_NOT_INSTALLEDRUN_CONNECT_AZ_ACCOUNTBLOCKED_BY_EXECUTION_POLICY_LOGGERdebugr   r?   )rn   rU   rV   r!   r!   r"   rT     s&   


rT   ).rg   loggingr]   rM   typingr   r   r   r   Zazure.core.credentialsr   r   r   Zazure.core.exceptionsr	   Z	azure_clir   r   r   	_internalr   r   r   r   r   r   Z_internal.decoratorsr   	getLoggerr?   rt   rp   rs   r   rq   rr   r5   rf   r   rC   rD   r9   rK   r:   r8   rT   r!   r!   r!   r"   <module>   s6    
) "