U s_%wã@s0dZddlmZddlZddlZddlZddlZddlZddlZzddl m Z Wne k rlddl Z YnXzddl mZmZmZmZWn4e k r¾ddlmZmZddlmZmZYnXddlmZddlmZmZd d lmZd d lmZmZmZGd d „d eƒZGdd„deƒZGdd„deƒZ dS)zn Provides AWS4Auth class for handling Amazon Web Services version 4 authentication with the Requests module. é)Úunicode_literalsN)ÚurlparseÚparse_qsÚquoteÚunquote)rr)rr)ÚAuthBase)ÚPY2Ú text_typeé)ÚAWS4SigningKey)ÚDateMismatchErrorÚNoSecretKeyErrorÚDateFormatErrorc@s¤eZdZdZddddhZdd„Zd!d d „Zd d „Zed d„ƒZ e dd„ƒZ dd„Z e dd„ƒZ dd„Zed"dd„ƒZe dd„ƒZdd„Ze dd„ƒZe dd „ƒZdS)#ÚAWS4Authaü Requests authentication class providing AWS version 4 authentication for HTTP requests. Implements header-based authentication only, GET URL parameter and POST parameter authentication are not supported. Provides authentication for regions and services listed at: http://docs.aws.amazon.com/general/latest/gr/rande.html The following services do not support AWS auth version 4 and are not usable with this package: * Simple Email Service (SES)' - AWS auth v3 only * Simple Workflow Service - AWS auth v3 only * Import/Export - AWS auth v2 only * SimpleDB - AWS auth V2 only * DevPay - AWS auth v1 only * Mechanical Turk - has own signing mechanism You can reuse AWS4Auth instances to sign as many requests as you need. Basic usage ----------- >>> import requests >>> from requests_aws4auth import AWS4Auth >>> auth = AWS4Auth('', '', 'eu-west-1', 's3') >>> endpoint = 'http://s3-eu-west-1.amazonaws.com' >>> response = requests.get(endpoint, auth=auth) >>> response.text bcaf1ffd86f461ca5fb16fd081034f webfile ... This example lists your buckets in the eu-west-1 region of the Amazon S3 service. STS Temporary Credentials ------------------------- >>> from requests_aws4auth import AWS4Auth >>> auth = AWS4Auth('', '', 'eu-west-1', 's3', session_token='') ... This example shows how to construct an AWS4Auth object for use with STS temporary credentials. The ``x-amz-security-token`` header is added with the session token. Temporary credential timeouts are not managed -- in case the temporary credentials expire, they need to be re-generated and the AWS4Auth object re-constructed with the new credentials. Date handling ------------- If an HTTP request to be authenticated contains a Date or X-Amz-Date header, AWS will only accept authorisation if the date in the header matches the scope date of the signing key (see http://docs.aws.amazon.com/general/latest/gr/sigv4-date-handling.html). From version 0.8 of requests-aws4auth, if the header date does not match the scope date, the AWS4Auth class will automatically regenerate its signing key, using the same scope parameters as the previous key except for the date, which will be changed to match the request date. (If a request does not include a date, the current date is added to the request in an X-Amz-Date header). The new behaviour from version 0.8 has implications for thread safety and secret key security, see the "Automatic key regeneration", "Secret key storage" and "Multithreading" sections below. This also means that AWS4Auth is now attempting to parse and extract dates from the values in X-Amz-Date and Date headers. Supported date formats are: * RFC 7231 (e.g. Mon, 09 Sep 2011 23:36:00 GMT) * RFC 850 (e.g. Sunday, 06-Nov-94 08:49:37 GMT) * C time (e.g. Wed Dec 4 00:00:00 2002) * Amz-Date format (e.g. 20090325T010101Z) * ISO 8601 / RFC 3339 (e.g. 2009-03-25T10:11:12.13-01:00) If either header is present but AWS4Auth cannot extract a date because all present date headers are in an unrecognisable format, AWS4Auth will delete any X-Amz-Date and Date headers present and replace with a single X-Amz-Date header containing the current date. This behaviour can be modified using the 'raise_invalid_date' keyword argument of the AWS4Auth constructor. Automatic key regeneration -------------------------- If you do not want the signing key to be automatically regenerated when a mismatch between the request date and the scope date is encountered, use the alternative StrictAWS4Auth class, which is identical to AWS4Auth except that upon encountering a date mismatch it just raises a DateMismatchError. You can also use the PassiveAWS4Auth class, which mimics the AWS4Auth behaviour prior to version 0.8 and just signs and sends the request, whether the date matches or not. In this case it is up to the calling code to handle an authentication failure response from AWS caused by a date mismatch. Secret key storage ------------------ To allow automatic key regeneration, the secret key is stored in the AWS4Auth instance, in the signing key object. If you do not want this to occur, instantiate the instance using an AWS4Signing key which was created with the store_secret_key parameter set to False: >>> sig_key = AWS4SigningKey(secret_key, region, service, date, False) >>> auth = StrictAWS4Auth(access_id, sig_key) The AWS4Auth class will then raise a NoSecretKeyError when it attempts to regenerate its key. A slightly more conceptually elegant way to handle this is to use the alternative StrictAWS4Auth class, again instantiating it with an AWS4SigningKey instance created with store_secret_key = False. Multithreading -------------- If you share AWS4Auth (or even StrictAWS4Auth) instances between threads you are likely to encounter problems. Because AWS4Auth instances may unpredictably regenerate their signing key as part of signing a request, threads using the same instance may find the key changed by another thread halfway through the signing process, which may result in undefined behaviour. It may be possible to rig up a workable instance sharing mechanism using locking primitives and the StrictAWS4Auth class, however this poor author can't think of a scenario which works safely yet doesn't suffer from at some point blocking all threads for at least the duration of an HTTP request, which could be several seconds. If several requests come in in close succession which all require key regenerations then the system could be forced into serial operation for quite a length of time. In short, it's best to create a thread-local instance of AWS4Auth for each thread that needs to do authentication. Class attributes ---------------- AWS4Auth.access_id -- the access ID supplied to the instance AWS4Auth.region -- the AWS region for the instance AWS4Auth.service -- the endpoint code for the service for this instance AWS4Auth.date -- the date the instance is valid for AWS4Auth.signing_key -- instance of AWS4SigningKey used for this instance, either generated from the supplied parameters or supplied directly on the command line Úhostú content-typeÚdateúx-amz-*cOsHt|ƒ}|dkr"d |¡}t|ƒ‚|d|_t|dtƒrl|dkrl|d|_|jj|_|jj|_|jj |_ nT|dkrº|d}|d|_|d|_|dkr |d nd |_ d |_|j |d ntƒ‚|  d d ¡}|dkrÜ||_ nt dƒ‚|  d¡|_|jr|j d¡t|jƒ|_d|kr:t|dtjƒr:t|dƒ|_t |¡d S)aç AWS4Auth instances can be created by supplying key scope parameters directly or by using an AWS4SigningKey instance: >>> auth = AWS4Auth(access_id, secret_key, region, service ... [, date][, raise_invalid_date=False][, session_token=None]) or >>> auth = AWS4Auth(access_id, signing_key[, raise_invalid_date=False]) access_id -- This is your AWS access ID secret_key -- This is your AWS secret access key region -- The region you're connecting to, as per the list at http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_region e.g. us-east-1. For services which don't require a region (e.g. IAM), use us-east-1. service -- The name of the service you're connecting to, as per endpoints at: http://docs.aws.amazon.com/general/latest/gr/rande.html e.g. elasticbeanstalk. date -- Date this instance is valid for. 8-digit date as str of the form YYYYMMDD. Key is only valid for requests with a Date or X-Amz-Date header matching this date. If date is not supplied the current date is used. signing_key -- An AWS4SigningKey instance. raise_invalid_date -- Must be supplied as keyword argument. AWS4Auth tries to parse a date from the X-Amz-Date and Date headers of the request, first trying X-Amz-Date, and then Date if X-Amz-Date is not present or is in an unrecognised format. If one or both of the two headers are present yet neither are in a format which AWS4Auth recognises then it will remove both headers and replace with a new X-Amz-Date header using the current date. If this behaviour is not wanted, set the raise_invalid_date keyword argument to True, and instead an InvalidDateError will be raised when neither date is recognised. If neither header is present at all then an X-Amz-Date header will still be added containing the current date. See the AWS4Auth class docstring for supported date formats. session_token -- Must be supplied as keyword argument. If session_token is set, then it is used for the x-amz-security-token header, for use with STS temporary credentials. )éééz.AWS4Auth() takes 2, 4 or 5 arguments, {} givenrr r)rrérrN)Ú secret_keyÚraise_invalid_dateF)TFz?raise_invalid_date must be True or False in AWS4Auth.__init__()Ú session_tokenúx-amz-security-tokenÚ include_hdrs)ÚlenÚformatÚ TypeErrorÚ access_idÚ isinstancer Ú signing_keyÚregionÚservicerÚregenerate_signing_keyÚgetrÚ ValueErrorrÚdefault_include_headersÚaddÚsetrÚabcÚIterablerÚ__init__)ÚselfÚargsÚkwargsÚlÚmsgrr©r3úr/private/var/folders/y3/n__7lzs1191bf6ypqtmfbcr1rfn98y/T/pip-unpacked-wheel-okadx6ca/requests_aws4auth/aws4auth.pyr-¶s:4            zAWS4Auth.__init__NcCs|dkr"|jdks|jjdkr"t‚|p,|jj}|p6|j}|p@|j}|pJ|j}|jdkr\d}n|jj}t|||||ƒ|_||_||_|jj|_dS)a{ Regenerate the signing key for this instance. Store the new key in signing_key property. Take scope elements of the new key from the equivalent properties (region, service, date) of the current AWS4Auth instance. Scope elements can be overridden for the new key by supplying arguments to this function. If overrides are supplied update the current AWS4Auth instance's equivalent properties to match the new values. If secret_key is not specified use the value of the secret_key property of the current AWS4Auth instance's signing key. If the existing signing key is not storing its secret key (i.e. store_secret_key was set to False at instantiation) then raise a NoSecretKeyError and do not regenerate the key. In order to regenerate a key which is not storing its secret key, secret_key must be supplied to this function. Use the value of the existing key's store_secret_key property when generating the new key. If there is no existing key, then default to setting store_secret_key to True for new key. NT)r"rr r#r$rÚstore_secret_keyr )r.rr#r$rr5r3r3r4r%s      ÿzAWS4Auth.regenerate_signing_keycCsl| |¡}|dkrXd|jkr$|jd=d|jkr6|jd=tj ¡}| ¡}| d¡|jd<| d¡}||jkrv| |¡t|dƒr¢|jdk r¢|  |¡t   |j¡}n t   d¡}|  ¡|jd<|j rÌ|j |jd <| ||j¡}|\}}| |||¡} | || |jj¡} |  d ¡} t |jj| t j ¡} |   ¡} d } | d  |j|jj¡7} | d  |¡7} | d | ¡7} | |jd<|S)af Interface used by Requests module to apply authentication to HTTP requests. Add x-amz-content-sha256 and Authorization headers to the request. Add x-amz-date header to request if not already present and req does not contain a Date header. Check request date matches date in the current signing key. If not, regenerate signing key to match request date. If request body is not already encoded to bytes, encode to charset specified in Content-Type header, or UTF-8 if not specified. req -- Requests PreparedRequest object Nrú x-amz-datez%Y%m%dT%H%M%SZú%Y%m%dÚbodyóúx-amz-content-sha256rúutf-8zAWS4-HMAC-SHA256 zCredential={}/{}, zSignedHeaders={}, z Signature={}Ú Authorization)Úget_request_dateÚheadersÚdatetimeÚutcnowrÚstrftimeÚhandle_date_mismatchÚhasattrr8Ú encode_bodyÚhashlibÚsha256Ú hexdigestrÚget_canonical_headersrÚget_canonical_requestÚget_sig_stringr"ÚscopeÚencodeÚhmacÚnewÚkeyrr )r.ÚreqZreq_dateÚnowZreq_scope_dateZ content_hashÚresultÚ cano_headersÚsigned_headersÚcano_reqÚ sig_stringÚhshÚsigÚauth_strr3r3r4Ú__call__>sH          ÿ  ÿ zAWS4Auth.__call__c Cs€d}dD]r}||jkrqz| |j|¡}Wntk rDYqYnXztj |d¡ ¡}Wntk rtYqYqXq|q|S)aC Try to pull a date from the request by looking first at the x-amz-date header, and if that's not present then the Date header. Return a datetime.date object, or None if neither date header is found or is in a recognisable format. req -- a requests PreparedRequest object N)r6rz%Y-%m-%d)r>Ú parse_daterr?Ústrptimerr')ÚclsrPrÚheaderÚdate_strr3r3r4r=ys    zAWS4Auth.get_request_datec s”ddddddddd d d d g ‰‡fd d„‡fdd„‡fdd„dd„dd„dœ}d}| ¡D]$\}}t ||¡}|rX||ƒ}q~qX|dkrŒt‚n|SdS)a  Check if date_str is in a recognised format and return an ISO yyyy-mm-dd format version if so. Raise DateFormatError if not. Recognised formats are: * RFC 7231 (e.g. Mon, 09 Sep 2011 23:36:00 GMT) * RFC 850 (e.g. Sunday, 06-Nov-94 08:49:37 GMT) * C time (e.g. Wed Dec 4 00:00:00 2002) * Amz-Date format (e.g. 20090325T010101Z) * ISO 8601 / RFC 3339 (e.g. 2009-03-25T10:11:12.13-01:00) date_str -- Str containing a date and optional time ÚjanÚfebÚmarÚaprÚmayÚjunÚjulÚaugÚsepÚoctÚnovÚdeccs.d | d¡ˆ | d¡ ¡¡d| d¡¡S)Nz {}-{:02d}-{}rrr )rÚgroupÚindexÚlower©Úm©Úmonthsr3r4Ú«sýz%AWS4Auth.parse_date..c sDd ttj ¡jƒdd…| d¡ˆ | d¡ ¡¡d| d¡¡S)Nz{}{}-{:02d}-{}rrr ) rÚstrr?rÚtodayÚyearrlrmrnrorqr3r4rs²s ücs2d | d¡ˆ | d¡ ¡¡dt| d¡ƒ¡S)Nz{}-{:02d}-{:02d}rr r)rrlrmrnÚintrorqr3r4rs¹s ýcSsdj| ¡ŽS)Nz{}-{}-{})rÚgroupsror3r3r4rs¿r9cSs | d¡S)Nr )rlror3r3r4rsÂr9)z)^(?:\w{3}, )?(\d{2}) (\w{3}) (\d{4})\D.*$z%^\w+day, (\d{2})-(\w{3})-(\d{2})\D.*$z3^\w{3} (\w{3}) (\d{1,2}) \d{2}:\d{2}:\d{2} (\d{4})$z^(\d{4})(\d{2})(\d{2})T\d{6}Z$z ^(\d{4}-\d{2}-\d{2})(?:[Tt].*)?$N)ÚitemsÚreÚsearchr)r_ÚformatsZout_dateÚregexZxformrpr3rqr4r[–s*ÿ   æ zAWS4Auth.parse_datecCs$| |¡}| d¡}|j|ddS)a$ Handle a request whose date doesn't match the signing key scope date. This AWS4Auth class implementation regenerates the signing key. See StrictAWS4Auth class if you would prefer an exception to be raised. req -- a requests prepared request object r7)rN)r=rAr%)r.rPZ req_datetimeZ new_key_dater3r3r4rBÐs  zAWS4Auth.handle_date_mismatchcCs˜t|jtƒr”|j dd¡ d¡}t|ƒdkrR|\}}| d¡d}|j |¡|_nB|d}|dksjd |krx|j ¡|_n|j d ¡|_|d |jd<d S) aÑ Encode body of request to bytes and update content-type if required. If the body of req is Unicode then encode to the charset found in content-type header if present, otherwise UTF-8, or ASCII if content-type is application/x-www-form-urlencoded. If encoding to UTF-8 then add charset to content-type. Modifies req directly, does not return a modified copy. req -- Requests PreparedRequest object rz text/plainú;rú=r rz!application/x-www-form-urlencodedúx-amz-r;z; charset=utf-8N)r!r8r r>r&ÚsplitrrL)rPrÚctÚcsr3r3r4rDÞs  zAWS4Auth.encode_bodyc Cstt|jƒ}| |j¡}|j dd¡}t|ƒdkr8|dnd}| |¡}|jd}|j  ¡|||||g} d  | ¡} | S)aÌ Create the AWS authentication Canonical Request string. req -- Requests PreparedRequest object. Should already include an x-amz-content-sha256 header cano_headers -- Canonical Headers section of Canonical Request, as returned by get_canonical_headers() signed_headers -- Signed Headers, as returned by get_canonical_headers() ú?r rÚr:Ú ) rÚurlÚ amz_cano_pathÚpathrrÚamz_cano_querystringr>ÚmethodÚupperÚjoin) r.rPrSrTr‡r‰rÚqsZ payload_hashZ req_partsrUr3r3r4rIús    ÿ zAWS4Auth.get_canonical_requestc Cs|dkr|j}dd„|Dƒ}|j ¡}d|krHt|jƒj d¡d|d<i}| ¡D]b\}}| ¡  ¡}|  |¡ ¡}||ks d|ks d|krT|  d ¡rT|d ksT|  |g¡}|  |¡qTd }g} t|ƒD]4}||}d  t|ƒ¡}|d  ||¡7}|   |¡qÈd | ¡} || fS)a3 Generate the Canonical Headers section of the Canonical Request. Return the Canonical Headers and the Signed Headers strs as a tuple (canonical_headers, signed_headers). req -- Requests PreparedRequest object include -- List of headers to include in the canonical and signed headers. It's primarily included to allow testing against specific examples from Amazon. If omitted or None it includes host, content-type and any header starting 'x-amz-' except for x-amz-client context, which appears to break mobile analytics auth if included. Except for the x-amz-client-context exclusion these defaults are per the AWS documentation. NcSsg|] }| ¡‘qSr3)rn)Ú.0Úxr3r3r4Ú (sz2AWS4Auth.get_canonical_headers..rú:rÚ*rr€zx-amz-client-contextr…ú,z{}:{} r~)r(r>Úcopyrr‡ÚnetlocrryÚstriprnÚamz_norm_whitespaceÚ startswithÚ setdefaultÚappendÚsortedrr) r]rPÚincluder>Zcano_headers_dictÚhdrÚvalÚvalsrSZsigned_headers_listrTr3r3r4rHs8  ÿÿþ     zAWS4Auth.get_canonical_headerscCs6|jd}t | ¡¡}d||| ¡g}d |¡}|S)a+ Generate the AWS4 auth string to sign for the request. req -- Requests PreparedRequest object. This should already include an x-amz-date header. cano_req -- The Canonical Request, as returned by get_canonical_request() r6zAWS4-HMAC-SHA256r†)r>rErFrLrGr)rPrUrKZamz_daterWZ sig_itemsrVr3r3r4rJHs  zAWS4Auth.get_sig_stringcCsÊd}d}|}d|kr$| dd¡\}}t |¡}t dd|¡}| d¡rX| d¡sX|d7}|}tr~| d¡}| d¡}| d¡}|jdkrt |ƒ}t ||d }|rºtr¨d nd}|  ||f¡}trÆt |ƒ}|S) zõ Generate the canonical path as per AWS4 auth requirements. Not documented anywhere, determined from aws4_testsuite examples, problem reports and testing against the live services. path -- request path z/~r…r„r z/+ú/r;)Zs3r©Úsafeó?) rÚ posixpathÚnormpathrzÚsubÚendswithrrLr$rrrÚunicode)r.r‰Z safe_charsrŽZ fixed_pathÚ full_pathZqmr3r3r4rˆYs.        zAWS4Auth.amz_cano_pathcsêd}d‰tr&| d¡}| ¡}ˆ ¡‰t|ƒ}tr6dnd}| |¡d}t||d}i}t|dd  ¡D].\}}t|ˆd}‡fd d „|Dƒ}|||<qhg}| ¡D]&\}}|D]}| d  ||g¡¡q°q¤d  t |ƒ¡}træt |ƒ}|S)z• Parse and format querystring as per AWS4 auth requirements. Perform percent quoting as needed. qs -- querystring z&=+z-_.~r;ó ú rr¢T)Úkeep_blank_valuescsg|]}t|ˆd‘qS)r¢)r)rrŸ©Zsafe_qs_unresvdr3r4r‘˜sz1AWS4Auth.amz_cano_querystring..rú&) rrLrrrrryr›rrœr©)rŽZsafe_qs_amz_charsÚspaceZqs_itemsÚnamer Z qs_stringsrŸr3r®r4rŠs.      zAWS4Auth.amz_cano_querystringcCsd tj|dd¡S)zk Replace runs of whitespace with a single space. Ignore text enclosed in quotes. r¬F)Úposix)rÚshlexr)Útextr3r3r4r˜£szAWS4Auth.amz_norm_whitespace)NNNN)N)Ú__name__Ú __module__Ú __qualname__Ú__doc__r(r-r%rZÚ classmethodr=Ú staticmethodr[rBrDrIrHrJrˆrŠr˜r3r3r3r4r%s4 \ÿ ,;  9  4 & #rc@seZdZdZdd„ZdS)ÚStrictAWS4Authaº Instances of this subclass will not automatically regenerate their signing keys when asked to sign a request whose date does not match the scope date of the signing key. Instances will instead raise a DateMismatchError. Keys of StrictAWSAuth instances can be regenerated manually by calling the regenerate_signing_key() method. Keys will still store the secret key by default. If this is not desired then create the instance by passing an AWS4SigningKey created with store_secret_key set to False to the StrictAWS4AUth constructor: >>> sig_key = AWS4SigningKey(secret_key, region, service, date, False) >>> auth = StrictAWS4Auth(access_id, sig_key) cCst‚dS)ap Handle a request whose date doesn't match the signing key process, by raising a DateMismatchError. Overrides the default behaviour of AWS4Auth where the signing key is automatically regenerated to match the request date To update the signing key if this is hit, call StrictAWS4Auth.regenerate_signing_key(). N)r ©r.rPr3r3r4rBÀs z#StrictAWS4Auth.handle_date_mismatchN©rµr¶r·r¸rBr3r3r3r4r»®sr»c@seZdZdZdd„ZdS)ÚPassiveAWS4AuthaL This subclass does not perform any special handling of a mismatched request and scope date, it signs the request and allows Requests to send it. It is up to the calling code to handle a failed authentication response from AWS. This behaviour mimics the behaviour of AWS4Auth for versions 0.7 and earlier. cCsdS)Nr3r¼r3r3r4rBÚsz$PassiveAWS4Auth.handle_date_mismatchNr½r3r3r3r4r¾Ïs r¾)!r¸Ú __future__rrMrEr¥rzr³r?Úcollections.abcr+Ú ImportErrorÚ collectionsÚ urllib.parserrrrÚurllibZ requests.authrÚsixrr Zaws4signingkeyr Ú exceptionsr r rrr»r¾r3r3r3r4Ús8   !