HEX
Server: Apache
System: Linux srv1.prosuiteplus.com 5.4.0-216-generic #236-Ubuntu SMP Fri Apr 11 19:53:21 UTC 2025 x86_64
User: prosuiteplus (1001)
PHP: 8.3.20
Disabled: NONE
Upload Files
File: //lib/python3/dist-packages/josepy/__pycache__/json_util.cpython-38.pyc
U

��]�=�@s�dZddlZddlZddlZddlZddlZddlmZmZm	Z	m
Z
e�e�Z
Gdd�de�ZGdd�dej�Ze�e�Gdd	�d	e
je	j��Zd
d�Zdd
d�Zdd�Zddd�Zdd�Zdd�Zdd�Zdd�ZGdd�de�ZdS)z�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)�b64�errors�
interfaces�utilc@sreZdZdZdZddd�Zedd��Zd	d
�Zdd�Z	d
d�Z
dd�Zdd�Zdd�Z
edd��Zedd��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.

    )�	json_name�default�	omitempty�fdec�fencNFcCs>||_||_||_|dkr |jn||_|dkr4|jn||_dS�N)rrr	�default_decoderr
�default_encoderr)�selfrrr	�decoder�encoder�r�2/usr/lib/python3/dist-packages/josepy/json_util.py�__init__/s
zField.__init__cCst|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��cls�valuerrr�_empty9szField._emptycCs|�|�o|jS)zOmit the value in output?)rr	�rrrrr�omitCsz
Field.omitcKs4t|j|j|j|j|jd�}|�|�t|�f|�S)N)rrr	rr)�dictrrr	r
r�update�type)r�kwargsZcurrentrrr�_update_paramsGs
�
zField._update_paramscCs|j|d�S)z6Descriptor to change the decoder on JSON object field.)r�r!)rr
rrrrNsz
Field.decodercCs|j|d�S)z6Descriptor to change the encoder on JSON object field.)rr")rrrrrrRsz
Field.encodercCs
|�|�S)z4Decode a value, optionally with context JSON object.)r
rrrr�decodeVszField.decodecCs
|�|�S)z4Encode a value, optionally with context JSON object.)rrrrr�encodeZszField.encodecsTt|t�r t�fdd�|D��St|t�rLt�t�fdd�t�|�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�rrr�	<genexpr>isz(Field.default_decoder.<locals>.<genexpr>c3s&|]\}}��|���|�fVqdSrr%)r&�keyrr'rrr(ls�N)r�list�tuplerrZ
frozendict�six�	iteritemsrrr'rr
^s


��zField.default_decodercCs|S)zDefault (passthrough) encoder.rrrrrrqszField.default_encoder)NFNN)�__name__�
__module__�__qualname__�__doc__�	__slots__r�classmethodrrr!rrr#r$r
rrrrrrs$�


	
rc@seZdZdZdd�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(object):
          __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).

    cCs�i}|D]}|�t|di��qtt�|��D] \}}t|t�r.|�|�||<q.|�dd�|d<tt	|d�t	t�
|���|d<||d<tj�
||||�S)N�_fieldsr2rZ_orig_slots)r�getattrr+r,r-rr�pop�getr*Ziterkeys�abc�ABCMeta�__new__)Zmcs�name�basesZdikt�fields�baser)rrrrr;�s
�z JSONObjectWithFieldsMeta.__new__N)r.r/r0r1r;rrrrr4ys'r4csheZdZdZedd��Z�fdd�Zdd�Zdd	�Zd
d�Z	edd
��Z
edd��Zedd��Z�Z
S)�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'

    cCstdd�t�|j�D��S)zGet default fields values.cSsg|]\}}||jf�qSr)r)r&�slot�fieldrrr�
<listcomp>�sz2JSONObjectWithFields._defaults.<locals>.<listcomp>)rr,r-r5r'rrr�	_defaults�s
�zJSONObjectWithFields._defaultscs"tt|�jft|��f|��dSr)�superr@rrrD)rr ��	__class__rrr�s�zJSONObjectWithFields.__init__cCsDz|j|}Wn$tk
r2t�d�|���YnX|�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})r5�KeyErrorr�Error�formatr$r6)rr<rBrrrr$�s
	zJSONObjectWithFields.encodecCs�i}t�}t�|j�D]z\}}t||�}|�|�rB|�||f�qz|�|�||j<Wqt	j
k
r�}zt	�
d�|||���W5d}~XYqXq|S)zSerialize fields to JSON.zCould not encode {0} ({1}): {2}N)�setr,r-r5r6r�addr$rrZSerializationErrorrJ)r�jobjZomittedrArBr�errorrrr�fields_to_partial_json�s"

��z+JSONObjectWithFields.fields_to_partial_jsoncCs|��Sr)rO)rrrr�to_partial_json�sz$JSONObjectWithFields.to_partial_jsoncCsVt�}t�|j�D]$\}}|js|j|kr|�|j�q|rRt�d�	d�
|����dS)Nz&The following fields are required: {0}�,)rKr,r-r5r	rrLr�DeserializationErrorrJ�join)rrMZmissing�_rBrrr�_check_requireds��z$JSONObjectWithFields._check_requiredcCs�|�|�i}t�|j�D]z\}}|j|kr>|jr>|j||<q||j}z|�|�||<Wqtj	k
r�}zt�	d�
|||���W5d}~XYqXq|S)zDeserialize fields from JSON.z#Could not decode {0!r} ({1!r}): {2}N)rUr,r-r5rr	rr#rrRrJ)rrMr>rArBrrNrrr�fields_from_json
s"

��z%JSONObjectWithFields.fields_from_jsoncCs|f|�|��Sr)rV)rrMrrr�	from_jsonszJSONObjectWithFields.from_json)r.r/r0r1r3rDrr$rOrPrUrVrW�
__classcell__rrrFrr@�s


r@cCst�|��d�S)zNEncode JOSE Base-64 field.

    :param bytes data:
    :rtype: `unicode`

    �ascii)rZ	b64encoder#)�datarrr�encode_b64jose$sr[Fc
Cs�tjr
tntj}zt�|���}Wn,|k
rN}zt�	|��W5d}~XYnX|dk	r�|sht
|�|ksx|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)r,�PY2�	TypeError�binasciirIrZ	b64decoder$rrR�lenrJ)rZ�size�minimum�	error_clsZdecodedrNrrr�decode_b64jose/s�
��rccCst�|���S)z;Hexlify.

    :param bytes value:
    :rtype: unicode

    )r^Zhexlifyr#)rrrr�encode_hex16Hsrdc
Cs�|��}|dk	r@|s$t|�|dks8|r@t|�|dkr@t���tjrJtntj}zt�	|�WS|k
r�}zt�|��W5d}~XYnXdS)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�)
r$r_rrRr,r\r]r^rIZ	unhexlify)rr`rarbrNrrr�decode_hex16Rs��rfcCsttj�tjj|j��S)z�Encode certificate as JOSE Base-64 DER.

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

    )r[�OpenSSL�cryptoZdump_certificate�
FILETYPE_ASN1�wrapped)Zcertrrr�encode_cerths�rkc
CsTzt�tj�tjjt|���WStjjk
rN}zt�	|��W5d}~XYnXdS)z�Decode JOSE Base-64 DER-encoded certificate.

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

    N)
r�ComparableX509rgrhZload_certificaterircrIrrR�Zb64derrNrrr�decode_certss
�rncCsttj�tjj|j��S)zEncode CSR as JOSE Base-64 DER.

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

    )r[rgrhZdump_certificate_requestrirj)Zcsrrrr�
encode_csr�s�roc
CsTzt�tj�tjjt|���WStjjk
rN}zt�	|��W5d}~XYnXdS)z�Decode JOSE Base-64 DER-encoded CSR.

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

    N)
rrlrgrhZload_certificate_requestrircrIrrRrmrrr�
decode_csr�s
�rpc@sJeZdZdZeZdZeZeddd��Z	edd��Z
dd	�Zed
d��ZdS)
�TypedJSONObjectWithFieldszJSON object with type.rNcCs |dkr|jn|}||j|<|S)z(Register class for JSON deserialization.N)�typ�TYPES)r�type_clsrrrrr�register�s
z"TypedJSONObjectWithFields.registercCs�|t�|j�kr0|j|kr,t�d�|j���|St|t�sJt�d�|���z||j}Wnt	k
rvt�d��YnXz|j|WSt	k
r�t�
||��YnXdS)z&Get the registered class for ``jobj``.zMissing type field ({0})z{0} is not a dictionary objectzmissing type fieldN)r,Z
itervaluesrs�type_field_namerrRrJrrrHZUnrecognizedTypeError)rrMrrrrr�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

        )rOrrrv)rrMrrrrP�s	z)TypedJSONObjectWithFields.to_partial_jsoncCs|�|�}|f|�|��S)z�Deserialize ACME object from valid JSON object.

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

        )rwrV)rrMrtrrrrW�s	
z#TypedJSONObjectWithFields.from_json)N)
r.r/r0r1�NotImplementedrrrvrsr3rurwrPrWrrrrrq�s

rq)NF)NF)r1r9r^Zloggingrgr,ZjosepyrrrrZ	getLoggerr.Zlogger�objectrr:r4Z
add_metaclassZImmutableMapZJSONDeSerializabler@r[rcrdrfrkrnrorprqrrrr�<module>s(
d;o