U
    dU                     @  s  U d Z ddlmZ ddlZddlZddlZddlZddlmZ ddl	m
Z
mZmZmZmZmZmZmZmZmZ zDd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k
r   dZe ZY nX 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/m0Z0 ddl1m2Z2 ddl3m4Z4 ddl5m6Z6 ddl7m8Z8 ddl9m:Z: ddl;m<Z< ddl=m>Z> ddl?m@Z@mAZA ddlBmCZCmDZDmEZEmFZFmGZGmHZH ddlImJZJ ddlKmLZL ddlMmNZN ddlOmPZPmQZQmRZR ddlSmTZT dd lUmVZVmWZW dd!lXmYZY dd"lZm[Z[ dd#l\m]Z] dd$l^m_Z_ e
r>dd%lm`Z` d&Zae8Zbd'Zce*e2e&d(Zdd)eed*< e*e/d+Zfejgd,d-d.d/ZhG d0d1 d1eZiG d2d3 d3ZjG d4d5 d5ZkG d6d7 d7elejmZnG d8d9 d9elejmZoG d:d; d;ee[ ZpdS )<z8Support for explicit client-side field level encryption.    )annotationsN)deepcopy)
TYPE_CHECKINGAnyDictGenericIteratorMappingMutableMappingOptionalSequenceTuple)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)
Collection)CONNECT_TIMEOUT)Cursor)_spawn_daemon)Database)AutoEncryptionOpts	RangeOpts)ConfigurationErrorEncryptedCollectionErrorEncryptionErrorInvalidOperationPyMongoErrorServerSelectionTimeoutError)MongoClient)BLOCKING_IO_ERRORS)	UpdateOne)PoolOptions_configured_socket_raise_connection_failure)ReadConcern)BulkWriteResultDeleteResult)get_ssl_context)_DocumentType)
parse_host)WriteConcern)MongoCryptKmsContexti  i'  )document_classZuuid_representationr   _DATA_KEY_OPTS)r;   zIterator[None]returnc               
   c  sN   z
dV  W n> t k
r     Y n* tk
rH }  zt| W 5 d} ~ X Y nX dS )z2Context manager to wrap encryption related errors.N)r   	Exceptionr)   )exc rA   6/tmp/pip-unpacked-wheel-oblwsawz/pymongo/encryption.py_wrap_encryption_errors^   s    
rC   c                   @  s   e Zd ZdddddddZddd	d
dZddddddZddddZddddddZdddddZddddd Z	d!dd"d#d$Z
ddd%d&Zd'S )(_EncryptionIOzOptional[MongoClient]r    r%   )clientkey_vault_collmongocryptd_clientoptsc                 C  sT   |  |dk	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.NZmajority)level)w)codec_optionsZread_concernZwrite_concernF)weakrefref
client_refZwith_options_KEY_VAULT_OPTSr3   r9   rF   rG   rH   _spawned)selfrE   rF   rG   rH   rA   rA   rB   __init__l   s    z_EncryptionIO.__init__r:   None)kms_contextr>   c              
   C  sN  |j }|j}|j}| jj|}|dkr<tddddddd}tt	t
d}t|||d}t|t\}}	zt||	f|}
zvzR|
| |jdkr|
tt	t
d |
|j}|std|| qW n tk
r   tdY nX W 5 |
  X W nL ttfk
r    Y n2 tk
rH } zt||	f| W 5 d}~X Y nX dS )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_providerrH   Z_kms_ssl_contextsgetr6   maxr   Zclamp_remaining_KMS_CONNECT_TIMEOUTr0   r8   _HTTPS_PORTr1   closesendallZbytes_needed
settimeoutrecvOSErrorfeedr.   sockettimeoutr+   r   r?   r2   )rQ   rT   rX   rY   providerctxrU   rH   hostportconndataerrorrA   rA   rB   kms_request   sL    	


z_EncryptionIO.kms_requestr$   bytesOptional[bytes])databasefilterr>   c              
   C  sV   |   | jt|d4}|D ]}t|dt  W  5 Q R  S W 5 Q R  dS Q R X 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.
        )rr   FN)rN   Zlist_collectionsr   r   r<   )rQ   rq   rr   cursordocrA   rA   rB   collection_info   s    z_EncryptionIO.collection_infor=   c                 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.
        TZmongocryptdN)rP   rH   Z_mongocryptd_spawn_pathextendZ_mongocryptd_spawn_argsr#   )rQ   argsrA   rA   rB   spawn   s    z_EncryptionIO.spawnstr)rq   cmdr>   c                 C  s   | j s| jjs|   t|t}| jdk	s.tz| j| j|td}W n: t	k
r   | jjr` |   | j| j|td}Y nX |j
S )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.
        NrK   )rP   rH   Z_mongocryptd_bypass_spawnrx   r   r   rG   AssertionErrorcommandr,   raw)rQ   rq   rz   Zinflated_cmdresrA   rA   rB   mark_command   s$    


 

 z_EncryptionIO.mark_commandzIterator[bytes])rr   r>   c              	   c  s@   | j dk	st| j t|}|D ]}|jV  q$W 5 Q R X 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)rF   r|   findr   r~   )rQ   rr   rs   keyrA   rA   rB   
fetch_keys   s    	z_EncryptionIO.fetch_keysr   )data_keyr>   c                 C  sN   t |t}|d}t|tr(|jtkr0td| jdk	s>t	| 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 subtypeN)r   rO   r[   
isinstancer   subtyper   	TypeErrorrF   r|   Z
insert_one)rQ   r   raw_docZdata_key_idrA   rA   rB   insert_data_key  s    	

z_EncryptionIO.insert_data_keyzMutableMapping[str, Any])rt   r>   c                 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   )rQ   rt   rA   rA   rB   bson_encode  s    z_EncryptionIO.bson_encodec                 C  s&   d| _ d| _| jr"| j  d| _dS )zjRelease resources.

        Note it is not safe to call this method from __del__ or any GC hooks.
        N)rN   rF   rG   r_   rQ   rA   rA   rB   r_      s
    
z_EncryptionIO.closeN)__name__
__module____qualname__rR   rn   ru   rx   r   r   r   r   r_   rA   rA   rA   rB   rD   k   s   6rD   c                   @  s4   e Zd ZdZddddddZeddd	d
ZdS )RewrapManyDataKeyResultzuResult object returned by a :meth:`~ClientEncryption.rewrap_many_data_key` operation.

    .. versionadded:: 4.2
    NzOptional[BulkWriteResult]rS   )bulk_write_resultr>   c                 C  s
   || _ d S NZ_bulk_write_result)rQ   r   rA   rA   rB   rR   2  s    z RewrapManyDataKeyResult.__init__r=   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   rA   rA   rB   r   5  s    z)RewrapManyDataKeyResult.bulk_write_result)N)r   r   r   __doc__rR   propertyr   rA   rA   rA   rB   r   ,  s   r   c                   @  s`   e Zd ZdZdddddZddd	d
dddZdddddZddddZddddZdS )
_EncrypterzEncrypts and decrypts MongoDB commands.

    This class is used to support automatic encryption and decryption of
    MongoDB commands.
    r-   r%   )rE   rH   c                 C  s   |j dkrd}nt|j dt}|jdkr.d}nt|jdt}|j| _d| _dddddd}|jdk	rn|j}n
|| |}|jrd}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`.
        NFr   r-   )	encryptermongo_clientr>   c                 S  s:   |j jjd kr|S | jd k	r"| jS |jdd d}|| _|S )Nr   )ZminPoolSizeZauto_encryption_opts)optionsZpool_optionsZmax_pool_size_internal_clientZ
_duplicate)r   r   Zinternal_clientrA   rA   rB   _get_internal_clientZ  s    
z1_Encrypter.__init__.<locals>._get_internal_client.   )connectZserverSelectionTimeoutMS)Zcrypt_shared_lib_pathZcrypt_shared_lib_requiredZbypass_encryptionencrypted_fields_mapZbypass_query_analysis)Z_schema_mapr   r<   Z_encrypted_fields_mapZ_bypass_auto_encryptionr   _key_vault_client_key_vault_namespacesplitr-   Z_mongocryptd_uri_MONGOCRYPTD_TIMEOUT_MSrD   r   r   _kms_providersZ_crypt_shared_lib_pathZ_crypt_shared_lib_requiredZ_bypass_query_analysis_auto_encrypter_closed)rQ   rE   rH   Z
schema_mapr   r   key_vault_clientZmetadata_clientdbcollrF   rG   Zio_callbacksrA   rA   rB   rR   G  sH    




  z_Encrypter.__init__ry   Mapping[str, Any]r   zDict[Any, Any])rq   rz   rK   r>   c              
   C  sN   |    t|d|}t * | j||}t|t}|W  5 Q R  S Q R X 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   rC   r   encryptr   r   )rQ   rq   rz   rK   Zencoded_cmdZencrypted_cmdZencrypt_cmdrA   rA   rB   r     s    
z_Encrypter.encryptro   rp   )responser>   c              
   C  s2   |    t  | j|W  5 Q R  S Q R X dS )zDecrypt a MongoDB command response.

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

        :Returns:
          The decrypted command response.
        N)r   rC   r   decrypt)rQ   r   rA   rA   rB   r     s    	z_Encrypter.decryptrS   r=   c                 C  s   | j rtdd S )Nz"Cannot use MongoClient after close)r   r*   r   rA   rA   rB   r     s    z_Encrypter._check_closedc                 C  s*   d| _ | j  | jr&| j  d| _dS )zCleanup resources.TN)r   r   r_   r   r   rA   rA   rB   r_     s
    

z_Encrypter.closeN)	r   r   r   r   rR   r   r   r   r_   rA   rA   rA   rB   r   @  s   >r   c                   @  s$   e Zd 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-RandomZIndexedZ	UnindexedZRangePreviewN)	r   r   r   r   Z+AEAD_AES_256_CBC_HMAC_SHA_512_DeterministicZ$AEAD_AES_256_CBC_HMAC_SHA_512_RandomZINDEXEDZ	UNINDEXEDRANGEPREVIEWrA   rA   rA   rB   r     s   r   c                   @  s   e Zd ZdZdZdZdS )	QueryTypezmAn enum that defines the supported values for explicit encryption query_type.

    .. versionadded:: 4.2
    ZequalityZrangePreviewN)r   r   r   r   ZEQUALITYr   rA   rA   rA   rB   r     s   r   c                   @  s  e Zd ZdZdLddddddd	d
dZdMddddddddddZdNddddddddZdOdddddddddd	dd ZdPddddddddd!d"d#ZdQdddddddd$d%d&d'Z	ddd(d)d*Z
dd+d,d-d.Zd/d0d1d2Zdd3d,d4d5Zdddd6d7d8Zdd+d9d:d;Zddd+d6d<d=ZdRdddd>d?d@dAZdBd0dCdDZdddddEdFdGZdd0dHdIZdd0dJdKZdS )SClientEncryptionz,Explicit client-side field level encryption.Nr   ry   r-   r   zOptional[Mapping[str, Any]]rS   )kms_providerskey_vault_namespacer   rK   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%   rD   _io_callbacksr   r   _encryptionrF   _key_vault_coll)
rQ   r   r   r   rK   r   r   r   rF   rH   rA   rA   rB   rR     s8    M
      zClientEncryption.__init__r$   zOptional[str]r   z3Tuple[Collection[_DocumentType], Mapping[str, Any]])rq   nameencrypted_fieldsrZ   
master_keykwargsr>   c           
      K  s   t |}t|d D ]n\}}t|tr|ddkrz| j||d|d | d< W q tk
r }	 zt|	||	W 5 d}	~	X Y qX q||d< d|d< z|jf d|i||fW S  t	k
r }	 zt|	||	W 5 d}	~	X Y nX dS )	a	  Create a collection with encryptedFields.

        .. warning::
            This function does not update the encryptedFieldsMap in the client's
            AutoEncryptionOpts, thus the user must create a new client after calling this function with
            the encryptedFields returned.

        Normally collection creation is automatic. This method should
        only be used to specify options on
        creation. :class:`~pymongo.errors.EncryptionError` will be
        raised if the collection already exists.

        :Parameters:
          - `name`: the name of the collection to create
          - `encrypted_fields` (dict): Document that describes the encrypted fields for
            Queryable Encryption. For example::

              {
                "escCollection": "enxcol_.encryptedCollection.esc",
                "ecocCollection": "enxcol_.encryptedCollection.ecoc",
                "fields": [
                    {
                        "path": "firstName",
                        "keyId": Binary.from_uuid(UUID('00000000-0000-0000-0000-000000000000')),
                        "bsonType": "string",
                        "queries": {"queryType": "equality"}
                    },
                    {
                        "path": "ssn",
                        "keyId": Binary.from_uuid(UUID('04104104-1041-0410-4104-104104104104')),
                        "bsonType": "string"
                    }
                  ]
              }

            The "keyId" may be set to ``None`` to auto-generate the data keys.
          - `kms_provider` (optional): the KMS provider to be used
          - `master_key` (optional): 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.
          - `**kwargs` (optional): additional keyword arguments are the same as "create_collection".

        All optional `create collection command`_ parameters should be passed
        as keyword arguments to this method.
        See the documentation for :meth:`~pymongo.database.Database.create_collection` for all valid options.

        :Raises:
          - :class:`~pymongo.errors.EncryptedCollectionError`: When either data-key creation or creating the collection fails.

        .. versionadded:: 4.4

        .. _create collection command:
            https://mongodb.com/docs/manual/reference/command/create

        fieldsZkeyIdN)rZ   r   ZencryptedFieldsFZcheck_existsr   )
r   	enumerater   dictr[   create_data_keyr)   r(   Zcreate_collectionr?   )
rQ   rq   r   r   rZ   r   r   ifieldr@   rA   rA   rB   create_encrypted_collectionN  s$    @ z,ClientEncryption.create_encrypted_collectionzOptional[Sequence[str]]rp   r   )rZ   r   key_alt_nameskey_materialr>   c              
   C  s:   |    t " | jj||||dW  5 Q R  S Q R X 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", key_alt_names=["name1"])
              # reference the key with the alternate name
              client_encryption.encrypt("457-55-5462", key_alt_name="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   rC   r   r   )rQ   rZ   r   r   r   rA   rA   rB   r     s    Mz ClientEncryption.create_data_keyFzOptional[Binary]zOptional[int]zOptional[RangeOpts]bool)	value	algorithmkey_idkey_alt_name
query_typecontention_factor
range_optsis_expressionr>   c	                 C  s   |    |d k	r,t|tr$|jtks,tdtd|i| jd}	d }
|rVt|j| jd}
t	 6 | j
j|	||||||
|d}t|d W  5 Q R  S Q R X d S )Nz2key_id must be a bson.binary.Binary with subtype 4vr{   r   r   r   r   r   r   r   r   )r   r   r   r   r   r   r   r   documentrC   r   r   r   )rQ   r   r   r   r   r   r   r   r   rt   Zrange_opts_bytesZencrypted_docrA   rA   rB   _encrypt_helper  s:    
z ClientEncryption._encrypt_helper)r   r   r   r   r   r   r   r>   c              
   C  s   | j |||||||ddS )a  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): The query type to execute. See :class:`QueryType` for valid options.
          - `contention_factor` (int): 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.
          - `range_opts`: Experimental only, not intended for public use.

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

        .. versionchanged:: 4.2
           Added the `query_type` and `contention_factor` parameters.
        Fr   r   )rQ   r   r   r   r   r   r   r   rA   rA   rB   r      s    $zClientEncryption.encryptr   )
expressionr   r   r   r   r   r   r>   c              
   C  s   | j |||||||ddS )a  Encrypt a BSON expression with a given key and algorithm.

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

        :Parameters:
          - `expression`: The BSON aggregate or match expression 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): The query type to execute. See
            :class:`QueryType` for valid options.
          - `contention_factor` (int): 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.
          - `range_opts`: Experimental only, not intended for public use.

        :Returns:
          The encrypted expression, a :class:`~bson.RawBSONDocument`.

        .. versionadded:: 4.4
        Tr   r   )rQ   r   r   r   r   r   r   r   rA   rA   rB   encrypt_expressionO  s    $z#ClientEncryption.encrypt_expression)r   r>   c              
   C  sl   |    t|tr|jdks$tdt 8 td|i}| j|}t	|| j
dd W  5 Q R  S Q R X 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   r{   N)r   r   r   r   r   rC   r   r   r   r   r   )rQ   r   rt   Zdecrypted_docrA   rA   rB   r   ~  s    
zClientEncryption.decryptzOptional[RawBSONDocument])idr>   c                 C  s&   |    | jdk	st| 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
        Nr   r   r   r|   Zfind_onerQ   r   rA   rA   rB   get_key  s    zClientEncryption.get_keyzCursor[RawBSONDocument]r=   c                 C  s"   |    | jdk	st| 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
        N)r   r   r|   r   r   rA   rA   rB   get_keys  s    	zClientEncryption.get_keysr5   c                 C  s&   |    | jdk	st| jd|iS )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
        Nr   )r   r   r|   Z
delete_oner   rA   rA   rB   
delete_key  s    zClientEncryption.delete_key)r   r   r>   c                 C  s4   |    dd|ii}| jdk	s"t| 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keyAltNamesNr   r   r   r|   Zfind_one_and_update)rQ   r   r   updaterA   rA   rB   add_key_alt_name  s    z!ClientEncryption.add_key_alt_name)r   r>   c                 C  s&   |    | jdk	st| jd|iS )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
        Nr   r   )rQ   r   rA   rA   rB   get_key_by_alt_name  s    z$ClientEncryption.get_key_by_alt_namec              
   C  s\   |    ddddd|ggiddddd	|gid
igiiig}| jdk	sJt| 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)inputZcondNr   r   )rQ   r   r   ZpipelinerA   rA   rB   remove_key_alt_name  s$    
z$ClientEncryption.remove_key_alt_namer   )rr   rg   r   r>   c              
   C  s   |dk	r|dkrt d|   t 0 | j|||}|dkrRt W  5 Q R  S W 5 Q R X t|t}g }|d D ]<}|d |d dddid	}td
|d
 i|}	|	|	 qr|st S | j
dk	st| j
|}
t|
S )a6  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`.

        This method allows you to re-encrypt all of your data-keys with a new CMK, or master key.
        Note that this does *not* require re-encrypting any of the data in your encrypted collections,
        but rather refreshes the key that protects the keys that encrypt the data:

        .. code-block:: python

           client_encryption.rewrap_many_data_key(
               filter={"keyAltNames": "optional filter for which keys you want to update"},
               master_key={
                   "provider": "azure",  # replace with your cloud provider
                   "master_key": {
                       # put the rest of your master_key options here
                       "key": "<your new key>"
                   },
               },
           )

        .. versionadded:: 4.2
        Nz1A provider must be given if a master_key is givenr   keyMaterial	masterKey)r   r   Z
updateDateT)r   z$currentDater   )r'   r   rC   r   rewrap_many_data_keyr   r   r   r/   appendr   r|   Z
bulk_write)rQ   rr   rg   r   Z
raw_resultr   replacementsr   Zupdate_modelopresultrA   rA   rB   r     s(    %
z%ClientEncryption.rewrap_many_data_keyz'ClientEncryption'c                 C  s   | S r   rA   r   rA   rA   rB   	__enter__D  s    zClientEncryption.__enter__)exc_typeexc_valexc_tbr>   c                 C  s   |    d S r   )r_   )rQ   r   r   r   rA   rA   rB   __exit__G  s    zClientEncryption.__exit__c                 C  s   | j d krtdd S )Nz"Cannot use closed ClientEncryption)r   r*   r   rA   rA   rB   r   J  s    
zClientEncryption._check_closedc                 C  s*   | j r&| j   | j  d| _ d| _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   r_   r   r   rA   rA   rB   r_   N  s
    

zClientEncryption.close)N)NN)NNN)NNNNNF)NNNNN)NNNNN)NN)r   r   r   r   rR   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r_   rA   rA   rA   rB   r     sV    p  W   Z       ,     3     /)  <r   )qr   
__future__r   
contextlibenumre   rL   copyr   typingr   r   r   r   r   r	   r
   r   r   r   Zpymongocrypt.auto_encrypterr   Zpymongocrypt.errorsr   Zpymongocrypt.explicit_encrypterr   Zpymongocrypt.mongocryptr   Zpymongocrypt.state_machiner   r   ImportErrorobjectZbsonr   r   r   Zbson.binaryr   r   r   Zbson.codec_optionsr   Zbson.errorsr   Zbson.raw_bsonr   r   r   Zbson.sonr   Zpymongor   Zpymongo.collectionr    Zpymongo.commonr!   Zpymongo.cursorr"   Zpymongo.daemonr#   Zpymongo.databaser$   Zpymongo.encryption_optionsr%   r&   Zpymongo.errorsr'   r(   r)   r*   r+   r,   Zpymongo.mongo_clientr-   Zpymongo.networkr.   Zpymongo.operationsr/   Zpymongo.poolr0   r1   r2   Zpymongo.read_concernr3   Zpymongo.resultsr4   r5   Zpymongo.ssl_supportr6   Zpymongo.typingsr7   Zpymongo.uri_parserr8   Zpymongo.write_concernr9   r:   r^   r]   r   r<   __annotations__rO   contextmanagerrC   rD   r   r   ry   Enumr   r   r   rA   rA   rA   rB   <module>   sr   0
 
 Bt