CasperSecurity

Current Path : /lib/python3/dist-packages/josepy/__pycache__/
Upload File :
Current File : //lib/python3/dist-packages/josepy/__pycache__/json_util.cpython-310.pyc

o

h9Ra�G�
@s�dZddlZddlZddlZddlmZmZmZmZm	Z	m
Z
mZddlm
Z
ddlZddlmZmZmZmZe�e�Z		d1deded	ed
eegefdeegefdefd
d�ZGdd�d�ZGdd�de�ZGdd�dej�ZGdd�dejejed�Z de!defdd�Z"d2dedee#dede!fdd�Z$de!defd d!�Z%d2dedee#dede!fd"d#�Z&d$ejj'defd%d&�Z(d'edejj'fd(d)�Z)d*ejj'defd+d,�Z*d'edejj'fd-d.�Z+Gd/d0�d0e �Z,dS)3z�JSON (de)serialization framework.

The framework presented here is somewhat based on `Go's "json" package`_
(especially the ``omitempty`` functionality).

.. _`Go's "json" package`: http://golang.org/pkg/encoding/json/

�N)�Dict�Type�Any�Callable�List�Mapping�Optional)�crypto)�b64�errors�
interfaces�utilF�	json_name�default�	omitempty�decoder�encoder�returncCst|||||d�S)a4Convenient function to declare a :class:`Field` with proper type annotations.

    This function allows to write the following code:

    import josepy
    class JSON(josepy.JSONObjectWithFields):
        typ: str = josepy.field('type')

        def other_type(self) -> str:
            return self.typ

    �rrrrr)�_TypedFieldr�r�2/usr/lib/python3/dist-packages/josepy/json_util.py�fields�rc
@seZdZdZdZ			d#dedededeegefd	eegefd
dfdd�Z	e
d
ed
efdd��Zd
ed
efdd�Zded
dfdd�Z
deegefd
dfdd�Zdeegefd
dfdd�Zd
ed
efdd�Zd
ed
efdd�Ze
d
ed
efdd ��Ze
d
ed
efd!d"��ZdS)$�Fielda�JSON object field.

    :class:`Field` is meant to be used together with
    :class:`JSONObjectWithFields`.

    ``encoder`` (``decoder``) is a callable that accepts a single
    parameter, i.e. a value to be encoded (decoded), and returns the
    serialized (deserialized) value. In case of errors it should raise
    :class:`~josepy.errors.SerializationError`
    (:class:`~josepy.errors.DeserializationError`).

    Note, that ``decoder`` should perform partial serialization only.

    :ivar str json_name: Name of the field when encoded to JSON.
    :ivar default: Default value (used when not present in JSON object).
    :ivar bool omitempty: If ``True`` and the field value is empty, then
        it will not be included in the serialized JSON object, and
        ``default`` will be used for deserialization. Otherwise, if ``False``,
        field is considered as required, value will always be included in the
        serialized JSON objected, and it must also be present when
        deserializing.

    )rrr�fdec�fencNFrrrrrrcCsD||_||_||_|dur|jn||_|dur|j|_dS||_dS�N)rrr�default_decoderr�default_encoderr)�selfrrrrrrrr�__init__Bs
zField.__init__�valuecCst|t�o|S)z�Is the provided value considered "empty" for this field?

        This is useful for subclasses that might want to override the
        definition of being empty, e.g. for some more exotic data types.

        )�
isinstance�bool��clsr!rrr�_emptyMszField._emptycCs|�|�o|jS)zOmit the value in output?)r&r�rr!rrr�omitWsz
Field.omit�kwargscKs0|j|j|j|j|jd�|�}t|�di|��S)Nrr)rrrrr�type)rr)�currentrrr�_update_params[s��zField._update_paramsrcC�|j|d�S)z6Descriptor to change the decoder on JSON object field.)r�r,)rrrrrrf�z
Field.decoderrcCr-)z6Descriptor to change the encoder on JSON object field.)rr.)rrrrrrjr/z
Field.encodercC�
|�|�S)z4Decode a value, optionally with context JSON object.)rr'rrr�decoden�
zField.decodecCr0)z4Encode a value, optionally with context JSON object.)rr'rrr�encoderr2zField.encodecsJt|t�rt�fdd�|D��St|t�r#t��fdd�|��D��S|S)z�Default decoder.

        Recursively deserialize into immutable types (
        :class:`josepy.util.frozendict` instead of
        :func:`dict`, :func:`tuple` instead of :func:`list`).

        c3s�|]}��|�VqdSr�r)�.0�subvalue�r%rr�	<genexpr>�s�z(Field.default_decoder.<locals>.<genexpr>cs"i|]
\}}��|���|��qSrr4)r5�keyr!r7rr�
<dictcomp>�s�z)Field.default_decoder.<locals>.<dictcomp>)r"�list�tuple�dictr
�
frozendict�itemsr$rr7rrvs



��zField.default_decodercCs|S)zDefault (passthrough) encoder.rr$rrrr�szField.default_encoder�NFNN)�__name__�
__module__�__qualname__�__doc__�	__slots__�strrr#rr �classmethodr&r(r,rrr1r3rrrrrrr(s2���
�	rc@seZdZdZdS)raSpecialized class to mark a JSON object field with typed annotations.

    This class is kept private because fields are supposed to be declared
    using the :function:`field` in this situation.

    In the future the :class:`Field` may be removed in favor of this one.N)rArBrCrDrrrrr�src@sLeZdZUdZiZeeefed<dede	edeee
fddfdd�Zd	S)
�JSONObjectWithFieldsMetaa�Metaclass for :class:`JSONObjectWithFields` and its subclasses.

    It makes sure that, for any class ``cls`` with ``__metaclass__``
    set to ``JSONObjectWithFieldsMeta``:

    1. All fields (attributes of type :class:`Field`) in the class
       definition are moved to the ``cls._fields`` dictionary, where
       keys are field attribute names and values are fields themselves.

    2. ``cls.__slots__`` is extended by all field attribute names
       (i.e. not :attr:`Field.json_name`). Original ``cls.__slots__``
       are stored in ``cls._orig_slots``.

    In a consequence, for a field attribute name ``some_field``,
    ``cls.some_field`` will be a slot descriptor and not an instance
    of :class:`Field`. For example::

      some_field = Field('someField', default=())

      class Foo:
          __metaclass__ = JSONObjectWithFieldsMeta
          __slots__ = ('baz',)
          some_field = some_field

      assert Foo.__slots__ == ('some_field', 'baz')
      assert Foo._orig_slots == ()
      assert Foo.some_field is not Field

      assert Foo._fields.keys() == ['some_field']
      assert Foo._fields['some_field'] is some_field

    As an implementation note, this metaclass inherits from
    :class:`abc.ABCMeta` (and not the usual :class:`type`) to mitigate
    the metaclass conflict (:class:`ImmutableMap` and
    :class:`JSONDeSerializable`, parents of :class:`JSONObjectWithFields`,
    use :class:`abc.ABCMeta` as its metaclass).

    �_fields�name�bases�	namespacercCs�i}|D]}|�t|di��q|����D](\}}t|t�r>t|t�r7||�di�vr7td|�d|�d���|�	|�||<q|�dd�|d<t
t|d�t|����|d<||d<t
j�||||�S)	NrI�__annotations__zField `z` in JSONObject `z` has no type annotation.rEr�_orig_slots)�update�getattr�copyr?r"rr�get�
ValueError�popr<r;�keys�abc�ABCMeta�__new__)�mcsrJrKrL�fields�baser9r!rrrrX�s$

���z JSONObjectWithFieldsMeta.__new__N)rArBrCrDrIrrFrrMrrrXrrrrrH�s
'
��rHcs�eZdZdZedeeeffdd��Zdeddf�fdd�Z	d	edefd
d�Z
deeeffdd
�Zdeeeffdd�Zede
eefddfdd��Zede
eefdefdd��Zedeeefddfdd��Z�ZS)�JSONObjectWithFieldsa�JSON object with fields.

    Example::

      class Foo(JSONObjectWithFields):
          bar = Field('Bar')
          empty = Field('Empty', omitempty=True)

          @bar.encoder
          def bar(value):
              return value + 'bar'

          @bar.decoder
          def bar(value):
              if not value.endswith('bar'):
                  raise errors.DeserializationError('No bar suffix!')
              return value[:-3]

      assert Foo(bar='baz').to_partial_json() == {'Bar': 'bazbar'}
      assert Foo.from_json({'Bar': 'bazbar'}) == Foo(bar='baz')
      assert (Foo.from_json({'Bar': 'bazbar', 'Empty': '!'})
              == Foo(bar='baz', empty='!'))
      assert Foo(bar='baz').bar == 'baz'

    rcCsdd�|j��D�S)zGet default fields values.cSsi|]\}}||j�qSr)r)r5�slotrrrrr:�s�z2JSONObjectWithFields._defaults.<locals>.<dictcomp>)rIr?r7rrr�	_defaults�s�zJSONObjectWithFields._defaultsr)Ncs"t�jdii|���|���dS�Nr)�superr r^)rr)��	__class__rrr s

�zJSONObjectWithFields.__init__rJcCs>z|j|}Wntyt�d�|���w|�t||��S)z�Encode a single field.

        :param str name: Name of the field to be encoded.

        :raises errors.SerializationError: if field cannot be serialized
        :raises errors.Error: if field could not be found

        zField not found: {0})rI�KeyErrorr�Error�formatr3rP)rrJrrrrr3s	�zJSONObjectWithFields.encodecCs�i}t�}|j��D]7\}}t||�}|�|�r |�||f�q
z
|�|�||j<Wq
tj	yA}z
t�	d�
|||���d}~ww|S)zSerialize fields to JSON.zCould not encode {0} ({1}): {2}N)�setrIr?rPr(�addr3rr�SerializationErrorre)r�jobj�omittedr]rr!�errorrrr�fields_to_partial_jsons"

����z+JSONObjectWithFields.fields_to_partial_jsoncCs|��Sr)rl)rrrr�to_partial_json)sz$JSONObjectWithFields.to_partial_jsonricCsTt�}|j��D]\}}|js|j|vr|�|j�q|r(t�d�d�	|����dS)Nz&The following fields are required: {0}�,)
rfrIr?rrrgr�DeserializationErrorre�join)r%ri�missing�_rrrr�_check_required,s����z$JSONObjectWithFields._check_requiredcCs�|�|�i}|j��D]7\}}|j|vr|jr|j||<q||j}z	|�|�||<WqtjyC}z
t�d�	|||���d}~ww|S)zDeserialize fields from JSON.z#Could not decode {0!r} ({1!r}): {2}N)
rsrIr?rrrr1rrore)r%rirZr]rr!rkrrr�fields_from_json8s"

����z%JSONObjectWithFields.fields_from_jsoncCs|di|�|���Sr_)rt)r%rirrr�	from_jsonJszJSONObjectWithFields.from_json)rArBrCrDrGrrFrr^r r3rlrmrrsrtru�
__classcell__rrrarr\�s$r\)�	metaclass�datacCst�|��d�S)zJEncode JOSE Base-64 field.

    :param bytes data:
    :rtype: `str`

    �ascii)r
�	b64encoder1)rxrrr�encode_b64joseOsr{�size�minimumc
Cstz	t�|���}Wntjy}zt�|��d}~ww|dur8|s(t|�|ks0|r8t|�|kr8t�d�|���|S)aDecode JOSE Base-64 field.

    :param unicode data:
    :param int size: Required length (after decoding).
    :param bool minimum: If ``True``, then `size` will be treated as
        minimum required length, as opposed to exact equality.

    :rtype: bytes

    Nz&Expected at least or exactly {0} bytes)	r
�	b64decoder3�binasciirdrro�lenre)rxr|r}�decodedrkrrr�decode_b64joseZs
����r�r!cCst�|���S)z;Hexlify.

    :param bytes value:
    :rtype: unicode

    )r�hexlifyr1)r!rrr�encode_hex16rsr�c
Csr|��}|dur |st|�|dks|r t|�|dkr t���zt�|�WStjy8}zt�|��d}~ww)aDecode hexlified field.

    :param unicode value:
    :param int size: Required length (after decoding).
    :param bool minimum: If ``True``, then `size` will be treated as
        minimum required length, as opposed to exact equality.

    :rtype: bytes

    N�)r3r�rror�	unhexlifyrd)r!r|r}�value_brkrrr�decode_hex16|s�
��r��certcC�*t|jtj�rtd��tt�tj|j��S)z�Encode certificate as JOSE Base-64 DER.

    :type cert: `OpenSSL.crypto.X509` wrapped in `.ComparableX509`
    :rtype: unicode

    z.Error input is actually a certificate request.)r"�wrappedr	�X509ReqrSr{�dump_certificate�
FILETYPE_ASN1)r�rrr�encode_cert��
�r��b64derc
C�@z
t�t�tjt|���WStjy}zt�|��d}~ww)z�Decode JOSE Base-64 DER-encoded certificate.

    :param unicode b64der:
    :rtype: `OpenSSL.crypto.X509` wrapped in `.ComparableX509`

    N)	r
�ComparableX509r	�load_certificater�r�rdrro�r�rkrrr�decode_cert��
�
��r��csrcCr�)zEncode CSR as JOSE Base-64 DER.

    :type csr: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509`
    :rtype: unicode

    z&Error input is actually a certificate.)r"r�r	�X509rSr{�dump_certificate_requestr�)r�rrr�
encode_csr�r�r�c
Cr�)z�Decode JOSE Base-64 DER-encoded CSR.

    :param unicode b64der:
    :rtype: `OpenSSL.crypto.X509Req` wrapped in `.ComparableX509`

    N)	r
r�r	�load_certificate_requestr�r�rdrror�rrr�
decode_csr�r�r�c	@s�eZdZUdZeZeed<	dZeed<	eZ	e
eefed<	e	ddedde
ededfd	d
��Zedeeefdedfdd
��Zde
eeffdd�Zedeeefddfdd��ZdS)�TypedJSONObjectWithFieldszJSON object with type.�typr*�type_field_name�TYPESN�type_clsrcCs |dur|jn|}||j|<|S)z(Register class for JSON deserialization.N)r�r�)r%r�r�rrr�register�s
z"TypedJSONObjectWithFields.registerricCs�||j��vr|j|vrt�d�|j���|St|t�s$t�d�|���z||j}Wnty7t�d��wz|j|WStyKt�	||��w)z&Get the registered class for ``jobj``.zMissing type field ({0})z{0} is not a dictionary objectzmissing type field)
r��valuesr�rrorer"r=rc�UnrecognizedTypeError)r%rir�rrr�get_type_cls�s(

�
�
��z&TypedJSONObjectWithFields.get_type_clscCs|��}|j||j<|S)aGet JSON serializable object.

        :returns: Serializable JSON object representing ACME typed object.
            :meth:`validate` will almost certainly not work, due to reasons
            explained in :class:`josepy.interfaces.IJSONSerializable`.
        :rtype: dict

        )rlr�r�)rrirrrrm�s	z)TypedJSONObjectWithFields.to_partial_jsoncCs|�|�}|di|�|���S)z�Deserialize ACME object from valid JSON object.

        :raises josepy.errors.UnrecognizedTypeError: if type
            of the ACME object has not been registered.

        Nr)r�rt)r%rir�rrrrus
	z#TypedJSONObjectWithFields.from_jsonr)rArBrCrD�NotImplementedr�rFrMr�r�rrrGrr�rrr�rmrurrrrr��s(
��� 
 r�r@)NF)-rDrVr�logging�typingrrrrrrr�OpenSSLr	�josepy.util�josepyr
rrr
�	getLoggerrA�loggerrFr#rrrrWrH�ImmutableMap�JSONDeSerializabler\�bytesr{�intr�r�r�r�r�r�r�r�r�rrrr�<module>sD$
���
�i	D�q  

Hacker Blog, Shell İndir, Sql İnjection, XSS Attacks, LFI Attacks, Social Hacking, Exploit Bot, Proxy Tools, Web Shell, PHP Shell, Alfa Shell İndir, Hacking Training Set, DDoS Script, Denial Of Service, Botnet, RFI Attacks, Encryption
Telegram @BIBIL_0DAY