a
    ø£Be¹£  ã                   @  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
Z
ddlZddlZddlmZ ddlmZ ddlmZmZmZmZmZ ddlmZ ddl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&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l0m1Z1 ddl2m3Z3m4Z4m5Z5m6Z6m7Z7m8Z8 e�râddl9m:Z: ddl;m<Z< ddl=m>Z> ddl?m@Z@ ddlAmBZBmCZC ddlDmEZE ddlFmGZG ddlHmIZI ddlJmKZK ddlLmMZM daNdd „ ZOd!d"œd#d$„ZPG d%d&„ d&e!jQƒZRG d'd(„ d(eRƒZSG d)d*„ d*eSƒZTG d+d,„ d,eSƒZUG d-d.„ d.eSe!jVƒZWd/d/d0œd1d2„ZXe!jYZYG d3d4„ d4eSe!jVƒZZG d5d6„ d6eTƒZ[G d7d8„ d8e!jQƒZ\G d9d:„ d:eSƒZ]G d;d<„ d<eSƒZ^G d=d>„ d>e!jQƒZ_G d?d@„ d@eSƒZ`dAZadBe\fdCe[fdDe!jVfdEe`fgZbdS )Fz-Base Tornado handlers for the Jupyter server.é    )ÚannotationsN)Ú	responses)ÚLogger)ÚTYPE_CHECKINGÚAnyÚ	AwaitableÚSequenceÚcast)Úurlparse)ÚTemplateNotFound)Ú	is_hidden)ÚEventLogger)Úweb)Úapp_log)ÚApplication)ÚCallContext)Úget_sys_info)Úutcnow)Ú
authorized)Úcombine_translations)Úcsp_report_uri)Úensure_asyncÚfilefindÚ
url_escapeÚurl_is_absoluteÚurl_path_joinÚurldecode_unix_socket_path)ÚKernelSpecManager)ÚTerminalManager)ÚFuture)Ú
Authorizer)ÚIdentityProviderÚUser)Ú	ServerApp)ÚConfigManager)ÚContentsManager)ÚAsyncMappingKernelManager)ÚSessionManagerc                   C  s   t du rt tƒ ¡a t S )zGet sys info as json.N)Ú_sys_info_cacheÚjsonÚdumpsr   © r+   r+   ú_/home/yuhw/wc/wire-cell-python/wcpy/lib/python3.9/site-packages/jupyter_server/base/handlers.pyÚjson_sys_infoA   s    r-   r   ©Úreturnc                   C  s   t  ¡ rt  ¡ jS tS dS )zGet the application log.N)r   ZinitializedÚinstanceÚlogr   r+   r+   r+   r,   r1   I   s    
r1   c                   @  s  e Zd ZdZeddœdd„ƒZeddœdd„ƒZddœd	d
„Zeddœdd„ƒZd+dddddœdd„Z	ddœdd„Z
ddœdd„Zddœdd„Zeddœdd„ƒZeddœdd„ƒZeddœdd „ƒZeddœd!d"„ƒZeddœd#d$„ƒZed%dœd&d'„ƒZed(dœd)d*„ƒZdS ),ÚAuthenticatedHandlerz,A RequestHandler with an authenticated user.Ústrr.   c                 C  s   | j  dd¡S )NÚbase_urlú/©ÚsettingsÚget©Úselfr+   r+   r,   r4   T   s    zAuthenticatedHandler.base_urlc              
   C  sD   d| j  di ¡v r | j d d S d dd| j  dt| jtƒ¡ g¡S )z‰The default Content-Security-Policy header

        Can be overridden by defining Content-Security-Policy in settings['headers']
        úContent-Security-PolicyÚheadersú; zframe-ancestors 'self'zreport-uri r   )r7   r8   Újoinr   r4   r   r9   r+   r+   r,   Úcontent_security_policyX   s    ÿýÿz,AuthenticatedHandler.content_security_policyÚNonec                 C  s„   i }d|d< |  | j di ¡¡ | j|d< | ¡ D ]L\}}z|  ||¡ W q2 ty| } z| j d|¡ W Y d}~q2d}~0 0 q2dS )zSet the default headers.ZnosniffzX-Content-Type-Optionsr<   r;   z!Could not set default headers: %sN)	Úupdater7   r8   r?   ÚitemsÚ
set_headerÚ	Exceptionr1   Ú	exception)r:   r<   Úheader_nameÚvalueÚer+   r+   r,   Úset_default_headersk   s    
ÿz(AuthenticatedHandler.set_default_headersc                 C  s   t jdtdd� | j | ¡S )NúqJupyterHandler.login_handler is deprecated in 2.0,
            use JupyterHandler.identity_provider.
            é   ©Ú
stacklevel)ÚwarningsÚwarnÚDeprecationWarningÚidentity_providerZget_cookie_namer9   r+   r+   r,   Úcookie_name   s    ûz AuthenticatedHandler.cookie_namer5   Nú
str | None)ÚnameÚpathÚdomainr/   c                 C  s(   t jdtdd� | jj| |||d� dS )zForce a cookie clear.rJ   rK   rL   )rU   rV   N)rN   rO   rP   rQ   Z_force_clear_cookie)r:   rT   rU   rV   r+   r+   r,   Úforce_clear_cookieŠ   s    ûz'AuthenticatedHandler.force_clear_cookiec                 C  s    t jdtdd� | j | ¡ dS )zClear a login cookie.rJ   rK   rL   N)rN   rO   rP   rQ   Úclear_login_cookier9   r+   r+   r,   rX   •   s    ûz'AuthenticatedHandler.clear_login_cookiec                 C  s@   | j j}d|› d�}t| dƒr4tj|tdd� | jS t|ƒ‚dS )zGet the current user.z	Calling `z{.get_current_user()` directly is deprecated in jupyter-server 2.0. Use `self.current_user` instead (works in all versions).Ú_jupyter_current_userrK   rL   N)Ú	__class__Ú__name__ÚhasattrrN   rO   rP   rY   ÚRuntimeError)r:   ÚclsnameÚmsgr+   r+   r,   Úget_current_user    s    
ÿ
ýz%AuthenticatedHandler.get_current_userÚboolc                 C  s   | j jdkrdS | j | ¡ S )zÂAsk my login_handler if I should skip the origin_check

        For example: in the default LoginHandler, if a request is token-authenticated,
        origin checking should be skipped.
        ÚOPTIONST)ÚrequestÚmethodrQ   Zshould_check_originr9   r+   r+   r,   Úskip_check_origin²   s    z&AuthenticatedHandler.skip_check_originc                 C  s   | j  | ¡S )z'Have I been authenticated with a token?)rQ   Zis_token_authenticatedr9   r+   r+   r,   Útoken_authenticated½   s    z(AuthenticatedHandler.token_authenticatedc                 C  s   | j }|o|dkS )zIs a user currently logged in?Z	anonymous)Úcurrent_user)r:   Úuserr+   r+   r,   Ú	logged_inÂ   s    zAuthenticatedHandler.logged_inr   c                 C  s   t jdtdd� | jjS )z6Return the login handler for this application, if any.rJ   rK   rL   )rN   rO   rP   rQ   Zlogin_handler_classr9   r+   r+   r,   Úlogin_handlerÈ   s    ûz"AuthenticatedHandler.login_handlerc                 C  s   | j jS )z4Return the login token for this application, if any.)rQ   Útokenr9   r+   r+   r,   rk   Ô   s    zAuthenticatedHandler.tokenc                 C  s   | j jS )zªMay a user proceed to log in?

        This returns True if login capability is available, irrespective of
        whether the user is already logged in or not.

        )rQ   Úlogin_availabler9   r+   r+   r,   rl   Ù   s    z$AuthenticatedHandler.login_availabler    c                 C  sT   d| j vrBtjddd� ddlm} || j  dd ¡| jd�| j d< td	| j  d¡ƒS )
NÚ
authorizeraª  The Tornado web application does not have an 'authorizer' defined in its settings. In future releases of jupyter_server, this will be a required key for all subclasses of `JupyterHandler`. For an example, see the jupyter_server source code for how to add an authorizer to the tornado settings: https://github.com/jupyter-server/jupyter_server/blob/653740cbad7ce0c8a8752ce83e4d3c2c754b13cb/jupyter_server/serverapp.py#L234-L256rK   rL   r   )ÚAllowAllAuthorizerÚconfig)ro   rQ   r    )r7   rN   rO   Újupyter_server.authrn   r8   rQ   r	   )r:   rn   r+   r+   r,   rm   ã   s    
÷þzAuthenticatedHandler.authorizerr!   c                 C  sH   d| j vr>tjddd� ddlm} || j  dd ¡d�| j d< | j d S )	NrQ   a‘  The Tornado web application does not have an 'identity_provider' defined in its settings. In future releases of jupyter_server, this will be a required key for all subclasses of `JupyterHandler`. For an example, see the jupyter_server source code for how to add an identity provider to the tornado settings: https://github.com/jupyter-server/jupyter_server/blob/v2.0.0/jupyter_server/serverapp.py#L242rK   rL   r   ©r!   ro   )ro   )r7   rN   rO   rp   r!   r8   )r:   r!   r+   r+   r,   rQ   ú   s    
ø
ÿz&AuthenticatedHandler.identity_provider)r5   N)r[   Ú
__module__Ú__qualname__Ú__doc__Úpropertyr4   r?   rI   rR   rW   rX   r`   re   rf   ri   rj   rk   rl   rm   rQ   r+   r+   r+   r,   r2   Q   s4   
	r2   c                      sN  e Zd ZdZeddœdd„ƒZeddœdd„ƒZed	dœd
d„ƒZeddœdd„ƒZeddœdd„ƒZ	eddœdd„ƒZ
eddœdd„ƒZeddœdd„ƒZeddœdd„ƒZeddœdd„ƒZeddœdd„ƒZeddœd d!„ƒZed"dœd#d$„ƒZed%dœd&d'„ƒZed(dœd)d*„ƒZed+dœd,d-„ƒZed.dœd/d0„ƒZeddœd1d2„ƒZeddœd3d4„ƒZed5dœd6d7„ƒZd8dœ‡ fd9d:„Zd8dœd;d<„Zdd8d=œd>d?„Zd@dœdAdB„Zd]dd5dDœdEdF„Zd5dœdGdH„Zd8dœ‡ fdIdJ„Zd5dœdKdL„Z dMdœ‡ fdNdO„Z!dPdQ„ Z"dRdS„ Z#ed	dœdTdU„ƒZ$ddœdVdW„Z%dXdYd8dZœd[d\„Z&‡  Z'S )^ÚJupyterHandlerzwJupyter-specific extensions to authenticated handling

    Mostly property shortcuts to Jupyter-specific settings.
    zdict[str, Any] | Noner.   c                 C  s   | j  dd ¡S )Nro   r6   r9   r+   r+   r,   ro     s    zJupyterHandler.configr   c                 C  s   t ƒ S )z@use the Jupyter log by default, falling back on tornado's logger)r1   r9   r+   r+   r,   r1     s    zJupyterHandler.logúdict[str, Any]c                 C  s   | j  di ¡S )z2User-supplied values to supply to jinja templates.Újinja_template_varsr6   r9   r+   r+   r,   rx     s    z"JupyterHandler.jinja_template_varszServerApp | Nonec                 C  s
   | j d S )NÚ	serverapp©r7   r9   r+   r+   r,   ry   $  s    zJupyterHandler.serverappr3   c                 C  s   | j  dd¡S )z8The version hash to use for cache hints for static filesÚversion_hashÚ r6   r9   r+   r+   r,   r{   ,  s    zJupyterHandler.version_hashc                 C  s*   | j  dd¡}|rt|ƒr|S t| j|ƒS )NÚmathjax_urlr|   )r7   r8   r   r   r4   )r:   Úurlr+   r+   r,   r}   1  s    zJupyterHandler.mathjax_urlc                 C  s   | j  dd¡S )NÚmathjax_configzTeX-AMS-MML_HTMLorMML-full,Safer6   r9   r+   r+   r,   r   8  s    zJupyterHandler.mathjax_configc                 C  s   | j  dd¡S )NÚdefault_urlr|   r6   r9   r+   r+   r,   r€   <  s    zJupyterHandler.default_urlc                 C  s   | j  dd¡S )NZwebsocket_urlr|   r6   r9   r+   r+   r,   Úws_url@  s    zJupyterHandler.ws_urlc                 C  s&   | j  d| j dd¡¡ | j dd¡S )NzUsing contents: %sÚcontents_js_sourcezservices/contents)r1   Údebugr7   r8   r9   r+   r+   r,   r‚   D  s
    þz!JupyterHandler.contents_js_sourcer&   c                 C  s
   | j d S )NÚkernel_managerrz   r9   r+   r+   r,   r„   P  s    zJupyterHandler.kernel_managerr%   c                 C  s
   | j d S )NÚcontents_managerrz   r9   r+   r+   r,   r…   T  s    zJupyterHandler.contents_managerr'   c                 C  s
   | j d S )NÚsession_managerrz   r9   r+   r+   r,   r†   X  s    zJupyterHandler.session_managerr   c                 C  s
   | j d S )NÚterminal_managerrz   r9   r+   r+   r,   r‡   \  s    zJupyterHandler.terminal_managerr   c                 C  s
   | j d S )NÚkernel_spec_managerrz   r9   r+   r+   r,   rˆ   `  s    z"JupyterHandler.kernel_spec_managerr$   c                 C  s
   | j d S )NÚconfig_managerrz   r9   r+   r+   r,   r‰   d  s    zJupyterHandler.config_managerr   c                 C  s
   | j d S )NÚevent_loggerrz   r9   r+   r+   r,   rŠ   h  s    zJupyterHandler.event_loggerc                 C  s   | j  dd¡S )z"Normal Access-Control-Allow-OriginÚallow_originr|   r6   r9   r+   r+   r,   r‹   p  s    zJupyterHandler.allow_originc                 C  s   | j  dd¡S )z*Regular expression version of allow_originÚallow_origin_patNr6   r9   r+   r+   r,   rŒ   u  s    zJupyterHandler.allow_origin_patra   c                 C  s   | j  dd¡S )z/Whether to set Access-Control-Allow-CredentialsÚallow_credentialsFr6   r9   r+   r+   r,   r�   z  s    z JupyterHandler.allow_credentialsr@   c                   s   t ƒ  ¡  dS )zAdd CORS headers, if definedN)ÚsuperrI   r9   ©rZ   r+   r,   rI     s    z"JupyterHandler.set_default_headersc                 C  sŠ   | j r|  d| j ¡ n^| jrD|  ¡ }|rtt | j|¡rt|  d|¡ n0| jrtd| j di ¡vrt|  d| j	j
 dd¡¡ | jr†|  dd¡ dS )z¶Add CORS headers, if defined

        Now that current_user is async (jupyter-server 2.0),
        must be called at the end of prepare(), instead of in set_default_headers.
        úAccess-Control-Allow-Originr<   ÚOriginr|   z Access-Control-Allow-CredentialsÚtrueN)r‹   rC   rŒ   Ú
get_originÚreÚmatchrf   r7   r8   rc   r<   r�   ©r:   Úoriginr+   r+   r,   Úset_cors_headersƒ  s    ÿzJupyterHandler.set_cors_headers)Úfilenamer/   c                 C  s   t |ƒ}|  dd|› �¡ dS )zpSet Content-Disposition: attachment header

        As a method to ensure handling of filename encoding
        zContent-Dispositionzattachment; filename*=utf-8''N)r   rC   )r:   r™   Zescaped_filenamer+   r+   r,   Úset_attachment_header™  s
    þz$JupyterHandler.set_attachment_headerrS   c                 C  s0   d| j jv r| j j d¡}n| j j dd ¡}|S )Nr‘   zSec-Websocket-Origin)rc   r<   r8   r–   r+   r+   r,   r“   ¤  s    zJupyterHandler.get_originr|   )Úorigin_to_satisfy_tornador/   c                 C  s²   | j dks|  ¡ rdS | jj d¡}| jj d¡}|du sB|du rFdS | ¡ }t|ƒj}||krddS | j rv| j |k}n| jr�t	t
 | j|¡ƒ}nd}|s®| j d| jj||¡ |S )zÙCheck Origin for cross-site API requests, including websockets

        Copied from WebSocket with changes:

        - allow unspecified host/origin (e.g. scripts)
        - allow token-authenticated requests
        Ú*TÚHostr‘   NFz?Blocking Cross Origin API request for %s.  Origin: %s, Host: %s)r‹   re   rc   r<   r8   Úlowerr
   ÚnetlocrŒ   ra   r”   r•   r1   ÚwarningrU   )r:   r›   Úhostr—   Úorigin_hostÚallowr+   r+   r,   Úcheck_origin±  s.    
üzJupyterHandler.check_originc                 C  sÔ   | j dks|  ¡ rdS | jj d¡}| jj d¡}|sF| j d¡ dS |sZ| j d¡ dS t|ƒ}|j}||krtdS |j	› d|j› �}| j r˜| j |k}n| j
r²tt | j
|¡ƒ}nd}|sÐ| j d	| jj||¡ |S )
a[  Check Referer for cross-site requests.
        Disables requests to certain endpoints with
        external or missing Referer.
        If set, allow_origin settings are applied to the Referer
        to whitelist specific cross-origin sites.
        Used on GET for api endpoints and /files/
        to block cross-site inclusion (XSSI).
        rœ   Tr�   ÚRefererzBlocking request with no hostFz Blocking request with no refererz://z<Blocking Cross Origin request for %s.  Referer: %s, Host: %s)r‹   re   rc   r<   r8   r1   r    r
   rŸ   ÚschemerŒ   ra   r”   r•   rU   )r:   r¡   ÚrefererZreferer_urlZreferer_hostr—   r£   r+   r+   r,   Úcheck_refererà  s8    	üzJupyterHandler.check_refererc              
     s¨   t | dƒsdS | js"| j dd¡r&dS ztƒ  ¡ W S  tjy¢ } zV| jj	dv rŒ|  
¡ sŽ| jj d¡}|rxd|› d�}nd	}t d
|¡|‚n‚ W Y d}~n
d}~0 0 dS )z2Bypass xsrf cookie checks when token-authenticatedrY   NZdisable_check_xsrfF>   ÚHEADÚGETr¥   z#Blocking Cross Origin request from Ú.z$Blocking request from unknown originé“  )r\   rf   r7   r8   rŽ   Úcheck_xsrf_cookier   Ú	HTTPErrorrc   rd   r¨   r<   )r:   rH   r§   r_   r�   r+   r,   r­     s    
z JupyterHandler.check_xsrf_cookiec                 C  sÔ   | j  dd¡rdS t d| jj¡}|dus.J ‚| d¡}| d¡rX| d¡rX|dd	… }t	|ƒ}| d
¡r|t
j |¡r|d}n<zt |¡}W n& ty°   || j  ddg¡v }Y n0 |j}|sÐ| j d|| jj¡ |S )z‚Check the host header if remote access disallowed.

        Returns True if the request should continue, False otherwise.
        Zallow_remote_accessFTz^(.*?)(:\d+)?$Né   ú[ú]éÿÿÿÿr5   Zlocal_hostnamesÚ	localhostz˜Blocking request with non-local 'Host' %s (%s). If the server should be accessible at that name, set ServerApp.allow_remote_access to disable the check.)r7   r8   r”   r•   rc   r¡   ÚgroupÚ
startswithÚendswithr   ÚosrU   ÚexistsÚ	ipaddressÚ
ip_addressÚ
ValueErrorÚis_loopbackr1   r    )r:   r•   r¡   Ú
check_hostr£   Úaddrr+   r+   r,   r½   &  s,    
ù	zJupyterHandler.check_hostzAwaitable[None] | Nonec                 ƒ  sÜ   t  t j| ¡ |  ¡ s,d | _| _t d¡‚ddlm	} t
 | j¡}|dusPJ ‚d}t| jƒ|u r†|jtkr†t dt¡ t|  ¡ ƒ}n$| j | ¡}t|tƒr¦|I dH }|}| | _| _|  ¡  | jjdvrÒ|  ¡  tƒ  ¡ S )zPrepare a response.Nr¬   r   rq   znOverriding JupyterHandler.get_current_user is deprecated in jupyter-server 2.0. Use an IdentityProvider class.>   r©   rª   rb   )r   ÚsetZJUPYTER_HANDLERr½   rg   rY   r   r®   rp   r!   ÚinspectÚ	getmoduler`   ÚtyperQ   r[   rN   rO   rP   r"   Zget_userÚ
isinstancer   r˜   rc   rd   r­   rŽ   Úprepare)r:   r!   Zmod_objrh   Ú_userr�   r+   r,   rÄ   P  s.    
ý

zJupyterHandler.preparec                 C  s   | j d  |¡S )z1Return the jinja template object for a given nameZ
jinja2_env)r7   Úget_template)r:   rT   r+   r+   r,   rÆ     s    zJupyterHandler.get_templatec                 K  s&   |  | j¡ |  |¡}|jf i |¤ŽS )zRender a template by name.)rA   Útemplate_namespacerÆ   Úrender)r:   rT   ÚnsÚtemplater+   r+   r,   Úrender_templateƒ  s    
zJupyterHandler.render_templatec                 C  s|   t f | j| j| j| jt| jddƒ| jj| jjt	| j
ƒ| jtƒ | j| j| j| j
| j d¡t t| jj dd¡ƒ¡dœ| j¤ŽS )NÚallow_password_changeFÚutf8zAccept-Languager|   )r4   r€   r�   ri   rÌ   Úauth_enabledrl   Ztoken_availableÚ
static_urlZsys_infor‚   r{   Úxsrf_form_htmlrk   Ú
xsrf_tokenZnbjs_translations)Údictr4   r€   r�   ri   ÚgetattrrQ   rÎ   rl   ra   rk   rÏ   r-   r‚   r{   rÐ   rÑ   Údecoder)   r*   r   rc   r<   r8   rx   r9   r+   r+   r,   rÇ   ‰  s,    
ÿðíz!JupyterHandler.template_namespacec              
   C  s‚   | j jsdS | j j ¡  d¡}zt |¡}W nP ty| } z8| j d|¡ | jj	ddd� t
 dd¡|‚W Y d}~n
d}~0 0 |S )	z,Return the body of the request as JSON data.Nzutf-8zBad JSON: %rzCouldn't parse JSONT©Úexc_infoi�  zInvalid JSON in body of request)rc   ÚbodyÚstriprÔ   r)   ÚloadsrD   r1   rƒ   Úerrorr   r®   )r:   r×   ÚmodelrH   r+   r+   r,   Úget_json_body¡  s    $zJupyterHandler.get_json_bodyÚintr   ©Ústatus_codeÚkwargsr/   c           
      K  sÊ   |  d¡}d}t  |d¡}|r`|d }z|j|j }W n tyH   Y n0 t|ddƒ}|rd|}nd}||||dœ}|  dd	¡ z| jd
| fi |¤Ž}	W n" tyº   | jdi |¤Ž}	Y n0 |  	|	¡ dS )zrender custom error pagesrÖ   r|   úUnknown HTTP Errorr¯   Úreasonz	(unknown))rß   Ústatus_messageÚmessagerE   úContent-Typez	text/htmlz%s.htmlú
error.htmlN)ræ   )
r8   r   Úlog_messageÚargsrD   rÓ   rC   rË   r   Úwrite)
r:   rß   rà   rÖ   rä   rã   rE   râ   rÉ   Úhtmlr+   r+   r,   Úwrite_error¯  s0    
üzJupyterHandler.write_error)r|   )(r[   rr   rs   rt   ru   ro   r1   rx   ry   r{   r}   r   r€   r�   r‚   r„   r…   r†   r‡   rˆ   r‰   rŠ   r‹   rŒ   r�   rI   r˜   rš   r“   r¤   r¨   r­   r½   rÄ   rÆ   rË   rÇ   rÜ   rë   Ú__classcell__r+   r+   r�   r,   rv     sp   /.*/rv   c                      sš   e Zd ZdZddœ‡ fdd„Zddddœd	d
„Zddœ‡ fdd„Zeddœ‡ fdd„ƒZdZ	ddœdd„Z
ddddœ‡ fdd„Zddddœdd„Z‡  ZS )Ú
APIHandlerzBase class for API handlersr@   r.   c                 ƒ  s&   t ƒ  ¡ I dH  |  ¡ s"t d¡‚dS )zPrepare an API response.Né”  )rŽ   rÄ   r¤   r   r®   r9   r�   r+   r,   rÄ   Ù  s    zAPIHandler.preparerÝ   r   rÞ   c                 K  s¨   |   dd¡ t |d¡}d|i}| d¡}|r~|d }t|tƒrZ|jpH||d< |j|d< n$d|d< d	|d< d
 tj	|Ž ¡|d< | j
jd|d dd� |  t |¡¡ d	S )z+APIHandler errors are JSON, not human pagesrå   úapplication/jsonrá   rä   rÖ   r¯   râ   zUnhandled errorNr|   Ú	tracebackzwrote error: %rTrÕ   )rC   r   r8   rÃ   r®   rç   râ   r>   rð   Úformat_exceptionr1   r    Úfinishr)   r*   )r:   rß   rà   rä   ZreplyrÖ   rH   r+   r+   r,   rë   ß  s    ÿ

zAPIHandler.write_errorr3   c                   s   | j st d¡‚tƒ  ¡ S )zGet the login url.r¬   )rg   r   r®   rŽ   Úget_login_urlr9   r�   r+   r,   ró   ó  s    
zAPIHandler.get_login_urlc                   s   d  tƒ jdg¡}|S )Nr=   zdefault-src 'none')r>   rŽ   r?   )r:   Zcspr�   r+   r,   r?   ü  s    þÿz"APIHandler.content_security_policyTc                 C  s2   | j r.t| ddƒr.|  dd¡du r.tƒ | jd< dS )z$Update last_activity of API requestsrY   NZno_track_activityZapi_last_activity)Ú_track_activityrÓ   Úget_argumentr   r7   r9   r+   r+   r,   Úupdate_api_activity	  s    ÿ
þýzAPIHandler.update_api_activityzFuture[Any])rè   rà   r/   c                   s2   |   ¡  | dd¡}|  d|¡ tƒ j|i |¤ŽS )zFinish an API response.Úset_content_typerï   rå   )rö   ÚpoprC   rŽ   rò   )r:   rè   rà   r÷   r�   r+   r,   rò     s    zAPIHandler.finishc                 O  s®   d| j  di ¡v r*|  d| j d d ¡ n|  dd¡ |  dd¡ | jj dd¡ d¡}|rªtd	d
„ |D ƒƒrª| jrª| js’| j	s’d| j  di ¡v rª|  d| jj dd¡¡ dS )zGet the options.zAccess-Control-Allow-Headersr<   z0accept, content-type, authorization, x-xsrftokenzAccess-Control-Allow-Methodsz&GET, PUT, POST, PATCH, DELETE, OPTIONSzAccess-Control-Request-Headersr|   ú,c                 s  s   | ]}|  ¡  ¡ d kV  qdS )ÚauthorizationN)rØ   rž   )Ú.0Úhr+   r+   r,   Ú	<genexpr>4  ó    z%APIHandler.options.<locals>.<genexpr>r�   r‘   N)
r7   r8   rC   rc   r<   ÚsplitÚanyrl   r‹   rŒ   )r:   rè   rà   Zrequested_headersr+   r+   r,   Úoptions  s4    þþÿÿþú	÷
öõzAPIHandler.options)r[   rr   rs   rt   rÄ   rë   ró   ru   r?   rô   rö   rò   r  rì   r+   r+   r�   r,   rí   Ö  s   	

rí   c                      s&   e Zd ZdZddœ‡ fdd„Z‡  ZS )ÚTemplate404zRender our 404 templater@   r.   c                 ƒ  s   t ƒ  ¡ I dH  t d¡‚dS )zPrepare a 404 response.Nrî   )rŽ   rÄ   r   r®   r9   r�   r+   r,   rÄ   F  s    zTemplate404.prepare)r[   rr   rs   rt   rÄ   rì   r+   r+   r�   r,   r  C  s   r  c                      s°   e Zd ZdZdZeddœ‡ fdd„ƒZeje	dddœ‡ fd	d
„ƒƒZ
eje	ddddœdd„ƒƒZddœ‡ fdd„Zddœ‡ fdd„Zddœdd„Zddddœ‡ fdd„Z‡  ZS )ÚAuthenticatedFileHandlerz5static files should only be accessible when logged inÚcontentsr3   r.   c                   s   t ƒ jd S )Nz; sandbox allow-scripts)rŽ   r?   r9   r�   r+   r,   r?   Q  s    z0AuthenticatedFileHandler.content_security_policyzAwaitable[None]©rU   r/   c                   s   |   ¡  tƒ  |¡S )z!Get the head response for a path.)r­   rŽ   Úhead©r:   rU   r�   r+   r,   r  W  s    zAuthenticatedFileHandler.headr   )rU   rà   r/   c                 K  sX   |   ¡  tj |¡d dks(|  dd¡rB| dd¡d }|  |¡ tjj	| |fi |¤ŽS )zGet a file by path.r¯   ú.ipynbÚdownloadNr5   r²   )
r­   r·   rU   Úsplitextrõ   Úrsplitrš   r   ÚStaticFileHandlerr8   )r:   rU   rà   rT   r+   r+   r,   r8   ^  s
     
zAuthenticatedFileHandler.getc                   sn   | j dusJ ‚| j  d¡}d|v r4| dd¡\}}n|}| d¡rFdS t |¡d }|dkr`dS tƒ  ¡ S dS )	zGet the content type.Nr5   r¯   r  zapplication/x-ipynb+jsonr   z
text/plainztext/plain; charset=UTF-8)Úabsolute_pathrØ   r  r¶   Ú	mimetypesÚ
guess_typerŽ   Úget_content_type)r:   rU   Ú_rT   Zcur_mimer�   r+   r,   r  k  s    
z)AuthenticatedFileHandler.get_content_typer@   c                   s&   t ƒ  ¡  d| jjvr"|  dd¡ dS )úSet the headers.ÚvúCache-Controlúno-cacheN)rŽ   Úset_headersrc   Ú	argumentsÚ
add_headerr9   r�   r+   r,   r  |  s    
z$AuthenticatedFileHandler.set_headersrS   c                 C  s   dS ©zCompute the etag.Nr+   r9   r+   r+   r,   Úcompute_etagƒ  s    z%AuthenticatedFileHandler.compute_etag©Úrootr  r/   c                   sR   t ƒ  ||¡}tj |¡}|dus&J ‚| jjsNt||ƒrN| j 	d¡ t
 d¡‚|S )z�Validate and return the absolute path.

        Requires tornado 3.1

        Adding to tornado's own handling, forbids the serving of hidden files.
        Nz_Refusing to serve hidden file, via 404 Error, use flag 'ContentsManager.allow_hidden' to enablerî   )rŽ   Úvalidate_absolute_pathr·   rU   Úabspathr…   Zallow_hiddenr   r1   Úinfor   r®   )r:   r  r  Úabs_pathZabs_rootr�   r+   r,   r  ‡  s    ÿ
z/AuthenticatedFileHandler.validate_absolute_path)r[   rr   rs   rt   Zauth_resourceru   r?   r   Úauthenticatedr   r  r8   r  r  r  r  rì   r+   r+   r�   r,   r  L  s   r  r   )rd   r/   c                   s*   t jdtdd� t ˆ ¡‡ fdd„ƒ}|S )a™  Decorate methods with this to return GitHub style JSON errors.

    This should be used on any JSON API on any handler method that can raise HTTPErrors.

    This will grab the latest HTTPError exception using sys.exc_info
    and then:

    1. Set the HTTP status code based on the HTTPError
    2. Create and return a JSON body with a message field describing
       the error in a human readable form.
    zJ@json_errors is deprecated in notebook 5.2.0. Subclass APIHandler instead.rK   rL   c                   s&   t  tj| ¡| _ˆ | g|¢R i |¤ŽS ©N)ÚtypesÚ
MethodTyperí   rë   )r:   rè   rà   ©rd   r+   r,   Úwrapper«  s    zjson_errors.<locals>.wrapper)rN   rO   rP   Ú	functoolsÚwraps)rd   r&  r+   r%  r,   Újson_errors™  s    ýr)  c                      sŒ   e Zd ZU dZi Zded< ded< ddœ‡ fdd	„Zddddddœdd„Zddœdd„Ze	ddddœdd„ƒZ
ddddœ‡ fdd„Z‡  ZS )ÚFileFindHandlera=  subclass of StaticFileHandler for serving files from a search path

    The setting "static_immutable_cache" can be set up to serve some static
    file as immutable (e.g. file name containing a hash). The setting is a
    list of base URL, every static file URL starting with one of those will
    be immutable.
    rw   Ú_static_pathsz
tuple[str]r  r@   r.   c                   sp   t ƒ  ¡  ˆ j dg ¡}t‡ fdd„|D ƒƒr<ˆ  dd¡ n0dˆ jjvs`t‡ fdd„ˆ jD ƒƒrlˆ  dd¡ d	S )
r  Zstatic_immutable_cachec                 3  s   | ]}ˆ j j |¡V  qd S r"  ©rc   rU   rµ   ©rû   rU   r9   r+   r,   rý   Ï  rþ   z.FileFindHandler.set_headers.<locals>.<genexpr>r  z#public, max-age=31536000, immutabler  c                 3  s   | ]}ˆ j j |¡V  qd S r"  r,  r-  r9   r+   r,   rý   Ó  s   r  N)	rŽ   r  r7   r8   r   rC   rc   r  Úno_cache_paths)r:   Zimmutable_pathsr�   r9   r,   r  È  s    
ÿzFileFindHandler.set_headersNzstr | list[str]rS   zlist[str] | None)rU   Údefault_filenamer.  r/   c                 C  s8   |pg | _ t|tƒr|g}tdd„ |D ƒƒ| _|| _dS )z!Initialize the file find handler.c                 s  s(   | ] }t j t j |¡¡t j V  qd S r"  )r·   rU   r  Ú
expanduserÚsep)rû   Úpr+   r+   r,   rý   ä  s   z-FileFindHandler.initialize.<locals>.<genexpr>N)r.  rÃ   r3   Útupler  r/  )r:   rU   r/  r.  r+   r+   r,   Ú
initializeØ  s    

ÿ
zFileFindHandler.initializec                 C  s   dS r  r+   r9   r+   r+   r,   r  é  s    zFileFindHandler.compute_etagzSequence[str]r3   )ÚrootsrU   r/   c              	   C  sª   | j �� || jv r*| j| W  d  ƒ S ztj t||ƒ¡}W n  ty`   Y W d  ƒ dS 0 || j|< tƒ  d|› d|› �¡ |W  d  ƒ S 1 sœ0    Y  dS )z5locate a file to serve on our static file search pathNr|   zPath z served from )	Ú_lockr+  r·   rU   r  r   ÚOSErrorr1   rƒ   )Úclsr5  rU   r  r+   r+   r,   Úget_absolute_pathí  s    

z!FileFindHandler.get_absolute_pathr  c                   s<   |st  d¡‚| jD ]}|tj  |¡r q.qtƒ  ||¡S )z:check if the file should be served (raises 404, 403, etc.)rî   )r   r®   r  r·   r1  rµ   rŽ   r  )r:   r  r  r�   r+   r,   r  þ  s    

z&FileFindHandler.validate_absolute_path)NN)r[   rr   rs   rt   r+  Ú__annotations__r  r4  r  Úclassmethodr9  r  rì   r+   r+   r�   r,   r*  »  s   
	  ür*  c                   @  s"   e Zd ZdZdZddœdd„ZdS )ÚAPIVersionHandlerz&An API handler for the server version.Fr@   r.   c                 C  s   |   t dtji¡¡ dS )zGet the server version info.ÚversionN)rò   r)   r*   Újupyter_serverÚ__version__r9   r+   r+   r,   r8     s    zAPIVersionHandler.getN)r[   rr   rs   rt   rô   r8   r+   r+   r+   r,   r<  
  s   r<  c                   @  s&   e Zd ZdZddœdd„Ze ZZdS )ÚTrailingSlashHandlerzrSimple redirect handler that strips trailing slashes

    This should be the first, highest priority handler.
    r@   r.   c                 C  sN   | j jdusJ ‚| j j d¡^}}d| d¡ }d |g|¢¡}|  |¡ dS )z!Handle trailing slashes in a get.Nú?r5   r|   )rc   ÚuriÚ	partitionrØ   r>   Úredirect)r:   rU   ÚrestZnew_urir+   r+   r,   r8     s
    zTrailingSlashHandler.getN©r[   rr   rs   rt   r8   ÚpostÚputr+   r+   r+   r,   r@    s   
r@  c                   @  s&   e Zd ZdZddœdd„Ze ZZdS )ÚMainHandlerzSimple handler for base_url.r@   r.   c                 C  s   |   d¡}|  |¡ dS )zGet the main template.z	main.htmlN)rË   ré   )r:   rê   r+   r+   r,   r8   +  s    
zMainHandler.getNrF  r+   r+   r+   r,   rI  (  s   rI  c                   @  s8   e Zd ZdZeddddœdd„ƒZddd	d
œdd„ZdS )ÚFilesRedirectHandlerz<Handler for redirecting relative URLs to the /files/ handlerr   r3   r@   )r:   rU   r/   c                 Ã  sÐ   | j }t| |¡ƒI dH r.t| jdt|ƒƒ}n€|}| d¡}t|j|d�ƒI dH s|d|v r|| j 	d|¡ | 
d¡ d |¡}t|j|d�ƒI dH sœt d¡‚t| jdt|ƒƒ}| j d| jj|¡ |  |¡ dS )	zgmake redirect logic a reusable static method

        so it can be called from other handlers.
        NÚtreer5   )rU   ÚfileszDeprecated files/ URL: %srî   zRedirecting %s to %s)r…   r   Z
dir_existsr   r4   r   rÿ   Zfile_existsr1   r    Úremover>   r   r®   rƒ   rc   rU   rD  )r:   rU   Úcmr~   Ú	orig_pathÚpartsr+   r+   r,   Úredirect_to_files6  s    



z&FilesRedirectHandler.redirect_to_filesr|   r   r  c                 C  s   |   | |¡S r"  )rQ  r  r+   r+   r,   r8   S  s    zFilesRedirectHandler.getN)r|   )r[   rr   rs   rt   ÚstaticmethodrQ  r8   r+   r+   r+   r,   rJ  3  s   rJ  c                   @  s2   e Zd ZdZdddddœdd„Zdd	œd
d„ZdS )ÚRedirectWithParamsz8Sam as web.RedirectHandler, but preserves URL parametersTr3   ra   r@   )r~   Ú	permanentr/   c                 C  s   || _ || _dS )zInitialize a redirect handler.N)Ú_urlÚ
_permanent)r:   r~   rT  r+   r+   r,   r4  Z  s    zRedirectWithParams.initializer.   c                 C  s:   d| j v rdnd}| | j | jjg¡}| j|| jd� dS )zGet a redirect.rA  ú&)rT  N)rU  r>   rc   ÚqueryrD  rV  )r:   r1  r~   r+   r+   r,   r8   _  s    zRedirectWithParams.getN)T)r[   rr   rs   rt   r4  r8   r+   r+   r+   r,   rS  W  s   rS  c                   @  s   e Zd ZdZddœdd„ZdS )ÚPrometheusMetricsHandlerz3
    Return prometheus metrics for this server
    r@   r.   c                 C  s>   | j d r| jst d¡‚|  dtj¡ |  t tj	¡¡ dS )zGet prometheus metrics.Zauthenticate_prometheusr¬   rå   N)
r7   ri   r   r®   rC   Úprometheus_clientZCONTENT_TYPE_LATESTré   Zgenerate_latestZREGISTRYr9   r+   r+   r,   r8   k  s    
zPrometheusMetricsHandler.getN)r[   rr   rs   rt   r8   r+   r+   r+   r,   rY  f  s   rY  z(?P<path>(?:(?:/[^/]+)+|/?))z.*/Úapiz/(robots\.txt|favicon\.ico)z/metrics)crt   Ú
__future__r   r'  rÀ   r¹   r)   r  r·   r”   rð   r#  rN   Úhttp.clientr   Úloggingr   Útypingr   r   r   r   r	   Úurllib.parser
   rZ  Zjinja2r   Zjupyter_core.pathsr   Zjupyter_eventsr   Útornador   Ztornado.logr   Ztraitlets.configr   r>  r   Zjupyter_server._sysinfor   Zjupyter_server._tzr   rp   r   Zjupyter_server.i18nr   Z jupyter_server.services.securityr   Zjupyter_server.utilsr   r   r   r   r   r   Zjupyter_client.kernelspecr   Z(jupyter_server_terminals.terminalmanagerr   Ztornado.concurrentr   Zjupyter_server.auth.authorizerr    Zjupyter_server.auth.identityr!   r"   Zjupyter_server.serverappr#   Z&jupyter_server.services.config.managerr$   Z(jupyter_server.services.contents.managerr%   Z-jupyter_server.services.kernels.kernelmanagerr&   Z/jupyter_server.services.sessions.sessionmanagerr'   r(   r-   r1   ZRequestHandlerr2   rv   rí   r  r  r  r)  r®   r*  r<  r@  rI  rJ  rS  rY  Z
path_regexZdefault_handlersr+   r+   r+   r,   Ú<module>   sˆ    	 @   Im	MO$ü