a
    8öjéD  ã                   @   sÊ  U d 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m	Z	m
Z
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 ddlmZ dd	lmZmZ dd
lmZ G dd„ dedd�Zejejejejej ej ej ej ej!ej!ej!ej!dœZ"ee#ee$gdf f e%d< e &ej'dk �rdnd¡Z(dZ)e	eed df  e%d< e*e+e" ,¡ ƒƒZ-e	ee#df  e%d< e.h d£ƒZ/e	e
e#  e%d< e#e#dœdd„Z0e#e#dœdd„Z1e#ee#e#f d œd!d"„Z2G d#d$„ d$ƒZ3dS )%av  
Digest authentication middleware for aiohttp client.

This middleware implements HTTP Digest Authentication according to RFC 7616,
providing a more secure alternative to Basic Authentication. It supports all
standard hash algorithms including MD5, SHA, SHA-256, SHA-512 and their session
variants, as well as both 'auth' and 'auth-int' quality of protection (qop) options.
é    N)	ÚCallableÚDictÚFinalÚ	FrozenSetÚListÚLiteralÚTupleÚ	TypedDictÚUnion)ÚURLé   )Úhdrs)ÚClientError)ÚClientHandlerType)ÚClientRequestÚClientResponse)ÚPayloadc                   @   sF   e Zd ZU eed< eed< eed< eed< eed< eed< eed< dS )	ÚDigestAuthChallengeÚrealmÚnonceÚqopÚ	algorithmÚopaqueÚdomainÚstaleN)Ú__name__Ú
__module__Ú__qualname__ÚstrÚ__annotations__© r    r    úd/mnt/bigstor/www/usecases/.venv/lib/python3.9/site-packages/aiohttp/client_middleware_digest_auth.pyr   $   s   
r   F)Útotal)ÚMD5zMD5-SESSÚSHAzSHA-SESSÚSHA256zSHA256-SESSzSHA-256zSHA-256-SESSÚSHA512zSHA512-SESSzSHA-512zSHA-512-SESSzhashlib._HashÚDigestFunctions)é   é   z:(?:^|\s|,\s*)(\w+)\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]+))z>(?:^|\s|,\s*)((?>\w+))\s*=\s*(?:"((?:[^"\\]|\\.)*)"|([^\s,]+)))r   r   r   r   r   r   r   .ÚCHALLENGE_FIELDSÚSUPPORTED_ALGORITHMS>   r   Úurir   Úresponser   ÚusernameÚcnonceÚQUOTED_AUTH_FIELDS)ÚvalueÚreturnc                 C   s   |   dd¡S )z,Escape double quotes for HTTP header values.ú"ú\"©Úreplace©r1   r    r    r!   Úescape_quotesu   s    r8   c                 C   s   |   dd¡S )z-Unescape double quotes in HTTP header values.r4   r3   r5   r7   r    r    r!   Úunescape_quotesz   s    r9   )Úheaderr2   c                    s   ‡ fdd„t  | ¡D ƒS )a�  
    Parse key-value pairs from WWW-Authenticate or similar HTTP headers.

    This function handles the complex format of WWW-Authenticate header values,
    supporting both quoted and unquoted values, proper handling of commas in
    quoted values, and whitespace variations per RFC 7616.

    Examples of supported formats:
      - key1="value1", key2=value2
      - key1 = "value1" , key2="value, with, commas"
      - key1=value1,key2="value2"
      - realm="example.com", nonce="12345", qop="auth"

    Args:
        header: The header value string to parse

    Returns:
        Dictionary mapping parameter names to their values
    c                    s0   i | ](\}}}|  ¡  ‰ rˆ |r(t|ƒn|“qS r    )Ústripr9   )Ú.0ÚkeyZ
quoted_valZunquoted_val©Zstripped_keyr    r!   Ú
<dictcomp>“   s   þz&parse_header_pairs.<locals>.<dictcomp>)Ú_HEADER_PAIRS_PATTERNÚfindall)r:   r    r>   r!   Úparse_header_pairs   s    
þrB   c                   @   sx   e Zd ZdZdeeeddœdd„Zeeee	e
d f edœd	d
„Zeedœdd„Zeedœdd„Zeeedœdd„ZdS )ÚDigestAuthMiddlewarea  
    HTTP digest authentication middleware for aiohttp client.

    This middleware intercepts 401 Unauthorized responses containing a Digest
    authentication challenge, calculates the appropriate digest credentials,
    and automatically retries the request with the proper Authorization header.

    Features:
    - Handles all aspects of Digest authentication handshake automatically
    - Supports all standard hash algorithms:
      - MD5, MD5-SESS
      - SHA, SHA-SESS
      - SHA256, SHA256-SESS, SHA-256, SHA-256-SESS
      - SHA512, SHA512-SESS, SHA-512, SHA-512-SESS
    - Supports 'auth' and 'auth-int' quality of protection modes
    - Properly handles quoted strings and parameter parsing
    - Includes replay attack protection with client nonce count tracking
    - Supports preemptive authentication per RFC 7616 Section 3.6

    Standards compliance:
    - RFC 7616: HTTP Digest Access Authentication (primary reference)
    - RFC 2617: HTTP Authentication (deprecated by RFC 7616)
    - RFC 1945: Section 11.1 (username restrictions)

    Implementation notes:
    The core digest calculation is inspired by the implementation in
    https://github.com/requests/requests/blob/v2.18.4/requests/auth.py
    with added support for modern digest auth features and error handling.
    TN)ÚloginÚpasswordÚ
preemptiver2   c                 C   sp   |d u rt dƒ‚|d u r t dƒ‚d|v r0t dƒ‚|| _| d¡| _| d¡| _d| _d| _i | _|| _g | _	d S )Nz"None is not allowed as login valuez%None is not allowed as password valueú:z8A ":" is not allowed in username (RFC 1945#section-11.1)úutf-8ó    r   )
Ú
ValueErrorÚ
_login_strÚencodeÚ_login_bytesÚ_password_bytesÚ_last_nonce_bytesÚ_nonce_countÚ
_challengeÚ_preemptiveÚ_protection_space)ÚselfrD   rE   rF   r    r    r!   Ú__init__¹   s    zDigestAuthMiddleware.__init__rI   )ÚmethodÚurlÚbodyr2   c           "   
   ƒ   sH  | j }d|vrtdƒ‚d|vr&tdƒ‚|d }|d }|sBtdƒ‚| dd¡}| dd	¡}| ¡ }	| d
d¡}
| d¡}| d¡}t|ƒj}d}d}|râddh dd„ | d¡D ƒ¡}|sÈtd|› �ƒ‚d|v rÔdnd}| d¡}|	t	v�rtd|	› dd 
t¡› �ƒ‚t	|	 ‰ttdœ‡fdd„‰ tttdœ‡ fdd„}d 
| j|| jf¡}| ¡ › d|› � ¡ }|dk�r¢t|tƒ�rˆ| ¡ I dH }n|}ˆ |ƒ}d 
||f¡}ˆ |ƒ}ˆ |ƒ}|| jk�rÎ|  jd7  _nd| _|| _| jd ›}| d¡}t d 
t| jƒ d¡|t ¡  d¡t d!¡g¡¡ ¡ dd"… }| d¡}|	 ¡  d#¡�r\ˆ d 
|||f¡ƒ}|�r‚d 
|||||f¡}|||ƒ}n||d 
||f¡ƒ}t| jƒt|ƒt|ƒ|| ¡ |d$œ}|
�rÌt|
ƒ|d
< |�rê||d< ||d%< ||d&< g }|  ¡ D ]@\} }!| t!v �r | "| › d'|!› d(�¡ n| "| › d)|!› �¡ �qöd*d 
|¡› �S )+aÕ  
        Build digest authorization header for the current challenge.

        Args:
            method: The HTTP method (GET, POST, etc.)
            url: The request URL
            body: The request body (used for qop=auth-int)

        Returns:
            A fully formatted Digest authorization header string

        Raises:
            ClientError: If the challenge is missing required parameters or
                         contains unsupported values

        r   z:Malformed Digest auth challenge: Missing 'realm' parameterr   z:Malformed Digest auth challenge: Missing 'nonce' parameterzBSecurity issue: Digest auth challenge contains empty 'nonce' valuer   Ú r   r#   r   rH   rI   Úauthzauth-intc                 S   s   h | ]}|  ¡ r|  ¡ ’qS r    )r;   )r<   Úqr    r    r!   Ú	<setcomp>  rI   z/DigestAuthMiddleware._encode.<locals>.<setcomp>ú,zEDigest auth error: Unsupported Quality of Protection (qop) value(s): z/Digest auth error: Unsupported hash algorithm: z. Supported algorithms: z, )Úxr2   c                    s   ˆ | ƒ  ¡  ¡ S )z<RFC 7616 Section 3: Hash function H(data) = hex(hash(data)).)Ú	hexdigestrL   )r^   )Úhash_fnr    r!   ÚH  s    z'DigestAuthMiddleware._encode.<locals>.H)ÚsÚdr2   c                    s   ˆ d  | |f¡ƒS )zDRFC 7616 Section 3: KD(secret, data) = H(concat(secret, ":", data)).ó   :)Újoin)rb   rc   )ra   r    r!   ÚKD   s    z(DigestAuthMiddleware._encode.<locals>.KDrd   rG   Nr   Ú08xé   é   z-SESS)r.   r   r   r,   r-   r   Úncr/   z="r3   ú=zDigest )#rQ   r   ÚgetÚupperrL   r   Zpath_qsÚintersectionÚsplitr'   re   r+   ÚbytesrM   rN   Ú
isinstancer   Úas_bytesrO   rP   ÚhashlibÚsha1r   ÚtimeÚctimeÚosÚurandomr_   Úendswithr8   rK   ÚdecodeÚitemsr0   Úappend)"rT   rV   rW   rX   Ú	challenger   r   Zqop_rawZalgorithm_originalr   r   Znonce_bytesZrealm_bytesÚpathr   Z	qop_bytesZ
valid_qopsrf   ÚA1ÚA2Zentity_bytesZentity_hashÚHA1ÚHA2ÚncvalueZncvalue_bytesr/   Zcnonce_bytesÚnoncebitZresponse_digestZheader_fieldsÚpairsÚfieldr1   r    )ra   r`   r!   Ú_encodeÓ   sÄ    ÿÿÿ


ÿÿ

ÿÿ


üÿÿ	÷

ÿù
zDigestAuthMiddleware._encode)rW   r2   c                 C   s\   t |ƒ}| jD ]H}| |¡sqt|ƒt|ƒks:|d dkr@ dS |t|ƒ dkr dS qdS )zô
        Check if the given URL is within the current protection space.

        According to RFC 7616, a URI is in the protection space if any URI
        in the protection space is a prefix of it (after both have been made absolute).
        éÿÿÿÿú/TF)r   rS   Ú
startswithÚlen)rT   rW   Zrequest_strZ	space_strr    r    r!   Ú_in_protection_spacev  s    

z)DigestAuthMiddleware._in_protection_space)r-   r2   c                 C   s  |j dkrdS |j dd¡}|s$dS | d¡\}}}|s<dS | ¡ dkrLdS |sTdS t|ƒ }sddS i | _tD ] }| |¡ }durn|| j|< qn|j 	¡ }	| j d¡ }
�rg | _
|
 ¡ D ]H}| d	¡}| d
¡rî| j
 t|	 t|ƒ¡ƒ¡ qº| j
 tt|ƒƒ¡ qºnt|	ƒg| _
t| jƒS )zŠ
        Takes the given response and tries digest-auth, if needed.

        Returns true if the original request must be resent.
        i‘  Fzwww-authenticaterY   ú ÚdigestNr   r3   r‰   )ÚstatusÚheadersrl   Ú	partitionÚlowerrB   rQ   r*   rW   ÚoriginrS   ro   r;   rŠ   r|   r   re   r   Úbool)rT   r-   Úauth_headerrV   Úsepr�   Zheader_pairsr†   r1   r“   r   r,   r    r    r!   Ú_authenticateŠ  s8    



z"DigestAuthMiddleware._authenticate)ÚrequestÚhandlerr2   c                 Ã   s€   d}t dƒD ]b}|dks0| jrR| jrR|  |j¡rR|  |j|j|j¡I dH |jt	j
< ||ƒI dH }|  |¡s qpq|dus|J ‚|S )zRun the digest auth middleware.Né   r   )ÚrangerR   rQ   rŒ   rW   r‡   rV   rX   r�   r   ZAUTHORIZATIONr—   )rT   r˜   r™   r-   Zretry_countr    r    r!   Ú__call__Å  s"    ÿþ
ýÿ
zDigestAuthMiddleware.__call__)T)r   r   r   Ú__doc__r   r”   rU   r   r
   r   r   r‡   rŒ   r   r—   r   r   rœ   r    r    r    r!   rC   š   s"   " üûþ $<þrC   )4r�   rs   rw   ÚreÚsysru   Útypingr   r   r   r   r   r   r   r	   r
   Zyarlr   rY   r   Zclient_exceptionsr   Zclient_middlewaresr   Zclient_reqrepr   r   Úpayloadr   r   Úmd5rt   Úsha256Úsha512r'   r   rp   r   ÚcompileÚversion_infor@   r*   ÚtupleÚsortedÚkeysr+   Ú	frozensetr0   r8   r9   rB   rC   r    r    r    r!   Ú<module>   sZ   	,ô ÿýü
ÿÿ$ÿ