
    Ld,                         d dl mZmZmZmZ d dlmZmZmZ d dl	m
Z
mZmZmZmZ ddlmZmZ  G d de          Zd Zd	 Zd
 ZdS )    )to_bytes
to_unicodeurlsafe_b64encodejson_b64encode)extract_headerextract_segmentensure_dict)DecodeErrorMissingAlgorithmErrorUnsupportedAlgorithmErrorBadSignatureErrorInvalidHeaderParameterNameError   )	JWSHeader	JWSObjectc                       e Zd Z eg d          Z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S )JsonWebSignature)algjkujwkkidx5ux5cx5tzx5t#S256typctycritNc                 "    || _         || _        d S N)_private_headers_algorithms)self
algorithmsprivate_headerss      >F:\djangOuth\env\Lib\site-packages\authlib/jose/rfc7515/jws.py__init__zJsonWebSignature.__init__!   s     /%    c                     |r|j         dk    r"t          d                    |                    || j        |j        <   d S )NJWSzInvalid algorithm for JWS, {!r})algorithm_type
ValueErrorformatALGORITHMS_REGISTRYname)cls	algorithms     r%   register_algorithmz#JsonWebSignature.register_algorithm%   sS     	EI4==188CCE E E2;	///r'   c                    t          |d          }|                     |           |                     |||          \  }}t          |j                  }t          t          |                    }d                    ||g          }t          |                    ||                    }	d                    |||	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_prepare_algorithm_keyr   	protectedr   r   joinsign)
r"   r6   payloadkey
jws_headerr0   protected_segmentpayload_segmentsigning_input	signatures
             r%   serialize_compactz"JsonWebSignature.serialize_compact,   s      y$//
&&y11144YMM	3*:+?@@+HW,=,=>> 		#4o"FGG%inn]C&H&HII	yy+_iHIIIr'   c                    	 t          |          }|                    dd          \  }}|                    dd          \  }}n# t          $ r t	          d          w xY wt          |          }t          |d          }	t          |          }
|r ||
          }
t          |          }t          |	|
d          }| 
                    |	|
|          \  }}|                    |||          r|S t          |          )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
        r3   r   zNot enough segmentsNcompact)r   rsplitsplitr+   r
   _extract_headerr   _extract_payload_extract_signaturer   r5   verifyr   )r"   sr:   decoder>   signature_segmentr<   r=   r6   r;   r9   r?   rvr0   s                 r%   deserialize_compactz$JsonWebSignature.deserialize_compactH   s   	5A/0xxa/@/@,M,1>1D1DT11M1M. 	5 	5 	53444	5 $$566	y$//
"?33 	&fWooG&'899	z7I6644Z#NN	3M9c:: 	I###s   AA Ac                     t                     fdt          |t                    r1 t          j        |                    }t                    |d<   |S fd|D             }t                    |dS )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                 b   
                     |            
                    |           \  }}t          | j                  }d                    |	g          }t          |                    ||                    }t          |          t          |          d}| j        
| j        |d<   |S )Nr3   )r6   r?   header)	r4   r5   r   r6   r7   r   r8   r   rP   )r;   _alg_keyr<   r>   r?   rL   r:   r9   r=   r"   s          r%   _signz.JsonWebSignature.serialize_json.<locals>._sign   s    **:66644Z#NNJD$ .z/C D D II'8/&JKKM)$))M4*H*HIII ((9::'	22 B  ,)08Ir'   r9   c                 J    g | ]} t          j        |                     S  )r   	from_dict).0hrS   s     r%   
<listcomp>z3JsonWebSignature.serialize_json.<locals>.<listcomp>   s.    HHHeeI/2233HHHr'   )r9   
signatures)r   
isinstancedictr   rV   r   )r"   
header_objr9   r:   datarZ   rS   r=   s   ` ``  @@r%   serialize_jsonzJsonWebSignature.serialize_jsonj   s    ( )11	 	 	 	 	 	 	 	  j$'' 	5,Z8899D(99DOKHHHHZHHH
!/22$
 
 	
r'   c                    t          |d          }|                    d          }|t          d          t          |          }t	          |          }|r ||          }d|vr?|                     ||||          \  }}t          ||d          }|r|S t          |          g }	d}
|d         D ]6}|                     ||||          \  }}|	                    |           |sd}
7t          |	|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)   r9   NzMissing "payload" valuerZ   flatTFjson)	r	   getr
   r   rF   _validate_json_jwsr   r   append)r"   objr:   rJ   r=   r9   r;   validrL   headersis_validr]   s               r%   deserialize_jsonz!JsonWebSignature.deserialize_json   sQ    #u%%''),,"7888"?33"?33 	&fWooGs"" $ 7 7#s!4 !4J :w77B 	#B'''l+ 	! 	!J $ 7 7*c!; !;JNN:&&& ! w00 	I###r'   c                     t          |t          t          f          r|                     |||          S d|v r|                     |||          S |                     |||          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
        r6   )r[   listtupler_   r@   )r"   rP   r9   r:   s       r%   	serializezJsonWebSignature.serialize   sm     ftUm,, 	=&&vw<<<&  &&vw<<<%%fgs;;;r'   c                 (   t          |t                    r|                     |||          S t          |          }|                    d          r,|                    d          r|                     |||          S |                     |||          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\   rj   r   
startswithendswithrM   )r"   rI   r:   rJ   s       r%   deserializezJsonWebSignature.deserialize   s     a 	9((C888QKK<< 	9!**T"2"2 	9((C888''3777r'   c                 @   d|vrt                      |d         }| j        || j        vrt                      || j        vrt                      | j        |         }t	          |          r |||          }n|d|v r|d         }|                    |          }||fS )Nr   r   )r   r!   r   r-   callableprepare_key)r"   rP   r9   r:   r   r0   s         r%   r5   z'JsonWebSignature._prepare_algorithm_key   s    ')))Um'Ct7G,G,G+---d...+---,S1	C== 	 #fg&&CC[Uf__-C##C((#~r'   c                     | j         K| j                                        }|                    | j                   }|D ]}||vrt	          |          d S d S r   )r    !REGISTERED_HEADER_PARAMETER_NAMEScopyunionr   )r"   rP   namesks       r%   r4   z*JsonWebSignature._validate_private_headers  sr      ,:??AAEKK 566E = =E>>9!<<< " -,= =r'   c                 D   |                     d          }|st          d          |                     d          }|st          d          t          |          }t          |          }|                     d          }|r$t	          |t
                    st          d          t          ||          }	|                     |	||          \  }
}d                    ||g          }t          t          |                    }|

                    |||          r|	dfS |	d	fS )
Nr6   zMissing "protected" valuer?   zMissing "signature" valuerP   zInvalid "header" valuer3   TF)rc   r
   r   rE   r[   r\   r   r5   r7   rG   rH   )r"   r=   r9   r]   r:   r<   rK   r6   rP   r;   r0   r>   r?   s                r%   rd   z#JsonWebSignature._validate_json_jws  s1   &NN;77  	;9:::&NN;77  	;9:::$%677#$566	)) 	8*VT22 	86777y&11
44Z#NN	3		#4o"FGG&x0A'B'BCC	M9c:: 	$t##5  r'   )NNr   )__name__
__module____qualname__	frozensetry   r-   r&   classmethodr1   r@   rM   r_   rj   rn   rt   r5   r4   rd   rU   r'   r%   r   r      s
        )2	 3 3 3 ) )% & & & & < < [<J J J8 $  $  $  $D/
 /
 /
b.$ .$ .$ .$`< < <$8 8 8 8*  $	= 	= 	=! ! ! ! !r'   r   c                 ,    t          | t                    S r   )r   r
   )header_segments    r%   rE   rE   '  s    .+666r'   c                 .    t          | t          d          S )Nr?   r   r
   )rK   s    r%   rG   rG   +  s    ,k;GGGr'   c                 .    t          | t          d          S )Nr9   r   )r=   s    r%   rF   rF   /  s    ?KCCCr'   N)authlib.common.encodingr   r   r   r   authlib.jose.utilr   r   r	   authlib.jose.errorsr
   r   r   r   r   modelsr   r   objectr   rE   rG   rF   rU   r'   r%   <module>r      sE                                    ) ( ( ( ( ( ( (O! O! O! O! O!v O! O! O!d7 7 7H H HD D D D Dr'   