o
    pj:                     @  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mZ ddl	m
Z
 ddlmZ ddlmZ ddlmZ d	ZdddZdddZd ddZdS )!zAAuthenticated internal request contract for the AroFlo UI worker.    )annotationsN)Request)select)get_control_plane_session)TenantIntegration)SecretsManager<   secretstrmethodpathbodybytes	timestampnoncereturnc                 C  sB   t | }d| ||||f }t|  |t j S )N
)hashlibsha256	hexdigestjoinupperencodehmacnew)r	   r   r   r   r   r   digestmessage r   ,apps/aroflo_connector_app/worker_security.pysign_worker_request   s   r   requestr   	tenant_idNonec                 C  s   | j dd}| j dd}| j dd}| r#|r#t|dks#|s'tdt j|ddd	p1d}|s8tdttt		 t| t
krJtd
t|| j| j| jdd||}t||sctdt||t| d S )NzX-AroFlo-Timestamp zX-AroFlo-NoncezX-AroFlo-Signature   zWorker authentication requiredaroflo_connector_appui_worker_shared_secret)r!   app_idsecret_namezWorker request expiredT)cachezWorker signature rejected)headersgetisdigitlenPermissionErrorr   
get_secretabsinttimeMAX_CLOCK_SKEWr   r   r   get_datar   compare_digest_consume_nonce)r    r!   r   r   suppliedr	   expectedr   r   r   authenticate_worker_request   s(   r9   r1   c              	     s   d}t t t  t ^}|tttj| ktj	dktj
|k  }|d u r;t| d|ddi id}||  fdd|jpDi dpIi  D }||v rVtd|||< d|i|_|  W d    d S 1 snw   Y  d S )	Nworker_auth_replayr%   activenonces)r!   r'   integration_namestatusconfig_jsonc                   s"   i | ]\}}t | kr||qS r   )r1   ).0keyvaluecutoffr   r   
<dictcomp>=   s    z"_consume_nonce.<locals>.<dictcomp>zWorker request replay detected)r1   r2   r3   r   executer   r   wherer!   r'   r=   with_for_updatescalar_one_or_noneaddr?   r+   itemsr.   commit)r!   r   r   namesessionrowr<   r   rC   r   r6   0   s0   

&

"r6   )r	   r
   r   r
   r   r
   r   r   r   r
   r   r
   r   r
   )r    r   r!   r
   r   r"   )r!   r
   r   r
   r   r1   r   r"   )__doc__
__future__r   r   r   osr2   flaskr   
sqlalchemyr   config.control_planer   bridge_platform.tenants.modelsr   'bridge_platform.secrets.secrets_managerr   r3   r   r9   r6   r   r   r   r   <module>   s    

