a
    ø£BeÇh  ã                   @  s\  d Z 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 ddlmZ ddlmZmZmZ ddlmZmZmZ ddlmZmZmZmZmZ dd	lmZ dd
lm Z  ddl!m"Z"m#Z# ddl$m%Z% erüddl&m'Z'm(Z( ddl)m*Z* e +d¡Z,eG dd„ dƒƒZ-dddœdd„Z.G dd„ deƒZ/G dd„ de/ƒZ0G dd„ de0ƒZ1dS )z®Identity Provider interface

This defines the _authentication_ layer of Jupyter Server,
to be used in combination with Authorizer for _authorization_.

.. versionadded:: 2.0
é    )ÚannotationsN)ÚasdictÚ	dataclass)ÚMorsel)ÚTYPE_CHECKINGÚAnyÚ	Awaitable)ÚescapeÚhttputilÚweb)ÚBoolÚDictÚTypeÚUnicodeÚdefault)ÚLoggingConfigurable)Ú_i18né   )Úpasswd_checkÚset_password)Úget_anonymous_username)ÚAuthenticatedHandlerÚJupyterHandler)Ú	ServerAppz[^A-Za-z0-9]c                   @  sf   e Zd ZU dZded< dZded< dZded< dZded	< dZded
< dZ	ded< dd„ Z
dd„ ZdS )ÚUserziObject representing a User

    This or a subclass should be returned from IdentityProvider.get_user
    ÚstrÚusernameÚ ÚnameÚdisplay_nameNú
str | NoneÚinitialsÚ
avatar_urlÚcolorc                 C  s   |   ¡  d S ©N)Úfill_defaults©Úself© r(   ú_/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/jupyter_server/auth/identity.pyÚ__post_init__>   s    zUser.__post_init__c                 C  s8   | j sd| › �}t|ƒ‚| js&| j | _| js4| j| _dS )zÑFill out default fields in the identity model

        - Ensures all values are defined
        - Fills out derivative values for name fields fields
        - Fills out null values for optional fields
        z!user.username must not be empty: N)r   Ú
ValueErrorr   r   )r'   Úmsgr(   r(   r)   r%   A   s    	
zUser.fill_defaults)Ú__name__Ú
__module__Ú__qualname__Ú__doc__Ú__annotations__r   r   r!   r"   r#   r*   r%   r(   r(   r(   r)   r   &   s   
r   r   )Úgot_userÚreturnc                 C  s®   t | tƒrt| d�S t | tƒr˜i }d| vr>d| v r>| d |d< tjD ]}|| v rD| | ||< qDztf i |¤ŽW S  ty”   d| › �}t|ƒd‚Y qª0 nd| › �}t|ƒ‚dS )a  Backward-compatibility for LoginHandler.get_user

    Prior to 2.0, LoginHandler.get_user could return anything truthy.

    Typically, this was either a simple string username,
    or a simple dict.

    Make some effort to allow common patterns to keep working.
    )r   r   r   zUnrecognized user: N)Ú
isinstancer   r   ÚdictÚ__dataclass_fields__Ú	TypeErrorr+   )r2   ÚkwargsÚfieldr,   r(   r(   r)   Ú_backward_compat_userU   s     






r:   c                   @  s6  e Zd ZU dZeddedƒd�Zded< ededƒd�Z	e
d	dded
ƒd�Zded< ededƒd�Zededƒd�jdd�Zded< edejdedƒd�Zedejdedƒd�ZdZedƒdd„ ƒZe
dƒZded< dddœd d!„Zdd"dœd#d$„Zd%d&d'œd(d)„Zd*d+œd,d-„Zd%d.d'œd/d0„Zd.d"d1œd2d3„Zd4d.dœd5d6„Zd4d%d7d8œd9d:„Zd]d4d.d.d<d7d=œd>d?„Z d4d7dœd@dA„Z!dddœdBdC„Z"e# $dDe#j%¡Z&dd<dœdEdF„Z'dd"dœdGdH„Z(dd%dœdIdJ„Z)d4dKdœdLdM„Z*d4dKdœdNdO„Z+d^dPdQd7dRœdSdT„Z,dd"dœdUdV„Z-e.dWdX„ ƒZ/e.dYdZ„ ƒZ0e.d[d\„ ƒZ1d	S )_ÚIdentityProvideraC  
    Interface for providing identity management and authentication.

    Two principle methods:

    - :meth:`~jupyter_server.auth.IdentityProvider.get_user` returns a :class:`~.User` object
      for successful authentication, or None for no-identity-found.
    - :meth:`~jupyter_server.auth.IdentityProvider.identity_model` turns a :class:`~jupyter_server.auth.User` into a JSONable dict.
      The default is to use :py:meth:`dataclasses.asdict`,
      and usually shouldn't need override.

    Additional methods can customize authentication.

    .. versionadded:: 2.0
    r   TzJName of the cookie to set for persisting login. Default: username-${Host}.©ÚconfigÚhelpzstr | UnicodeÚcookie_nameziExtra keyword arguments to pass to `set_secure_cookie`. See tornado's set_secure_cookie docs for details.Nz–Specify whether login cookie should have the `secure` property (HTTPS-only).Only needed when protocol-detection gives the wrong answer due to proxies.)Ú
allow_noner=   r>   zbool | BoolÚsecure_cookieziExtra keyword arguments to pass to `get_secure_cookie`. See tornado's get_secure_cookie docs for details.z<generated>aÔ  Token used for authenticating first-time connections to the server.

        The token can be read from the file referenced by JUPYTER_TOKEN_FILE or set directly
        with the JUPYTER_TOKEN environment variable.

        When no password is enabled,
        the default is to generate a new, random token.

        Setting to an empty string disables authentication altogether, which is NOT RECOMMENDED.

        Prior to 2.0: configured as ServerApp.token
        )r>   )r=   Útokenz*jupyter_server.auth.login.LoginFormHandlerz'The login handler class to use, if any.)Údefault_valueÚklassr=   r>   z(jupyter_server.auth.logout.LogoutHandlerz The logout handler class to use.Fc                 C  s�   t  d¡rd| _t jd S t  d¡r`d| _tt jd ƒ�}| ¡ W  d   ƒ S 1 sV0    Y  | jspd| _dS d| _t t  	d¡¡ 
d¡S d S )NZJUPYTER_TOKENFZJUPYTER_TOKEN_FILEr   Té   Úascii)ÚosÚgetenvÚtoken_generatedÚenvironÚopenÚreadÚ
need_tokenÚbinasciiÚhexlifyÚurandomÚdecode)r'   Z
token_filer(   r(   r)   Ú_token_defaultÅ   s    


&zIdentityProvider._token_defaultrM   r   z$User | None | Awaitable[User | None]©Úhandlerr3   c                 C  s
   |   |¡S )zèGet the authenticated user for a request

        Must return a :class:`jupyter_server.auth.User`,
        though it may be a subclass.

        Return None if the request is not authenticated.

        _may_ be a coroutine
        )Ú	_get_user©r'   rT   r(   r(   r)   Úget_userØ   s    
zIdentityProvider.get_userúUser | Nonec           	      Ã  sè   t |ddƒr|jS |  |¡}t|tƒr0|I dH }|}|  |¡}t|tƒrR|I dH }|}|p\|}|durˆ|durˆ||kr‚|  ||¡ d|_|du rä|  |¡}| 	|¡}|durÈ| j
 d|› �¡ |  |¡ | jsä|  |¡}|  ||¡ |S )úGet the user.Ú_jupyter_current_userNTz&Clearing invalid/expired login cookie )ÚgetattrrZ   Úget_user_tokenr4   r   Úget_user_cookieÚset_login_cookieÚ_token_authenticatedÚget_cookie_nameZ
get_cookieÚlogÚwarningÚclear_login_cookieÚauth_enabledÚgenerate_anonymous_user)	r'   rT   Z_token_userZ
token_userZ_cookie_userZcookie_userÚuserr?   Úcookier(   r(   r)   rU   ç   s2    









zIdentityProvider._get_userr   r5   )rf   r3   c                 C  s   t |ƒS )z"Return a User as an Identity model)r   )r'   rf   r(   r(   r)   Úidentity_model  s    zIdentityProvider.identity_modelÚlist©r3   c                 C  s4   g }| j r| d| jf¡ | jr0| d| jf¡ |S )zwReturn list of additional handlers for this identity provider

        For example, an OAuth callback handler.
        z/loginz/logout)Úlogin_availableÚappendÚlogin_handler_classÚlogout_availableÚlogout_handler_class)r'   Úhandlersr(   r(   r)   Úget_handlers  s    zIdentityProvider.get_handlersr   c                 C  s$   t  |j|j|j|j|jdœ¡}|S )z¿Serialize a user to a string for storage in a cookie

        If overriding in a subclass, make sure to define user_from_cookie as well.

        Default is just the user's username.
        )r   r   r   r!   r#   )ÚjsonÚdumpsr   r   r   r!   r#   )r'   rf   rg   r(   r(   r)   Úuser_to_cookie%  s    ûÿ	zIdentityProvider.user_to_cookie)Úcookie_valuer3   c                 C  s0   t  |¡}t|d |d |d |d d|d ƒS )zInverse of user_to_cookier   r   r   r!   Nr#   )rr   Úloadsr   )r'   ru   rf   r(   r(   r)   Úuser_from_cookie8  s    
úz!IdentityProvider.user_from_cookier   c                 C  s&   | j r| j S t dd|jj› �¡S dS )zõReturn the login cookie name

        Uses IdentityProvider.cookie_name, if defined.
        Default is to generate a string taking host into account to avoid
        collisions for multiple servers on one hostname with different ports.
        ú-z	username-N)r?   Ú_non_alphanumÚsubÚrequestÚhostrV   r(   r(   r)   r`   D  s    z IdentityProvider.get_cookie_nameÚNone)rT   rf   r3   c                 C  s|   i }|  | j¡ | dd¡ | j}|du r6|jjdk}|rF| dd¡ | d|j¡ |  |¡}|j||  	|¡fi |¤Ž dS )z9Call this on handlers to set the login cookie for successÚhttponlyTNÚhttpsÚsecureÚpath)
ÚupdateÚcookie_optionsÚ
setdefaultrA   r{   ÚprotocolÚbase_urlr`   Zset_secure_cookiert   )r'   rT   rf   rƒ   rA   r?   r(   r(   r)   r^   P  s    
z!IdentityProvider.set_login_cookieú/r    )rT   r   r�   Údomainr3   c                 C  sr   t  |¡}tjjtjjd�tjdd� }tƒ }| |dd¡ t	 
|¡|d< ||d< |r^||d< | d	| ¡ ¡ d
S )a™  Deletes the cookie with the given name.

        Tornado's cookie handling currently (Jan 2018) stores cookies in a dict
        keyed by name, so it can only modify one cookie with a given name per
        response. The browser can store multiple cookies with the same name
        but different domains and/or paths. This method lets us clear multiple
        cookies with the same name.

        Due to limitations of the cookie protocol, you must pass the same
        path and domain to clear a cookie as were used when that cookie
        was set (but there is no way to find out on the server side
        which values were used for a given cookie).
        )Útzim  )Údaysr   z""Úexpiresr�   rˆ   z
Set-CookieN)r	   Z
native_strÚdatetimeÚnowÚtimezoneÚutcÚ	timedeltar   Úsetr
   Zformat_timestampÚ
add_headerÚOutputString)r'   rT   r   r�   rˆ   r‹   Úmorselr(   r(   r)   Ú_force_clear_cookie`  s    
z$IdentityProvider._force_clear_cookiec                 C  sR   i }|  | j¡ | d|j¡}|  |¡}|j||d� |rN|dkrN|  ||¡ dS )z<Clear the login cookie, effectively logging out the session.r�   )r�   r‡   N)r‚   rƒ   r„   r†   r`   Zclear_cookier•   )r'   rT   rƒ   r�   r?   r(   r(   r)   rc   {  s    
z#IdentityProvider.clear_login_cookiec              
   C  sŠ   |j |  |¡fi | j¤Ž}|s"dS | ¡ }z|  |¡W S  ty„ } z6| jjd|› �dd� | j d|› �¡ W Y d}~dS d}~0 0 dS )z[Get user from a cookie

        Calls user_from_cookie to deserialize cookie value
        Nz)Error unpacking user from cookie: cookie=T)Úexc_infoz"Error unpacking user from cookie: )	Zget_secure_cookier`   Úget_secure_cookie_kwargsrQ   rw   Ú	Exceptionra   ÚdebugÚerror)r'   rT   Z_user_cookieZuser_cookieÚer(   r(   r)   r]   ‰  s    ÿþz IdentityProvider.get_user_cookiez(token|bearer)\s+(.+)c                 C  s:   |  dd¡}|s6| j |jj dd¡¡}|r6| d¡}|S )z›Get the user token from a request

        Default:

        - in URL parameters: ?token=<token>
        - in header: Authorization: token <token>
        rB   r   ÚAuthorizationé   )Úget_argumentÚauth_header_patÚmatchr{   ÚheadersÚgetÚgroup)r'   rT   Ú
user_tokenÚmr(   r(   r)   Ú	get_token   s    
zIdentityProvider.get_tokenc                 Ã  s~   |j }|sdS |  |¡}d}||kr:| j d|jj¡ d}|rv|  |¡}t|tƒr\|I dH }|}|du rr|  	|¡}|S dS dS )z–Identify the user based on a token in the URL or Authorization header

        Returns:
        - uuid if authenticated
        - None if not
        NFz-Accepting token-authenticated request from %sT)
rB   r¦   ra   r™   r{   Z	remote_ipr]   r4   r   re   )r'   rT   rB   r¤   ÚauthenticatedÚ_userrf   r(   r(   r)   r\   °  s(    
þ



zIdentityProvider.get_user_tokenc                 C  sT   t  ¡ j}tƒ }d|› � }}d|d › �}d}|j d|› �¡ t||||d|ƒS )z…Generate a random anonymous user.

        For use when a single shared token is used,
        but does not identify a user.
        z
Anonymous ÚAr   Nz5Generating new user for token-authenticated request: )ÚuuidÚuuid4Úhexr   ra   r™   r   )r'   rT   Zuser_idÚmoonr   r   r!   r#   r(   r(   r)   re   Ó  s    
z(IdentityProvider.generate_anonymous_userÚboolc                 C  s   |   |¡ S )a3  Should the Handler check for CORS origin validation?

        Origin check should be skipped for token-authenticated requests.

        Returns:
        - True, if Handler must check for valid CORS origin.
        - False, if Handler should skip origin check since requests are token-authenticated.
        )Úis_token_authenticatedrV   r(   r(   r)   Úshould_check_originá  s    	z$IdentityProvider.should_check_originc                 C  s   |j  t|ddƒS )zÿReturns True if handler has been token authenticated. Otherwise, False.

        Login with a token is used to signal certain things, such as:

        - permit access to REST API
        - xsrf protection
        - skip origin-checks for scripts
        r_   F)Zcurrent_userr[   rV   r(   r(   r)   r¯   ì  s    
z'IdentityProvider.is_token_authenticatedr   údict | None©ÚappÚssl_optionsr3   c                 C  sT   |j s>d}|du r$|j |› d�¡ | jsP|j |› d�¡ n| jsP|j d¡ dS )z~Check the application's security.

        Show messages, or abort if necessary, based on the security configuration.
        z<WARNING: The Jupyter server is listening on all IP addressesNz3 and not using encryption. This is not recommended.zK and not using authentication. This is highly insecure and not recommended.z`All authentication is disabled.  Anyone who can connect to this server will be able to run code.)Úipra   rb   rd   )r'   r³   r´   rb   r(   r(   r)   Úvalidate_securityù  s    	ÿÿz"IdentityProvider.validate_securityc                 C  sL   |j ddd�}d}| js.| j d¡ |  |¡S | jrH| j|krH|  |¡S |S )ú_Process login form data

        Return authenticated User if successful, None if not.
        Úpasswordr   ©r   Nú6Accepting anonymous login because auth fully disabled!)rž   rd   ra   rb   re   rB   Zuser_for_token)r'   rT   Útyped_passwordrf   r(   r(   r)   Úprocess_login_form  s    

z#IdentityProvider.process_login_formc                 C  s   dS )zÓIs authentication enabled?

        Should always be True, but may be False in rare, insecure cases
        where requests with no auth are allowed.

        Previously: LoginHandler.get_login_available
        Tr(   r&   r(   r(   r)   rd   !  s    	zIdentityProvider.auth_enabledc                 C  s   | j S ©z\Whether a LoginHandler is needed - and therefore whether the login page should be displayed.©rd   r&   r(   r(   r)   rk   ,  s    z IdentityProvider.login_availablec                 C  s   dS )z"Whether a LogoutHandler is needed.Tr(   r&   r(   r(   r)   rn   1  s    z!IdentityProvider.logout_available)r‡   N)N)2r-   r.   r/   r0   r   r   r?   r1   r   rƒ   r   rA   r—   ÚtagrB   r   r   ZRequestHandlerrm   ro   rI   r   rR   rM   rW   rU   rh   rq   rt   rw   r`   r^   r•   rc   r]   ÚreÚcompileÚ
IGNORECASErŸ   r¦   r\   re   r°   r¯   r¶   r¼   Úpropertyrd   rk   rn   r(   r(   r(   r)   r;   r   sš   
ýÿþÿü
ÿþÿþðüü
- ÿ# ý


r;   c                      s®   e Zd ZdZeddedƒd�Zeddedƒd�Zeddedƒd�Z	e
d	ƒd
d„ ƒZeddœdd„ƒZeddœdd„ƒZdd„ Zdddœdd„Zd ddddœ‡ fdd„Z‡  ZS )!ÚPasswordIdentityProviderzA password identity provider.r   Ta  
            Hashed password to use for web authentication.

            To generate, type in a python/IPython shell:

                from jupyter_server.auth import passwd; passwd()

            The string should be of the form type:salt:hashed-password.
            r<   Fao  
            Forces users to use a password for the Jupyter server.
            This is useful in a multi user environment, for instance when
            everybody in the LAN can access each other's machine through ssh.

            In such a case, serving on localhost is not secure since
            any user can connect to the Jupyter server via ssh.

            a�  
            Allow password to be changed at login for the Jupyter server.

            While logging in with a token, the Jupyter server UI will give the opportunity to
            the user to enter a new password at the same time that will replace
            the token login mechanism.

            This can be set to False to prevent changing password from the UI/API.
            rM   c                 C  s   t | jƒ S r$   )r®   Úhashed_passwordr&   r(   r(   r)   Ú_need_token_defaultj  s    z,PasswordIdentityProvider._need_token_defaultr®   rj   c                 C  s   | j S r½   r¾   r&   r(   r(   r)   rk   n  s    z(PasswordIdentityProvider.login_availablec                 C  s   t | jp| jƒS )z"Return whether any auth is enabled)r®   rÅ   rB   r&   r(   r(   r)   rd   s  s    z%PasswordIdentityProvider.auth_enabledc                 C  s   t | j|ƒS )z1Check password against our stored hashed password)r   rÅ   )r'   r¸   r(   r(   r)   r   x  s    z%PasswordIdentityProvider.passwd_checkr   rX   rS   c                 C  s¼   |j ddd�}|j ddd�}d}| js<| j d¡ |  |¡S |  |¡rT|sT|  |¡S | jr¸| j|kr¸|  |¡}|r¸| jr¸|j 	dd¡}t
j |d¡}t||d	�| _| j td
|› �ƒ¡ |S )r·   r¸   r   r¹   Únew_passwordNrº   Ú
config_dirzjupyter_server_config.json)Úconfig_filezWrote hashed password to )rž   rd   ra   rb   re   r   rB   Úallow_password_changeÚsettingsr¢   rG   r�   Újoinr   rÅ   Úinfor   )r'   rT   r»   rÇ   rf   rÈ   rÉ   r(   r(   r)   r¼   |  s     



z+PasswordIdentityProvider.process_login_formNr   r±   r}   r²   c                   sX   t ƒ  ||¡ | jrT| jsT| j tdƒ¡ | j tdƒ¡ | j tdƒ¡ t d¡ dS )zHandle security validation.ú>Jupyter servers are configured to only be run with a password.ú1Hint: run the following command to set a passwordú)	$ python -m jupyter_server.auth passwordr   N)	Úsuperr¶   Úpassword_requiredrÅ   ra   Úcriticalr   ÚsysÚexit©r'   r³   r´   ©Ú	__class__r(   r)   r¶   ”  s    ÿz*PasswordIdentityProvider.validate_security)N)r-   r.   r/   r0   r   r   rÅ   r   rÒ   rÊ   r   rÆ   rÃ   rk   rd   r   r¼   r¶   Ú__classcell__r(   r(   r×   r)   rÄ   7  s@   ÿýÿýÿý
 ýrÄ   c                   @  s’   e Zd ZdZeƒ Zedƒdd„ ƒZedƒdd„ ƒZe	dd	„ ƒZ
d
ddœdd„Ze	dd„ ƒZdddœdd„Zdddœdd„Zdddddœdd„ZdS )ÚLegacyIdentityProviderz¢Legacy IdentityProvider for use with custom LoginHandlers

    Login configuration has moved from LoginHandler to IdentityProvider
    in Jupyter Server 2.0.
    rË   c                 C  s   | j | jdœS )N)rB   r¸   )rB   rÅ   r&   r(   r(   r)   Ú_default_settings®  s    þz(LegacyIdentityProvider._default_settingsrm   c                 C  s   ddl m} |S )Nr   )ÚLegacyLoginHandler)ÚloginrÜ   )r'   rÜ   r(   r(   r)   Ú_default_login_handler_classµ  s    z3LegacyIdentityProvider._default_login_handler_classc                 C  s   | j S r$   )rk   r&   r(   r(   r)   rd   »  s    z#LegacyIdentityProvider.auth_enabledr   rX   rS   c                 C  s    | j  |¡}|du rdS t|ƒS )rY   N)rm   rW   r:   )r'   rT   rf   r(   r(   r)   rW   ¿  s    zLegacyIdentityProvider.get_userc                 C  s   | j  | j¡S r$   )rm   Zget_login_availablerË   r&   r(   r(   r)   rk   Æ  s    ÿz&LegacyIdentityProvider.login_availabler   r®   c                 C  s   | j  |¡S )zWhether we should check origin.)rm   r°   rV   r(   r(   r)   r°   Ì  s    z*LegacyIdentityProvider.should_check_originc                 C  s   | j  |¡S )z#Whether we are token authenticated.)rm   r¯   rV   r(   r(   r)   r¯   Ð  s    z-LegacyIdentityProvider.is_token_authenticatedNr   r±   r}   r²   c                 C  sT   | j rF| jsF| j tdƒ¡ | j tdƒ¡ | j tdƒ¡ t d¡ | j ||¡S )zValidate security.rÎ   rÏ   rÐ   r   )	rÒ   rÅ   ra   rÓ   r   rÔ   rÕ   rm   r¶   rÖ   r(   r(   r)   r¶   Ô  s    ÿ
ÿz(LegacyIdentityProvider.validate_security)N)r-   r.   r/   r0   r   rË   r   rÛ   rÞ   rÃ   rd   rW   rk   r°   r¯   r¶   r(   r(   r(   r)   rÚ   ¤  s   



 ýrÚ   )2r0   Ú
__future__r   rN   rŒ   rr   rG   rÀ   rÔ   rª   Údataclassesr   r   Úhttp.cookiesr   Útypingr   r   r   Útornador	   r
   r   Z	traitletsr   r   r   r   r   Ztraitlets.configr   Zjupyter_server.transutilsr   Úsecurityr   r   Úutilsr   Zjupyter_server.base.handlersr   r   Zjupyter_server.serverappr   rÁ   ry   r   r:   r;   rÄ   rÚ   r(   r(   r(   r)   Ú<module>   s<   
.   Hm