o
    7cۅ                     @   s^  U d Z ddlZddlZddlZddlZddlmZmZmZm	Z	 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	ZW n eyN   d
ZeZY nw ddlmZmZmZ ddlmZmZmZ ddlm Z  ddl!m"Z" ddl#m$Z$m%Z%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/m0Z0 ddl1m2Z2m3Z3m4Z4m5Z5 ddl6m7Z7 ddl8m9Z9 ddl:m;Z; ddl<m=Z=m>Z> ddl?m@Z@ ddlAmBZBmCZC ddlDmEZE ddlFmGZG ddlHmIZI dZJd ZKd!ZLe e(ed"ZMe eNd#< e e%d$ZOejPd%d& ZQG d'd( d(eZRG d)d* d*eZSG d+d, d,eZTG d-d. d.eUejVZWG d/d0 d0eUejVZXG d1d2 d2eZYdS )3z8Support for explicit client-side field level encryption.    N)AnyMappingOptionalSequence)AutoEncrypter)MongoCryptError)ExplicitEncrypter)MongoCryptOptions)MongoCryptCallbackTF)_dict_to_bsondecodeencode)STANDARDUUID_SUBTYPEBinary)CodecOptions)	BSONError)DEFAULT_RAW_BSON_OPTIONSRawBSONDocument_inflate_bson)SON)_csot)Cursor)_spawn_daemon)AutoEncryptionOpts)ConfigurationErrorEncryptionErrorInvalidOperationServerSelectionTimeoutError)MongoClient)BLOCKING_IO_ERRORS)	UpdateOne)PoolOptions_configured_socket)ReadConcern)BulkWriteResultDeleteResult)get_ssl_context)
parse_host)WriteConcerni  
   i'  )document_classuuid_representation_DATA_KEY_OPTS)r+   c               
   c   s>    zdV  W dS  t y     ty }  zt| d} ~ ww )z2Context manager to wrap encryption related errors.N)r   	Exceptionr   )exc r0   P/var/www/milkbook_backend/env/lib/python3.10/site-packages/pymongo/encryption.py_wrap_encryption_errorsH   s   r2   c                   @   sT   e Zd Zdd Zdd Zdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd ZdS )_EncryptionIOc                 C   sT   |  |durt || _nd| _|jttddtddd| _|| _|| _	d| _
dS )z8Internal class to perform I/O on behalf of pymongocrypt.Nmajority)level)w)codec_optionsread_concernwrite_concernF)weakrefref
client_refwith_options_KEY_VAULT_OPTSr$   r)   key_vault_collmongocryptd_clientopts_spawned)selfclientr?   r@   rA   r0   r0   r1   __init__V   s   
z_EncryptionIO.__init__c                 C   s  |j }|j}|j}| jj|}|du rtddddddd}tt	t
d}t|||d}t|t\}}	t||	f|}
zAz-|
| |jdkrh|
tt	t
d |
|j}|s^td|| |jdksGW n tyu   tdw W |
  dS |
  w )zComplete a KMS request.

        :Parameters:
          - `kms_context`: A :class:`MongoCryptKmsContext`.

        :Returns:
          None
        NFgMbP?)connect_timeoutsocket_timeoutssl_contextr   zKMS connection closedz	timed out)endpointmessagekms_providerrA   _kms_ssl_contextsgetr'   maxr   clamp_remaining_KMS_CONNECT_TIMEOUTr"   r(   _HTTPS_PORTr#   sendallbytes_needed
settimeoutrecvOSErrorfeedr    sockettimeoutclose)rC   kms_contextrI   rJ   providerctxrF   rA   hostportconndatar0   r0   r1   kms_requestg   sJ   	





z_EncryptionIO.kms_requestc                 C   sd   |   | jt|d}|D ]}t|dt  W  d   S W d   dS 1 s+w   Y  dS )a  Get the collection info for a namespace.

        The returned collection info is passed to libmongocrypt which reads
        the JSON schema.

        :Parameters:
          - `database`: The database on which to run listCollections.
          - `filter`: The filter to pass to listCollections.

        :Returns:
          The first document from the listCollections command response as BSON.
        )filterFN)r<   list_collectionsr   r   r-   )rC   databaserc   cursordocr0   r0   r1   collection_info   s   "z_EncryptionIO.collection_infoc                 C   s.   d| _ | jjpdg}|| jj t| dS )z~Spawn mongocryptd.

        Note this method is thread safe; at most one mongocryptd will start
        successfully.
        TmongocryptdN)rB   rA   _mongocryptd_spawn_pathextend_mongocryptd_spawn_argsr   )rC   argsr0   r0   r1   spawn   s   z_EncryptionIO.spawnc                 C   sz   | j s| jjs|   t|t}z| j| j|td}W |j	S  ty<   | jjr* |   | j| j|td}Y |j	S w )zMark a command for encryption.

        :Parameters:
          - `database`: The database on which to run this command.
          - `cmd`: The BSON command to run.

        :Returns:
          The marked command response from mongocryptd.
        r7   )
rB   rA   _mongocryptd_bypass_spawnrn   r   r   r@   commandr   raw)rC   re   cmdinflated_cmdresr0   r0   r1   mark_command   s"   




z_EncryptionIO.mark_commandc                 c   sJ    | j t|}|D ]}|jV  qW d   dS 1 sw   Y  dS )zYields one or more keys from the key vault.

        :Parameters:
          - `filter`: The filter to pass to find.

        :Returns:
          A generator which yields the requested keys from the key vault.
        N)r?   findr   rr   )rC   rc   rf   keyr0   r0   r1   
fetch_keys   s   	
"z_EncryptionIO.fetch_keysc                 C   s@   t |t}|d}t|tr|jtkrtd| j	| |S )zInsert a data key into the key vault.

        :Parameters:
          - `data_key`: The data key document to insert.

        :Returns:
          The _id of the inserted data key document.
        _idz/data_key _id must be Binary with a UUID subtype)
r   r>   rM   
isinstancer   subtyper   	TypeErrorr?   
insert_one)rC   data_keyraw_docdata_key_idr0   r0   r1   insert_data_key   s   
	
z_EncryptionIO.insert_data_keyc                 C   s   t |S )zEncode a document to BSON.

        A document can be any mapping type (like :class:`dict`).

        :Parameters:
          - `doc`: mapping type representing a document

        :Returns:
          The encoded BSON bytes.
        )r   )rC   rg   r0   r0   r1   bson_encode   s   z_EncryptionIO.bson_encodec                 C   s*   d| _ d| _| jr| j  d| _dS dS )zjRelease resources.

        Note it is not safe to call this method from __del__ or any GC hooks.
        N)r<   r?   r@   rZ   rC   r0   r0   r1   rZ      s   

z_EncryptionIO.closeN)__name__
__module____qualname__rE   rb   rh   rn   rv   ry   r   r   rZ   r0   r0   r0   r1   r3   U   s    0r3   c                   @   s>   e Zd ZdZd	dee ddfddZedee fddZdS )
RewrapManyDataKeyResultzuResult object returned by a :meth:`~ClientEncryption.rewrap_many_data_key` operation.

    .. versionadded:: 4.2
    Nbulk_write_resultreturnc                 C   s
   || _ d S N_bulk_write_result)rC   r   r0   r0   r1   rE     s   
z RewrapManyDataKeyResult.__init__c                 C   s   | j S )aD  The result of the bulk write operation used to update the key vault
        collection with one or more rewrapped data keys. If
        :meth:`~ClientEncryption.rewrap_many_data_key` does not find any matching keys to rewrap,
        no bulk write operation will be executed and this field will be
        ``None``.
        r   r   r0   r0   r1   r     s   z)RewrapManyDataKeyResult.bulk_write_resultr   )	r   r   r   __doc__r   r%   rE   propertyr   r0   r0   r0   r1   r     s
    r   c                   @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )
_EncrypterzEncrypts and decrypts MongoDB commands.

    This class is used to support automatic encryption and decryption of
    MongoDB commands.c                 C   s   |j du rd}nt|j dt}|jdu rd}nt|jdt}|j| _d| _dd }|jdur2|j}n|| |}|jr=d}n|| |}|jdd\}}	|| |	 }
t	|j
dtd}t||
||}t|t|j||j|j|j||jd| _d| _dS )	zCreate a _Encrypter for a client.

        :Parameters:
          - `client`: The encrypted MongoClient.
          - `opts`: The encrypted client's :class:`AutoEncryptionOpts`.
        NFc                 S   s:   |j jjd u r	|S | jd ur| jS |jdd d}|| _|S )Nr   )minPoolSizeauto_encryption_opts)optionspool_optionsmax_pool_size_internal_client
_duplicate)	encryptermongo_clientinternal_clientr0   r0   r1   _get_internal_client3  s   
z1_Encrypter.__init__.<locals>._get_internal_client.   )connectserverSelectionTimeoutMS)crypt_shared_lib_pathcrypt_shared_lib_requiredbypass_encryptionencrypted_fields_mapbypass_query_analysis)_schema_mapr   r-   _encrypted_fields_map_bypass_auto_encryptionr   _key_vault_client_key_vault_namespacesplitr   _mongocryptd_uri_MONGOCRYPTD_TIMEOUT_MSr3   r   r	   _kms_providers_crypt_shared_lib_path_crypt_shared_lib_required_bypass_query_analysis_auto_encrypter_closed)rC   rD   rA   
schema_mapr   r   key_vault_clientmetadata_clientdbcollr?   r@   io_callbacksr0   r0   r1   rE      sD   





z_Encrypter.__init__c                 C   sZ   |    t|d|}t  | j||}t|t}|W  d   S 1 s&w   Y  dS )a!  Encrypt a MongoDB command.

        :Parameters:
          - `database`: The database for this command.
          - `cmd`: A command document.
          - `codec_options`: The CodecOptions to use while encoding `cmd`.

        :Returns:
          The encrypted command to execute.
        FN)_check_closedr   r2   r   encryptr   r   )rC   re   rs   r7   encoded_cmdencrypted_cmdencrypt_cmdr0   r0   r1   r   ^  s   
$z_Encrypter.encryptc                 C   s>   |    t  | j|W  d   S 1 sw   Y  dS )zDecrypt a MongoDB command response.

        :Parameters:
          - `response`: A MongoDB command response as BSON.

        :Returns:
          The decrypted command response.
        N)r   r2   r   decrypt)rC   responser0   r0   r1   r   q  s   	
$z_Encrypter.decryptc                 C   s   | j rtdd S )Nz"Cannot use MongoClient after close)r   r   r   r0   r0   r1   r   ~  s   z_Encrypter._check_closedc                 C   s.   d| _ | j  | jr| j  d| _dS dS )zCleanup resources.TN)r   r   rZ   r   r   r0   r0   r1   rZ     s   


z_Encrypter.closeN)	r   r   r   r   rE   r   r   r   rZ   r0   r0   r0   r1   r     s    >r   c                   @   s&   e Zd ZdZdZ	 dZ	 dZ	 dZdS )	Algorithmz9An enum that defines the supported encryption algorithms.z+AEAD_AES_256_CBC_HMAC_SHA_512-Deterministicz$AEAD_AES_256_CBC_HMAC_SHA_512-RandomIndexed	UnindexedN)r   r   r   r   +AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic$AEAD_AES_256_CBC_HMAC_SHA_512_RandomINDEXED	UNINDEXEDr0   r0   r0   r1   r     s    r   c                   @   s   e Zd ZdZdZdS )	QueryTypez**(BETA)** An enum that defines the supported values for explicit encryption query_type.

    .. note:: Support for Queryable Encryption is in beta.
       Backwards-breaking changes may be made before the final release.

    .. versionadded:: 4.2
    equalityN)r   r   r   r   EQUALITYr0   r0   r0   r1   r     s    r   c                   @   s  e Zd ZdZ	d7deeef dededede	eeef  ddfd	d
Z
			d8dede	eeef  de	ee  de	e def
ddZ				d9dedede	e de	e de	e de	e defddZdedefddZdede	e fddZdee fddZdedefd d!Zdededefd"d#Zdede	e fd$d%Zdedede	e fd&d'Z		d:d(eeef d)e	e de	eeef  defd*d+Zd;d,d-Zd.ed/ed0eddfd1d2Zd3d4 Zd<d5d6Z dS )=ClientEncryptionz,Explicit client-side field level encryption.Nkms_providerskey_vault_namespacer   r7   kms_tls_optionsr   c           
      C   s   t stdt|tstd|| _|| _|| _|| _|	dd\}}|| | }t
|||d}	td|d|	| _t| jt|d| _| jj| _dS )a  Explicit client-side field level encryption.

        The ClientEncryption class encapsulates explicit operations on a key
        vault collection that cannot be done directly on a MongoClient. Similar
        to configuring auto encryption on a MongoClient, it is constructed with
        a MongoClient (to a MongoDB cluster containing the key vault
        collection), KMS provider configuration, and keyVaultNamespace. It
        provides an API for explicitly encrypting and decrypting values, and
        creating data keys. It does not provide an API to query keys from the
        key vault collection, as this can be done directly on the MongoClient.

        See :ref:`explicit-client-side-encryption` for an example.

        :Parameters:
          - `kms_providers`: Map of KMS provider options. The `kms_providers`
            map values differ by provider:

              - `aws`: Map with "accessKeyId" and "secretAccessKey" as strings.
                These are the AWS access key ID and AWS secret access key used
                to generate KMS messages. An optional "sessionToken" may be
                included to support temporary AWS credentials.
              - `azure`: Map with "tenantId", "clientId", and "clientSecret" as
                strings. Additionally, "identityPlatformEndpoint" may also be
                specified as a string (defaults to 'login.microsoftonline.com').
                These are the Azure Active Directory credentials used to
                generate Azure Key Vault messages.
              - `gcp`: Map with "email" as a string and "privateKey"
                as `bytes` or a base64 encoded string.
                Additionally, "endpoint" may also be specified as a string
                (defaults to 'oauth2.googleapis.com'). These are the
                credentials used to generate Google Cloud KMS messages.
              - `kmip`: Map with "endpoint" as a host with required port.
                For example: ``{"endpoint": "example.com:443"}``.
              - `local`: Map with "key" as `bytes` (96 bytes in length) or
                a base64 encoded string which decodes
                to 96 bytes. "key" is the master key used to encrypt/decrypt
                data keys. This key should be generated and stored as securely
                as possible.

          - `key_vault_namespace`: The namespace for the key vault collection.
            The key vault collection contains all data keys used for encryption
            and decryption. Data keys are stored as documents in this MongoDB
            collection. Data keys are protected with encryption by a KMS
            provider.
          - `key_vault_client`: A MongoClient connected to a MongoDB cluster
            containing the `key_vault_namespace` collection.
          - `codec_options`: An instance of
            :class:`~bson.codec_options.CodecOptions` to use when encoding a
            value for encryption and decoding the decrypted BSON value. This
            should be the same CodecOptions instance configured on the
            MongoClient, Database, or Collection used to access application
            data.
          - `kms_tls_options` (optional): A map of KMS provider names to TLS
            options to use when creating secure connections to KMS providers.
            Accepts the same TLS options as
            :class:`pymongo.mongo_client.MongoClient`. For example, to
            override the system default CA file::

              kms_tls_options={'kmip': {'tlsCAFile': certifi.where()}}

            Or to supply a client certificate::

              kms_tls_options={'kmip': {'tlsCertificateKeyFile': 'client.pem'}}

        .. versionchanged:: 4.0
           Added the `kms_tls_options` parameter and the "kmip" KMS provider.

        .. versionadded:: 3.9
        zclient-side field level encryption requires the pymongocrypt library: install a compatible version with: python -m pip install 'pymongo[encryption]'zDcodec_options must be an instance of bson.codec_options.CodecOptionsr   r   )r   N)_HAVE_PYMONGOCRYPTr   r{   r   r}   r   r   r   _codec_optionsr   r   r3   _io_callbacksr   r	   _encryptionr?   _key_vault_coll)
rC   r   r   r   r7   r   r   r   r?   rA   r0   r0   r1   rE     s,   M
zClientEncryption.__init__rK   
master_keykey_alt_nameskey_materialc                 C   sF   |    t  | jj||||dW  d   S 1 sw   Y  dS )a  Create and insert a new data key into the key vault collection.

        :Parameters:
          - `kms_provider`: The KMS provider to use. Supported values are
            "aws", "azure", "gcp", "kmip", and "local".
          - `master_key`: Identifies a KMS-specific key used to encrypt the
            new data key. If the kmsProvider is "local" the `master_key` is
            not applicable and may be omitted.

            If the `kms_provider` is "aws" it is required and has the
            following fields::

              - `region` (string): Required. The AWS region, e.g. "us-east-1".
              - `key` (string): Required. The Amazon Resource Name (ARN) to
                 the AWS customer.
              - `endpoint` (string): Optional. An alternate host to send KMS
                requests to. May include port number, e.g.
                "kms.us-east-1.amazonaws.com:443".

            If the `kms_provider` is "azure" it is required and has the
            following fields::

              - `keyVaultEndpoint` (string): Required. Host with optional
                 port, e.g. "example.vault.azure.net".
              - `keyName` (string): Required. Key name in the key vault.
              - `keyVersion` (string): Optional. Version of the key to use.

            If the `kms_provider` is "gcp" it is required and has the
            following fields::

              - `projectId` (string): Required. The Google cloud project ID.
              - `location` (string): Required. The GCP location, e.g. "us-east1".
              - `keyRing` (string): Required. Name of the key ring that contains
                the key to use.
              - `keyName` (string): Required. Name of the key to use.
              - `keyVersion` (string): Optional. Version of the key to use.
              - `endpoint` (string): Optional. Host with optional port.
                Defaults to "cloudkms.googleapis.com".

            If the `kms_provider` is "kmip" it is optional and has the
            following fields::

              - `keyId` (string): Optional. `keyId` is the KMIP Unique
                Identifier to a 96 byte KMIP Secret Data managed object. If
                keyId is omitted, the driver creates a random 96 byte KMIP
                Secret Data managed object.
              - `endpoint` (string): Optional. Host with optional
                 port, e.g. "example.vault.azure.net:".

          - `key_alt_names` (optional): An optional list of string alternate
            names used to reference a key. If a key is created with alternate
            names, then encryption may refer to the key by the unique alternate
            name instead of by ``key_id``. The following example shows creating
            and referring to a data key by alternate name::

              client_encryption.create_data_key("local", keyAltNames=["name1"])
              # reference the key with the alternate name
              client_encryption.encrypt("457-55-5462", keyAltName="name1",
                                        algorithm=Algorithm.AEAD_AES_256_CBC_HMAC_SHA_512_Random)
          - `key_material` (optional): Sets the custom key material to be used
            by the data key for encryption and decryption.

        :Returns:
          The ``_id`` of the created data key document as a
          :class:`~bson.binary.Binary` with subtype
          :data:`~bson.binary.UUID_SUBTYPE`.

        .. versionchanged:: 4.2
           Added the `key_material` parameter.
        )r   r   r   N)r   r2   r   create_data_key)rC   rK   r   r   r   r0   r0   r1   r     s   M$z ClientEncryption.create_data_keyvalue	algorithmkey_idkey_alt_name
query_typecontention_factorc           	   	   C   s   |    |durt|tr|jtkstdtd|i| jd}t  | j	j
||||||d}t|d W  d   S 1 s?w   Y  dS )aV  Encrypt a BSON value with a given key and algorithm.

        Note that exactly one of ``key_id`` or  ``key_alt_name`` must be
        provided.

        :Parameters:
          - `value`: The BSON value to encrypt.
          - `algorithm` (string): The encryption algorithm to use. See
            :class:`Algorithm` for some valid options.
          - `key_id`: Identifies a data key by ``_id`` which must be a
            :class:`~bson.binary.Binary` with subtype 4 (
            :attr:`~bson.binary.UUID_SUBTYPE`).
          - `key_alt_name`: Identifies a key vault document by 'keyAltName'.
          - `query_type` (str): **(BETA)** The query type to execute. See
            :class:`QueryType` for valid options.
          - `contention_factor` (int): **(BETA)** The contention factor to use
            when the algorithm is :attr:`Algorithm.INDEXED`.  An integer value
            *must* be given when the :attr:`Algorithm.INDEXED` algorithm is
            used.

        .. note:: `query_type` and `contention_factor` are part of the
           Queryable Encryption beta. Backwards-breaking changes may be made before the
           final release.

        :Returns:
          The encrypted value, a :class:`~bson.binary.Binary` with subtype 6.

        .. versionchanged:: 4.2
           Added the `query_type` and `contention_factor` parameters.

        Nz2key_id must be a bson.binary.Binary with subtype 4vro   )r   r   r   r   )r   r{   r   r|   r   r}   r   r   r2   r   r   r   )	rC   r   r   r   r   r   r   rg   encrypted_docr0   r0   r1   r   u  s&   (
$zClientEncryption.encryptc                 C   sx   |    t|tr|jdkstdt  td|i}| j|}t	|| j
dd W  d   S 1 s5w   Y  dS )zDecrypt an encrypted value.

        :Parameters:
          - `value` (Binary): The encrypted value, a
            :class:`~bson.binary.Binary` with subtype 6.

        :Returns:
          The decrypted BSON value.
           z<value to decrypt must be a bson.binary.Binary with subtype 6r   ro   N)r   r{   r   r|   r}   r2   r   r   r   r   r   )rC   r   rg   decrypted_docr0   r0   r1   r     s   
$zClientEncryption.decryptidc                 C      |    | jd|iS )a+  Get a data key by id.

        :Parameters:
          - `id` (Binary): The UUID of a key a which must be a
            :class:`~bson.binary.Binary` with subtype 4 (
            :attr:`~bson.binary.UUID_SUBTYPE`).

        :Returns:
          The key document.

        .. versionadded:: 4.2
        rz   r   r   find_onerC   r   r0   r0   r1   get_key     zClientEncryption.get_keyc                 C   s   |    | ji S )zGet all of the data keys.

        :Returns:
          An instance of :class:`~pymongo.cursor.Cursor` over the data key
          documents.

        .. versionadded:: 4.2
        )r   r   rw   r   r0   r0   r1   get_keys  s   	zClientEncryption.get_keysc                 C   r   )ag  Delete a key document in the key vault collection that has the given ``key_id``.

        :Parameters:
          - `id` (Binary): The UUID of a key a which must be a
            :class:`~bson.binary.Binary` with subtype 4 (
            :attr:`~bson.binary.UUID_SUBTYPE`).

        :Returns:
          The delete result.

        .. versionadded:: 4.2
        rz   )r   r   
delete_oner   r0   r0   r1   
delete_key  r   zClientEncryption.delete_keyc                 C   s&   |    dd|ii}| jd|i|S )a  Add ``key_alt_name`` to the set of alternate names in the key document with UUID ``key_id``.

        :Parameters:
          - ``id``: The UUID of a key a which must be a
            :class:`~bson.binary.Binary` with subtype 4 (
            :attr:`~bson.binary.UUID_SUBTYPE`).
          - ``key_alt_name``: The key alternate name to add.

        :Returns:
          The previous version of the key document.

        .. versionadded:: 4.2
        z	$addToSetkeyAltNamesrz   r   r   find_one_and_update)rC   r   r   updater0   r0   r1   add_key_alt_name  s   z!ClientEncryption.add_key_alt_namec                 C   r   )a  Get a key document in the key vault collection that has the given ``key_alt_name``.

        :Parameters:
          - `key_alt_name`: (str): The key alternate name of the key to get.

        :Returns:
          The key document.

        .. versionadded:: 4.2
        r   r   )rC   r   r0   r0   r1   get_key_by_alt_name   s   z$ClientEncryption.get_key_by_alt_namec              
   C   sN   |    ddddd|ggiddddd	|gid
igiiig}| jd|i|S )a.  Remove ``key_alt_name`` from the set of keyAltNames in the key document with UUID ``id``.

        Also removes the ``keyAltNames`` field from the key document if it would otherwise be empty.

        :Parameters:
          - ``id``: The UUID of a key a which must be a
            :class:`~bson.binary.Binary` with subtype 4 (
            :attr:`~bson.binary.UUID_SUBTYPE`).
          - ``key_alt_name``: The key alternate name to remove.

        :Returns:
          Returns the previous version of the key document.

        .. versionadded:: 4.2
        $setr   z$condz$eqz$keyAltNamesz$$REMOVEz$filterz$nez$$this)inputcondrz   r   )rC   r   r   pipeliner0   r0   r1   remove_key_alt_name  s"   
z$ClientEncryption.remove_key_alt_namerc   r\   c                 C   s   |    t  | j|||}|du rt W  d   S W d   n1 s(w   Y  t|t}g }|d D ]}|d |d dddid}td	|d	 i|}	||	 q8|s\t S | j	
|}
t|
S )
a4  Decrypts and encrypts all matching data keys in the key vault with a possibly new `master_key` value.

        :Parameters:
          - `filter`: A document used to filter the data keys.
          - `provider`: The new KMS provider to use to encrypt the data keys,
            or ``None`` to use the current KMS provider(s).
          - ``master_key``: The master key fields corresponding to the new KMS
            provider when ``provider`` is not ``None``.

        :Returns:
          A :class:`RewrapManyDataKeyResult`.

        .. versionadded:: 4.2
        Nr   keyMaterial	masterKey)r   r   
updateDateT)r   z$currentDaterz   )r   r2   r   rewrap_many_data_keyr   r   r   r!   appendr   
bulk_write)rC   rc   r\   r   
raw_resultr   replacementsrx   update_modelopresultr0   r0   r1   r   3  s(   
z%ClientEncryption.rewrap_many_data_keyc                 C   s   | S r   r0   r   r0   r0   r1   	__enter__[  s   zClientEncryption.__enter__exc_typeexc_valexc_tbc                 C   s   |    d S r   )rZ   )rC   r  r  r  r0   r0   r1   __exit__^  s   zClientEncryption.__exit__c                 C   s   | j d u r	tdd S )Nz"Cannot use closed ClientEncryption)r   r   r   r0   r0   r1   r   a  s   
zClientEncryption._check_closedc                 C   s.   | j r| j   | j  d| _ d| _dS dS )aE  Release resources.

        Note that using this class in a with-statement will automatically call
        :meth:`close`::

            with ClientEncryption(...) as client_encryption:
                encrypted = client_encryption.encrypt(value, ...)
                decrypted = client_encryption.decrypt(encrypted)

        N)r   rZ   r   r   r0   r0   r1   rZ   e  s   


zClientEncryption.closer   )NNN)NNNN)NN)r   r   )r   N)!r   r   r   r   r   strr   r   r   r   rE   r   bytesr   r   intr   r   r   r   r   r   r&   r   r   r   r   r   r   r  r  r   rZ   r0   r0   r0   r1   r     s    

n

Z
:(


(r   )Zr   
contextlibenumrX   r:   typingr   r   r   r   pymongocrypt.auto_encrypterr   pymongocrypt.errorsr   pymongocrypt.explicit_encrypterr   pymongocrypt.mongocryptr	   pymongocrypt.state_machiner
   r   ImportErrorobjectbsonr   r   r   bson.binaryr   r   r   bson.codec_optionsr   bson.errorsr   bson.raw_bsonr   r   r   bson.sonr   pymongor   pymongo.cursorr   pymongo.daemonr   pymongo.encryption_optionsr   pymongo.errorsr   r   r   r   pymongo.mongo_clientr   pymongo.networkr    pymongo.operationsr!   pymongo.poolr"   r#   pymongo.read_concernr$   pymongo.resultsr%   r&   pymongo.ssl_supportr'   pymongo.uri_parserr(   pymongo.write_concernr)   rQ   rP   r   r-   __annotations__r>   contextmanagerr2   r3   r   r   r  Enumr   r   r   r0   r0   r0   r1   <module>   sf   

 2q