o
    iv!                     @   s   d dl Z d dlmZmZ d dlmZ d dlmZmZm	Z	 d dl
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ZdZdZdededefddZdd ZG dd dZdS )    N)AnyOptional)ClientAuthenticationError)AccessTokenAccessTokenInfoTokenRequestOptions)HttpRequestHttpResponse   )ClientAssertionCredential   )CredentialUnavailableError)validate_tenant_id)build_pipelineSYSTEM_OIDCREQUESTURIz7.1zJhttps://aka.ms/azsdk/python/identity/azurepipelinescredential/troubleshootservice_connection_idaccess_tokenreturnc                 C   sD   t jt d}| dt d|  }dd| dd}td||d	S )
N/z?api-version=z&serviceConnectionId=zapplication/jsonzBearer Suppress)zContent-TypeAuthorizationzX-TFS-FedAuthRedirectPOST)headers)osenvironr   rstripOIDC_API_VERSIONr   )r   r   Zbase_uriurlr    r   b/home/app/Keep/.python/lib/python3.10/site-packages/azure/identity/_credentials/azure_pipelines.pybuild_oidc_request   s   r    c                   C   s,   t tjvrtdt  dt  dt ddd S )NzMissing value for the za environment variable. AzurePipelinesCredential is intended for use in Azure Pipelines where the zK environment variable is set. Please refer to the troubleshooting guide at .message)r   r   r   r   TROUBLESHOOTING_GUIDEr   r   r   r   validate_env_vars$   s   
r%   c                   @   s   e Zd ZdZdedededededdfd	d
Zdddddedee dee dedede	fddZ
dddedee defddZdefddZdd Zdd ZdddZdS )AzurePipelinesCredentialaa  Authenticates using Microsoft Entra Workload ID in Azure Pipelines.

    This credential enables authentication in Azure Pipelines using workload identity federation for Azure service
    connections.

    :keyword str tenant_id: The tenant ID for the service connection. Required.
    :keyword str client_id: The client ID for the service connection. Required.
    :keyword str service_connection_id: The service connection ID for the service connection associated with the
        pipeline. From the service connection's configuration page URL in the Azure DevOps web portal, the ID
        is the value of the "resourceId" query parameter. Required.
    :keyword str system_access_token: The pipeline's System.AccessToken value. It is recommended to assign the value
        of System.AccessToken to a secure variable in the Azure Pipelines environment. See
        https://learn.microsoft.com/azure/devops/pipelines/build/variables#systemaccesstoken for more info. Required.
    :keyword str authority: Authority of a Microsoft Entra endpoint, for example "login.microsoftonline.com",
        the authority for Azure Public Cloud (which is the default). :class:`~azure.identity.AzureAuthorityHosts`
        defines authorities for other clouds.
    :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.

    .. admonition:: Example:

        .. literalinclude:: ../samples/credential_creation_code_snippets.py
            :start-after: [START create_azure_pipelines_credential]
            :end-before: [END create_azure_pipelines_credential]
            :language: python
            :dedent: 4
            :caption: Create an AzurePipelinesCredential.
    	tenant_id	client_idr   system_access_tokenkwargsr   Nc                K   sb   |r|r|r|st dt dt| || _|| _td||| jd|| _tdi || _	d S )Nz'tenant_id', 'client_id', 'service_connection_id', and 'system_access_token' must be passed in as keyword arguments. Please refer to the troubleshooting guide at r!   )r'   r(   funcr   )

ValueErrorr$   r   _system_access_token_service_connection_idr   _get_oidc_token_client_assertion_credentialr   	_pipeline)selfr'   r(   r   r)   r*   r   r   r   __init__M   s   
z!AzurePipelinesCredential.__init__Fclaimsr'   
enable_caescopesr5   r6   c                O   s    t   | jj||||d|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.
        r4   )r%   r0   	get_token)r2   r5   r'   r6   r7   r*   r   r   r   r8   d   s   z"AzurePipelinesCredential.get_token)optionsr9   c                G   s   t   | j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.

        :param str scopes: desired scope 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.core.exceptions.ClientAuthenticationError: authentication failed. The error's ``message``
            attribute gives a reason.
        r9   )r%   r0   get_token_info)r2   r9   r7   r   r   r   r:      s   z'AzurePipelinesCredential.get_token_infoc                 C   s`   t | j| j}| jj||jgd}|j}|jdvrtd|d|	 }d|vr,tdd|d S )N)Zretry_on_methods)   z-Unexpected response from OIDC token endpoint.)r#   responseZ	oidcTokenz!OIDC token not found in response.r"   )
r    r.   r-   r1   runmethodhttp_responsestatus_coder   json)r2   requestr<   r?   Zjson_responser   r   r   r/      s   

z(AzurePipelinesCredential._get_oidc_tokenc                 C   s   | j   | j  | S N)r0   	__enter__r1   r2   r   r   r   rD      s   

z"AzurePipelinesCredential.__enter__c                 G   s   | j j|  | jj|  d S rC   )r0   __exit__r1   )r2   argsr   r   r   rF      s   z!AzurePipelinesCredential.__exit__c                 C   s   |    dS )z)Close the credential's transport session.N)rF   rE   r   r   r   close   s   zAzurePipelinesCredential.close)r   N)__name__
__module____qualname____doc__strr   r3   r   boolr   r8   r   r   r:   r/   rD   rF   rH   r   r   r   r   r&   .   sH    

 !r&   )r   typingr   r   Zazure.core.exceptionsr   Zazure.core.credentialsr   r   r   Zazure.core.restr   r	   Zclient_assertionr    r   	_internalr   Z_internal.pipeliner   r   r   r$   rM   r    r%   r&   r   r   r   r   <module>   s   
