a
    ]DfG2                     @  s<  U d Z ddlmZ ddlZee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mZ ddlmZ ddlmZ dd	lmZ erdd
lmZ dZdZeeef Zde d< ddddZ!e" e# fddddddZ$e" e# ddfdddddddddZ%dddd d!Z&dddd"d#Z'e" e# fddddd$d%d&Z(e" e# fddd'dd(d)d*Z)G d+d, d,ej*Z+G d-d. d.ej,Z-d/dd0d1Z.d2dd3d4d5Z/ddd6d7d8d9Z0d:dd;d<d=Z1d:d>d?d@dAZ2ddddBdCdDZ3dEdFe" fdddddGdHdIZ4e. \Z5Z6dS )Jz Utilities for generating and manipulating session IDs.

A session ID would typically be associated with each browser tab viewing
an application or plot. Each session has its own state separate from any
other sessions hosted by the server.

    )annotationsN)TYPE_CHECKINGAny   )ID)settings   )warn)	TypeAlias)check_session_id_signaturecheck_token_signaturegenerate_secret_keygenerate_jwt_tokengenerate_session_idget_session_idget_token_payloadZ__bk__zlib_r
   TokenPayloadstr)returnc                   C  s   t  S )z Generate a new securely-generated secret key appropriate for SHA-256
    HMAC signatures.

    This key could be used to sign Bokeh server session IDs, for example.
    )_get_random_string r   r   ]/nfs/NAS7/SABIOD/METHODE/ermites/ermites_venv/lib/python3.9/site-packages/bokeh/util/token.pyr   E   s    r   zbytes | Noneboolr   )
secret_keysignedr   c                 C  s&   t  }|rd|t|| g}t|S )a   Generate a random session ID.

    Typically, each browser tab connected to a Bokeh application has its own
    session ID. In production deployments of a Bokeh app, session IDs should be
    random and unguessable - otherwise users of the app could interfere with one
    another.
    .)r   join
_signaturer   )r   r   
session_idr   r   r   r   M   s    	r   i,  zTokenPayload | Noneint)r   r   r   extra_payload
expirationr   c           
      C  s   t tjjtjjd }| || d}|rld|v r>tdt	j
|tdd}tj|dd}t||t< tt	
|}	t|}|s|	S |	d	 t|	| S )
av   Generates a JWT token given a session_id and additional payload.

    Args:
        session_id (str):
            The session id to add to the token

        secret_key (str, optional) :
            Secret key (default: value of BOKEH_SECRET_KEY environment variable)

        signed (bool, optional) :
            Whether to sign the session ID (default: value of BOKEH_SIGN_SESSIONS
            environment variable)

        extra_payload (dict, optional) :
            Extra key/value pairs to include in the Bokeh session token

        expiration (int, optional) :
            Expiration time

    Returns:
        str
    )tz)r   Zsession_expiryr   z=extra_payload for session tokens may not contain 'session_id'clsutf-8	   )levelr   )calendartimegmdtdatetimenowtimezoneutc	timetupleRuntimeErrorjsondumps_BytesEncoderencodezlibcompress_base64_encode_TOKEN_ZLIB_KEY_ensure_bytesr   )
r   r   r   r    r!   r,   payloadZextra_payload_str
compressedtokenr   r   r   r   [   s    r   )r<   r   c                 C  s    t t| dd }|d S )zExtracts the session id from a JWT token.

    Args:
        token (str):
            A JWT token containing the session_id and other data.

    Returns:
       str
    r   r   r   )r1   loads_base64_decodesplit)r<   decodedr   r   r   r      s    
r   c                 C  sV   t t| dd }t|v rLtt|t }|t= |t j|td |d= |S )zExtract the payload from the token.

    Args:
        token (str):
            A JWT token containing the session_id and other data.

    Returns:
        dict
    r   r   r#   r   )	r1   r=   r>   r?   r8   r5   
decompressupdate_BytesDecoder)r<   r@   decompressedr   r   r   r      s    
r   )r<   r   r   r   c           
      C  sn   t |}|rj| dd}t|dkr(dS |d }|d }t||}t||}t| }t|||}	|oh|	S dS )au  Check the signature of a token and the contained signature.

    The server uses this function to check whether a token and the
    contained session id was generated with the correct secret key.
    If signed sessions are disabled, this function always returns True.

    Args:
        token (str) :
            The token to check

        secret_key (str, optional) :
            Secret key (default: value of BOKEH_SECRET_KEY environment variable)

        signed (bool, optional) :
            Whether to check anything (default: value of BOKEH_SIGN_SESSIONS
            environment variable)

    Returns:
        bool

    r   r   r   Fr   T)r9   r?   lenr   hmaccompare_digestr   r   )
r<   r   r   Ztoken_piecesZ
base_tokenZprovided_token_signatureZexpected_token_signatureZtoken_validr   Zsession_id_validr   r   r   r      s    
r   zbool | None)r   r   r   r   c                 C  sN   t |}|rJ| dd}t|dkr(dS |d }t|d |}t||S dS )zCheck the signature of a session ID, returning True if it's valid.

    The server uses this function to check whether a session ID was generated
    with the correct secret key. If signed sessions are disabled, this function
    always returns True.
    r   r   r   Fr   T)r9   r?   rE   r   rF   rG   )r   r   r   Z	id_piecesZprovided_id_signatureZexpected_id_signaturer   r   r   r      s    	r   c                      s$   e Zd Zddd fddZ  ZS )r3   r   )or   c                   s$   t |trtt|dS t |S )N)bytes)
isinstancerI   dictr7   superdefault)selfrH   	__class__r   r   rM      s    
z_BytesEncoder.default)__name__
__module____qualname__rM   __classcell__r   r   rO   r   r3      s   r3   c                      s6   e Zd Zdddd fddZddddd	Z  ZS )
rC   r   None)argskwargsr   c                   s   t  j|d| ji| d S )Nobject_hook)rL   __init__bytes_object_hook)rN   rV   rW   rO   r   r   rY      s    z_BytesDecoder.__init__zdict[Any, Any])objr   c                 C  s"   t | dhkrt|d S |S )NrI   )setkeysr>   )rN   r[   r   r   r   rZ      s    z_BytesDecoder.bytes_object_hook)rQ   rR   rS   rY   rZ   rT   r   r   rO   r   rC      s   rC   ztuple[Any, bool]c                  C  s^   dd l } z|  }d}||fW S  tyX   td t d u rHtd d}| |f Y S 0 d S )Nr   TzjA secure pseudo-random number generator is not available on your system. Falling back to Mersenne Twister.zA secure pseudo-random number generator is not available and no BOKEH_SECRET_KEY has been set. Setting a secret key will mitigate the lack of a secure generator.F)randomSystemRandomNotImplementedErrorr	   r   r   )r^   Z	sysrandomusing_sysrandomr   r   r   _get_sysrandom   s    
rb   zstr | bytes | None)r   r   c                 C  s*   | d u rd S t | tr| S t| dS d S Nr%   )rJ   rI   codecsr4   )r   r   r   r   r9     s
    
r9   rU   )ra   r   r   c                 C  s@   t |}| s<t  t  | }tt|  d S N)	r9   r^   getstatetimer4   seedhashlibsha256digest)ra   r   datar   r   r   _reseed_if_needed  s    rm   zbytes | str)r@   r   c                 C  s(   t | }tt|d}t|dS )Nascii=)r9   rd   decodebase64urlsafe_b64encoder   rstrip)r@   Zdecoded_as_bytesencodedr   r   r   r7   #  s    r7   rI   )rt   r   c                 C  s\   t | trt| dn| }t|d }|dkr>|dd|   }t|d dksRJ t|S )Nrn      r      =)rJ   r   rd   r4   rE   rq   urlsafe_b64decode)rt   Zencoded_as_bytesmodr   r   r   r>   .  s    r>   )base_idr   r   c                 C  s<   t |}t| d}|d us J t||tj}t| S rc   )	r9   rd   r4   rF   newri   rj   r7   rk   )ry   r   Zbase_id_encodedZsignerr   r   r   r   8  s
    r   ,   Z>abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789)lengthallowed_charsr   r   c                   s.   t |}tt| d fddt| D S )z Return a securely generated random string.

    With the a-z, A-Z, 0-9 character set:
    Length 12 is a 71-bit value. log_2((26+26+10)^12) =~ 71
    Length 44 is a 261-bit value. log_2((26+26+10)^44) = 261

     c                 3  s   | ]}t  V  qd S re   )r^   choice).0_r}   r   r   	<genexpr>L      z%_get_random_string.<locals>.<genexpr>)r9   rm   ra   r   range)r|   r}   r   r   r   r   r   ?  s    
r   )7__doc__
__future__r   logging	getLoggerrQ   logrq   r(   rd   r+   r*   ri   rF   r1   rg   r5   typingr   r   Z
core.typesr   r   warningsr	   Ztyping_extensionsr
   __all__r8   rK   r   r   __annotations__r   Zsecret_key_bytesZsign_sessionsr   r   r   r   r   r   JSONEncoderr3   JSONDecoderrC   rb   r9   rm   r7   r>   r   r   r^   ra   r   r   r   r   <module>   sf   

)+		
