
    Ki5                         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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mZ ddlmZ ddlmZ  G d d      Zd Zd Zd Zy)    )json_b64encode)to_bytes)
to_unicode)urlsafe_b64encode)BadSignatureError)DecodeError)#InvalidCritHeaderParameterNameErrorInvalidHeaderParameterNameError)MissingAlgorithmError)UnsupportedAlgorithmError)ensure_dict)extract_header)extract_segment   )	JWSHeader)	JWSObjectc                       e Zd ZU  eg d      ZdZeed<   i ZddZ	e
d        Zd ZddZd	 Zdd
Zd ZddZd Zd Zd Zd Zd Zy)JsonWebSignature)algjkujwkkidx5ux5cx5tzx5t#S256typctycriti  MAX_CONTENT_LENGTHNc                      || _         || _        y N)_private_headers_algorithms)self
algorithmsprivate_headerss      d/home/jay/workspace/scripts/.codegraph-venv/lib/python3.12/site-packages/authlib/jose/rfc7515/jws.py__init__zJsonWebSignature.__init__*   s     /%    c                 t    |r|j                   dk7  rt        d|      || j                  |j                  <   y )NJWSzInvalid algorithm for JWS, )algorithm_type
ValueErrorALGORITHMS_REGISTRYname)cls	algorithms     r(   register_algorithmz#JsonWebSignature.register_algorithm.   s9    I44=:9-HII2;	/r*   c                 `   t        |d      }| j                  |       | j                  |       | j                  |||      \  }}t	        |j
                        }t        t        |            }dj                  ||g      }t        |j                  ||            }	dj                  |||	g      S )a"  Generate a JWS Compact Serialization. The JWS Compact Serialization
        represents digitally signed or MACed content as a compact, URL-safe
        string, per `Section 7.1`_.

        .. code-block:: text

            BASE64URL(UTF8(JWS Protected Header)) || '.' ||
            BASE64URL(JWS Payload) || '.' ||
            BASE64URL(JWS Signature)

        :param protected: A dict of protected header
        :param payload: A bytes/string of payload
        :param key: Private key used to generate signature
        :return: byte
        N   .)
r   _validate_private_headers_validate_crit_headers_prepare_algorithm_keyr   	protectedr   r   joinsign)
r%   r9   payloadkey
jws_headerr2   protected_segmentpayload_segmentsigning_input	signatures
             r(   serialize_compactz"JsonWebSignature.serialize_compact4   s      y$/
&&y1##I.44YM	3*:+?+?@+HW,=> 		#4o"FG%inn]C&HI	yy+_iHIIr*   c                    t        |      | j                  kD  rt        d      	 t        |      }|j	                  dd      \  }}|j                  dd      \  }}t        |      }	| j                  |	       t        |	d      }
t        |      }|r ||      }t        |      }t        |
|d      }| j                  |
||      \  }}|j                  |||      r|S t        |      # t        $ r}t        d      |d}~ww xY w)a  Exact JWS Compact Serialization, and validate with the given key.
        If key is not provided, the returned dict will contain the signature,
        and signing input values. Via `Section 7.1`_.

        :param s: text of JWS Compact Serialization
        :param key: key used to verify the signature
        :param decode: a function to decode payload data
        :return: JWSObject
        :raise: BadSignatureError

        .. _`Section 7.1`: https://tools.ietf.org/html/rfc7515#section-7.1
        zSerialization is too long.r5   r   zNot enough segmentsNcompact)lenr    r.   r   rsplitsplitr   _extract_headerr7   r   _extract_payload_extract_signaturer   r8   verifyr   )r%   sr=   decoderA   signature_segmentr?   r@   excr9   r>   r<   rB   rvr2   s                  r(   deserialize_compactz$JsonWebSignature.deserialize_compactQ   s    q6D+++9::	>A/0xxa/@,M,1>1D1DT11M. $$56	##I.y$/
"?3WoG&'89	z7I644Z#N	3M9c:I##!  	>34#=	>s   5C% %	C?.C::C?c                     t               fd}t        |t              r+ |t        j                  |            }t              |d<   |S |D cg c]  } |t        j                  |             }}t              |dS c c}w )a  Generate a JWS JSON Serialization. The JWS JSON Serialization
        represents digitally signed or MACed content as a JSON object,
        per `Section 7.2`_.

        :param header_obj: A dict/list of header
        :param payload: A string/dict of payload
        :param key: Private key used to generate signature
        :return: JWSObject

        Example ``header_obj`` of JWS JSON Serialization::

            {
                "protected: {"alg": "HS256"},
                "header": {"kid": "jose"}
            }

        Pass a dict to generate flattened JSON Serialization, pass a list of
        header dict to generate standard JSON Serialization.
        c                    
j                  |        
j                  | j                         
j                  | j                         
j                  |       \  }}t        | j                        }dj                  |	g      }t        |j                  ||            }t        |      t        |      d}| j                  | j                  |d<   |S )Nr5   )r9   rB   header)r6   _reject_unprotected_critrU   r7   r9   r8   r   r:   r   r;   r   )r>   _alg_keyr?   rA   rB   rQ   r=   r<   r@   r%   s          r(   _signz.JsonWebSignature.serialize_json.<locals>._sign   s    **:6 ))**;*;<''
(<(<=44Z#NJD$ .z/C/C D II'8/&JKM)$))M4*HII ((9:'	2B   ,)008Ir*   r<   )r<   
signatures)r   
isinstancedictr   	from_dictr   )	r%   
header_objr<   r=   rY   datahrZ   r@   s	   ` ``    @r(   serialize_jsonzJsonWebSignature.serialize_jsonw   s    ( )1	* j$',,Z89D(9DOK=GHeI//23H
H%o6jQQ Is   "B	c                    t        |d      }|j                  d      }|t        d      t        |      }t	        |      }|r ||      }d|vr3| j                  ||||      \  }}t        ||d      }|r|S t        |      g }	d}
|d   D ]/  }| j                  ||||      \  }}|	j                  |       |r.d}
1 t        |	|d      }|
r|S t        |      )	a  Exact JWS JSON Serialization, and validate with the given key.
        If key is not provided, it will return a dict without signature
        verification. Header will still be validated. Via `Section 7.2`_.

        :param obj: text of JWS JSON Serialization
        :param key: key used to verify the signature
        :param decode: a function to decode payload data
        :return: JWSObject
        :raise: BadSignatureError

        .. _`Section 7.2`: https://tools.ietf.org/html/rfc7515#section-7.2
        r,   r<   zMissing "payload" valuerZ   flatTFjson)	r   getr   r   rJ   _validate_json_jwsr   r   append)r%   objr=   rN   r@   r<   r>   validrQ   headersis_validr^   s               r(   deserialize_jsonz!JsonWebSignature.deserialize_json   s    #u%''),"788"?3"?3WoGs" $ 7 7#s!J :w7B	#B''l+ 	!J $ 7 7*c!J NN:& 	! w0I##r*   c                     t        |t        t        f      r| j                  |||      S d|v r| j                  |||      S | j	                  |||      S )a  Generate a JWS Serialization. It will automatically generate a
        Compact or JSON Serialization depending on the given header. If a
        header is in a JSON header format, it will call
        :meth:`serialize_json`, otherwise it will call
        :meth:`serialize_compact`.

        :param header: A dict/list of header
        :param payload: A string/dict of payload
        :param key: Private key used to generate signature
        :return: byte/dict
        r9   )r[   listtuplera   rC   )r%   rU   r<   r=   s       r(   	serializezJsonWebSignature.serialize   sY     ftUm,&&vw<<& &&vw<<%%fgs;;r*   c                     t        |t              r| j                  |||      S t        |      }|j	                  d      r$|j                  d      r| j                  |||      S | j                  |||      S )a  Deserialize JWS Serialization, both compact and JSON format.
        It will automatically deserialize depending on the given JWS.

        :param s: text of JWS Compact/JSON Serialization
        :param key: key used to verify the signature
        :param decode: a function to decode payload data
        :return: dict
        :raise: BadSignatureError

        If key is not provided, it will still deserialize the serialization
        without verification.
           {   })r[   r\   rl   r   
startswithendswithrR   )r%   rM   r=   rN   s       r(   deserializezJsonWebSignature.deserialize   sm     a((C88QK<<!**T"2((C88''377r*   c                 <   d|vr
t               |d   }|| j                  vr
t               | j                  |   }| j                  |j                  r"t               || j                  vr
t               t        |      r	 |||      }|j                  |      }||fS )Nr   )r   r/   r   r$   
deprecatedcallableprepare_key)r%   rU   r<   r=   r   r2   s         r(   r8   z'JsonWebSignature._prepare_algorithm_key  s    '))Umd...+--,,S1	###/11(((+--C=fg&C##C(#~r*   c                     | j                   L| j                  j                         }|j                  | j                         }|D ]  }||vst	        |       y y r"   )r#   !REGISTERED_HEADER_PARAMETER_NAMEScopyunionr   )r%   rU   namesks       r(   r6   z*JsonWebSignature._validate_private_headers  s^       ,::??AEKK 5 56E =E>9!<<=	 -r*   c                 (    |rd|v rt        d      yy)uG   Reject 'crit' when found in the unprotected header (RFC 7515 §4.1.11).r   Nr
   )r%   unprotected_headers     r(   rV   z)JsonWebSignature._reject_unprotected_crit"  s     &,>">1&99 #?r*   c                 >   d|v r|d   }t        |t              rt        d |D              st        d      | j                  j                         }| j                  r|j                  | j                        }|D ]   }||vrt        |      ||vst        |       y y )Nr   c              3   <   K   | ]  }t        |t                y wr"   )r[   str).0xs     r(   	<genexpr>z:JsonWebSignature._validate_crit_headers.<locals>.<genexpr>+  s      ='(
1c"=s   )	r[   rn   allr   r|   r}   r#   r~   r	   )r%   rU   crit_headersr   r   s        r(   r7   z'JsonWebSignature._validate_crit_headers'  s    V!&>LlD1 =,8= : 6f==::??AE$$D$9$9:! AE>=a@@f_=a@@	A r*   c                    |j                  d      }|st        d      |j                  d      }|st        d      t        |      }t        |      }|j                  d      }|rt	        |t
              st        d      | j                  |       | j                  |       t        ||      }	| j                  |	||      \  }
}dj                  ||g      }t        t        |            }|
j                  |||      r|	dfS |	d	fS )
Nr9   zMissing "protected" valuerB   zMissing "signature" valuerU   zInvalid "header" valuer5   TF)re   r   r   rI   r[   r\   rV   r7   r   r8   r:   rK   rL   )r%   r@   r<   r^   r=   r?   rO   r9   rU   r>   r2   rA   rB   s                r(   rf   z#JsonWebSignature._validate_json_jws8  s   &NN;7 9::&NN;7 9::$%67#$56	)*VT2677 	%%f-
 	##I.y&1
44Z#N	3		#4o"FG&x0A'BC	M9c:t##5  r*   )NNr"   )__name__
__module____qualname__	frozensetr|   r    int__annotations__r/   r)   classmethodr3   rC   rR   ra   rl   rp   rv   r8   r6   rV   r7   rf    r*   r(   r   r      s}    (1	
)%  %$ & < <
J:$$L1Rf0$d<$8*(	=:
A"!r*   r   c                 "    t        | t              S r"   )r   r   )header_segments    r(   rI   rI   W  s    .+66r*   c                 $    t        | t        d      S )NrB   r   r   )rO   s    r(   rK   rK   [  s    ,k;GGr*   c                 $    t        | t        d      S )Nr<   r   )r@   s    r(   rJ   rJ   _  s    ?KCCr*   N)authlib.common.encodingr   r   r   r   authlib.jose.errorsr   r   r	   r   r   r   authlib.jose.utilr   r   r   modelsr   r   r   rI   rK   rJ   r   r*   r(   <module>r      sP    2 , . 5 1 + C ? 5 9 ) , -  A! A!H
7HDr*   