o
    .&ßaün  ã                   @   s  d dl Z d dlZd dlZd dlZd dlZd dlZd dlmZmZ d dl	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mZ G d	d
„ d
eƒZG dd„ deƒZdd„ Zddd„ZG dd„ deƒZdd„ Z		ddd„Zdd„ Z		d dd„Zdd„ ZdS )!é    N)ÚsixÚOrderedDict)Úcreate_request_objectÚprepare_request_dict)ÚUnknownSignatureVersionError)ÚUnknownClientMethodError)Ú UnsupportedSignatureVersionError)Údatetime2timestamp)Úfix_s3_hostc                   @   sz   e Zd ZdZdd„ Zedd„ ƒZedd„ ƒZedd	„ ƒZddd„Z		
	
ddd„Z
dd„ Z	
ddd„ZeZ	
	
ddd„Zd
S )ÚRequestSignera0  
    An object to sign requests before they go out over the wire using
    one of the authentication mechanisms defined in ``auth.py``. This
    class fires two events scoped to a service and operation name:

    * choose-signer: Allows overriding the auth signer name.
    * before-sign: Allows mutating the request before signing.

    Together these events allow for customization of the request
    signing pipeline, including overrides, request path manipulation,
    and disabling signing per operation.


    :type service_id: botocore.model.ServiceId
    :param service_id: The service id for the service, e.g. ``S3``

    :type region_name: string
    :param region_name: Name of the service region, e.g. ``us-east-1``

    :type signing_name: string
    :param signing_name: Service signing name. This is usually the
                         same as the service name, but can differ. E.g.
                         ``emr`` vs. ``elasticmapreduce``.

    :type signature_version: string
    :param signature_version: Signature name like ``v4``.

    :type credentials: :py:class:`~botocore.credentials.Credentials`
    :param credentials: User credentials with which to sign requests.

    :type event_emitter: :py:class:`~botocore.hooks.BaseEventHooks`
    :param event_emitter: Extension mechanism to fire events.
    c                 C   s.   || _ || _|| _|| _|| _t |¡| _d S ©N)Ú_region_nameÚ_signing_nameÚ_signature_versionÚ_credentialsÚ_service_idÚweakrefÚproxyÚ_event_emitter)ÚselfÚ
service_idÚregion_nameÚsigning_nameÚsignature_versionÚcredentialsÚevent_emitter© r   ú2/usr/lib/python3/dist-packages/botocore/signers.pyÚ__init__A   s   zRequestSigner.__init__c                 C   ó   | j S r   )r   ©r   r   r   r   r   L   ó   zRequestSigner.region_namec                 C   r   r   )r   r    r   r   r   r   P   r!   zRequestSigner.signature_versionc                 C   r   r   )r   r    r   r   r   r   T   r!   zRequestSigner.signing_nameNc                 K   s   |   ||¡S r   )Úsign)r   Úoperation_nameÚrequestÚkwargsr   r   r   ÚhandlerX   s   zRequestSigner.handlerÚstandardc              
   C   s  |}|du r	| j }|du r| j}|  |||j¡}| jjd | j ¡ |¡||| j || |d� |t	j
krˆ|||dœ}	|dur@||	d< |j di ¡}
|sT|
 d¡rT|
d |	d< |
 d	¡r_|
d	 |	d	< z
| jdi |	¤Ž}W n ty€ } z|d
krzt|d�‚|‚d}~ww | |¡ dS dS )a<  Sign a request before it goes out over the wire.

        :type operation_name: string
        :param operation_name: The name of the current operation, e.g.
                               ``ListBuckets``.
        :type request: AWSRequest
        :param request: The request object to be sent over the wire.

        :type region_name: str
        :param region_name: The region to sign the request for.

        :type signing_type: str
        :param signing_type: The type of signing to perform. This can be one of
            three possible values:

            * 'standard'     - This should be used for most requests.
            * 'presign-url'  - This should be used when pre-signing a request.
            * 'presign-post' - This should be used when pre-signing an S3 post.

        :type expires_in: int
        :param expires_in: The number of seconds the presigned url is valid
            for. This parameter is only valid for signing type 'presign-url'.

        :type signing_name: str
        :param signing_name: The name to use for the service when signing.
        Nzbefore-sign.{0}.{1})r$   r   r   r   Úrequest_signerr#   )r   r   r   ÚexpiresÚsigningÚregionr   r   r'   ©r   r   )r   r   Ú_choose_signerÚcontextr   ÚemitÚformatr   Ú	hyphenizeÚbotocoreÚUNSIGNEDÚgetÚget_auth_instancer   r   Úadd_auth)r   r#   r$   r   Úsigning_typeÚ
expires_inr   Úexplicit_region_namer   r%   Úsigning_contextÚauthÚer   r   r   r"   _   sR   ÿ
ÿú
	ý
ÿ€ûêzRequestSigner.signc           	      C   s�   dddœ}|  |d¡}| j}|tjur| |¡s||7 }| jjd | j 	¡ |¡| j
| j||d�\}}|durF|}|tjurF| |¡sF||7 }|S )ai  
        Allow setting the signature version via the choose-signer event.
        A value of `botocore.UNSIGNED` means no signing will be performed.

        :param operation_name: The operation to sign.
        :param signing_type: The type of signing that the signer is to be used
            for.
        :return: The signature version to sign with.
        z-presign-postz-query)úpresign-postúpresign-urlÚ zchoose-signer.{0}.{1})r   r   r   r.   N)r4   r   r2   r3   Úendswithr   Úemit_until_responser0   r   r1   r   r   )	r   r#   r7   r.   Úsigning_type_suffix_mapÚsuffixr   r&   Úresponser   r   r   r-   §   s.   þ
ÿ
ÿ
ü
ÿzRequestSigner._choose_signerc                 K   sŠ   |du r| j }tjj |¡}|du rt|d�‚d}| jdur#| j ¡ }||d< |jr<| j	du r4tj
 ¡ ‚||d< ||d< |di |¤Ž}|S )a©  
        Get an auth instance which can be used to sign a request
        using the given signature version.

        :type signing_name: string
        :param signing_name: Service signing name. This is usually the
                             same as the service name, but can differ. E.g.
                             ``emr`` vs. ``elasticmapreduce``.

        :type region_name: string
        :param region_name: Name of the service region, e.g. ``us-east-1``

        :type signature_version: string
        :param signature_version: Signature name like ``v4``.

        :rtype: :py:class:`~botocore.auth.BaseSigner`
        :return: Auth instance to sign a request.
        Nr,   r   r   Úservice_namer   )r   r2   r;   ÚAUTH_TYPE_MAPSr4   r   r   Úget_frozen_credentialsÚREQUIRES_REGIONr   Ú
exceptionsÚNoRegionError)r   r   r   r   r%   ÚclsÚfrozen_credentialsr;   r   r   r   r5   Ì   s$   ÿ



zRequestSigner.get_auth_instanceé  c                 C   s*   t |ƒ}|  |||d||¡ | ¡  |jS )aÍ  Generates a presigned url

        :type request_dict: dict
        :param request_dict: The prepared request dictionary returned by
            ``botocore.awsrequest.prepare_request_dict()``

        :type operation_name: str
        :param operation_name: The operation being signed.

        :type expires_in: int
        :param expires_in: The number of seconds the presigned url is valid
            for. By default it expires in an hour (3600 seconds)

        :type region_name: string
        :param region_name: The region name to sign the presigned url.

        :type signing_name: str
        :param signing_name: The name to use for the service when signing.

        :returns: The presigned url
        r>   )r   r"   ÚprepareÚurl)r   Úrequest_dictr#   r8   r   r   r$   r   r   r   Úgenerate_presigned_urlú   s   
ÿz$RequestSigner.generate_presigned_url©NN)Nr'   NNr   )rM   NN)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Úpropertyr   r   r   r&   r"   r-   r5   Úget_authrQ   r   r   r   r   r      s(    !




ÿH&
ÿ,þr   c                   @   s>   e Zd ZdZdd„ Zddd„Zdd„ Z	dd	d
„Zdd„ ZdS )ÚCloudFrontSigneraà  A signer to create a signed CloudFront URL.

    First you create a cloudfront signer based on a normalized RSA signer::

        import rsa
        def rsa_signer(message):
            private_key = open('private_key.pem', 'r').read()
            return rsa.sign(
                message,
                rsa.PrivateKey.load_pkcs1(private_key.encode('utf8')),
                'SHA-1')  # CloudFront requires SHA-1 hash
        cf_signer = CloudFrontSigner(key_id, rsa_signer)

    To sign with a canned policy::

        signed_url = cf_signer.generate_signed_url(
            url, date_less_than=datetime(2015, 12, 1))

    To sign with a custom policy::

        signed_url = cf_signer.generate_signed_url(url, policy=my_policy)
    c                 C   s   || _ || _dS )a–  Create a CloudFrontSigner.

        :type key_id: str
        :param key_id: The CloudFront Key Pair ID

        :type rsa_signer: callable
        :param rsa_signer: An RSA signer.
               Its only input parameter will be the message to be signed,
               and its output will be the signed content as a binary string.
               The hash algorithm needed by CloudFront is SHA-1.
        N)Úkey_idÚ
rsa_signer)r   rZ   r[   r   r   r   r   2  s   
zCloudFrontSigner.__init__Nc           	      C   sÊ   |duo|du}|du o|du }|s|rd}t |ƒ‚|dur$|  ||¡}t|tjƒr/| d¡}|dur=dtt|ƒƒ g}nd|  |¡ 	d¡ g}|  
|¡}| d|  |¡ 	d¡ d| j g¡ |  ||¡S )a¤  Creates a signed CloudFront URL based on given parameters.

        :type url: str
        :param url: The URL of the protected object

        :type date_less_than: datetime
        :param date_less_than: The URL will expire after that date and time

        :type policy: str
        :param policy: The custom policy, possibly built by self.build_policy()

        :rtype: str
        :return: The signed URL.
        Nz=Need to provide either date_less_than or policy, but not bothÚutf8z
Expires=%sz	Policy=%szSignature=%szKey-Pair-Id=%s)Ú
ValueErrorÚbuild_policyÚ
isinstancer   Ú	text_typeÚencodeÚintr	   Ú_url_b64encodeÚdecoder[   ÚextendrZ   Ú
_build_url)	r   rO   Údate_less_thanÚpolicyÚboth_args_suppliedÚneither_arg_suppliedr<   ÚparamsÚ	signaturer   r   r   rQ   A  s$   

þz'CloudFrontSigner.generate_presigned_urlc                 C   s"   d|v rdnd}|| d  |¡ S )Nú?ú&)Újoin)r   Úbase_urlÚextra_paramsÚ	separatorr   r   r   rf   e  s   zCloudFrontSigner._build_urlc           	      C   s„   t t|ƒƒ}tdd|iiƒ}|rd|vr|d7 }d|i|d< |r,t t|ƒƒ}d|i|d< d|fd	|fg}d
t|ƒgi}tj|dd�S )a0  A helper to build policy.

        :type resource: str
        :param resource: The URL or the stream filename of the protected object

        :type date_less_than: datetime
        :param date_less_than: The URL will expire after the time has passed

        :type date_greater_than: datetime
        :param date_greater_than: The URL will not be valid until this time

        :type ip_address: str
        :param ip_address: Use 'x.x.x.x' for an IP, or 'x.x.x.x/x' for a subnet

        :rtype: str
        :return: The policy in a compact string.
        ÚDateLessThanzAWS:EpochTimeú/z/32zAWS:SourceIpÚ	IpAddressÚDateGreaterThanÚResourceÚ	ConditionÚ	Statement)ú,ú:)Ú
separators)rb   r	   r   ÚjsonÚdumps)	r   Úresourcerg   Údate_greater_thanÚ
ip_addressÚmomentÚ	conditionÚordered_payloadÚcustom_policyr   r   r   r^   i  s   zCloudFrontSigner.build_policyc                 C   s"   t  |¡ dd¡ dd¡ dd¡S )Nó   +ó   -ó   =ó   _ó   /ó   ~)Úbase64Ú	b64encodeÚreplace)r   Údatar   r   r   rc   ’  s
   ÿÿzCloudFrontSigner._url_b64encoderR   )	rS   rT   rU   rV   r   rQ   rf   r^   rc   r   r   r   r   rY     s    
$
ÿ)rY   c                 K   ó   t | d< d S )NÚgenerate_db_auth_token)r‘   ©Úclass_attributesr%   r   r   r   Úadd_generate_db_auth_token™  ó   r”   c                 C   sp   |}|du r
| j j}d|dœ}ddi |ddœ}d}d	|||f }	t||	ƒ | jjd||d
dd�}
|
t|ƒd… S )a  Generates an auth token used to connect to a db with IAM credentials.

    :type DBHostname: str
    :param DBHostname: The hostname of the database to connect to.

    :type Port: int
    :param Port: The port number the database is listening on.

    :type DBUsername: str
    :param DBUsername: The username to log in as.

    :type Region: str
    :param Region: The region the database is in. If None, the client
        region will be used.

    :return: A presigned url which can be used as an auth token.
    NÚconnect)ÚActionÚDBUserrt   r?   ÚGET)Úurl_pathÚquery_stringÚheadersÚbodyÚmethodzhttps://z%s%s:%si„  zrds-db)r#   rP   r   r8   r   )Úmetar   r   Ú_request_signerrQ   Úlen)r   Ú
DBHostnameÚPortÚ
DBUsernameÚRegionr+   rk   rP   ÚschemeÚendpoint_urlÚpresigned_urlr   r   r   r‘   �  s(   þû
þr‘   c                   @   s$   e Zd Zdd„ Z			ddd„ZdS )ÚS3PostPresignerc                 C   s
   || _ d S r   )r    )r   r(   r   r   r   r   Ñ  s   
zS3PostPresigner.__init__NrM   c                 C   s¢   |du ri }|du rg }i }t j  ¡ }|t j|d� }| tjj¡|d< g |d< |D ]	}	|d  |	¡ q*t|ƒ}
||
j	d< ||
j	d< | j
 d|
|d¡ |
j|d	œS )
aÁ  Generates the url and the form fields used for a presigned s3 post

        :type request_dict: dict
        :param request_dict: The prepared request dictionary returned by
            ``botocore.awsrequest.prepare_request_dict()``

        :type fields: dict
        :param fields: A dictionary of prefilled form fields to build on top
            of.

        :type conditions: list
        :param conditions: A list of conditions to include in the policy. Each
            element can be either a list or a structure. For example:
            [
             {"acl": "public-read"},
             {"bucket": "mybucket"},
             ["starts-with", "$key", "mykey"]
            ]

        :type expires_in: int
        :param expires_in: The number of seconds the presigned post is valid
            for.

        :type region_name: string
        :param region_name: The region name to sign the presigned post to.

        :rtype: dict
        :returns: A dictionary with two elements: ``url`` and ``fields``.
            Url is the url to post to. Fields is a dictionary filled with
            the form fields and respective values to use when submitting the
            post. For example:

            {'url': 'https://mybucket.s3.amazonaws.com
             'fields': {'acl': 'public-read',
                        'key': 'mykey',
                        'signature': 'mysignature',
                        'policy': 'mybase64 encoded policy'}
            }
        N)ÚsecondsÚ
expirationÚ
conditionszs3-presign-post-fieldszs3-presign-post-policyÚ	PutObjectr=   )rO   Úfields)ÚdatetimeÚutcnowÚ	timedeltaÚstrftimer2   r;   ÚISO8601Úappendr   r.   r    r"   rO   )r   rP   r®   r¬   r8   r   rh   Údatetime_nowÚexpire_daterƒ   r$   r   r   r   Úgenerate_presigned_postÔ  s$   *


ÿz'S3PostPresigner.generate_presigned_post)NNrM   N)rS   rT   rU   r   r·   r   r   r   r   r©   Ð  s    þr©   c                 K   r�   )NrQ   )rQ   r’   r   r   r   Úadd_generate_presigned_url  r•   r¸   rM   c                 C   s¸   |}|}|du r
i }|}|}dt | ƒdœ}	| j}
| j}z| j| }W n ty.   t|d�‚w | jj |¡}|  	|||	¡}| 
||¡}|durK||d< t|| jj|	d� |
j|||d�S )ax  Generate a presigned url given a client, its method, and arguments

    :type ClientMethod: string
    :param ClientMethod: The client method to presign for

    :type Params: dict
    :param Params: The parameters normally passed to
        ``ClientMethod``.

    :type ExpiresIn: int
    :param ExpiresIn: The number of seconds the presigned url is valid
        for. By default it expires in an hour (3600 seconds)

    :type HttpMethod: string
    :param HttpMethod: The http method to use on the generated url. By
        default, the http method is whatever is used in the method's model.

    :returns: The presigned url
    NT©Úis_presign_requestÚuse_global_endpoint)Úmethod_namerž   ©r§   r.   )rP   r8   r#   )Ú_should_use_global_endpointr    Ú_serializerÚ_PY_TO_OP_NAMEÚKeyErrorr   rŸ   Úservice_modelÚoperation_modelÚ_emit_api_paramsÚserialize_to_requestr   r§   rQ   )r   ÚClientMethodÚParamsÚ	ExpiresInÚ
HttpMethodÚclient_methodrk   r8   Úhttp_methodr.   r(   Ú
serializerr#   rÃ   rP   r   r   r   rQ      s@   þ
ÿÿÿ
ÿþrQ   c                 K   r�   )Nr·   )r·   r’   r   r   r   Úadd_generate_presigned_post_  r•   rÍ   c                 C   sà   |}|}|}|}	|}
|du ri }n|  ¡ }|	du rg }	t| jƒ}| j}| jj d¡}| d|i|¡}t|| jj	dt
| ƒdœd� |	 d|i¡ | d¡r\|	 d	d
|dtdƒ … g¡ n|	 d|i¡ ||d< |j|||	|
d�S )a×	  Builds the url and the form fields used for a presigned s3 post

    :type Bucket: string
    :param Bucket: The name of the bucket to presign the post to. Note that
        bucket related conditions should not be included in the
        ``conditions`` parameter.

    :type Key: string
    :param Key: Key name, optionally add ${filename} to the end to
        attach the submitted filename. Note that key related conditions and
        fields are filled out for you and should not be included in the
        ``Fields`` or ``Conditions`` parameter.

    :type Fields: dict
    :param Fields: A dictionary of prefilled form fields to build on top
        of. Elements that may be included are acl, Cache-Control,
        Content-Type, Content-Disposition, Content-Encoding, Expires,
        success_action_redirect, redirect, success_action_status,
        and x-amz-meta-.

        Note that if a particular element is included in the fields
        dictionary it will not be automatically added to the conditions
        list. You must specify a condition for the element as well.

    :type Conditions: list
    :param Conditions: A list of conditions to include in the policy. Each
        element can be either a list or a structure. For example:

        [
         {"acl": "public-read"},
         ["content-length-range", 2, 5],
         ["starts-with", "$success_action_redirect", ""]
        ]

        Conditions that are included may pertain to acl,
        content-length-range, Cache-Control, Content-Type,
        Content-Disposition, Content-Encoding, Expires,
        success_action_redirect, redirect, success_action_status,
        and/or x-amz-meta-.

        Note that if you include a condition, you must specify
        the a valid value in the fields dictionary as well. A value will
        not be added automatically to the fields dictionary based on the
        conditions.

    :type ExpiresIn: int
    :param ExpiresIn: The number of seconds the presigned post
        is valid for.

    :rtype: dict
    :returns: A dictionary with two elements: ``url`` and ``fields``.
        Url is the url to post to. Fields is a dictionary filled with
        the form fields and respective values to use when submitting the
        post. For example:

        {'url': 'https://mybucket.s3.amazonaws.com
         'fields': {'acl': 'public-read',
                    'key': 'mykey',
                    'signature': 'mysignature',
                    'policy': 'mybase64 encoded policy'}
        }
    NÚCreateBucketÚBucketTr¹   r½   Úbucketz${filename}zstarts-withz$keyÚkey)rP   r®   r¬   r8   )Úcopyr©   r    r¿   rŸ   rÂ   rÃ   rÅ   r   r§   r¾   r´   r@   r¡   r·   )r   rÏ   ÚKeyÚFieldsÚ
ConditionsrÈ   rÐ   rÑ   r®   r¬   r8   Úpost_presignerrÌ   rÃ   rP   r   r   r   r·   c  sB   @
ÿÿþþ	
 þr·   c                 C   sR   | j jdkrdS | j jj}|r'| dd¡rdS | d¡dkr'| j jjdkr'dS dS )NÚawsFÚuse_dualstack_endpointÚus_east_1_regional_endpointÚregionalz	us-east-1T)rŸ   Ú	partitionÚconfigÚs3r4   r   )ÚclientÚ	s3_configr   r   r   r¾   Ø  s   
r¾   r   )NrM   N)NNrM   )r¯   r   r}   rŒ   r2   Úbotocore.authÚbotocore.compatr   r   Úbotocore.awsrequestr   r   Úbotocore.exceptionsr   r   r   Úbotocore.utilsr	   r
   Úobjectr   rY   r”   r‘   r©   r¸   rQ   rÍ   r·   r¾   r   r   r   r   Ú<module>   s8    |
3L
ÿ?
ÿu