
    yjl                        d dl Z d dlZd dlmZ d dlZd dlmZmZ d dlm	Z	m
Z
 d dlmZmZ d dlmZ d dlmZmZ dd	lmZ  ej        e          Z e
d
          Z G d de          ZdefdZdedefdZdedefdZ	 	 	 	 ddedz  dedz  dedz  dedz  fdZ	 	 	 	 ddee	 ee          f         dedz  dedz  dedz  dedz  defdZ dS )    N)	Annotated)DependsRequest)HTTPAuthorizationCredentials
HTTPBearer)	BaseModelField)settings)parse_datetime_isoutc_now_iso   )AuthenticationExceptionF)
auto_errorc                       e Zd ZU dZ ee          Zeed<   dZ	edz  ed<   dZ
edz  ed<   dZedz  ed<   dZedz  ed<   dZedz  ed	<   dS )
	JWTParamsa  
    JWT parameters used to produce tokens valid for different routes.
    Workspaces are the top level of the hierarchy -- a workspace key will
    give access to all peers/sessions/collections in that workspace.

    A session key will allow the listing and creation of messages in
    that session.

    A peer key will allow the listing and creation of peer-level messages
    and querying the peer's dialectic endpoint.

    Names shortened to minimize token size. Timestamp is included
    so that many unique tokens can be generated for the same resource.
    Note that the timestamp itself is not used for security, and can
    be omitted, such as when Honcho generates the initial admin JWT.

    Fields (all optional other than `t`):

    `t`: a string timestamp of when the JWT was created
    `exp`: a string timestamp of when the JWT expires (optional)
    `ad`: a boolean flag indicating if the JWT is an admin JWT
    `w`: (string) workspace name
    `p`: (string) peer name
    `s`: (string) session name
    )default_factorytNexpadwps)__name__
__module____qualname____doc__r	   r   r   str__annotations__r   r   boolr   r   r        4/DATA/AppData/hermes/projects/honcho/src/security.pyr   r      s          4 U;///As///CtBtAsTzAsTzAsTzr!   r   returnc                  F    t          dd          } t          |           }|S )z"Create a JWT for admin operations. Tr   r   )r   
create_jwt)paramskeys     r"   create_admin_jwtr*   B   s&    %%%F
V

CJr!   r(   c                     d | j                                         D             }t          j        j        st          d          t          j        |t          j        j                            d          d          S )z'Create a JWT from the given parameters.c                     i | ]
\  }}|||S )Nr    ).0kvs      r"   
<dictcomp>zcreate_jwt.<locals>.<dictcomp>K   s    III11=q!===r!   z.AUTH_JWT_SECRET is not set, cannot create JWT.utf-8HS256)	algorithm)__dict__itemsr
   AUTH
JWT_SECRET
ValueErrorjwtencode)r(   payloads     r"   r'   r'   I   ss    II 5 5 7 7IIIG=# KIJJJ:)0099W   r!   tokenc                    t                      }	 t          j        j        st	          d          t          j        | t          j        j                            d          dg          }d|v r|d         |_        d|v rk|d         |_	        |j	        rWt          |j	                  }t          j                            t          j        j                  }||k     rt          d          d|v r|d         |_        d	|v r|d	         |_        d
|v r|d
         |_        d|v r|d         |_        |S # t
          j        $ r t          d          dw xY w)z/Verify a JWT and return the decoded parameters.z.AUTH_JWT_SECRET is not set, cannot verify JWT.r1   r2   )
algorithmsr   r   zJWT expiredr   r   r   r   zInvalid JWTN)r   r
   r6   r7   r8   r9   decoder:   r   r   r   datetimenowtimezoneutcr   r   r   r   r   
PyJWTError)r<   r(   decodedexp_timecurrent_times        r"   
verify_jwtrH   S   s^    [[F?}' 	OMNNN*8=+227;;	
 
 
 '>>s|FHG FJz A-fj99'044X5F5JKKl**1-@@@7??FI'>>s|FH'>>s|FH'>>s|FH> ? ? ?%m44$>?s   DD0 0 Eadminworkspace_name	peer_namesession_namec                 d     t          t                    fdt          dt          f fd}|S )zV
    Generate a dependency that requires authentication for the given parameters.
    requestcredentialsc                   K   r4| j                                       p| j                                      nd }r4| j                                       p| j                                      nd }r4| j                                       p| j                                      nd }t          ||||           d {V S )N)rO   rI   rJ   rK   rL   )path_paramsgetquery_paramsauth)	rN   rO   workspace_name_parampeer_name_paramsession_name_paramrI   rK   rL   rJ   s	        r"   auth_dependencyz%require_auth.<locals>.auth_dependency}   s      G##N33 8#''77	 	 G##I..U'2F2J2J92U2U 	 G##L11 6#''55	 	 #/%+
 
 
 
 
 
 
 
 
 	
r!   )r   securityr   r   )rI   rJ   rK   rL   rX   s   ```` r"   require_authrZ   s   s]     5<H4E4E
 

1
 
 
 
 
 
 
 
 
< r!   rO   c                   K   t           j        j        st          dd          S | r| j        s)t
                              d           t          d          t          | j                  }|j	        r|S |rt          d          |r)|j
        |k    r|r|j        |k    rt          d          |S |r)|j        |k    r|r|j        |k    rt          d          |S |r|j        |k    r|S t          |||g          rt          d          |S )z=Authenticate the given JWT and return the decoded parameters.r%   Tr&   zNo access token providedz"Resource requires admin privilegesz&JWT not permissioned for this resource)r
   r6   USE_AUTHr   rO   loggerwarningr   rH   r   r   r   r   any)rO   rI   rJ   rK   rL   
jwt_paramss         r"   rT   rT      sc      =! (2$'''' Bk5 B1222%&@AAAK344J }  L%&JKKK  
44 	Tjln<<)*RSSS  Z\Y.. 	Tjln<<)*RSSS  *,.88
L)^455 P%&NOOO r!   )NNNN)!r@   loggingtypingr   r9   fastapir   r   fastapi.securityr   r   pydanticr   r	   
src.configr
   src.utils.formattingr   r   
exceptionsr   	getLoggerr   r]   rY   r   r   r*   r'   rH   r   rZ   rT   r    r!   r"   <module>rj      sV           



 $ $ $ $ $ $ $ $ E E E E E E E E % % % % % % % %       @ @ @ @ @ @ @ @ / / / / / /		8	$	$:           	      F#    y S    ?c ?i ? ? ? ?B !% #	( ($;($J( Tz( *	( ( ( (Z !% #* *79J9JJK*$;* $J* Tz	*
 ** * * * * * *r!   