JFIF$        dd7 

Viewing File: /usr/lib/python3.9/site-packages/josepy/__pycache__/json_util.cpython-39.pyc

a

�BgtH�	@s�dZddlZddlZddlZddlmZmZmZmZm	Z	m
Z
mZmZm
Z
ddlmZddlmZmZmZmZe�e�Zd/eeeeeegefeeegefed�dd	�ZGd
d�d�ZGdd
�d
e�ZGdd�dej�Ze
ddd�ZGdd�dej ej!ed�Z"e#ed�dd�Z$d0eee%ee#d�dd�Z&e#ed�dd�Z'd1eee%ee#d�dd �Z(ej)ed!�d"d#�Z*eej)d$�d%d&�Z+ej)ed'�d(d)�Z,eej)d$�d*d+�Z-e
d,d-d�Z.Gd.d-�d-e"�Z/dS)2z�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)	�Any�Callable�Dict�Iterable�List�Mapping�Optional�Type�TypeVar)�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�4/usr/lib/python3.9/site-packages/josepy/json_util.py�fields
�rc	@s�eZdZdZdZdeeeee	egefee	egefdd�dd�Z
eeed�d	d
��Zeed�dd�Z
edd
�dd�Ze	egefdd�dd�Ze	egefdd�dd�Zeed�dd�Zeed�dd�Zeeed�dd��Zeeed�dd��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�fencNFrcCs>||_||_||_|dur |jn||_|dur4|jn||_dS�N)rrr�default_decoderr�default_encoderr)�selfrrrrrrrr�__init__Rs
zField.__init__��valuercCst|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�_emptyaszField._emptycCs|�|�o|jS)zOmit the value in output?)r*r�r"r%rrr�omitksz
Field.omit��kwargsrcKs0|j|j|j|j|jd�|�}t|�fi|��S)Nr)rrrrr�type)r"r.�currentrrr�_update_paramsos��zField._update_params)rrcCs|j|d�S)z6Descriptor to change the decoder on JSON object field.)r�r1)r"rrrrrzsz
Field.decoder)rrcCs|j|d�S)z6Descriptor to change the encoder on JSON object field.)rr2)r"rrrrr~sz
Field.encodercCs
|�|�S)z4Decode a value, optionally with context JSON object.)rr+rrr�decode�szField.decodecCs
|�|�S)z4Encode a value, optionally with context JSON object.)rr+rrr�encode�szField.encodecsNt|t�r t�fdd�|D��St|t�rFt��fdd�|��D��S|SdS)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 )�.0Zsubvalue�r)rr�	<genexpr>��z(Field.default_decoder.<locals>.<genexpr>cs"i|]\}}��|���|��qSrr5)r6�keyr%r7rr�
<dictcomp>�s�z)Field.default_decoder.<locals>.<dictcomp>N)r&�list�tuple�dictrZ
frozendict�itemsr(rr7rr �s



��zField.default_decodercCs|S)zDefault (passthrough) encoder.rr(rrrr!�szField.default_encoder)NFNN)�__name__�
__module__�__qualname__�__doc__�	__slots__�strrr'rrr#�classmethodr*r,r1rrr3r4r r!rrrrr7s4��	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)r@rArBrCrrrrr�src@sReZdZUdZiZeeefed<e	eed<ee
eeeefdd�dd�ZdS)�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�_orig_slots)�name�bases�	namespacercCs�i}|D]}|�t|di��q|����D]P\}}t|t�r,t|t�rn||�di�vrntd|�d|�d���|�	|�||<q,|�dd�|d<t
t|d�t|����|d<||d<t
j�||||�S)	NrH�__annotations__zField `z` in JSONObject `z` has no type annotation.rDrrI)�update�getattr�copyr?r&rr�get�
ValueError�popr=r<�keys�abc�ABCMeta�__new__)ZmcsrJrKrL�fields�baser:r%rrrrW�s

� z JSONObjectWithFieldsMeta.__new__N)
r@rArBrCrHrrErrMrrrrWrrrrrG�s
'�rG�GenericJSONObjectWithFields�JSONObjectWithFields)�boundcs�eZdZdZeeeefd�dd��Zedd��fdd�Z	eed	�d
d�Z
eeefd�dd
�Zeeefd�dd�Zee
eefdd�dd��Zee
eefed�dd��Zeeee
eefed�dd��Z�ZS)r[a�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)r6�slotrrrrr;r9z2JSONObjectWithFields._defaults.<locals>.<dictcomp>)rHr?r7rrr�	_defaultsszJSONObjectWithFields._defaultsNr-cs"t�jfii|���|���dSr)�superr#r_)r"r.��	__class__rrr#szJSONObjectWithFields.__init__)rJrcCsBz|j|}Wn"ty0t�d�|���Yn0|�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})rH�KeyErrorr
�Error�formatr4rO)r"rJrrrrr4s
	zJSONObjectWithFields.encodecCs�i}t�}|j��D]|\}}t||�}|�|�r@|�||f�qz|�|�||j<Wqtj	y�}z t�	d�
|||���WYd}~qd}~00q|S)zSerialize fields to JSON.zCould not encode {0} ({1}): {2}N)�setrHr?rOr,�addr4rr
ZSerializationErrorre)r"�jobjZomittedr^rr%�errorrrr�fields_to_partial_json/s

�z+JSONObjectWithFields.fields_to_partial_jsoncCs|��Sr)rj)r"rrr�to_partial_jsonAsz$JSONObjectWithFields.to_partial_json�rhrcCsTt�}|j��D]$\}}|js|j|vr|�|j�q|rPt�d�d�	|����dS)Nz&The following fields are required: {0}�,)
rfrHr?rrrgr
�DeserializationErrorre�join)r)rh�missing�_rrrr�_check_requiredDs�z$JSONObjectWithFields._check_requiredcCs�|�|�i}|j��D]|\}}|j|vr<|jr<|j||<q||j}z|�|�||<Wqtjy�}z t�d�	|||���WYd}~qd}~00q|S)zDeserialize fields from JSON.z#Could not decode {0!r} ({1!r}): {2}N)
rrrHr?rrrr3r
rnre)r)rhrXr^rr%rirrr�fields_from_jsonPs

�z%JSONObjectWithFields.fields_from_json)r)rhrcCs|fi|�|���Sr)rs)r)rhrrr�	from_jsonbszJSONObjectWithFields.from_json)r@rArBrCrFrrErr_r#r4rjrkrrrrsr	rZrt�
__classcell__rrrarr[�s�)�	metaclass)�datarcCst�|��d�S)zJEncode JOSE Base-64 field.

    :param bytes data:
    :rtype: `str`

    �ascii)rZ	b64encoder3)rwrrr�encode_b64joseisry)rw�size�minimumrc
Cs�zt�|���}Wn0tjyB}zt�|��WYd}~n
d}~00|dur||s\t|�|ksl|r|t|�|kr|t�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)	rZ	b64decoder4�binasciirdr
rn�lenre)rwrzr{Zdecodedrirrr�decode_b64josets �
��
�r~r$cCst�|���S)z;Hexlify.

    :param bytes value:
    :rtype: unicode

    )r|Zhexlifyr3)r%rrr�encode_hex16�sr)r%rzr{rc
Cs�|��}|dur@|s$t|�|dks8|r@t|�|dkr@t���zt�|�WStjy|}zt�|��WYd}~n
d}~00dS)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�)r4r}r
rnr|Z	unhexlifyrd)r%rzr{Zvalue_brirrr�decode_hex16�s����r�)�certrcCs*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&�wrappedrZX509ReqrRryZdump_certificate�
FILETYPE_ASN1)r�rrr�encode_cert�sr�)�b64derrc
CsPzt�t�tjt|���WStjyJ}zt�|��WYd}~n
d}~00dS)z�Decode JOSE Base-64 DER-encoded certificate.

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

    N)	r�ComparableX509rZload_certificater�r~rdr
rn�r�rirrr�decode_cert�s�r�)�csrrcCs*t|jtj�rtd��tt�tj|j��S)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�rZX509rRryZdump_certificate_requestr�)r�rrr�
encode_csr�sr�c
CsPzt�t�tjt|���WStjyJ}zt�|��WYd}~n
d}~00dS)z�Decode JOSE Base-64 DER-encoded CSR.

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

    N)	rr�rZload_certificate_requestr�r~rdr
rnr�rrr�
decode_csr�s�r�� GenericTypedJSONObjectWithFields�TypedJSONObjectWithFieldsc@s�eZdZUdZeZeed<dZeed<eZ	e
eefed<edee
eeee
d�dd	��Zeeeefedd
�dd��Ze
eefd
�dd�Zeeeefdd
�dd��ZdS)r�zJSON object with type.�typr/�type_field_name�TYPESN)�type_clsr�rcCs |dur|jn|}||j|<|S)z(Register class for JSON deserialization.N)r�r�)r)r�r�rrr�register�s
z"TypedJSONObjectWithFields.registerrlcCs�||j��vr.|j|vr*t�d�|j���|St|t�sHt�d�|���z||j}Wntyrt�d��Yn0z|j|WSty�t�	||��Yn0dS)z&Get the registered class for ``jobj``.zMissing type field ({0})z{0} is not a dictionary objectzmissing type fieldN)
r��valuesr�r
rnrer&r>rcZUnrecognizedTypeError)r)rhr�rrr�get_type_clss 

�
z&TypedJSONObjectWithFields.get_type_clsr]cCs|��}|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

        )rjr�r�)r"rhrrrrks	z)TypedJSONObjectWithFields.to_partial_jsoncCs|�|�}|fi|�|���S)z�Deserialize ACME object from valid JSON object.

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

        )r�rs)r)rhr�rrrrt(s	
z#TypedJSONObjectWithFields.from_json)N)r@rArBrC�NotImplementedr�rErMr�r�rr	rFr�rr�rrr�rkrtrrrrr��s
��
)NFNN)NF)NF)0rCrUr|Zlogging�typingrrrrrrrr	r
ZOpenSSLrZjosepyrr
rrZ	getLoggerr@�loggerrEr'rrrrVrGrZZImmutableMapZJSONDeSerializabler[�bytesry�intr~rr�r�r�r�r�r�r�r�rrrr�<module>sL,
��q	F

�o


�
Back to Directory  nL+D550H?Mx ,D"v]qv;6*Zqn)ZP0!1 A "#a$2Qr D8 a Ri[f\mIykIw0cuFcRı?lO7к_f˓[C$殷WF<_W ԣsKcëIzyQy/_LKℂ;C",pFA:/]=H  ~,ls/9ć:[=/#f;)x{ٛEQ )~ =𘙲r*2~ a _V=' kumFD}KYYC)({ *g&f`툪ry`=^cJ.I](*`wq1dđ#̩͑0;H]u搂@:~וKL Nsh}OIR*8:2 !lDJVo(3=M(zȰ+i*NAr6KnSl)!JJӁ* %݉?|D}d5:eP0R;{$X'xF@.ÊB {,WJuQɲRI;9QE琯62fT.DUJ;*cP A\ILNj!J۱+O\͔]ޒS߼Jȧc%ANolՎprULZԛerE2=XDXgVQeӓk yP7U*omQIs,K`)6\G3t?pgjrmۛجwluGtfh9uyP0D;Uڽ"OXlif$)&|ML0Zrm1[HXPlPR0'G=i2N+0e2]]9VTPO׮7h(F*癈'=QVZDF,d߬~TX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