o
    i;                     @   s   d dl Z zd dlmZ W n ey   d dlmZ Y nw d dlZeeZdZdZ	dZ
dZeee	degZeg dZg dZd	ZG d
d deZG dd deZdd Zdd Zdd ZdS )    N)urlparselogin.microsoftonline.uslogin.chinacloudapi.cnlogin.microsoftonline.comlogin-us.microsoftonline.com)r   zlogin.microsoft.comzlogin.windows.netzsts.windows.netr   z login.partner.microsoftonline.cnzlogin.microsoftonline.der   zlogin.usgovcloudapi.netr   z"https://login.sovcloud-identity.frz"https://login.sovcloud-identity.dez"https://login.sovcloud-identity.sg)zb2clogin.comzb2clogin.cnzb2clogin.uszb2clogin.dezciamlogin.comz.ciamlogin.comc                   @   s   e Zd Zdd Zdd ZdS )AuthorityBuilderc                 C   s   | d| _|d| _dS )zA helper to save caller from doing string concatenation.

        Usage is documented in :func:`application.ClientApplication.__init__`.
        /N)rstrip	_instancestrip_tenant)selfinstancetenant r   E/home/app/Keep/.python/lib/python3.10/site-packages/msal/authority.py__init__8   s   zAuthorityBuilder.__init__c                 C   s   d | j| jS )Nzhttps://{}/{})formatr
   r   r   r   r   r   __str__@   s   zAuthorityBuilder.__str__N)__name__
__module____qualname__r   r   r   r   r   r   r   7   s    r   c                   @   sJ   e Zd ZdZeg Z			dddZdd Zdd	 Zdd
dZ	dd Z
dS )	AuthorityzThis class represents an (already-validated) authority.

    Once constructed, it contains members named "*_endpoint" for this instance.
    TODO: It will also cache the previously-validated authority instances.
    TNc           
      C   s   || _ || _|rtd| | |}n| |||}zt|| j }W n ty=   |r2dj|dnd|d }t|w |	d| _
|d | _|d | _|	d	| _t| j\}	}	| _| jrn|  sptd
j| j
|ddS dS )a`  Creates an authority instance, and also validates it.

        :param validate_authority:
            The Authority validation process actually checks two parts:
            instance (a.k.a. host) and tenant. We always do a tenant discovery.
            This parameter only controls whether an instance discovery will be
            performed.
        z$Initializing with OIDC authority: %szUnable to get OIDC authority configuration for {url} because its OIDC Discovery endpoint is unavailable at {url}/.well-known/openid-configuration )urlzUnable to get authority configuration for {}. Authority would typically be in a format of https://login.microsoftonline.com/your_tenant or https://tenant_name.ciamlogin.com or https://tenant_name.b2clogin.com/tenant.onmicrosoft.com/policy. z> Also please double check your tenant name or GUID is correct.Zissuerauthorization_endpointtoken_endpointdevice_authorization_endpointav  The issuer '{iss}' does not match the authority '{auth}' or a known pattern. When using the 'oidc_authority' parameter in ClientApplication, the authority will be validated against the issuer from {auth}/.well-known/openid-configuration .If using a known Entra authority (e.g. login.microsoftonline.com) the 'authority' parameter should be used instead of 'oidc_authority'. )ZissauthN)_http_client_oidc_authority_urlloggerdebug_initialize_oidc_authority_initialize_entra_authoritytenant_discovery
ValueErrorr   get_issuerr   r   r   canonicalizer   has_valid_issuer)
r   authority_urlhttp_clientvalidate_authorityinstance_discoveryoidc_authority_urltenant_discovery_endpointZopenid_configerror_message_r   r   r   r   L   sJ   

zAuthority.__init__c                 C   s2   t |\}| _}| dk| _d| _d| _|d S )NadfsTz!/.well-known/openid-configuration)r)   r   loweris_adfs_is_b2c_is_known_to_developer)r   r/   	authorityr   r   r   r   r#      s
   z$Authority._initialize_oidc_authorityc                    sF  t |tr	t|}t|\} _} jt}| dko|  _|j	
d}t fddtD p@t|dko@|d  d _ jpJ jpJ|  _ jtv }|dv rZd	tn|}	|	r|s jstd
 j|j	 j|	}
|
ddkr}td| |
d }|S |jdj|rt|j	dkr|n|j	 jrdnddd }|S )Nr3   r   c                 3   s     | ]} j d | V  qdS ).N)r   endswith).0dr   r   r   	<genexpr>   s    
z8Authority._initialize_entra_authority.<locals>.<genexpr>      Zb2c_)NTz$https://{}/common/discovery/instancez"https://{}{}/oauth2/v2.0/authorizeerrorZinvalid_instancezinvalid_instance: The authority you provided, %s, is not whitelisted. If it is indeed your legit customized domain name, you can turn off this check by passing in instance_discovery=Falser0   z2{prefix}{version}/.well-known/openid-configuration    z/v2.0)prefixversion)path)
isinstancer   strr)   r   r:   _CIAM_DOMAIN_SUFFIXr4   r5   rE   splitanyWELL_KNOWN_B2C_HOSTSlen
startswithr6   r7   WELL_KNOWN_AUTHORITY_HOSTSr   
WORLD_WIDE_instance_discoveryr   r'   r&   _replacegeturl)r   r+   r-   r.   r8   r   Zis_ciampartsZis_known_to_microsoftinstance_discovery_endpointpayloadr0   r   r   r   r$      sb   

	z%Authority._initialize_entra_authorityc                 C   sf   | j | jjvr1|p| jjdj| j |dd|dd}|jdkr)|  t	|j
S | jj| j  i S )Nz<https://{netloc}/common/userrealm/{username}?api-version=1.0)netlocusernamezapplication/json)Acceptzclient-request-id)headersi  )r   	__class__%_domains_without_user_realm_discoveryr   r'   r   status_coderaise_for_statusjsonloadstextadd)r   rW   Zcorrelation_idresponserespr   r   r   user_realm_discovery   s   

zAuthority.user_realm_discoveryc                    s   | j r| jsdS | j d| jdkrdS t| j }t| j}|jr(|j nd  s.dS  tv r4dS  d}|dkrc |d d }d d| vrc|tv rSdS |jr[|j nd}||krcdS |j|jkrq|j	|j	krqdS t
 fd	d
tD r~dS dS )a]  
        Returns True if the issuer from OIDC discovery is valid for this authority.

        An issuer is valid if one of the following is true:
        - It exactly matches the authority URL (with/without trailing slash)
        - It has the same scheme and host as the authority (path can be different)
        - The issuer host is a well-known Microsoft authority host
        - The issuer host is a regional variant of a well-known host (e.g., westus2.login.microsoft.com)
        - For CIAM, hosts that end with well-known B2C hosts (e.g., tenant.b2clogin.com) are accepted as valid issuers
        Fr   TNr9   r   rA   rB   c                 3   s    | ]}  |V  qd S )N)r:   )r;   hZissuer_hostr   r   r=     s    z-Authority.has_valid_issuer.<locals>.<genexpr>)r(   r    r	   r   hostnamer4   TRUSTED_ISSUER_HOSTSfindschemerV   rJ   rK   )r   Zissuer_parsedZauthority_parsedZ	dot_indexZpotential_baseZauthority_hostr   rf   r   r*      s4   


zAuthority.has_valid_issuer)TNN)NN)r   r   r   __doc__setr[   r   r#   r$   rd   r*   r   r   r   r   r   D   s    
9	
1r   c                 C   s   t | }|jdkrP|jrP|jd}t|dkr |d r |d nd }|jtr>|r,|nd|j	tdd }||j|fS t|dkrP|d rP||j|d fS t
d|  )Nhttpsr   r?   rA   z{}.onmicrosoft.comr   a  Your given address (%s) should consist of an https url with hostname and a minimum of one segment in a path: e.g. https://login.microsoftonline.com/{tenant} or https://{tenant_name}.ciamlogin.com/{tenant} or https://{tenant_name}.b2clogin.com/{tenant_name}.onmicrosoft.com/policy)r   rj   rg   rE   rI   rL   r:   rH   r   rsplitr&   )Zauthority_or_auth_endpointr8   rS   Z
first_partr   r   r   r   r)     s     r)   c                 K   s(   |j |fd| ddi|}t|jS )Nparamsz1.0)r   zapi-version)r'   r^   r_   r`   )r   r,   rT   kwargsrc   r   r   r   rP     s   rP   c                 K   st   |j | fi |}|jdkrt|jS d|j  krdk r,n ntd| |j|j|  td|j|jf )N   i  i  z7OIDC Discovery failed on {}. HTTP status: {}, Error: {}z)Unable to complete OIDC Discovery: %d, %s)	r'   r\   r^   r_   r`   r&   r   r]   RuntimeError)r0   r,   rp   rc   r   r   r   r%   $  s   
r%   )r^   urllib.parser   ImportErrorlogging	getLoggerr   r!   ZAZURE_US_GOVERNMENTZAZURE_CHINAZAZURE_PUBLICrO   rl   rN   	frozensetrh   rK   rH   objectr   r   r)   rP   r%   r   r   r   r   <module>   s6    
	 C