o
    i+                     @   s   d dl Z d dlZd dlmZmZ d dl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 dd
lmZ ddlmZmZ dZddgZdee fddZdeddfddZG dd dZdS )    N)AnyOptional)AccessTokenTokenRequestOptionsAccessTokenInfo)ClientAuthenticationError   )AuthenticationRecord)CredentialUnavailableError)AZURE_VSCODE_CLIENT_ID)
within_dac)log_get_token)get_broker_credentialvalidate_tenant_idi (  zA~/.azure/ms-azuretools.vscode-azureresourcegroups/authRecord.jsonzA~/.Azure/ms-azuretools.vscode-azureresourcegroups/authRecord.jsonreturnc               	   C   s   t D ]U} tj| }tj|rWtj|}|tkr d}t|t|ddd}t	
|}W d   n1 s7w   Y  t| t|d |d |d |d	 |d
 d}|  S qdS )a  Load the authentication record corresponding to a known location.

    This will load from ~/.azure/ms-azuretools.vscode-azureresourcegroups/authRecord.json
    or ~/.Azure/ms-azuretools.vscode-azureresourcegroups/authRecord.json

    :return: The authentication record if it exists, otherwise None.
    :rtype: Optional[AuthenticationRecord]
    :raises: ValueError if the authentication record is not in the expected format
    zkVS Code auth record file is unexpectedly large. Please check the file for corruption or unexpected content.rzutf-8)encodingN	authorityclientIdhomeAccountIdtenantIdusername)r   	client_idhome_account_id	tenant_idr   )VSCODE_AUTH_RECORD_PATHSospath
expanduserexistsgetsizeMAX_AUTH_RECORD_SIZE
ValueErroropenjsonload_validate_auth_record_jsonr	   )Zauth_record_pathZexpanded_path	file_sizeerror_messagefZdeserializedZauth_record r*   Y/home/app/Keep/.python/lib/python3.10/site-packages/azure/identity/_credentials/vscode.pyload_vscode_auth_record   s,   r,   datac           	   
   C   s  g }z4| d }|rt |ts|d n!zt| W n ty4 } z|d|  W Y d}~nd}~ww W n tyD   |d Y nw z| d }|rQt |tsW|d n|tkrc|dt  W n tyr   |d	 Y nw z| d
 }|rt |ts|d W n ty   |d Y nw z| d }|rt |ts|d W n ty   |d Y nw z| d }|rt |ts|d W n ty   |d Y nw |rdd| }t|dS )zValidate the authentication record.

    :param dict data: The authentication record data to validate.
    :raises ValueError: If the authentication record fails validation checks.
    r   z#tenantId must be a non-empty stringztenantId validation failed: NztenantId field is missingr   z#clientId must be a non-empty stringzJclientId must match expected VS Code Azure Resources extension client ID: zclientId field is missingr   z#username must be a non-empty stringzusername field is missingr   z(homeAccountId must be a non-empty stringzhomeAccountId field is missingr   z$authority must be a non-empty stringzauthority field is missingz)Authentication record validation failed: z; )
isinstancestrappendr   r"   KeyErrorr   join)	r-   errorsr   er   r   r   r   r(   r*   r*   r+   r&   G   sn   


r&   c                   @   s   e Zd ZdZ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ddde
dee defddZdS )VisualStudioCodeCredentiala  Authenticates as the Azure user signed in to Visual Studio Code via the 'Azure Resources' extension.

    This currently only works in Windows/WSL environments and requires the 'azure-identity-broker'
    package to be installed.

    :keyword str tenant_id: A Microsoft Entra tenant ID. Defaults to the tenant specified in the authentication
        record file used by the Azure Resources extension.
    :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.
    kwargsr   Nc              
   K   s   d | _ d| _t }|rDzt }|sd| _W d S |dt|tjjddd|| _ W d S  tyC } zd| d| _W Y d }~d S d }~ww d S )NzVisualStudioCodeCredential requires the 'azure-identity-broker' package to be installed. You must also ensure you have the Azure Resources extension installed and have signed in to Azure via Visual Studio Code.zVisualStudioCodeCredential requires the user to be signed in to Azure via Visual Studio Code. Please ensure you have the Azure Resources extension installed and have signed in.T)r   authentication_recordZparent_window_handleZuse_default_broker_accountZdisable_interactive_fallbackz>Failed to load authentication record from Visual Studio Code: zO. Please ensure you have the Azure Resources extension installed and signed in.r*   )	_broker_credential_unavailable_messager   r,   r   msalZPublicClientApplicationZCONSOLE_WINDOW_HANDLEr"   )selfr6   Zbroker_credential_classr7   exr*   r*   r+   __init__   s8   z#VisualStudioCodeCredential.__init__c                 C   s   | j r| j   | S N)r8   	__enter__r;   r*   r*   r+   r?      s   
z$VisualStudioCodeCredential.__enter__argsc                 G   s   | j r| j j|  d S d S r>   )r8   __exit__)r;   rA   r*   r*   r+   rB      s   z#VisualStudioCodeCredential.__exit__c                 C   s   | j r
| j   dS dS )z)Close the credential's transport session.N)r8   closer@   r*   r*   r+   rC      s   z VisualStudioCodeCredential.closeclaimsr   scopesrE   r   c             
   O   sx   | j s	t| jdt r0z| j j|||d|}|W S  ty/ } zt|jd|d}~ww | j j|||d|S )a  Request an access token for `scopes` as the user currently signed in to Visual Studio Code.

        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.

        :return: An access token with the desired scopes.
        :rtype: ~azure.core.credentials.AccessToken
        :raises ~azure.identity.CredentialUnavailableError: the credential cannot retrieve user details from Visual
          Studio Code
        messagerD   N)r8   r
   r9   r   get	get_tokenr   rH   )r;   rE   r   rF   r6   tokenr<   r*   r*   r+   rJ      s   z$VisualStudioCodeCredential.get_token)optionsrL   c             
   G   sl   | j s	t| jdt r-z| j j|d|i}|W S  ty, } zt|jd|d}~ww | j j|d|iS )a  Request an access token for `scopes` as the user currently signed in to Visual Studio Code.

        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: ~azure.core.credentials.AccessTokenInfo
        :return: An AccessTokenInfo instance containing information about the token.
        :raises ~azure.identity.CredentialUnavailableError: the credential cannot retrieve user details from Visual
          Studio Code.
        rG   rL   N)r8   r
   r9   r   rI   get_token_infor   rH   )r;   rL   rF   rK   r<   r*   r*   r+   rM      s   z)VisualStudioCodeCredential.get_token_info)r   r5   )r   N)__name__
__module____qualname____doc__r   r=   r?   rB   rC   r   r/   r   r   rJ   r   r   rM   r*   r*   r*   r+   r5      s(    
"
$r5   )r   r$   typingr   r   r:   Zazure.core.credentialsr   r   r   Zazure.core.exceptionsr   Z_auth_recordr	   _exceptionsr
   
_constantsr   	_internalr   Z_internal.decoratorsr   Z_internal.utilsr   r   r!   r   r,   dictr&   r5   r*   r*   r*   r+   <module>   s&   +: