U
    W+d                     @   sl   d dl 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 dlmZ d dlZG dd	 d	eZdS )
    N)json)AWSQueryConnection)
RegionInfo)JSONResponseError)
exceptions)sixc                       sj  e Zd ZdZdZdZdZdZdZe	Z
ejejejejejejejejejejejejejejejdZ fdd	Zd
d Zdd ZdAddZdBddZ dCddZ!dd Z"dd Z#dd Z$dd Z%dd Z&dd  Z'dDd!d"Z(dEd#d$Z)dFd%d&Z*dGd'd(Z+d)d* Z,d+d, Z-dHd-d.Z.dId/d0Z/dJd1d2Z0dKd3d4Z1d5d6 Z2dLd7d8Z3d9d: Z4d;d< Z5d=d> Z6d?d@ Z7  Z8S )MKMSConnectiona
  
    AWS Key Management Service
    AWS Key Management Service (KMS) is an encryption and key
    management web service. This guide describes the KMS actions that
    you can call programmatically. For general information about KMS,
    see (need an address here). For the KMS developer guide, see (need
    address here).

    AWS provides SDKs that consist of libraries and sample code for
    various programming languages and platforms (Java, Ruby, .Net,
    iOS, Android, etc.). The SDKs provide a convenient way to create
    programmatic access to KMS and AWS. For example, the SDKs take
    care of tasks such as signing requests (see below), managing
    errors, and retrying requests automatically. For more information
    about the AWS SDKs, including how to download and install them,
    see `Tools for Amazon Web Services`_.

    We recommend that you use the AWS SDKs to make programmatic API
    calls to KMS. However, you can also use the KMS Query API to make
    to make direct calls to the KMS web service.

    **Signing Requests**

    Requests must be signed by using an access key ID and a secret
    access key. We strongly recommend that you do not use your AWS
    account access key ID and secret key for everyday work with KMS.
    Instead, use the access key ID and secret access key for an IAM
    user, or you can use the AWS Security Token Service to generate
    temporary security credentials that you can use to sign requests.

    All KMS operations require `Signature Version 4`_.

    **Recording API Requests**

    KMS supports AWS CloudTrail, a service that records AWS API calls
    and related events for your AWS account and delivers them to an
    Amazon S3 bucket that you specify. By using the information
    collected by CloudTrail, you can determine what requests were made
    to KMS, who made the request, when it was made, and so on. To
    learn more about CloudTrail, including how to turn it on and find
    your log files, see the `AWS CloudTrail User Guide`_

    **Additional Resources**

    For more information about credentials and request signing, see
    the following:


    + `AWS Security Credentials`_. This topic provides general
      information about the types of credentials used for accessing AWS.
    + `AWS Security Token Service`_. This guide describes how to
      create and use temporary security credentials.
    + `Signing AWS API Requests`_. This set of topics walks you
      through the process of signing a request using an access key ID
      and a secret access key.
    z
2014-11-01z	us-east-1zkms.us-east-1.amazonaws.comZKMSZTrentService)InvalidGrantTokenExceptionDisabledExceptionLimitExceededExceptionDependencyTimeoutExceptionInvalidMarkerExceptionAlreadyExistsExceptionInvalidCiphertextExceptionKeyUnavailableExceptionInvalidAliasNameExceptionUnsupportedOperationExceptionInvalidArnExceptionKMSInternalExceptionInvalidKeyUsageException MalformedPolicyDocumentExceptionNotFoundExceptionc                    sZ   | dd }|s t| | j| j}d|ks4|d d kr>|j|d< tt| jf | || _d S )Nregionhost)	popr   DefaultRegionNameDefaultRegionEndpointendpointsuperr   __init__r   )selfkwargsr   	__class__ 3/tmp/pip-unpacked-wheel-dlxw5sjy/boto/kms/layer1.pyr   t   s    
zKMSConnection.__init__c                 C   s   dgS )Nzhmac-v4r$   )r    r$   r$   r%   _required_auth_capability   s    z'KMSConnection._required_auth_capabilityc                 C   s   ||d}| j dt|dS )a{  
        Creates a display name for a customer master key. An alias can
        be used to identify a key and should be unique. The console
        enforces a one-to-one mapping between the alias and a key. An
        alias name can contain only alphanumeric characters, forward
        slashes (/), underscores (_), and dashes (-). An alias must
        start with the word "alias" followed by a forward slash
        (alias/). An alias that begins with "aws" after the forward
        slash (alias/aws...) is reserved by Amazon Web Services (AWS).

        :type alias_name: string
        :param alias_name: String that contains the display name. Aliases that
            begin with AWS are reserved.

        :type target_key_id: string
        :param target_key_id: An identifier of the key for which you are
            creating the alias. This value cannot be another alias.

        )	AliasNameZTargetKeyIdZCreateAliasactionbodymake_requestr   dumps)r    
alias_nameZtarget_key_idparamsr$   r$   r%   create_alias   s    zKMSConnection.create_aliasNc                 C   s^   ||d}|dk	r||d< |dk	r*||d< |dk	r:||d< |dk	rJ||d< | j dt|dS )	a  
        Adds a grant to a key to specify who can access the key and
        under what conditions. Grants are alternate permission
        mechanisms to key policies. If absent, access to the key is
        evaluated based on IAM policies attached to the user. By
        default, grants do not expire. Grants can be listed, retired,
        or revoked as indicated by the following APIs. Typically, when
        you are finished using a grant, you retire it. When you want
        to end a grant immediately, revoke it. For more information
        about grants, see `Grants`_.

        #. ListGrants
        #. RetireGrant
        #. RevokeGrant

        :type key_id: string
        :param key_id: A unique key identifier for a customer master key. This
            value can be a globally unique identifier, an ARN, or an alias.

        :type grantee_principal: string
        :param grantee_principal: Principal given permission by the grant to
            use the key identified by the `keyId` parameter.

        :type retiring_principal: string
        :param retiring_principal: Principal given permission to retire the
            grant. For more information, see RetireGrant.

        :type operations: list
        :param operations: List of operations permitted by the grant. This can
            be any combination of one or more of the following values:

        #. Decrypt
        #. Encrypt
        #. GenerateDataKey
        #. GenerateDataKeyWithoutPlaintext
        #. ReEncryptFrom
        #. ReEncryptTo
        #. CreateGrant

        :type constraints: dict
        :param constraints: Specifies the conditions under which the actions
            specified by the `Operations` parameter are allowed.

        :type grant_tokens: list
        :param grant_tokens: List of grant tokens.

        )KeyIdZGranteePrincipalNZRetiringPrincipalZ
OperationsZConstraintsGrantTokensZCreateGrantr(   r+   )r    key_idZgrantee_principalZretiring_principal
operationsconstraintsgrant_tokensr/   r$   r$   r%   create_grant   s    3zKMSConnection.create_grantc                 C   sH   i }|dk	r||d< |dk	r$||d< |dk	r4||d< | j dt|dS )a  
        Creates a customer master key. Customer master keys can be
        used to encrypt small amounts of data (less than 4K) directly,
        but they are most commonly used to encrypt or envelope data
        keys that are then used to encrypt customer data. For more
        information about data keys, see GenerateDataKey and
        GenerateDataKeyWithoutPlaintext.

        :type policy: string
        :param policy: Policy to be attached to the key. This is required and
            delegates back to the account. The key is the root of trust.

        :type description: string
        :param description: Description of the key. We recommend that you
            choose a description that helps your customer decide whether the
            key is appropriate for a task.

        :type key_usage: string
        :param key_usage: Specifies the intended use of the key. Currently this
            defaults to ENCRYPT/DECRYPT, and only symmetric encryption and
            decryption are supported.

        NPolicyDescriptionZKeyUsageZ	CreateKeyr(   r+   )r    policydescriptionZ	key_usager/   r$   r$   r%   
create_key   s    zKMSConnection.create_keyc                 C   s   t |tjstdtj t|}d|di}|dk	rB||d< |dk	rR||d< | jdt	|d}|
d	dk	rt|d	 d|d	< |S )
a  
        Decrypts ciphertext. Ciphertext is plaintext that has been
        previously encrypted by using the Encrypt function.

        :type ciphertext_blob: blob
        :param ciphertext_blob: Ciphertext including metadata.

        :type encryption_context: map
        :param encryption_context: The encryption context. If this was
            specified in the Encrypt function, it must be specified here or the
            decryption operation will fail. For more information, see
            `Encryption Context`_.

        :type grant_tokens: list
        :param grant_tokens: A list of grant tokens that represent grants which
            can be used to provide long term permissions to perform decryption.

        9Value of argument ``ciphertext_blob`` must be of type %s.CiphertextBlobutf-8NEncryptionContextr2   ZDecryptr(   	Plaintext
isinstancer   binary_type	TypeErrorbase64	b64encodedecoder,   r   r-   get	b64decodeencode)r    ciphertext_blobencryption_contextr6   r/   responser$   r$   r%   decrypt  s(    
zKMSConnection.decryptc                 C   s   d|i}| j dt|dS )z
        Deletes the specified alias.

        :type alias_name: string
        :param alias_name: The alias to be deleted.

        r'   ZDeleteAliasr(   r+   )r    r.   r/   r$   r$   r%   delete_alias&  s    zKMSConnection.delete_aliasc                 C   s   d|i}| j dt|dS )a+  
        Provides detailed information about the specified customer
        master key.

        :type key_id: string
        :param key_id: Unique identifier of the customer master key to be
            described. This can be an ARN, an alias, or a globally unique
            identifier.

        r1   ZDescribeKeyr(   r+   r    r3   r/   r$   r$   r%   describe_key2  s    zKMSConnection.describe_keyc                 C   s   d|i}| j dt|dS )a  
        Marks a key as disabled, thereby preventing its use.

        :type key_id: string
        :param key_id: Unique identifier of the customer master key to be
            disabled. This can be an ARN, an alias, or a globally unique
            identifier.

        r1   Z
DisableKeyr(   r+   rQ   r$   r$   r%   disable_keyA  s    
zKMSConnection.disable_keyc                 C   s   d|i}| j dt|dS )a  
        Disables rotation of the specified key.

        :type key_id: string
        :param key_id: Unique identifier of the customer master key for which
            rotation is to be disabled. This can be an ARN, an alias, or a
            globally unique identifier.

        r1   ZDisableKeyRotationr(   r+   rQ   r$   r$   r%   disable_key_rotationO  s    
z"KMSConnection.disable_key_rotationc                 C   s   d|i}| j dt|dS )aF  
        Marks a key as enabled, thereby permitting its use. You can
        have up to 25 enabled keys at one time.

        :type key_id: string
        :param key_id: Unique identifier of the customer master key to be
            enabled. This can be an ARN, an alias, or a globally unique
            identifier.

        r1   Z	EnableKeyr(   r+   rQ   r$   r$   r%   
enable_key]  s    zKMSConnection.enable_keyc                 C   s   d|i}| j dt|dS )a'  
        Enables rotation of the specified customer master key.

        :type key_id: string
        :param key_id: Unique identifier of the customer master key for which
            rotation is to be enabled. This can be an ARN, an alias, or a
            globally unique identifier.

        r1   ZEnableKeyRotationr(   r+   rQ   r$   r$   r%   enable_key_rotationl  s    
z!KMSConnection.enable_key_rotationc                 C   s   t |tjstdtj t|}||dd}|dk	rD||d< |dk	rT||d< | jdt	|d}|
d	dk	rt|d	 d|d	< |S )
a  
        Encrypts plaintext into ciphertext by using a customer master
        key.

        :type key_id: string
        :param key_id: Unique identifier of the customer master. This can be an
            ARN, an alias, or the Key ID.

        :type plaintext: blob
        :param plaintext: Data to be encrypted.

        :type encryption_context: map
        :param encryption_context: Name:value pair that specifies the
            encryption context to be used for authenticated encryption. For
            more information, see `Authenticated Encryption`_.

        :type grant_tokens: list
        :param grant_tokens: A list of grant tokens that represent grants which
            can be used to provide long term permissions to perform encryption.

        z3Value of argument ``plaintext`` must be of type %s.r?   )r1   rA   Nr@   r2   ZEncryptr(   r>   rB   )r    r3   	plaintextrM   r6   r/   rN   r$   r$   r%   encryptz  s(    
zKMSConnection.encryptc                 C   s   d|i}|dk	r||d< |dk	r(||d< |dk	r8||d< |dk	rH||d< | j dt|d}|d	dk	rt|d	 d
|d	< |ddk	rt|d d
|d< |S )a  
        Generates a secure data key. Data keys are used to encrypt and
        decrypt data. They are wrapped by customer master keys.

        :type key_id: string
        :param key_id: Unique identifier of the key. This can be an ARN, an
            alias, or a globally unique identifier.

        :type encryption_context: map
        :param encryption_context: Name/value pair that contains additional
            data to be authenticated during the encryption and decryption
            processes that use the key. This value is logged by AWS CloudTrail
            to provide context around the data encrypted by the key.

        :type number_of_bytes: integer
        :param number_of_bytes: Integer that contains the number of bytes to
            generate. Common values are 128, 256, 512, 1024 and so on. 1024 is
            the current limit.

        :type key_spec: string
        :param key_spec: Value that identifies the encryption algorithm and key
            size to generate a data key for. Currently this can be AES_128 or
            AES_256.

        :type grant_tokens: list
        :param grant_tokens: A list of grant tokens that represent grants which
            can be used to provide long term permissions to generate a key.

        r1   Nr@   NumberOfBytesKeySpecr2   ZGenerateDataKeyr(   r>   r?   rA   r,   r   r-   rI   rF   rJ   rK   )r    r3   rM   number_of_byteskey_specr6   r/   rN   r$   r$   r%   generate_data_key  s*     zKMSConnection.generate_data_keyc                 C   s   d|i}|dk	r||d< |dk	r(||d< |dk	r8||d< |dk	rH||d< | j dt|d}|d	dk	rt|d	 d
|d	< |S )aA  
        Returns a key wrapped by a customer master key without the
        plaintext copy of that key. To retrieve the plaintext, see
        GenerateDataKey.

        :type key_id: string
        :param key_id: Unique identifier of the key. This can be an ARN, an
            alias, or a globally unique identifier.

        :type encryption_context: map
        :param encryption_context: Name:value pair that contains additional
            data to be authenticated during the encryption and decryption
            processes.

        :type key_spec: string
        :param key_spec: Value that identifies the encryption algorithm and key
            size. Currently this can be AES_128 or AES_256.

        :type number_of_bytes: integer
        :param number_of_bytes: Integer that contains the number of bytes to
            generate. Common values are 128, 256, 512, 1024 and so on.

        :type grant_tokens: list
        :param grant_tokens: A list of grant tokens that represent grants which
            can be used to provide long term permissions to generate a key.

        r1   Nr@   rZ   rY   r2   ZGenerateDataKeyWithoutPlaintextr(   r>   r?   r[   )r    r3   rM   r]   r\   r6   r/   rN   r$   r$   r%   #generate_data_key_without_plaintext  s"     z1KMSConnection.generate_data_key_without_plaintextc                 C   sR   i }|dk	r||d< | j dt|d}|ddk	rNt|d d|d< |S )a#  
        Generates an unpredictable byte string.

        :type number_of_bytes: integer
        :param number_of_bytes: Integer that contains the number of bytes to
            generate. Common values are 128, 256, 512, 1024 and so on. The
            current limit is 1024 bytes.

        NrY   ZGenerateRandomr(   rA   r?   r[   )r    r\   r/   rN   r$   r$   r%   generate_random  s    
zKMSConnection.generate_randomc                 C   s   ||d}| j dt|dS )a  
        Retrieves a policy attached to the specified key.

        :type key_id: string
        :param key_id: Unique identifier of the key. This can be an ARN, an
            alias, or a globally unique identifier.

        :type policy_name: string
        :param policy_name: String that contains the name of the policy.
            Currently, this must be "default". Policy names can be discovered
            by calling ListKeyPolicies.

        )r1   
PolicyNameZGetKeyPolicyr(   r+   )r    r3   policy_namer/   r$   r$   r%   get_key_policy  s    
zKMSConnection.get_key_policyc                 C   s   d|i}| j dt|dS )a  
        Retrieves a Boolean value that indicates whether key rotation
        is enabled for the specified key.

        :type key_id: string
        :param key_id: Unique identifier of the key. This can be an ARN, an
            alias, or a globally unique identifier.

        r1   ZGetKeyRotationStatusr(   r+   rQ   r$   r$   r%   get_key_rotation_status+  s    
z%KMSConnection.get_key_rotation_statusc                 C   s8   i }|dk	r||d< |dk	r$||d< | j dt|dS )a  
        Lists all of the key aliases in the account.

        :type limit: integer
        :param limit: Specify this parameter when paginating results to
            indicate the maximum number of aliases you want in each response.
            If there are additional aliases beyond the maximum you specify, the
            `Truncated` response element will be set to `true.`

        :type marker: string
        :param marker: Use this parameter when paginating results, and only in
            a subsequent request after you've received a response where the
            results are truncated. Set it to the value of the `NextMarker`
            element in the response you just received.

        NLimitMarkerZListAliasesr(   r+   r    limitmarkerr/   r$   r$   r%   list_aliases9  s    zKMSConnection.list_aliasesc                 C   s<   d|i}|dk	r||d< |dk	r(||d< | j dt|dS )aZ  
        List the grants for a specified key.

        :type key_id: string
        :param key_id: Unique identifier of the key. This can be an ARN, an
            alias, or a globally unique identifier.

        :type limit: integer
        :param limit: Specify this parameter only when paginating results to
            indicate the maximum number of grants you want listed in the
            response. If there are additional grants beyond the maximum you
            specify, the `Truncated` response element will be set to `true.`

        :type marker: string
        :param marker: Use this parameter only when paginating results, and
            only in a subsequent request after you've received a response where
            the results are truncated. Set it to the value of the `NextMarker`
            in the response you just received.

        r1   Nre   rf   Z
ListGrantsr(   r+   r    r3   rh   ri   r/   r$   r$   r%   list_grantsR  s    zKMSConnection.list_grantsc                 C   s<   d|i}|dk	r||d< |dk	r(||d< | j dt|dS )ai  
        Retrieves a list of policies attached to a key.

        :type key_id: string
        :param key_id: Unique identifier of the key. This can be an ARN, an
            alias, or a globally unique identifier.

        :type limit: integer
        :param limit: Specify this parameter only when paginating results to
            indicate the maximum number of policies you want listed in the
            response. If there are additional policies beyond the maximum you
            specify, the `Truncated` response element will be set to `true.`

        :type marker: string
        :param marker: Use this parameter only when paginating results, and
            only in a subsequent request after you've received a response where
            the results are truncated. Set it to the value of the `NextMarker`
            in the response you just received.

        r1   Nre   rf   ZListKeyPoliciesr(   r+   rk   r$   r$   r%   list_key_policieso  s    zKMSConnection.list_key_policiesc                 C   s8   i }|dk	r||d< |dk	r$||d< | j dt|dS )a  
        Lists the customer master keys.

        :type limit: integer
        :param limit: Specify this parameter only when paginating results to
            indicate the maximum number of keys you want listed in the
            response. If there are additional keys beyond the maximum you
            specify, the `Truncated` response element will be set to `true.`

        :type marker: string
        :param marker: Use this parameter only when paginating results, and
            only in a subsequent request after you've received a response where
            the results are truncated. Set it to the value of the `NextMarker`
            in the response you just received.

        Nre   rf   ZListKeysr(   r+   rg   r$   r$   r%   	list_keys  s    zKMSConnection.list_keysc                 C   s    |||d}| j dt|dS )a  
        Attaches a policy to the specified key.

        :type key_id: string
        :param key_id: Unique identifier of the key. This can be an ARN, an
            alias, or a globally unique identifier.

        :type policy_name: string
        :param policy_name: Name of the policy to be attached. Currently, the
            only supported name is "default".

        :type policy: string
        :param policy: The policy, in JSON format, to be attached to the key.

        )r1   ra   r8   ZPutKeyPolicyr(   r+   )r    r3   rb   r:   r/   r$   r$   r%   put_key_policy  s    zKMSConnection.put_key_policyc                 C   s   t |tjstdtj t|}||d}|dk	r>||d< |dk	rN||d< |dk	r^||d< | jdt|d}|	d	dk	rt
|d	 d
|d	< |S )aT  
        Encrypts data on the server side with a new customer master
        key without exposing the plaintext of the data on the client
        side. The data is first decrypted and then encrypted. This
        operation can also be used to change the encryption context of
        a ciphertext.

        :type ciphertext_blob: blob
        :param ciphertext_blob: Ciphertext of the data to re-encrypt.

        :type source_encryption_context: map
        :param source_encryption_context: Encryption context used to encrypt
            and decrypt the data specified in the `CiphertextBlob` parameter.

        :type destination_key_id: string
        :param destination_key_id: Key identifier of the key used to re-encrypt
            the data.

        :type destination_encryption_context: map
        :param destination_encryption_context: Encryption context to be used
            when the data is re-encrypted.

        :type grant_tokens: list
        :param grant_tokens: Grant tokens that identify the grants that have
            permissions for the encryption and decryption process.

        r=   )r>   ZDestinationKeyIdNZSourceEncryptionContextZDestinationEncryptionContextr2   Z	ReEncryptr(   r>   r?   )rC   r   rD   rE   rF   rG   r,   r   r-   rI   rJ   rK   )r    rL   Zdestination_key_idZsource_encryption_contextZdestination_encryption_contextr6   r/   rN   r$   r$   r%   
re_encrypt  s0    
zKMSConnection.re_encryptc                 C   s   d|i}| j dt|dS )a8  
        Retires a grant. You can retire a grant when you're done using
        it to clean up. You should revoke a grant when you intend to
        actively deny operations that depend on it.

        :type grant_token: string
        :param grant_token: Token that identifies the grant to be retired.

        Z
GrantTokenZRetireGrantr(   r+   )r    Zgrant_tokenr/   r$   r$   r%   retire_grant  s    
zKMSConnection.retire_grantc                 C   s   ||d}| j dt|dS )a>  
        Revokes a grant. You can revoke a grant to actively deny
        operations that depend on it.

        :type key_id: string
        :param key_id: Unique identifier of the key associated with the grant.

        :type grant_id: string
        :param grant_id: Identifier of the grant to be revoked.

        )r1   ZGrantIdZRevokeGrantr(   r+   )r    r3   Zgrant_idr/   r$   r$   r%   revoke_grant  s    
zKMSConnection.revoke_grantc                 C   s   ||d}| j dt|dS )z
        

        :type key_id: string
        :param key_id:

        :type description: string
        :param description:

        )r1   r9   ZUpdateKeyDescriptionr(   r+   )r    r3   r;   r/   r$   r$   r%   update_key_description  s    
z$KMSConnection.update_key_descriptionc           
      C   s   d| j |f | jjdtt|d}| jdddi ||d}| j|d dd}| d	}t	j
| |jd
kr~|rt|S n8t|}|dd }| j|| j}	|	|j|j|dd S )Nz%s.%szapplication/x-amz-json-1.1)zX-Amz-TargetHostzContent-TypezContent-LengthPOST/)methodpathZ	auth_pathr/   headersdata
   )ZsenderZoverride_num_retriesr?      Z__type)r*   )TargetPrefixr   r   strlenZbuild_base_http_requestZ_mexereadrH   botologdebugstatusr   loadsrI   _faultsResponseErrorreason)
r    r)   r*   ry   http_requestrN   Zresponse_bodyZ	json_bodyZ
fault_nameZexception_classr$   r$   r%   r,     s6    
    


zKMSConnection.make_request)NNNN)NNN)NN)NN)NNNN)NNNN)N)NN)NN)NN)NN)NNN)9__name__
__module____qualname____doc__Z
APIVersionr   r   ZServiceNamer}   r   r   r   r	   r
   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r&   r0   r7   r<   rO   rP   rR   rS   rT   rU   rV   rX   r^   r_   r`   rc   rd   rj   rl   rm   rn   ro   rp   rq   rr   rs   r,   __classcell__r$   r$   r"   r%   r   !   s   8      
A
"  
%  
(     
4    
0




    
4r   )r   Zboto.compatr   Zboto.connectionr   Zboto.regioninfor   Zboto.exceptionr   Zboto.kmsr   r   rF   r   r$   r$   r$   r%   <module>   s   