oauthlib
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Kenneth Reitz · committed by Kenneth Reitz · parent 6541ceb · Browse files · 14 files·+2862 added−7 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
14 files+2862 added−7 removed
- other:+2862 added−7 removed
Provenance
- Commit
9576518- Tree
7a07679- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent
6541ceb
14 files changed+2862 added−7 removed
added:requests/packages/oauthlib/oauth1/rfc5849/__init__.py+887 added
1+# -*- coding: utf-8 -*-2+from __future__ import absolute_import3+4+"""5+oauthlib.oauth1.rfc58496+~~~~~~~~~~~~~~7+8+This module is an implementation of various logic needed9+for signing and checking OAuth 1.0 RFC 5849 requests.10+"""11+12+import logging13+import time14+import urlparse15+16+from oauthlib.common import Request, urlencode, generate_nonce17+from oauthlib.common import generate_timestamp18+from . import parameters, signature, utils19+20+SIGNATURE_HMAC = u"HMAC-SHA1"21+SIGNATURE_RSA = u"RSA-SHA1"22+SIGNATURE_PLAINTEXT = u"PLAINTEXT"23+SIGNATURE_METHODS = (SIGNATURE_HMAC, SIGNATURE_RSA, SIGNATURE_PLAINTEXT)24+25+SIGNATURE_TYPE_AUTH_HEADER = u'AUTH_HEADER'26+SIGNATURE_TYPE_QUERY = u'QUERY'27+SIGNATURE_TYPE_BODY = u'BODY'28+29+CONTENT_TYPE_FORM_URLENCODED = u'application/x-www-form-urlencoded'30+31+32+class Client(object):33+ """A client used to sign OAuth 1.0 RFC 5849 requests"""34+ def __init__(self, client_key,35+ client_secret=None,36+ resource_owner_key=None,37+ resource_owner_secret=None,38+ callback_uri=None,39+ signature_method=SIGNATURE_HMAC,40+ signature_type=SIGNATURE_TYPE_AUTH_HEADER,41+ rsa_key=None, verifier=None):42+ self.client_key = client_key43+ self.client_secret = client_secret44+ self.resource_owner_key = resource_owner_key45+ self.resource_owner_secret = resource_owner_secret46+ self.signature_method = signature_method47+ self.signature_type = signature_type48+ self.callback_uri = callback_uri49+ self.rsa_key = rsa_key50+ self.verifier = verifier51+52+ if self.signature_method == SIGNATURE_RSA and self.rsa_key is None:53+ raise ValueError('rsa_key is required when using RSA signature method.')54+55+ def get_oauth_signature(self, request):56+ """Get an OAuth signature to be used in signing a request57+ """58+ if self.signature_method == SIGNATURE_PLAINTEXT:59+ # fast-path60+ return signature.sign_plaintext(self.client_secret,61+ self.resource_owner_secret)62+63+ uri, headers, body = self._render(request)64+65+ collected_params = signature.collect_parameters(66+ uri_query=urlparse.urlparse(uri).query,67+ body=body,68+ headers=headers)69+ logging.debug("Collected params: {0}".format(collected_params))70+71+ normalized_params = signature.normalize_parameters(collected_params)72+ normalized_uri = signature.normalize_base_string_uri(request.uri)73+ logging.debug("Normalized params: {0}".format(normalized_params))74+ logging.debug("Normalized URI: {0}".format(normalized_uri))75+76+ base_string = signature.construct_base_string(request.http_method,77+ normalized_uri, normalized_params)78+79+ logging.debug("Base signing string: {0}".format(base_string))80+81+ if self.signature_method == SIGNATURE_HMAC:82+ sig = signature.sign_hmac_sha1(base_string, self.client_secret,83+ self.resource_owner_secret)84+ elif self.signature_method == SIGNATURE_RSA:85+ sig = signature.sign_rsa_sha1(base_string, self.rsa_key)86+ else:87+ sig = signature.sign_plaintext(self.client_secret,88+ self.resource_owner_secret)89+90+ logging.debug("Signature: {0}".format(sig))91+ return sig92+93+ def get_oauth_params(self):94+ """Get the basic OAuth parameters to be used in generating a signature.95+ """96+ params = [97+ (u'oauth_nonce', generate_nonce()),98+ (u'oauth_timestamp', generate_timestamp()),99+ (u'oauth_version', u'1.0'),100+ (u'oauth_signature_method', self.signature_method),101+ (u'oauth_consumer_key', self.client_key),102+ ]103+ if self.resource_owner_key:104+ params.append((u'oauth_token', self.resource_owner_key))105+ if self.callback_uri:106+ params.append((u'oauth_callback', self.callback_uri))107+ if self.verifier:108+ params.append((u'oauth_verifier', self.verifier))109+110+ return params111+112+ def _render(self, request, formencode=False):113+ """Render a signed request according to signature type114+115+ Returns a 3-tuple containing the request URI, headers, and body.116+117+ If the formencode argument is True and the body contains parameters, it118+ is escaped and returned as a valid formencoded string.119+ """120+ # TODO what if there are body params on a header-type auth?121+ # TODO what if there are query params on a body-type auth?122+123+ uri, headers, body = request.uri, request.headers, request.body124+125+ # TODO: right now these prepare_* methods are very narrow in scope--they126+ # only affect their little thing. In some cases (for example, with127+ # header auth) it might be advantageous to allow these methods to touch128+ # other parts of the request, like the headers—so the prepare_headers129+ # method could also set the Content-Type header to x-www-form-urlencoded130+ # like the spec requires. This would be a fundamental change though, and131+ # I'm not sure how I feel about it.132+ if self.signature_type == SIGNATURE_TYPE_AUTH_HEADER:133+ headers = parameters.prepare_headers(request.oauth_params, request.headers)134+ elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None:135+ body = parameters.prepare_form_encoded_body(request.oauth_params, request.decoded_body)136+ if formencode:137+ body = urlencode(body)138+ headers['Content-Type'] = u'application/x-www-form-urlencoded'139+ elif self.signature_type == SIGNATURE_TYPE_QUERY:140+ uri = parameters.prepare_request_uri_query(request.oauth_params, request.uri)141+ else:142+ raise ValueError('Unknown signature type specified.')143+144+ return uri, headers, body145+146+ def sign(self, uri, http_method=u'GET', body=None, headers=None):147+ """Sign a request148+149+ Signs an HTTP request with the specified parts.150+151+ Returns a 3-tuple of the signed request's URI, headers, and body.152+ Note that http_method is not returned as it is unaffected by the OAuth153+ signing process.154+155+ The body argument may be a dict, a list of 2-tuples, or a formencoded156+ string. The Content-Type header must be 'application/x-www-form-urlencoded'157+ if it is present.158+159+ If the body argument is not one of the above, it will be returned160+ verbatim as it is unaffected by the OAuth signing process. Attempting to161+ sign a request with non-formencoded data using the OAuth body signature162+ type is invalid and will raise an exception.163+164+ If the body does contain parameters, it will be returned as a properly-165+ formatted formencoded string.166+167+ All string data MUST be unicode. This includes strings inside body168+ dicts, for example.169+ """170+ # normalize request data171+ request = Request(uri, http_method, body, headers)172+173+ # sanity check174+ content_type = request.headers.get('Content-Type', None)175+ multipart = content_type and content_type.startswith('multipart/')176+ should_have_params = content_type == CONTENT_TYPE_FORM_URLENCODED177+ has_params = request.decoded_body is not None178+ # 3.4.1.3.1. Parameter Sources179+ # [Parameters are collected from the HTTP request entity-body, but only180+ # if [...]:181+ # * The entity-body is single-part.182+ if multipart and has_params:183+ raise ValueError("Headers indicate a multipart body but body contains parameters.")184+ # * The entity-body follows the encoding requirements of the185+ # "application/x-www-form-urlencoded" content-type as defined by186+ # [W3C.REC-html40-19980424].187+ elif should_have_params and not has_params:188+ raise ValueError("Headers indicate a formencoded body but body was not decodable.")189+ # * The HTTP request entity-header includes the "Content-Type"190+ # header field set to "application/x-www-form-urlencoded".191+ elif not should_have_params and has_params:192+ raise ValueError("Body contains parameters but Content-Type header was not set.")193+194+ # 3.5.2. Form-Encoded Body195+ # Protocol parameters can be transmitted in the HTTP request entity-196+ # body, but only if the following REQUIRED conditions are met:197+ # o The entity-body is single-part.198+ # o The entity-body follows the encoding requirements of the199+ # "application/x-www-form-urlencoded" content-type as defined by200+ # [W3C.REC-html40-19980424].201+ # o The HTTP request entity-header includes the "Content-Type" header202+ # field set to "application/x-www-form-urlencoded".203+ elif self.signature_type == SIGNATURE_TYPE_BODY and not (204+ should_have_params and has_params and not multipart):205+ raise ValueError('Body signatures may only be used with form-urlencoded content')206+207+ # generate the basic OAuth parameters208+ request.oauth_params = self.get_oauth_params()209+210+ # generate the signature211+ request.oauth_params.append((u'oauth_signature', self.get_oauth_signature(request)))212+213+ # render the signed request and return it214+ return self._render(request, formencode=True)215+216+217+class Server(object):218+ """A server base class used to verify OAuth 1.0 RFC 5849 requests219+220+ OAuth providers should inherit from Server and implement the methods221+ and properties outlined below. Further details are provided in the222+ documentation for each method and property.223+224+ Methods used to check the format of input parameters. Common tests include225+ length, character set, membership, range or pattern. These tests are226+ referred to as `whitelisting or blacklisting`_. Whitelisting is better227+ but blacklisting can be usefull to spot malicious activity.228+ The following have methods a default implementation:229+230+ - check_client_key231+ - check_request_token232+ - check_access_token233+ - check_nonce234+ - check_verifier235+ - check_realm236+237+ The methods above default to whitelist input parameters, checking that they238+ are alphanumerical and between a minimum and maximum length. Rather than239+ overloading the methods a few properties can be used to configure these240+ methods.241+242+ @ safe_characters -> (character set)243+ @ client_key_length -> (min, max)244+ @ request_token_length -> (min, max)245+ @ access_token_length -> (min, max)246+ @ nonce_length -> (min, max)247+ @ verifier_length -> (min, max)248+ @ realms -> [list, of, realms]249+250+ Methods used to validate input parameters. These checks usually hit either251+ persistent or temporary storage such as databases or the filesystem. See252+ each methods documentation for detailed usage.253+ The following methods must be implemented:254+255+ - validate_client256+ - validate_request_token257+ - validate_access_token258+ - validate_nonce_and_timestamp259+ - validate_redirect_uri260+ - validate_requested_realm261+ - validate_realm262+ - validate_verifier263+264+ Method used to retrieve sensitive information from storage.265+ The following methods must be implemented:266+267+ - get_client_secret268+ - get_request_token_secret269+ - get_access_token_secret270+ - get_rsa_key271+272+ To prevent timing attacks it is necessary to not exit early even if the273+ client key or resource owner key is invalid. Instead dummy values should274+ be used during the remaining verification process. It is very important275+ that the dummy client and token are valid input parameters to the methods276+ get_client_secret, get_rsa_key and get_(access/request)_token_secret and277+ that the running time of those methods when given a dummy value remain278+ equivalent to the running time when given a valid client/resource owner.279+ The following properties must be implemented:280+281+ @ dummy_client282+ @ dummy_request_token283+ @ dummy_access_token284+285+ .. _`whitelisting or blacklisting`: http://www.schneier.com/blog/archives/2011/01/whitelisting_vs.html286+ """287+288+ def __init__(self):289+ pass290+291+ @property292+ def allowed_signature_methods(self):293+ return SIGNATURE_METHODS294+295+ @property296+ def safe_characters(self):297+ return set(utils.UNICODE_ASCII_CHARACTER_SET)298+299+ @property300+ def client_key_length(self):301+ return 20, 30302+303+ @property304+ def request_token_length(self):305+ return 20, 30306+307+ @property308+ def access_token_length(self):309+ return 20, 30310+311+ @property312+ def timestamp_lifetime(self):313+ return 600314+315+ @property316+ def nonce_length(self):317+ return 20, 30318+319+ @property320+ def verifier_length(self):321+ return 20, 30322+323+ @property324+ def realms(self):325+ return []326+327+ @property328+ def enforce_ssl(self):329+ return True330+331+ def check_client_key(self, client_key):332+ """Check that the client key only contains safe characters333+ and is no shorter than lower and no longer than upper.334+ """335+ lower, upper = self.client_key_length336+ return (set(client_key) <= self.safe_characters and337+ lower <= len(client_key) <= upper)338+339+ def check_request_token(self, request_token):340+ """Checks that the request token contains only safe characters341+ and is no shorter than lower and no longer than upper.342+ """343+ lower, upper = self.request_token_length344+ return (set(request_token) <= self.safe_characters and345+ lower <= len(request_token) <= upper)346+347+ def check_access_token(self, request_token):348+ """Checks that the token contains only safe characters349+ and is no shorter than lower and no longer than upper.350+ """351+ lower, upper = self.access_token_length352+ return (set(request_token) <= self.safe_characters and353+ lower <= len(request_token) <= upper)354+355+ def check_nonce(self, nonce):356+ """Checks that the nonce only contains only safe characters357+ and is no shorter than lower and no longer than upper.358+ """359+ lower, upper = self.nonce_length360+ return (set(nonce) <= self.safe_characters and361+ lower <= len(nonce) <= upper)362+363+ def check_verifier(self, verifier):364+ """Checks that the verifier contains only safe characters365+ and is no shorter than lower and no longer than upper.366+ """367+ lower, upper = self.verifier_length368+ return (set(verifier) <= self.safe_characters and369+ lower <= len(verifier) <= upper)370+371+ def check_realm(self, realm):372+ """Check that the realm is one of a set allowed realms.373+ """374+ return realm in self.realms375+376+ def get_client_secret(self, client_key):377+ """Retrieves the client secret associated with the client key.378+379+ This method must allow the use of a dummy client_key value.380+ Fetching the secret using the dummy key must take the same amount of381+ time as fetching a secret for a valid client.382+383+ Note that the returned key must be in plaintext.384+ """385+ raise NotImplementedError("Subclasses must implement this function.")386+387+ @property388+ def dummy_client(self):389+ """Dummy client used when an invalid client key is supplied.390+391+ The dummy client should be associated with either a client secret,392+ a rsa key or both depending on which signature methods are supported.393+ Providers should make sure that394+395+ get_client_secret(dummy_client)396+ get_rsa_key(dummy_client)397+398+ return a valid secret or key for the dummy client.399+ """400+ raise NotImplementedError("Subclasses must implement this function.")401+402+ def get_request_token_secret(self, client_key, request_token):403+ """Retrieves the shared secret associated with the request token.404+405+ This method must allow the use of a dummy values and the running time406+ must be roughly equivalent to that of the running time of valid values.407+408+ Note that the returned key must be in plaintext.409+ """410+ raise NotImplementedError("Subclasses must implement this function.")411+412+ def get_access_token_secret(self, client_key, access_token):413+ """Retrieves the shared secret associated with the access token.414+415+ This method must allow the use of a dummy values and the running time416+ must be roughly equivalent to that of the running time of valid values.417+418+ Note that the returned key must be in plaintext.419+ """420+ raise NotImplementedError("Subclasses must implement this function.")421+422+ @property423+ def dummy_request_token(self):424+ """Dummy request token used when an invalid token was supplied.425+426+ The dummy request token should be associated with a request token427+ secret such that get_request_token_secret(.., dummy_request_token)428+ returns a valid secret.429+ """430+ raise NotImplementedError("Subclasses must implement this function.")431+432+ @property433+ def dummy_access_token(self):434+ """Dummy access token used when an invalid token was supplied.435+436+ The dummy access token should be associated with an access token437+ secret such that get_access_token_secret(.., dummy_access_token)438+ returns a valid secret.439+ """440+ raise NotImplementedError("Subclasses must implement this function.")441+442+ def get_rsa_key(self, client_key):443+ """Retrieves a previously stored client provided RSA key.444+445+ This method must allow the use of a dummy client_key value. Fetching446+ the rsa key using the dummy key must take the same aount of time447+ as fetching a key for a valid client.448+449+ Note that the key must be returned in plaintext.450+ """451+ raise NotImplementedError("Subclasses must implement this function.")452+453+ def get_signature_type_and_params(self, request):454+ """Extracts parameters from query, headers and body. Signature type455+ is set to the source in which parameters were found.456+ """457+ header_params = signature.collect_parameters(headers=request.headers,458+ exclude_oauth_signature=False)459+ body_params = signature.collect_parameters(body=request.body,460+ exclude_oauth_signature=False)461+ query_params = signature.collect_parameters(uri_query=request.uri_query,462+ exclude_oauth_signature=False)463+464+ params = []465+ params.extend(header_params)466+ params.extend(body_params)467+ params.extend(query_params)468+ signature_types_with_oauth_params = filter(lambda s: s[2], (469+ (SIGNATURE_TYPE_AUTH_HEADER, params,470+ utils.filter_oauth_params(header_params)),471+ (SIGNATURE_TYPE_BODY, params,472+ utils.filter_oauth_params(body_params)),473+ (SIGNATURE_TYPE_QUERY, params,474+ utils.filter_oauth_params(query_params))475+ ))476+477+ if len(signature_types_with_oauth_params) > 1:478+ raise ValueError('oauth_ params must come from only 1 signature type but were found in %s' % ', '.join(479+ [s[0] for s in signature_types_with_oauth_params]))480+ try:481+ signature_type, params, oauth_params = signature_types_with_oauth_params[0]482+ except IndexError:483+ raise ValueError('oauth_ params are missing. Could not determine signature type.')484+485+ return signature_type, params, oauth_params486+487+ def validate_client_key(self, client_key):488+ """Validates that supplied client key is a registered and valid client.489+490+ Note that if the dummy client is supplied it should validate in same491+ or nearly the same amount of time as a valid one.492+493+ Bad:494+495+ if client_key == self.dummy_client:496+ return False497+ else:498+ return storage.has_client(client_key)499+500+ Good:501+502+ return storage.has_client(client_key) and client_key != self.dummy_client503+ """504+ raise NotImplementedError("Subclasses must implement this function.")505+506+ def validate_request_token(self, client_key, request_token):507+ """Validates that supplied request token is registered and valid.508+509+ Note that if the dummy request_token is supplied it should validate in510+ the same nearly the same amount of time as a valid one.511+512+ Bad:513+514+ if request_token == self.dummy_request_token:515+ return False516+ else:517+ return storage.has_request_token(request_token)518+519+ Good:520+521+ return (storage.has_request_token(request_token) and522+ request_token != self.dummy_request_token)523+ """524+ raise NotImplementedError("Subclasses must implement this function.")525+526+ def validate_access_token(self, client_key, access_token):527+ """Validates that supplied access token is registered and valid.528+529+ Note that if the dummy access token is supplied it should validate in530+ the same or nearly the same amount of time as a valid one.531+532+ Bad:533+534+ if access_token == self.dummy_access_token:535+ return False536+ else:537+ return storage.has_access_token(access_token)538+539+ Good:540+541+ return (storage.has_access_token(access_token) and542+ access_token != self.dummy_access_token)543+ """544+ raise NotImplementedError("Subclasses must implement this function.")545+546+ def validate_timestamp_and_nonce(self, client_key, timestamp, nonce,547+ request_token=None, access_token=None):548+ """Validates that the nonce has not been used before.549+550+ Per `Section 3.3`_ of the spec.551+552+ "A nonce is a random string, uniquely generated by the client to allow553+ the server to verify that a request has never been made before and554+ helps prevent replay attacks when requests are made over a non-secure555+ channel. The nonce value MUST be unique across all requests with the556+ same timestamp, client credentials, and token combinations."557+558+ .. _`Section 3.3`: http://tools.ietf.org/html/rfc5849#section-3.3559+560+ """561+ raise NotImplementedError("Subclasses must implement this function.")562+563+ def validate_redirect_uri(self, client_key, redirect_uri):564+ """Validates the client supplied redirection URI.565+566+ It is highly recommended that OAuth providers require their clients567+ to register all redirection URIs prior to using them in requests and568+ register them as absolute URIs. See `CWE-601`_ for more information569+ about open redirection attacks.570+571+ By requiring registration of all redirection URIs it should be572+ straightforward for the provider to verify whether the supplied573+ redirect_uri is valid or not.574+575+ .. _`CWE-601`: http://cwe.mitre.org/top25/index.html#CWE-601576+ """577+ raise NotImplementedError("Subclasses must implement this function.")578+579+580+ def validate_requested_realm(self, client_key, realm):581+ """Validates that the client may request access to the realm.582+583+ This method is invoked when obtaining a request token and should584+ tie a realm to the request token and after user authorization585+ this realm restriction should transfer to the access token.586+ """587+ raise NotImplementedError("Subclasses must implement this function.")588+589+ def validate_realm(self, client_key, access_token, uri=None,590+ required_realm=None):591+ """Validates access to the request realm.592+593+ How providers choose to use the realm parameter is outside the OAuth594+ specification but it is commonly used to restrict access to a subset595+ of protected resources such as "photos".596+597+ required_realm is a convenience parameter which can be used to provide598+ a per view method pre-defined list of allowed realms.599+ """600+ raise NotImplementedError("Subclasses must implement this function.")601+602+ def validate_verifier(self, client_key, request_token, verifier):603+ """Validates a verification code.604+605+ OAuth providers issue a verification code to clients after the606+ resource owner authorizes access. This code is used by the client to607+ obtain token credentials and the provider must verify that the608+ verifier is valid and associated with the client as well as the609+ resource owner.610+ """611+ raise NotImplementedError("Subclasses must implement this function.")612+613+ def verify_request(self, uri, http_method=u'GET', body=None,614+ headers=None, require_resource_owner=True, require_verifier=False,615+ require_realm=False, required_realm=None):616+ """Verifies a request ensuring that the following is true:617+618+ Per `section 3.2`_ of the spec.619+620+ - all mandated OAuth parameters are supplied621+ - parameters are only supplied in one source which may be the URI622+ query, the Authorization header or the body623+ - all parameters are checked and validated, see comments and the624+ methods and properties of this class for further details.625+ - the supplied signature is verified against a recalculated one626+627+ A ValueError will be raised if any parameter is missing,628+ supplied twice or invalid. A HTTP 400 Response should be returned629+ upon catching an exception.630+631+ A HTTP 401 Response should be returned if verify_request returns False.632+633+ `Timing attacks`_ are prevented through the use of dummy credentials to634+ create near constant time verification even if an invalid credential635+ is used. Early exit on invalid credentials would enable attackers636+ to perform `enumeration attacks`_. Near constant time string comparison637+ is used to prevent secret key guessing. Note that timing attacks can638+ only be prevented through near constant time execution, not by adding639+ a random delay which would only require more samples to be gathered.640+641+ .. _`section 3.2`: http://tools.ietf.org/html/rfc5849#section-3.2642+ .. _`Timing attacks`: http://rdist.root.org/2010/07/19/exploiting-remote-timing-attacks/643+ .. _`enumeration attacks`: http://www.sans.edu/research/security-laboratory/article/attacks-browsing644+ """645+ # Only include body data from x-www-form-urlencoded requests646+ headers = headers or {}647+ if (u"Content-Type" in headers and648+ headers[u"Content-Type"] == CONTENT_TYPE_FORM_URLENCODED):649+ request = Request(uri, http_method, body, headers)650+ else:651+ request = Request(uri, http_method, u'', headers)652+653+ if self.enforce_ssl and not request.uri.lower().startswith("https://"):654+ raise ValueError("Insecure transport, only HTTPS is allowed.")655+656+ signature_type, params, oauth_params = self.get_signature_type_and_params(request)657+658+ # The server SHOULD return a 400 (Bad Request) status code when659+ # receiving a request with duplicated protocol parameters.660+ if len(dict(oauth_params)) != len(oauth_params):661+ raise ValueError("Duplicate OAuth entries.")662+663+ oauth_params = dict(oauth_params)664+ request_signature = oauth_params.get(u'oauth_signature')665+ client_key = oauth_params.get(u'oauth_consumer_key')666+ resource_owner_key = oauth_params.get(u'oauth_token')667+ nonce = oauth_params.get(u'oauth_nonce')668+ timestamp = oauth_params.get(u'oauth_timestamp')669+ callback_uri = oauth_params.get(u'oauth_callback')670+ verifier = oauth_params.get(u'oauth_verifier')671+ signature_method = oauth_params.get(u'oauth_signature_method')672+ realm = dict(params).get(u'realm')673+674+ # The server SHOULD return a 400 (Bad Request) status code when675+ # receiving a request with missing parameters.676+ if not all((request_signature, client_key, nonce,677+ timestamp, signature_method)):678+ raise ValueError("Missing OAuth parameters.")679+680+ # OAuth does not mandate a particular signature method, as each681+ # implementation can have its own unique requirements. Servers are682+ # free to implement and document their own custom methods.683+ # Recommending any particular method is beyond the scope of this684+ # specification. Implementers should review the Security685+ # Considerations section (`Section 4`_) before deciding on which686+ # method to support.687+ # .. _`Section 4`: http://tools.ietf.org/html/rfc5849#section-4688+ if not signature_method in self.allowed_signature_methods:689+ raise ValueError("Invalid signature method.")690+691+ # Servers receiving an authenticated request MUST validate it by:692+ # If the "oauth_version" parameter is present, ensuring its value is693+ # "1.0".694+ if u'oauth_version' in oauth_params and oauth_params[u'oauth_version'] != u'1.0':695+ raise ValueError("Invalid OAuth version.")696+697+ # The timestamp value MUST be a positive integer. Unless otherwise698+ # specified by the server's documentation, the timestamp is expressed699+ # in the number of seconds since January 1, 1970 00:00:00 GMT.700+ if len(timestamp) != 10:701+ raise ValueError("Invalid timestamp size")702+ try:703+ ts = int(timestamp)704+705+ except ValueError:706+ raise ValueError("Timestamp must be an integer")707+708+ else:709+ # To avoid the need to retain an infinite number of nonce values for710+ # future checks, servers MAY choose to restrict the time period after711+ # which a request with an old timestamp is rejected.712+ if time.time() - ts > self.timestamp_lifetime:713+ raise ValueError("Request too old, over 10 minutes.")714+715+ # Provider specific validation of parameters, used to enforce716+ # restrictions such as character set and length.717+ if not self.check_client_key(client_key):718+ raise ValueError("Invalid client key.")719+720+ if not resource_owner_key and require_resource_owner:721+ raise ValueError("Missing resource owner.")722+723+ if (require_resource_owner and not require_verifier and724+ not self.check_access_token(resource_owner_key)):725+ raise ValueError("Invalid resource owner key.")726+727+ if (require_resource_owner and require_verifier and728+ not self.check_request_token(resource_owner_key)):729+ raise ValueError("Invalid resource owner key.")730+731+ if not self.check_nonce(nonce):732+ raise ValueError("Invalid nonce.")733+734+ if realm and not self.check_realm(realm):735+ raise ValueError("Invalid realm. Allowed are %s" % self.realms)736+737+ if not verifier and require_verifier:738+ raise ValueError("Missing verifier.")739+740+ if require_verifier and not self.check_verifier(verifier):741+ raise ValueError("Invalid verifier.")742+743+ # Servers receiving an authenticated request MUST validate it by:744+ # If using the "HMAC-SHA1" or "RSA-SHA1" signature methods, ensuring745+ # that the combination of nonce/timestamp/token (if present)746+ # received from the client has not been used before in a previous747+ # request (the server MAY reject requests with stale timestamps as748+ # described in `Section 3.3`_).749+ # .._`Section 3.3`: http://tools.ietf.org/html/rfc5849#section-3.3750+ #751+ # We check this before validating client and resource owner for752+ # increased security and performance, both gained by doing less work.753+ if require_verifier:754+ token = {"request_token": resource_owner_key}755+ else:756+ token = {"access_token": resource_owner_key}757+ if not self.validate_timestamp_and_nonce(client_key, timestamp,758+ nonce, **token):759+ return False760+761+ # The server SHOULD return a 401 (Unauthorized) status code when762+ # receiving a request with invalid client credentials.763+ # Note: This is postponed in order to avoid timing attacks, instead764+ # a dummy client is assigned and used to maintain near constant765+ # time request verification.766+ #767+ # Note that early exit would enable client enumeration768+ valid_client = self.validate_client_key(client_key)769+ if not valid_client:770+ client_key = self.dummy_client771+772+ # Ensure a valid redirection uri is used773+ valid_redirect = self.validate_redirect_uri(client_key, callback_uri)774+775+ # The server SHOULD return a 401 (Unauthorized) status code when776+ # receiving a request with invalid or expired token.777+ # Note: This is postponed in order to avoid timing attacks, instead778+ # a dummy token is assigned and used to maintain near constant779+ # time request verification.780+ #781+ # Note that early exit would enable resource owner enumeration782+ if resource_owner_key:783+ if require_verifier:784+ valid_resource_owner = self.validate_request_token(785+ client_key, resource_owner_key)786+ else:787+ valid_resource_owner = self.validate_access_token(788+ client_key, resource_owner_key)789+ if not valid_resource_owner:790+ resource_owner_key = self.dummy_resource_owner791+ else:792+ valid_resource_owner = True793+794+ # Note that `realm`_ is only used in authorization headers and how795+ # it should be interepreted is not included in the OAuth spec.796+ # However they could be seen as a scope or realm to which the797+ # client has access and as such every client should be checked798+ # to ensure it is authorized access to that scope or realm.799+ # .. _`realm`: http://tools.ietf.org/html/rfc2617#section-1.2800+ #801+ # Note that early exit would enable client realm access enumeration.802+ #803+ # The require_realm indicates this is the first step in the OAuth804+ # workflow where a client requests access to a specific realm.805+ #806+ # Clients obtaining an access token will not supply a realm and it will807+ # not be checked. Instead the previously requested realm should be808+ # transferred from the request token to the access token.809+ #810+ # Access to protected resources will always validate the realm but note811+ # that the realm is now tied to the access token and not provided by812+ # the client.813+ if require_realm and not resource_owner_key:814+ valid_realm = self.validate_requested_realm(client_key, realm)815+ elif require_verifier:816+ valid_realm = True817+ else:818+ valid_realm = self.validate_realm(client_key, resource_owner_key,819+ uri=request.uri, required_realm=required_realm)820+821+ # The server MUST verify (Section 3.2) the validity of the request,822+ # ensure that the resource owner has authorized the provisioning of823+ # token credentials to the client, and ensure that the temporary824+ # credentials have not expired or been used before. The server MUST825+ # also verify the verification code received from the client.826+ # .. _`Section 3.2`: http://tools.ietf.org/html/rfc5849#section-3.2827+ #828+ # Note that early exit would enable resource owner authorization829+ # verifier enumertion.830+ if verifier:831+ valid_verifier = self.validate_verifier(client_key,832+ resource_owner_key, verifier)833+ else:834+ valid_verifier = True835+836+ # Parameters to Client depend on signature method which may vary837+ # for each request. Note that HMAC-SHA1 and PLAINTEXT share parameters838+839+ request.params = filter(lambda x: x[0] != "oauth_signature", params)840+ request.signature = request_signature841+842+ # ---- RSA Signature verification ----843+ if signature_method == SIGNATURE_RSA:844+ # The server verifies the signature per `[RFC3447] section 8.2.2`_845+ # .. _`[RFC3447] section 8.2.2`: http://tools.ietf.org/html/rfc3447#section-8.2.1846+ rsa_key = self.get_rsa_key(client_key)847+ valid_signature = signature.verify_rsa_sha1(request, rsa_key)848+849+ # ---- HMAC or Plaintext Signature verification ----850+ else:851+ # Servers receiving an authenticated request MUST validate it by:852+ # Recalculating the request signature independently as described in853+ # `Section 3.4`_ and comparing it to the value received from the854+ # client via the "oauth_signature" parameter.855+ # .. _`Section 3.4`: http://tools.ietf.org/html/rfc5849#section-3.4856+ client_secret = self.get_client_secret(client_key)857+ if require_verifier:858+ resource_owner_secret = self.get_request_token_secret(859+ client_key, resource_owner_key)860+ else:861+ resource_owner_secret = self.get_access_token_secret(862+ client_key, resource_owner_key)863+864+ if signature_method == SIGNATURE_HMAC:865+ valid_signature = signature.verify_hmac_sha1(request,866+ client_secret, resource_owner_secret)867+ else:868+ valid_signature = signature.verify_plaintext(request,869+ client_secret, resource_owner_secret)870+871+ # We delay checking validity until the very end, using dummy values for872+ # calculations and fetching secrets/keys to ensure the flow of every873+ # request remains almost identical regardless of whether valid values874+ # have been supplied. This ensures near constant time execution and875+ # prevents malicious users from guessing sensitive information876+ v = all((valid_client, valid_resource_owner, valid_realm,877+ valid_redirect, valid_verifier, valid_signature))878+ logger = logging.getLogger("oauthlib")879+ if not v:880+ logger.info("[Failure] OAuthLib request verification failed.")881+ logger.info("Valid client:\t%s" % valid_client)882+ logger.info("Valid token:\t%s\t(Required: %s" % (valid_resource_owner, require_resource_owner))883+ logger.info("Valid realm:\t%s\t(Required: %s)" % (valid_realm, require_realm))884+ logger.info("Valid callback:\t%s" % valid_redirect)885+ logger.info("Valid verifier:\t%s\t(Required: %s)" % (valid_verifier, require_verifier))886+ logger.info("Valid signature:\t%s" % valid_signature)887+ return vadded:requests/packages/oauthlib/oauth1/rfc5849/parameters.py+134 added
1+# -*- coding: utf-8 -*-2+from __future__ import absolute_import3+4+"""5+oauthlib.parameters6+~~~~~~~~~~~~~~~~~~~7+8+This module contains methods related to `section 3.5`_ of the OAuth 1.0a spec.9+10+.. _`section 3.5`: http://tools.ietf.org/html/rfc5849#section-3.511+"""12+13+from urlparse import urlparse, urlunparse14+from . import utils15+from oauthlib.common import extract_params, urlencode16+17+18+# TODO: do we need filter_params now that oauth_params are handled by Request?19+# We can easily pass in just oauth protocol params.20+@utils.filter_params21+def prepare_headers(oauth_params, headers=None, realm=None):22+ """**Prepare the Authorization header.**23+ Per `section 3.5.1`_ of the spec.24+25+ Protocol parameters can be transmitted using the HTTP "Authorization"26+ header field as defined by `RFC2617`_ with the auth-scheme name set to27+ "OAuth" (case insensitive).28+29+ For example::30+31+ Authorization: OAuth realm="Example",32+ oauth_consumer_key="0685bd9184jfhq22",33+ oauth_token="ad180jjd733klru7",34+ oauth_signature_method="HMAC-SHA1",35+ oauth_signature="wOJIO9A2W5mFwDgiDvZbTSMK%2FPY%3D",36+ oauth_timestamp="137131200",37+ oauth_nonce="4572616e48616d6d65724c61686176",38+ oauth_version="1.0"39+40+41+ .. _`section 3.5.1`: http://tools.ietf.org/html/rfc5849#section-3.5.142+ .. _`RFC2617`: http://tools.ietf.org/html/rfc261743+ """44+ headers = headers or {}45+46+ # Protocol parameters SHALL be included in the "Authorization" header47+ # field as follows:48+ authorization_header_parameters_parts = []49+ for oauth_parameter_name, value in oauth_params:50+ # 1. Parameter names and values are encoded per Parameter Encoding51+ # (`Section 3.6`_)52+ #53+ # .. _`Section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.654+ escaped_name = utils.escape(oauth_parameter_name)55+ escaped_value = utils.escape(value)56+57+ # 2. Each parameter's name is immediately followed by an "=" character58+ # (ASCII code 61), a """ character (ASCII code 34), the parameter59+ # value (MAY be empty), and another """ character (ASCII code 34).60+ part = u'{0}="{1}"'.format(escaped_name, escaped_value)61+62+ authorization_header_parameters_parts.append(part)63+64+ # 3. Parameters are separated by a "," character (ASCII code 44) and65+ # OPTIONAL linear whitespace per `RFC2617`_.66+ #67+ # .. _`RFC2617`: http://tools.ietf.org/html/rfc261768+ authorization_header_parameters = ', '.join(69+ authorization_header_parameters_parts)70+71+ # 4. The OPTIONAL "realm" parameter MAY be added and interpreted per72+ # `RFC2617 section 1.2`_.73+ #74+ # .. _`RFC2617 section 1.2`: http://tools.ietf.org/html/rfc2617#section-1.275+ if realm:76+ # NOTE: realm should *not* be escaped77+ authorization_header_parameters = (u'realm="%s", ' % realm +78+ authorization_header_parameters)79+80+ # the auth-scheme name set to "OAuth" (case insensitive).81+ authorization_header = u'OAuth %s' % authorization_header_parameters82+83+ # contribute the Authorization header to the given headers84+ full_headers = {}85+ full_headers.update(headers)86+ full_headers[u'Authorization'] = authorization_header87+ return full_headers88+89+90+def _append_params(oauth_params, params):91+ """Append OAuth params to an existing set of parameters.92+93+ Both params and oauth_params is must be lists of 2-tuples.94+95+ Per `section 3.5.2`_ and `3.5.3`_ of the spec.96+97+ .. _`section 3.5.2`: http://tools.ietf.org/html/rfc5849#section-3.5.298+ .. _`3.5.3`: http://tools.ietf.org/html/rfc5849#section-3.5.399+100+ """101+ merged = list(params)102+ merged.extend(oauth_params)103+ # The request URI / entity-body MAY include other request-specific104+ # parameters, in which case, the protocol parameters SHOULD be appended105+ # following the request-specific parameters, properly separated by an "&"106+ # character (ASCII code 38)107+ merged.sort(key=lambda i: i[0].startswith('oauth_'))108+ return merged109+110+111+def prepare_form_encoded_body(oauth_params, body):112+ """Prepare the Form-Encoded Body.113+114+ Per `section 3.5.2`_ of the spec.115+116+ .. _`section 3.5.2`: http://tools.ietf.org/html/rfc5849#section-3.5.2117+118+ """119+ # append OAuth params to the existing body120+ return _append_params(oauth_params, body)121+122+123+def prepare_request_uri_query(oauth_params, uri):124+ """Prepare the Request URI Query.125+126+ Per `section 3.5.3`_ of the spec.127+128+ .. _`section 3.5.3`: http://tools.ietf.org/html/rfc5849#section-3.5.3129+130+ """131+ # append OAuth params to the existing set of query components132+ sch, net, path, par, query, fra = urlparse(uri)133+ query = urlencode(_append_params(oauth_params, extract_params(query) or []))134+ return urlunparse((sch, net, path, par, query, fra))added:requests/packages/oauthlib/oauth1/rfc5849/signature.py+551 added
1+# -*- coding: utf-8 -*-2+from __future__ import absolute_import3+"""4+oauthlib.oauth1.rfc5849.signature5+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~6+7+This module represents a direct implementation of `section 3.4`_ of the spec.8+9+Terminology:10+ * Client: software interfacing with an OAuth API11+ * Server: the API provider12+ * Resource Owner: the user who is granting authorization to the client13+14+Steps for signing a request:15+16+1. Collect parameters from the uri query, auth header, & body17+2. Normalize those parameters18+3. Normalize the uri19+4. Pass the normalized uri, normalized parameters, and http method to20+ construct the base string21+5. Pass the base string and any keys needed to a signing function22+23+.. _`section 3.4`: http://tools.ietf.org/html/rfc5849#section-3.424+"""25+import binascii26+import hashlib27+import hmac28+import urlparse29+from . import utils30+from oauthlib.common import extract_params, safe_string_equals31+32+33+def construct_base_string(http_method, base_string_uri,34+ normalized_encoded_request_parameters):35+ """**String Construction**36+ Per `section 3.4.1.1`_ of the spec.37+38+ For example, the HTTP request::39+40+ POST /request?b5=%3D%253D&a3=a&c%40=&a2=r%20b HTTP/1.141+ Host: example.com42+ Content-Type: application/x-www-form-urlencoded43+ Authorization: OAuth realm="Example",44+ oauth_consumer_key="9djdj82h48djs9d2",45+ oauth_token="kkk9d7dh3k39sjv7",46+ oauth_signature_method="HMAC-SHA1",47+ oauth_timestamp="137131201",48+ oauth_nonce="7d8f3e4a",49+ oauth_signature="bYT5CMsGcbgUdFHObYMEfcx6bsw%3D"50+51+ c2&a3=2+q52+53+ is represented by the following signature base string (line breaks54+ are for display purposes only)::55+56+ POST&http%3A%2F%2Fexample.com%2Frequest&a2%3Dr%2520b%26a3%3D2%2520q57+ %26a3%3Da%26b5%3D%253D%25253D%26c%2540%3D%26c2%3D%26oauth_consumer_58+ key%3D9djdj82h48djs9d2%26oauth_nonce%3D7d8f3e4a%26oauth_signature_m59+ ethod%3DHMAC-SHA1%26oauth_timestamp%3D137131201%26oauth_token%3Dkkk60+ 9d7dh3k39sjv761+62+ .. _`section 3.4.1.1`: http://tools.ietf.org/html/rfc5849#section-3.4.1.163+ """64+65+ # The signature base string is constructed by concatenating together,66+ # in order, the following HTTP request elements:67+68+ # 1. The HTTP request method in uppercase. For example: "HEAD",69+ # "GET", "POST", etc. If the request uses a custom HTTP method, it70+ # MUST be encoded (`Section 3.6`_).71+ #72+ # .. _`Section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.673+ base_string = utils.escape(http_method.upper())74+75+ # 2. An "&" character (ASCII code 38).76+ base_string += u'&'77+78+ # 3. The base string URI from `Section 3.4.1.2`_, after being encoded79+ # (`Section 3.6`_).80+ #81+ # .. _`Section 3.4.1.2`: http://tools.ietf.org/html/rfc5849#section-3.4.1.282+ # .. _`Section 3.4.6`: http://tools.ietf.org/html/rfc5849#section-3.4.683+ base_string += utils.escape(base_string_uri)84+85+ # 4. An "&" character (ASCII code 38).86+ base_string += u'&'87+88+ # 5. The request parameters as normalized in `Section 3.4.1.3.2`_, after89+ # being encoded (`Section 3.6`).90+ #91+ # .. _`Section 3.4.1.3.2`: http://tools.ietf.org/html/rfc5849#section-3.4.1.3.292+ # .. _`Section 3.4.6`: http://tools.ietf.org/html/rfc5849#section-3.4.693+ base_string += utils.escape(normalized_encoded_request_parameters)94+95+ return base_string96+97+98+def normalize_base_string_uri(uri):99+ """**Base String URI**100+ Per `section 3.4.1.2`_ of the spec.101+102+ For example, the HTTP request::103+104+ GET /r%20v/X?id=123 HTTP/1.1105+ Host: EXAMPLE.COM:80106+107+ is represented by the base string URI: "http://example.com/r%20v/X".108+109+ In another example, the HTTPS request::110+111+ GET /?q=1 HTTP/1.1112+ Host: www.example.net:8080113+114+ is represented by the base string URI: "https://www.example.net:8080/".115+116+ .. _`section 3.4.1.2`: http://tools.ietf.org/html/rfc5849#section-3.4.1.2117+ """118+ if not isinstance(uri, unicode):119+ raise ValueError('uri must be a unicode object.')120+121+ # FIXME: urlparse does not support unicode122+ scheme, netloc, path, params, query, fragment = urlparse.urlparse(uri)123+124+ # The scheme, authority, and path of the request resource URI `RFC3986`125+ # are included by constructing an "http" or "https" URI representing126+ # the request resource (without the query or fragment) as follows:127+ #128+ # .. _`RFC2616`: http://tools.ietf.org/html/rfc3986129+130+ # 1. The scheme and host MUST be in lowercase.131+ scheme = scheme.lower()132+ netloc = netloc.lower()133+134+ # 2. The host and port values MUST match the content of the HTTP135+ # request "Host" header field.136+ # TODO: enforce this constraint137+138+ # 3. The port MUST be included if it is not the default port for the139+ # scheme, and MUST be excluded if it is the default. Specifically,140+ # the port MUST be excluded when making an HTTP request `RFC2616`_141+ # to port 80 or when making an HTTPS request `RFC2818`_ to port 443.142+ # All other non-default port numbers MUST be included.143+ #144+ # .. _`RFC2616`: http://tools.ietf.org/html/rfc2616145+ # .. _`RFC2818`: http://tools.ietf.org/html/rfc2818146+ default_ports = (147+ (u'http', u'80'),148+ (u'https', u'443'),149+ )150+ if u':' in netloc:151+ host, port = netloc.split(u':', 1)152+ if (scheme, port) in default_ports:153+ netloc = host154+155+ return urlparse.urlunparse((scheme, netloc, path, u'', u'', u''))156+157+158+# ** Request Parameters **159+#160+# Per `section 3.4.1.3`_ of the spec.161+#162+# In order to guarantee a consistent and reproducible representation of163+# the request parameters, the parameters are collected and decoded to164+# their original decoded form. They are then sorted and encoded in a165+# particular manner that is often different from their original166+# encoding scheme, and concatenated into a single string.167+#168+# .. _`section 3.4.1.3`: http://tools.ietf.org/html/rfc5849#section-3.4.1.3169+170+def collect_parameters(uri_query='', body=[], headers=None,171+ exclude_oauth_signature=True):172+ """**Parameter Sources**173+174+ Parameters starting with `oauth_` will be unescaped.175+176+ Body parameters must be supplied as a dict, a list of 2-tuples, or a177+ formencoded query string.178+179+ Headers must be supplied as a dict.180+181+ Per `section 3.4.1.3.1`_ of the spec.182+183+ For example, the HTTP request::184+185+ POST /request?b5=%3D%253D&a3=a&c%40=&a2=r%20b HTTP/1.1186+ Host: example.com187+ Content-Type: application/x-www-form-urlencoded188+ Authorization: OAuth realm="Example",189+ oauth_consumer_key="9djdj82h48djs9d2",190+ oauth_token="kkk9d7dh3k39sjv7",191+ oauth_signature_method="HMAC-SHA1",192+ oauth_timestamp="137131201",193+ oauth_nonce="7d8f3e4a",194+ oauth_signature="djosJKDKJSD8743243%2Fjdk33klY%3D"195+196+ c2&a3=2+q197+198+ contains the following (fully decoded) parameters used in the199+ signature base sting::200+201+ +------------------------+------------------+202+ | Name | Value |203+ +------------------------+------------------+204+ | b5 | =%3D |205+ | a3 | a |206+ | c@ | |207+ | a2 | r b |208+ | oauth_consumer_key | 9djdj82h48djs9d2 |209+ | oauth_token | kkk9d7dh3k39sjv7 |210+ | oauth_signature_method | HMAC-SHA1 |211+ | oauth_timestamp | 137131201 |212+ | oauth_nonce | 7d8f3e4a |213+ | c2 | |214+ | a3 | 2 q |215+ +------------------------+------------------+216+217+ Note that the value of "b5" is "=%3D" and not "==". Both "c@" and218+ "c2" have empty values. While the encoding rules specified in this219+ specification for the purpose of constructing the signature base220+ string exclude the use of a "+" character (ASCII code 43) to221+ represent an encoded space character (ASCII code 32), this practice222+ is widely used in "application/x-www-form-urlencoded" encoded values,223+ and MUST be properly decoded, as demonstrated by one of the "a3"224+ parameter instances (the "a3" parameter is used twice in this225+ request).226+227+ .. _`section 3.4.1.3.1`: http://tools.ietf.org/html/rfc5849#section-3.4.1.3.1228+ """229+ headers = headers or {}230+ params = []231+232+ # The parameters from the following sources are collected into a single233+ # list of name/value pairs:234+235+ # * The query component of the HTTP request URI as defined by236+ # `RFC3986, Section 3.4`_. The query component is parsed into a list237+ # of name/value pairs by treating it as an238+ # "application/x-www-form-urlencoded" string, separating the names239+ # and values and decoding them as defined by240+ # `W3C.REC-html40-19980424`_, Section 17.13.4.241+ #242+ # .. _`RFC3986, Section 3.4`: http://tools.ietf.org/html/rfc3986#section-3.4243+ # .. _`W3C.REC-html40-19980424`: http://tools.ietf.org/html/rfc5849#ref-W3C.REC-html40-19980424244+ if uri_query:245+ params.extend(urlparse.parse_qsl(uri_query, keep_blank_values=True))246+247+ # * The OAuth HTTP "Authorization" header field (`Section 3.5.1`_) if248+ # present. The header's content is parsed into a list of name/value249+ # pairs excluding the "realm" parameter if present. The parameter250+ # values are decoded as defined by `Section 3.5.1`_.251+ #252+ # .. _`Section 3.5.1`: http://tools.ietf.org/html/rfc5849#section-3.5.1253+ if headers:254+ headers_lower = dict((k.lower(), v) for k, v in headers.items())255+ authorization_header = headers_lower.get(u'authorization')256+ if authorization_header is not None:257+ params.extend([i for i in utils.parse_authorization_header(258+ authorization_header) if i[0] != u'realm'])259+260+ # * The HTTP request entity-body, but only if all of the following261+ # conditions are met:262+ # * The entity-body is single-part.263+ #264+ # * The entity-body follows the encoding requirements of the265+ # "application/x-www-form-urlencoded" content-type as defined by266+ # `W3C.REC-html40-19980424`_.267+268+ # * The HTTP request entity-header includes the "Content-Type"269+ # header field set to "application/x-www-form-urlencoded".270+ #271+ # .._`W3C.REC-html40-19980424`: http://tools.ietf.org/html/rfc5849#ref-W3C.REC-html40-19980424272+273+ # TODO: enforce header param inclusion conditions274+ bodyparams = extract_params(body) or []275+ params.extend(bodyparams)276+277+ # ensure all oauth params are unescaped278+ unescaped_params = []279+ for k, v in params:280+ if k.startswith(u'oauth_'):281+ v = utils.unescape(v)282+ unescaped_params.append((k, v))283+284+ # The "oauth_signature" parameter MUST be excluded from the signature285+ # base string if present.286+ if exclude_oauth_signature:287+ unescaped_params = filter(lambda i: i[0] != u'oauth_signature',288+ unescaped_params)289+290+ return unescaped_params291+292+293+def normalize_parameters(params):294+ """**Parameters Normalization**295+ Per `section 3.4.1.3.2`_ of the spec.296+297+ For example, the list of parameters from the previous section would298+ be normalized as follows:299+300+ Encoded::301+302+ +------------------------+------------------+303+ | Name | Value |304+ +------------------------+------------------+305+ | b5 | %3D%253D |306+ | a3 | a |307+ | c%40 | |308+ | a2 | r%20b |309+ | oauth_consumer_key | 9djdj82h48djs9d2 |310+ | oauth_token | kkk9d7dh3k39sjv7 |311+ | oauth_signature_method | HMAC-SHA1 |312+ | oauth_timestamp | 137131201 |313+ | oauth_nonce | 7d8f3e4a |314+ | c2 | |315+ | a3 | 2%20q |316+ +------------------------+------------------+317+318+ Sorted::319+320+ +------------------------+------------------+321+ | Name | Value |322+ +------------------------+------------------+323+ | a2 | r%20b |324+ | a3 | 2%20q |325+ | a3 | a |326+ | b5 | %3D%253D |327+ | c%40 | |328+ | c2 | |329+ | oauth_consumer_key | 9djdj82h48djs9d2 |330+ | oauth_nonce | 7d8f3e4a |331+ | oauth_signature_method | HMAC-SHA1 |332+ | oauth_timestamp | 137131201 |333+ | oauth_token | kkk9d7dh3k39sjv7 |334+ +------------------------+------------------+335+336+ Concatenated Pairs::337+338+ +-------------------------------------+339+ | Name=Value |340+ +-------------------------------------+341+ | a2=r%20b |342+ | a3=2%20q |343+ | a3=a |344+ | b5=%3D%253D |345+ | c%40= |346+ | c2= |347+ | oauth_consumer_key=9djdj82h48djs9d2 |348+ | oauth_nonce=7d8f3e4a |349+ | oauth_signature_method=HMAC-SHA1 |350+ | oauth_timestamp=137131201 |351+ | oauth_token=kkk9d7dh3k39sjv7 |352+ +-------------------------------------+353+354+ and concatenated together into a single string (line breaks are for355+ display purposes only)::356+357+ a2=r%20b&a3=2%20q&a3=a&b5=%3D%253D&c%40=&c2=&oauth_consumer_key=9dj358+ dj82h48djs9d2&oauth_nonce=7d8f3e4a&oauth_signature_method=HMAC-SHA1359+ &oauth_timestamp=137131201&oauth_token=kkk9d7dh3k39sjv7360+361+ .. _`section 3.4.1.3.2`: http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2362+ """363+364+ # The parameters collected in `Section 3.4.1.3`_ are normalized into a365+ # single string as follows:366+ #367+ # .. _`Section 3.4.1.3`: http://tools.ietf.org/html/rfc5849#section-3.4.1.3368+369+ # 1. First, the name and value of each parameter are encoded370+ # (`Section 3.6`_).371+ #372+ # .. _`Section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.6373+ key_values = [(utils.escape(k), utils.escape(v)) for k, v in params]374+375+ # 2. The parameters are sorted by name, using ascending byte value376+ # ordering. If two or more parameters share the same name, they377+ # are sorted by their value.378+ key_values.sort()379+380+ # 3. The name of each parameter is concatenated to its corresponding381+ # value using an "=" character (ASCII code 61) as a separator, even382+ # if the value is empty.383+ parameter_parts = [u'{0}={1}'.format(k, v) for k, v in key_values]384+385+ # 4. The sorted name/value pairs are concatenated together into a386+ # single string by using an "&" character (ASCII code 38) as387+ # separator.388+ return u'&'.join(parameter_parts)389+390+391+def sign_hmac_sha1(base_string, client_secret, resource_owner_secret):392+ """**HMAC-SHA1**393+394+ The "HMAC-SHA1" signature method uses the HMAC-SHA1 signature395+ algorithm as defined in `RFC2104`_::396+397+ digest = HMAC-SHA1 (key, text)398+399+ Per `section 3.4.2`_ of the spec.400+401+ .. _`RFC2104`: http://tools.ietf.org/html/rfc2104402+ .. _`section 3.4.2`: http://tools.ietf.org/html/rfc5849#section-3.4.2403+ """404+405+ # The HMAC-SHA1 function variables are used in following way:406+407+ # text is set to the value of the signature base string from408+ # `Section 3.4.1.1`_.409+ #410+ # .. _`Section 3.4.1.1`: http://tools.ietf.org/html/rfc5849#section-3.4.1.1411+ text = base_string412+413+ # key is set to the concatenated values of:414+ # 1. The client shared-secret, after being encoded (`Section 3.6`_).415+ #416+ # .. _`Section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.6417+ key = utils.escape(client_secret or u'')418+419+ # 2. An "&" character (ASCII code 38), which MUST be included420+ # even when either secret is empty.421+ key += u'&'422+423+ # 3. The token shared-secret, after being encoded (`Section 3.6`_).424+ #425+ # .. _`Section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.6426+ key += utils.escape(resource_owner_secret or u'')427+428+ # FIXME: HMAC does not support unicode!429+ key_utf8 = key.encode('utf-8')430+ text_utf8 = text.encode('utf-8')431+ signature = hmac.new(key_utf8, text_utf8, hashlib.sha1)432+433+ # digest is used to set the value of the "oauth_signature" protocol434+ # parameter, after the result octet string is base64-encoded435+ # per `RFC2045, Section 6.8`.436+ #437+ # .. _`RFC2045, Section 6.8`: http://tools.ietf.org/html/rfc2045#section-6.8438+ return binascii.b2a_base64(signature.digest())[:-1].decode('utf-8')439+440+441+def sign_rsa_sha1(base_string, rsa_private_key):442+ """**RSA-SHA1**443+444+ Per `section 3.4.3`_ of the spec.445+446+ The "RSA-SHA1" signature method uses the RSASSA-PKCS1-v1_5 signature447+ algorithm as defined in `RFC3447, Section 8.2`_ (also known as448+ PKCS#1), using SHA-1 as the hash function for EMSA-PKCS1-v1_5. To449+ use this method, the client MUST have established client credentials450+ with the server that included its RSA public key (in a manner that is451+ beyond the scope of this specification).452+453+ NOTE: this method requires the python-rsa library.454+455+ .. _`section 3.4.3`: http://tools.ietf.org/html/rfc5849#section-3.4.3456+ .. _`RFC3447, Section 8.2`: http://tools.ietf.org/html/rfc3447#section-8.2457+458+ """459+ # TODO: finish RSA documentation460+ from Crypto.PublicKey import RSA461+ from Crypto.Signature import PKCS1_v1_5462+ from Crypto.Hash import SHA463+ key = RSA.importKey(rsa_private_key)464+ h = SHA.new(base_string)465+ p = PKCS1_v1_5.new(key)466+ return binascii.b2a_base64(p.sign(h))[:-1].decode('utf-8')467+468+469+def sign_plaintext(client_secret, resource_owner_secret):470+ """Sign a request using plaintext.471+472+ Per `section 3.4.4`_ of the spec.473+474+ The "PLAINTEXT" method does not employ a signature algorithm. It475+ MUST be used with a transport-layer mechanism such as TLS or SSL (or476+ sent over a secure channel with equivalent protections). It does not477+ utilize the signature base string or the "oauth_timestamp" and478+ "oauth_nonce" parameters.479+480+ .. _`section 3.4.4`: http://tools.ietf.org/html/rfc5849#section-3.4.4481+482+ """483+484+ # The "oauth_signature" protocol parameter is set to the concatenated485+ # value of:486+487+ # 1. The client shared-secret, after being encoded (`Section 3.6`_).488+ #489+ # .. _`Section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.6490+ signature = utils.escape(client_secret or u'')491+492+ # 2. An "&" character (ASCII code 38), which MUST be included even493+ # when either secret is empty.494+ signature += u'&'495+496+ # 3. The token shared-secret, after being encoded (`Section 3.6`_).497+ #498+ # .. _`Section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.6499+ signature += utils.escape(resource_owner_secret or u'')500+501+ return signature502+503+504+def verify_hmac_sha1(request, client_secret=None, 505+ resource_owner_secret=None):506+ """Verify a HMAC-SHA1 signature.507+508+ Per `section 3.4`_ of the spec.509+510+ .. _`section 3.4`: http://tools.ietf.org/html/rfc5849#section-3.4511+ """512+ norm_params = normalize_parameters(request.params)513+ uri = normalize_base_string_uri(request.uri)514+ base_string = construct_base_string(request.http_method, uri, norm_params)515+ signature = sign_hmac_sha1(base_string, client_secret,516+ resource_owner_secret)517+ return safe_string_equals(signature, request.signature)518+519+520+def verify_rsa_sha1(request, rsa_public_key):521+ """Verify a RSASSA-PKCS #1 v1.5 base64 encoded signature.522+523+ Per `section 3.4.3`_ of the spec.524+525+ Note this method requires the PyCrypto library.526+527+ .. _`section 3.4.3`: http://tools.ietf.org/html/rfc5849#section-3.4.3528+529+ """530+ from Crypto.PublicKey import RSA531+ from Crypto.Signature import PKCS1_v1_5532+ from Crypto.Hash import SHA533+ key = RSA.importKey(rsa_public_key)534+ norm_params = normalize_parameters(request.params)535+ uri = normalize_base_string_uri(request.uri)536+ message = construct_base_string(request.http_method, uri, norm_params)537+ h = SHA.new(message)538+ p = PKCS1_v1_5.new(key)539+ sig = binascii.a2b_base64(request.signature)540+ return p.verify(h, sig)541+542+543+def verify_plaintext(request, client_secret=None, resource_owner_secret=None):544+ """Verify a PLAINTEXT signature.545+546+ Per `section 3.4`_ of the spec.547+548+ .. _`section 3.4`: http://tools.ietf.org/html/rfc5849#section-3.4549+ """550+ signature = sign_plaintext(client_secret, resource_owner_secret)551+ return safe_string_equals(signature, request.signature)added:requests/packages/oauthlib/oauth1/rfc5849/utils.py+99 added
1+# -*- coding: utf-8 -*-2+3+"""4+oauthlib.utils5+~~~~~~~~~~~~~~6+7+This module contains utility methods used by various parts of the OAuth8+spec.9+"""10+11+import string12+import urllib213+14+from oauthlib.common import quote, unquote15+16+UNICODE_ASCII_CHARACTER_SET = (string.ascii_letters.decode('ascii') +17+ string.digits.decode('ascii'))18+19+20+def filter_params(target):21+ """Decorator which filters params to remove non-oauth_* parameters22+23+ Assumes the decorated method takes a params dict or list of tuples as its24+ first argument.25+ """26+ def wrapper(params, *args, **kwargs):27+ params = filter_oauth_params(params)28+ return target(params, *args, **kwargs)29+30+ wrapper.__doc__ = target.__doc__31+ return wrapper32+33+34+def filter_oauth_params(params):35+ """Removes all non oauth parameters from a dict or a list of params."""36+ is_oauth = lambda kv: kv[0].startswith(u"oauth_")37+ if isinstance(params, dict):38+ return filter(is_oauth, params.items())39+ else:40+ return filter(is_oauth, params)41+42+43+def escape(u):44+ """Escape a unicode string in an OAuth-compatible fashion.45+46+ Per `section 3.6`_ of the spec.47+48+ .. _`section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.649+50+ """51+ if not isinstance(u, unicode):52+ raise ValueError('Only unicode objects are escapable.')53+ # Letters, digits, and the characters '_.-' are already treated as safe54+ # by urllib.quote(). We need to add '~' to fully support rfc5849.55+ return quote(u, safe='~')56+57+58+def unescape(u):59+ if not isinstance(u, unicode):60+ raise ValueError('Only unicode objects are unescapable.')61+ return unquote(u)62+63+64+def urlencode(query):65+ """Encode a sequence of two-element tuples or dictionary into a URL query string.66+67+ Operates using an OAuth-safe escape() method, in contrast to urllib.urlencode.68+ """69+ # Convert dictionaries to list of tuples70+ if isinstance(query, dict):71+ query = query.items()72+ return u"&".join([u'='.join([escape(k), escape(v)]) for k, v in query])73+74+75+def parse_keqv_list(l):76+ """A unicode-safe version of urllib2.parse_keqv_list"""77+ encoded_list = [u.encode('utf-8') for u in l]78+ encoded_parsed = urllib2.parse_keqv_list(encoded_list)79+ return dict((k.decode('utf-8'),80+ v.decode('utf-8')) for k, v in encoded_parsed.items())81+82+83+def parse_http_list(u):84+ """A unicode-safe version of urllib2.parse_http_list"""85+ encoded_str = u.encode('utf-8')86+ encoded_list = urllib2.parse_http_list(encoded_str)87+ return [s.decode('utf-8') for s in encoded_list]88+89+90+def parse_authorization_header(authorization_header):91+ """Parse an OAuth authorization header into a list of 2-tuples"""92+ auth_scheme = u'OAuth '93+ if authorization_header.startswith(auth_scheme):94+ authorization_header = authorization_header.replace(auth_scheme, u'', 1)95+ items = parse_http_list(authorization_header)96+ try:97+ return parse_keqv_list(items).items()98+ except ValueError:99+ raise ValueError('Malformed authorization header')added:requests/packages/oauthlib/oauth1/__init__.py+13 added
1+# -*- coding: utf-8 -*-2+from __future__ import absolute_import3+4+"""5+oauthlib.oauth16+~~~~~~~~~~~~~~7+8+This module is a wrapper for the most recent implementation of OAuth 1.0 Client9+and Server classes.10+"""11+12+from .rfc5849 import Client, Server13+added:requests/packages/oauthlib/oauth2/draft25/__init__.py+497 added
1+"""2+oauthlib.oauth2.draft_253+~~~~~~~~~~~~~~4+5+This module is an implementation of various logic needed6+for signing and checking OAuth 2.0 draft 25 requests.7+"""8+from tokens import prepare_bearer_uri, prepare_bearer_headers9+from tokens import prepare_bearer_body, prepare_mac_header10+from parameters import prepare_grant_uri, prepare_token_request11+from parameters import parse_authorization_code_response12+from parameters import parse_implicit_response, parse_token_response13+14+15+AUTH_HEADER = u'auth_header'16+URI_QUERY = u'query'17+BODY = u'body'18+19+20+class Client(object):21+22+ def __init__(self, client_id,23+ default_redirect_uri=None,24+ token_type=None,25+ access_token=None,26+ refresh_token=None):27+ """Initialize a client with commonly used attributes."""28+29+ self.client_id = client_id30+ self.default_redirect_uri = default_redirect_uri31+ self.token_type = token_type32+ self.access_token = access_token33+ self.refresh_token = refresh_token34+ self.token_types = {35+ u'bearer': self._add_bearer_token,36+ u'mac': self._add_mac_token37+ }38+39+ def add_token(self, uri, http_method=u'GET', body=None, headers=None,40+ token_placement=AUTH_HEADER):41+ """Add token to the request uri, body or authorization header.42+43+ The access token type provides the client with the information44+ required to successfully utilize the access token to make a protected45+ resource request (along with type-specific attributes). The client46+ MUST NOT use an access token if it does not understand the token47+ type.48+49+ For example, the "bearer" token type defined in50+ [I-D.ietf-oauth-v2-bearer] is utilized by simply including the access51+ token string in the request:52+53+ GET /resource/1 HTTP/1.154+ Host: example.com55+ Authorization: Bearer mF_9.B5f-4.1JqM56+57+ while the "mac" token type defined in [I-D.ietf-oauth-v2-http-mac] is58+ utilized by issuing a MAC key together with the access token which is59+ used to sign certain components of the HTTP requests:60+61+ GET /resource/1 HTTP/1.162+ Host: example.com63+ Authorization: MAC id="h480djs93hd8",64+ nonce="274312:dj83hs9s",65+ mac="kDZvddkndxvhGRXZhvuDjEWhGeE="66+67+ .. _`I-D.ietf-oauth-v2-bearer`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#ref-I-D.ietf-oauth-v2-bearer68+ .. _`I-D.ietf-oauth-v2-http-mac`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#ref-I-D.ietf-oauth-v2-http-mac69+ """70+ return self.token_types[self.token_type](uri, http_method, body,71+ headers, token_placement)72+73+ def prepare_refresh_body(self, body=u'', refresh_token=None, scope=None):74+ """Prepare an access token request, using a refresh token.75+76+ If the authorization server issued a refresh token to the client, the77+ client makes a refresh request to the token endpoint by adding the78+ following parameters using the "application/x-www-form-urlencoded"79+ format in the HTTP request entity-body:80+81+ grant_type82+ REQUIRED. Value MUST be set to "refresh_token".83+ refresh_token84+ REQUIRED. The refresh token issued to the client.85+ scope86+ OPTIONAL. The scope of the access request as described by87+ Section 3.3. The requested scope MUST NOT include any scope88+ not originally granted by the resource owner, and if omitted is89+ treated as equal to the scope originally granted by the90+ resource owner.91+ """92+ refresh_token = refresh_token or self.refresh_token93+ return prepare_token_request(u'refresh_token', body=body, scope=scope,94+ refresh_token=refresh_token)95+96+ def _add_bearer_token(self, uri, http_method=u'GET', body=None,97+ headers=None, token_placement=AUTH_HEADER):98+ """Add a bearer token to the request uri, body or authorization header."""99+ if token_placement == AUTH_HEADER:100+ headers = prepare_bearer_headers(self.token, headers)101+102+ if token_placement == URI_QUERY:103+ uri = prepare_bearer_uri(self.token, uri)104+105+ if token_placement == BODY:106+ body = prepare_bearer_body(self.token, body)107+108+ return uri, headers, body109+110+ def _add_mac_token(self, uri, http_method=u'GET', body=None,111+ headers=None, token_placement=AUTH_HEADER):112+ """Add a MAC token to the request authorization header."""113+ headers = prepare_mac_header(self.token, uri, self.key, http_method,114+ headers=headers, body=body, ext=self.ext,115+ hash_algorithm=self.hash_algorithm)116+ return uri, headers, body117+118+ def _populate_attributes(self, response):119+ """Add commonly used values such as access_token to self."""120+121+ if u'access_token' in response:122+ self.access_token = response.get(u'access_token')123+124+ if u'refresh_token' in response:125+ self.refresh_token = response.get(u'refresh_token')126+127+ if u'token_type' in response:128+ self.token_type = response.get(u'token_type')129+130+ if u'expires_in' in response:131+ self.expires_in = response.get(u'expires_in')132+133+ if u'code' in response:134+ self.code = response.get(u'code')135+136+ def prepare_request_uri(self, *args, **kwargs):137+ """Abstract method used to create request URIs."""138+ raise NotImplementedError("Must be implemented by inheriting classes.")139+140+ def prepare_request_body(self, *args, **kwargs):141+ """Abstract method used to create request bodies."""142+ raise NotImplementedError("Must be implemented by inheriting classes.")143+144+ def parse_request_uri_response(self, *args, **kwargs):145+ """Abstract method used to parse redirection responses."""146+147+ def parse_request_body_response(self, *args, **kwargs):148+ """Abstract method used to parse JSON responses."""149+150+151+class WebApplicationClient(Client):152+ """A client utilizing the authorization code grant workflow.153+154+ A web application is a confidential client running on a web155+ server. Resource owners access the client via an HTML user156+ interface rendered in a user-agent on the device used by the157+ resource owner. The client credentials as well as any access158+ token issued to the client are stored on the web server and are159+ not exposed to or accessible by the resource owner.160+161+ The authorization code grant type is used to obtain both access162+ tokens and refresh tokens and is optimized for confidential clients.163+ As a redirection-based flow, the client must be capable of164+ interacting with the resource owner's user-agent (typically a web165+ browser) and capable of receiving incoming requests (via redirection)166+ from the authorization server.167+ """168+169+ def prepare_request_uri(self, uri, redirect_uri=None, scope=None,170+ state=None, **kwargs):171+ """Prepare the authorization code request URI172+173+ The client constructs the request URI by adding the following174+ parameters to the query component of the authorization endpoint URI175+ using the "application/x-www-form-urlencoded" format as defined by176+ [`W3C.REC-html401-19991224`_]:177+178+ response_type179+ REQUIRED. Value MUST be set to "code".180+ client_id181+ REQUIRED. The client identifier as described in `Section 2.2`_.182+ redirect_uri183+ OPTIONAL. As described in `Section 3.1.2`_.184+ scope185+ OPTIONAL. The scope of the access request as described by186+ `Section 3.3`_.187+ state188+ RECOMMENDED. An opaque value used by the client to maintain189+ state between the request and callback. The authorization190+ server includes this value when redirecting the user-agent back191+ to the client. The parameter SHOULD be used for preventing192+ cross-site request forgery as described in `Section 10.12`_.193+194+ .. _`W3C.REC-html401-19991224`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#ref-W3C.REC-html401-19991224195+ .. _`Section 2.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-2.2196+ .. _`Section 3.1.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.1.2197+ .. _`Section 3.3`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.3198+ .. _`Section 10.12`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-10.12199+ """200+ redirect_uri = redirect_uri or self.default_redirect_uri201+ return prepare_grant_uri(uri, self.client_id, u'code',202+ redirect_uri=redirect_uri, scope=scope, state=state, **kwargs)203+204+ def prepare_request_body(self, code, body=u'', redirect_uri=None, **kwargs):205+ """Prepare the access token request body.206+207+ The client makes a request to the token endpoint by adding the208+ following parameters using the "application/x-www-form-urlencoded"209+ format in the HTTP request entity-body:210+211+ grant_type212+ REQUIRED. Value MUST be set to "authorization_code".213+ code214+ REQUIRED. The authorization code received from the215+ authorization server.216+ redirect_uri217+ REQUIRED, if the "redirect_uri" parameter was included in the218+ authorization request as described in Section 4.1.1, and their219+ values MUST be identical.220+221+ .. _`Section 4.1.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-4.1.1222+ """223+ redirect_uri = redirect_uri or self.default_redirect_uri224+ code = code or self.code225+ return prepare_token_request(u'authorization_code', code=code, body=body,226+ redirect_uri=redirect_uri, **kwargs)227+228+ def parse_request_uri_response(self, uri, state=None):229+ """Parse the URI query for code and state.230+231+ If the resource owner grants the access request, the authorization232+ server issues an authorization code and delivers it to the client by233+ adding the following parameters to the query component of the234+ redirection URI using the "application/x-www-form-urlencoded" format:235+236+ code237+ REQUIRED. The authorization code generated by the238+ authorization server. The authorization code MUST expire239+ shortly after it is issued to mitigate the risk of leaks. A240+ maximum authorization code lifetime of 10 minutes is241+ RECOMMENDED. The client MUST NOT use the authorization code242+ more than once. If an authorization code is used more than243+ once, the authorization server MUST deny the request and SHOULD244+ revoke (when possible) all tokens previously issued based on245+ that authorization code. The authorization code is bound to246+ the client identifier and redirection URI.247+ state248+ REQUIRED if the "state" parameter was present in the client249+ authorization request. The exact value received from the250+ client.251+ """252+ response = parse_authorization_code_response(uri, state=state)253+ self._populate_attributes(response)254+ return response255+256+ def parse_request_body_response(self, body, scope=None):257+ """Parse the JSON response body.258+259+ If the access token request is valid and authorized, the260+ authorization server issues an access token and optional refresh261+ token as described in `Section 5.1`_. If the request client262+ authentication failed or is invalid, the authorization server returns263+ an error response as described in `Section 5.2`_.264+265+ .. `Section 5.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-5.1266+ .. `Section 5.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-5.2267+ """268+ response = parse_token_response(body, scope=scope)269+ self._populate_attributes(response)270+ return response271+272+273+class UserAgentClient(Client):274+ """A public client utilizing the implicit code grant workflow.275+276+ A user-agent-based application is a public client in which the277+ client code is downloaded from a web server and executes within a278+ user-agent (e.g. web browser) on the device used by the resource279+ owner. Protocol data and credentials are easily accessible (and280+ often visible) to the resource owner. Since such applications281+ reside within the user-agent, they can make seamless use of the282+ user-agent capabilities when requesting authorization.283+284+ The implicit grant type is used to obtain access tokens (it does not285+ support the issuance of refresh tokens) and is optimized for public286+ clients known to operate a particular redirection URI. These clients287+ are typically implemented in a browser using a scripting language288+ such as JavaScript.289+290+ As a redirection-based flow, the client must be capable of291+ interacting with the resource owner's user-agent (typically a web292+ browser) and capable of receiving incoming requests (via redirection)293+ from the authorization server.294+295+ Unlike the authorization code grant type in which the client makes296+ separate requests for authorization and access token, the client297+ receives the access token as the result of the authorization request.298+299+ The implicit grant type does not include client authentication, and300+ relies on the presence of the resource owner and the registration of301+ the redirection URI. Because the access token is encoded into the302+ redirection URI, it may be exposed to the resource owner and other303+ applications residing on the same device.304+ """305+306+ def prepare_request_uri(self, uri, redirect_uri=None, scope=None,307+ state=None, **kwargs):308+ """Prepare the implicit grant request URI.309+310+ The client constructs the request URI by adding the following311+ parameters to the query component of the authorization endpoint URI312+ using the "application/x-www-form-urlencoded" format:313+314+ response_type315+ REQUIRED. Value MUST be set to "token".316+ client_id317+ REQUIRED. The client identifier as described in Section 2.2.318+ redirect_uri319+ OPTIONAL. As described in Section 3.1.2.320+ scope321+ OPTIONAL. The scope of the access request as described by322+ Section 3.3.323+ state324+ RECOMMENDED. An opaque value used by the client to maintain325+ state between the request and callback. The authorization326+ server includes this value when redirecting the user-agent back327+ to the client. The parameter SHOULD be used for preventing328+ cross-site request forgery as described in Section 10.12.329+ """330+ redirect_uri = redirect_uri or self.default_redirect_uri331+ return prepare_grant_uri(uri, self.client_id, u'token',332+ redirect_uri=redirect_uri, state=state, scope=scope, **kwargs)333+334+ def parse_request_uri_response(self, uri, state=None, scope=None):335+ """Parse the response URI fragment.336+337+ If the resource owner grants the access request, the authorization338+ server issues an access token and delivers it to the client by adding339+ the following parameters to the fragment component of the redirection340+ URI using the "application/x-www-form-urlencoded" format:341+342+ access_token343+ REQUIRED. The access token issued by the authorization server.344+ token_type345+ REQUIRED. The type of the token issued as described in346+ `Section 7.1`_. Value is case insensitive.347+ expires_in348+ RECOMMENDED. The lifetime in seconds of the access token. For349+ example, the value "3600" denotes that the access token will350+ expire in one hour from the time the response was generated.351+ If omitted, the authorization server SHOULD provide the352+ expiration time via other means or document the default value.353+ scope354+ OPTIONAL, if identical to the scope requested by the client,355+ otherwise REQUIRED. The scope of the access token as described356+ by `Section 3.3`_.357+ state358+ REQUIRED if the "state" parameter was present in the client359+ authorization request. The exact value received from the360+ client.361+362+ .. _`Section 7.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-7.1363+ .. _`Section 3.3`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.3364+ """365+ response = parse_implicit_response(uri, state=state, scope=scope)366+ self._populate_attributes(response)367+ return response368+369+370+class NativeApplicationClient(Client):371+ """A public client utilizing the client credentials grant workflow.372+373+ A native application is a public client installed and executed on374+ the device used by the resource owner. Protocol data and375+ credentials are accessible to the resource owner. It is assumed376+ that any client authentication credentials included in the377+ application can be extracted. On the other hand, dynamically378+ issued credentials such as access tokens or refresh tokens can379+ receive an acceptable level of protection. At a minimum, these380+ credentials are protected from hostile servers with which the381+ application may interact with. On some platforms these382+ credentials might be protected from other applications residing on383+ the same device.384+385+ The client can request an access token using only its client386+ credentials (or other supported means of authentication) when the387+ client is requesting access to the protected resources under its388+ control, or those of another resource owner which has been previously389+ arranged with the authorization server (the method of which is beyond390+ the scope of this specification).391+392+ The client credentials grant type MUST only be used by confidential393+ clients.394+395+ Since the client authentication is used as the authorization grant,396+ no additional authorization request is needed.397+ """398+399+ def prepare_request_body(self, body=u'', scope=None, **kwargs):400+ """Add the client credentials to the request body.401+402+ The client makes a request to the token endpoint by adding the403+ following parameters using the "application/x-www-form-urlencoded"404+ format in the HTTP request entity-body:405+406+ grant_type407+ REQUIRED. Value MUST be set to "client_credentials".408+ scope409+ OPTIONAL. The scope of the access request as described by410+ `Section 3.3`_.411+412+ .. _`Section 3.3`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.3413+ """414+ return prepare_token_request(u'client_credentials', body=body,415+ scope=scope, **kwargs)416+417+ def parse_request_body_response(self, body, scope=None):418+ """Parse the JSON response body.419+420+ If the access token request is valid and authorized, the421+ authorization server issues an access token as described in422+ `Section 5.1`_. A refresh token SHOULD NOT be included. If the request423+ failed client authentication or is invalid, the authorization server424+ returns an error response as described in `Section 5.2`_.425+426+ .. `Section 5.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-5.1427+ .. `Section 5.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-5.2428+ """429+ response = parse_token_response(body, scope=scope)430+ self._populate_attributes(response)431+ return response432+433+434+class PasswordCredentialsClient(Client):435+ """A public client using the resource owner password and username directly.436+437+ The resource owner password credentials grant type is suitable in438+ cases where the resource owner has a trust relationship with the439+ client, such as the device operating system or a highly privileged440+ application. The authorization server should take special care when441+ enabling this grant type, and only allow it when other flows are not442+ viable.443+444+ The grant type is suitable for clients capable of obtaining the445+ resource owner's credentials (username and password, typically using446+ an interactive form). It is also used to migrate existing clients447+ using direct authentication schemes such as HTTP Basic or Digest448+ authentication to OAuth by converting the stored credentials to an449+ access token.450+451+ The method through which the client obtains the resource owner452+ credentials is beyond the scope of this specification. The client453+ MUST discard the credentials once an access token has been obtained.454+ """455+456+ def prepare_request_body(self, username, password, body=u'', scope=None,457+ **kwargs):458+ """Add the resource owner password and username to the request body.459+460+ The client makes a request to the token endpoint by adding the461+ following parameters using the "application/x-www-form-urlencoded"462+ format in the HTTP request entity-body:463+464+ grant_type465+ REQUIRED. Value MUST be set to "password".466+ username467+ REQUIRED. The resource owner username.468+ password469+ REQUIRED. The resource owner password.470+ scope471+ OPTIONAL. The scope of the access request as described by472+ `Section 3.3`_.473+474+ .. _`Section 3.3`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.3475+ """476+ return prepare_token_request(u'password', body=body, username=username,477+ password=password, scope=scope, **kwargs)478+479+ def parse_request_body_response(self, body, scope=None):480+ """Parse the JSON response body.481+482+ If the access token request is valid and authorized, the483+ authorization server issues an access token and optional refresh484+ token as described in `Section 5.1`_. If the request failed client485+ authentication or is invalid, the authorization server returns an486+ error response as described in `Section 5.2`_.487+488+ .. `Section 5.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-5.1489+ .. `Section 5.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-5.2490+ """491+ response = parse_token_response(body, scope=scope)492+ self._populate_attributes(response)493+ return response494+495+496+class Server(object):497+ passadded:requests/packages/oauthlib/oauth2/draft25/parameters.py+256 added
1+"""2+oauthlib.oauth2_draft28.parameters3+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~4+5+This module contains methods related to `Section 4`_ of the OAuth 2 draft.6+7+.. _`Section 4`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-48+"""9+10+import json11+import urlparse12+from oauthlib.common import add_params_to_uri, add_params_to_qs13+14+15+def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None,16+ scope=None, state=None, **kwargs):17+ """Prepare the authorization grant request URI.18+19+ The client constructs the request URI by adding the following20+ parameters to the query component of the authorization endpoint URI21+ using the "application/x-www-form-urlencoded" format as defined by22+ [W3C.REC-html401-19991224]:23+24+ response_type25+ REQUIRED. Value MUST be set to "code".26+ client_id27+ REQUIRED. The client identifier as described in `Section 2.2`_.28+ redirect_uri29+ OPTIONAL. As described in `Section 3.1.2`_.30+ scope31+ OPTIONAL. The scope of the access request as described by32+ `Section 3.3`_.33+ state34+ RECOMMENDED. An opaque value used by the client to maintain35+ state between the request and callback. The authorization36+ server includes this value when redirecting the user-agent back37+ to the client. The parameter SHOULD be used for preventing38+ cross-site request forgery as described in `Section 10.12`_.39+40+ GET /authorize?response_type=code&client_id=s6BhdRkqt3&state=xyz41+ &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb HTTP/1.142+ Host: server.example.com43+44+ .. _`W3C.REC-html401-19991224`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#ref-W3C.REC-html401-1999122445+ .. _`Section 2.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-2.246+ .. _`Section 3.1.2`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.1.247+ .. _`Section 3.3`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.348+ .. _`section 10.12`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-10.1249+ """50+ params = [((u'response_type', response_type)),51+ ((u'client_id', client_id))]52+53+ if redirect_uri:54+ params.append((u'redirect_uri', redirect_uri))55+ if scope:56+ params.append((u'scope', scope))57+ if state:58+ params.append((u'state', state))59+60+ for k in kwargs:61+ params.append((unicode(k), kwargs[k]))62+63+ return add_params_to_uri(uri, params)64+65+66+def prepare_token_request(grant_type, body=u'', **kwargs):67+ """Prepare the access token request.68+69+ The client makes a request to the token endpoint by adding the70+ following parameters using the "application/x-www-form-urlencoded"71+ format in the HTTP request entity-body:72+73+ grant_type74+ REQUIRED. Value MUST be set to "authorization_code".75+ code76+ REQUIRED. The authorization code received from the77+ authorization server.78+ redirect_uri79+ REQUIRED, if the "redirect_uri" parameter was included in the80+ authorization request as described in `Section 4.1.1`_, and their81+ values MUST be identical.82+83+ grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA84+ &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb85+86+ .. _`Section 4.1.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-4.1.187+ """88+ params = [(u'grant_type', grant_type)]89+ for k in kwargs:90+ params.append((unicode(k), kwargs[k]))91+92+ return add_params_to_qs(body, params)93+94+95+def parse_authorization_code_response(uri, state=None):96+ """Parse authorization grant response URI into a dict.97+98+ If the resource owner grants the access request, the authorization99+ server issues an authorization code and delivers it to the client by100+ adding the following parameters to the query component of the101+ redirection URI using the "application/x-www-form-urlencoded" format:102+103+ code104+ REQUIRED. The authorization code generated by the105+ authorization server. The authorization code MUST expire106+ shortly after it is issued to mitigate the risk of leaks. A107+ maximum authorization code lifetime of 10 minutes is108+ RECOMMENDED. The client MUST NOT use the authorization code109+ more than once. If an authorization code is used more than110+ once, the authorization server MUST deny the request and SHOULD111+ revoke (when possible) all tokens previously issued based on112+ that authorization code. The authorization code is bound to113+ the client identifier and redirection URI.114+ state115+ REQUIRED if the "state" parameter was present in the client116+ authorization request. The exact value received from the117+ client.118+119+ For example, the authorization server redirects the user-agent by120+ sending the following HTTP response:121+122+ HTTP/1.1 302 Found123+ Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA124+ &state=xyz125+126+ """127+ query = urlparse.urlparse(uri).query128+ params = dict(urlparse.parse_qsl(query))129+130+ if not u'code' in params:131+ raise KeyError("Missing code parameter in response.")132+133+ if state and params.get(u'state', None) != state:134+ raise ValueError("Mismatching or missing state in response.")135+136+ return params137+138+139+def parse_implicit_response(uri, state=None, scope=None):140+ """Parse the implicit token response URI into a dict.141+142+ If the resource owner grants the access request, the authorization143+ server issues an access token and delivers it to the client by adding144+ the following parameters to the fragment component of the redirection145+ URI using the "application/x-www-form-urlencoded" format:146+147+ access_token148+ REQUIRED. The access token issued by the authorization server.149+ token_type150+ REQUIRED. The type of the token issued as described in151+ Section 7.1. Value is case insensitive.152+ expires_in153+ RECOMMENDED. The lifetime in seconds of the access token. For154+ example, the value "3600" denotes that the access token will155+ expire in one hour from the time the response was generated.156+ If omitted, the authorization server SHOULD provide the157+ expiration time via other means or document the default value.158+ scope159+ OPTIONAL, if identical to the scope requested by the client,160+ otherwise REQUIRED. The scope of the access token as described161+ by Section 3.3.162+ state163+ REQUIRED if the "state" parameter was present in the client164+ authorization request. The exact value received from the165+ client.166+167+ HTTP/1.1 302 Found168+ Location: http://example.com/cb#access_token=2YotnFZFEjr1zCsicMWpAA169+ &state=xyz&token_type=example&expires_in=3600170+ """171+ fragment = urlparse.urlparse(uri).fragment172+ params = dict(urlparse.parse_qsl(fragment, keep_blank_values=True))173+ validate_token_parameters(params, scope)174+175+ if state and params.get(u'state', None) != state:176+ raise ValueError("Mismatching or missing state in params.")177+178+ return params179+180+181+def parse_token_response(body, scope=None):182+ """Parse the JSON token response body into a dict.183+184+ The authorization server issues an access token and optional refresh185+ token, and constructs the response by adding the following parameters186+ to the entity body of the HTTP response with a 200 (OK) status code:187+188+ access_token189+ REQUIRED. The access token issued by the authorization server.190+ token_type191+ REQUIRED. The type of the token issued as described in192+ `Section 7.1`_. Value is case insensitive.193+ expires_in194+ RECOMMENDED. The lifetime in seconds of the access token. For195+ example, the value "3600" denotes that the access token will196+ expire in one hour from the time the response was generated.197+ If omitted, the authorization server SHOULD provide the198+ expiration time via other means or document the default value.199+ refresh_token200+ OPTIONAL. The refresh token which can be used to obtain new201+ access tokens using the same authorization grant as described202+ in `Section 6`_.203+ scope204+ OPTIONAL, if identical to the scope requested by the client,205+ otherwise REQUIRED. The scope of the access token as described206+ by `Section 3.3`_.207+208+ The parameters are included in the entity body of the HTTP response209+ using the "application/json" media type as defined by [`RFC4627`_]. The210+ parameters are serialized into a JSON structure by adding each211+ parameter at the highest structure level. Parameter names and string212+ values are included as JSON strings. Numerical values are included213+ as JSON numbers. The order of parameters does not matter and can214+ vary.215+216+ For example:217+218+ HTTP/1.1 200 OK219+ Content-Type: application/json;charset=UTF-8220+ Cache-Control: no-store221+ Pragma: no-cache222+223+ {224+ "access_token":"2YotnFZFEjr1zCsicMWpAA",225+ "token_type":"example",226+ "expires_in":3600,227+ "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",228+ "example_parameter":"example_value"229+ }230+231+ .. _`Section 7.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-7.1232+ .. _`Section 6`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-6233+ .. _`Section 3.3`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-3.3234+ .. _`RFC4627`: http://tools.ietf.org/html/rfc4627235+ """236+ params = json.loads(body)237+ validate_token_parameters(params, scope)238+ return params239+240+241+def validate_token_parameters(params, scope=None):242+ """Ensures token precence, token type, expiration and scope in params."""243+244+ if not u'access_token' in params:245+ raise KeyError("Missing access token parameter.")246+247+ if not u'token_type' in params:248+ raise KeyError("Missing token type parameter.")249+250+ # If the issued access token scope is different from the one requested by251+ # the client, the authorization server MUST include the "scope" response252+ # parameter to inform the client of the actual scope granted.253+ # http://tools.ietf.org/html/draft-ietf-oauth-v2-25#section-3.3254+ new_scope = params.get(u'scope', None)255+ if scope and new_scope and scope != new_scope:256+ raise Warning("Scope has changed to %s." % new_scope)added:requests/packages/oauthlib/oauth2/draft25/tokens.py+132 added
1+from __future__ import absolute_import2+"""3+oauthlib.oauth2.draft25.tokens4+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~5+6+This module contains methods for adding two types of access tokens to requests.7+8+- Bearer http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-089+- MAC http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-0010+11+"""12+from binascii import b2a_base6413+import hashlib14+import hmac15+from urlparse import urlparse16+17+from oauthlib.common import add_params_to_uri, add_params_to_qs18+from . import utils19+20+21+def prepare_mac_header(token, uri, key, http_method, nonce=None, headers=None,22+ body=None, ext=u'', hash_algorithm=u'hmac-sha-1'):23+ """Add an `MAC Access Authentication`_ signature to headers.24+25+ Unlike OAuth 1, this HMAC signature does not require inclusion of the request26+ payload/body, neither does it use a combination of client_secret and27+ token_secret but rather a mac_key provided together with the access token.28+29+ Currently two algorithms are supported, "hmac-sha-1" and "hmac-sha-256",30+ `extension algorithms`_ are not supported.31+32+ Example MAC Authorization header, linebreaks added for clarity33+34+ Authorization: MAC id="h480djs93hd8",35+ nonce="1336363200:dj83hs9s",36+ mac="bhCQXTVyfj5cmA9uKkPFx1zeOXM="37+38+ .. _`MAC Access Authentication`: http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-0139+ .. _`extension algorithms`: http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-7.140+41+ :param uri: Request URI.42+ :param headers: Request headers as a dictionary.43+ :param http_method: HTTP Request method.44+ :param key: MAC given provided by token endpoint.45+ :param algorithm: HMAC algorithm provided by token endpoint.46+ :return: headers dictionary with the authorization field added.47+ """48+ http_method = http_method.upper()49+ host, port = utils.host_from_uri(uri)50+51+ if hash_algorithm.lower() == u'hmac-sha-1':52+ h = hashlib.sha153+ else:54+ h = hashlib.sha25655+56+ nonce = nonce or u'{0}:{1}'.format(utils.generate_nonce(), utils.generate_timestamp())57+ sch, net, path, par, query, fra = urlparse(uri)58+59+ if query:60+ request_uri = path + u'?' + query61+ else:62+ request_uri = path63+64+ # Hash the body/payload65+ if body is not None:66+ bodyhash = b2a_base64(h(body).digest())[:-1].decode('utf-8')67+ else:68+ bodyhash = u''69+70+ # Create the normalized base string71+ base = []72+ base.append(nonce)73+ base.append(http_method.upper())74+ base.append(request_uri)75+ base.append(host)76+ base.append(port)77+ base.append(bodyhash)78+ base.append(ext)79+ base_string = '\n'.join(base) + u'\n'80+81+ # hmac struggles with unicode strings - http://bugs.python.org/issue528582+ if isinstance(key, unicode):83+ key = key.encode('utf-8')84+ sign = hmac.new(key, base_string, h)85+ sign = b2a_base64(sign.digest())[:-1].decode('utf-8')86+87+ header = []88+ header.append(u'MAC id="%s"' % token)89+ header.append(u'nonce="%s"' % nonce)90+ if bodyhash:91+ header.append(u'bodyhash="%s"' % bodyhash)92+ if ext:93+ header.append(u'ext="%s"' % ext)94+ header.append(u'mac="%s"' % sign)95+96+ headers = headers or {}97+ headers[u'Authorization'] = u', '.join(header)98+ return headers99+100+101+def prepare_bearer_uri(token, uri):102+ """Add a `Bearer Token`_ to the request URI.103+ Not recommended, use only if client can't use authorization header or body.104+105+ http://www.example.com/path?access_token=h480djs93hd8106+107+ .. _`Bearer Token`: http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-18108+ """109+ return add_params_to_uri(uri, [((u'access_token', token))])110+111+112+def prepare_bearer_headers(token, headers=None):113+ """Add a `Bearer Token`_ to the request URI.114+ Recommended method of passing bearer tokens.115+116+ Authorization: Bearer h480djs93hd8117+118+ .. _`Bearer Token`: http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-18119+ """120+ headers = headers or {}121+ headers[u'Authorization'] = u'Bearer %s' % token122+ return headers123+124+125+def prepare_bearer_body(token, body=u''):126+ """Add a `Bearer Token`_ to the request body.127+128+ access_token=h480djs93hd8129+130+ .. _`Bearer Token`: http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-18131+ """132+ return add_params_to_qs(body, [((u'access_token', token))])added:requests/packages/oauthlib/oauth2/draft25/utils.py+39 added
1+"""2+oauthlib.utils3+~~~~~~~~~~~~~~4+5+This module contains utility methods used by various parts of the OAuth 2 spec.6+"""7+8+import urllib9+import urlparse10+11+12+def host_from_uri(uri):13+ """Extract hostname and port from URI.14+15+ Will use default port for HTTP and HTTPS if none is present in the URI.16+ """17+ default_ports = {18+ u'HTTP': u'80',19+ u'HTTPS': u'443',20+ }21+22+ sch, netloc, path, par, query, fra = urlparse.urlparse(uri)23+ if u':' in netloc:24+ netloc, port = netloc.split(u':', 1)25+ else:26+ port = default_ports.get(sch.upper())27+28+ return netloc, port29+30+31+def escape(u):32+ """Escape a string in an OAuth-compatible fashion.33+34+ TODO: verify whether this can in fact be used for OAuth 235+36+ """37+ if not isinstance(u, unicode):38+ raise ValueError('Only unicode objects are escapable.')39+ return urllib.quote(u.encode('utf-8'), safe='~')added:requests/packages/oauthlib/oauth2/__init__.py+13 added
1+# -*- coding: utf-8 -*-2+from __future__ import absolute_import3+4+"""5+oauthlib.oauth26+~~~~~~~~~~~~~~7+8+This module is a wrapper for the most recent implementation of OAuth 2.0 Client9+and Server classes.10+"""11+12+from .draft25 import Client, Server13+added:requests/packages/oauthlib/__init__.py
added:requests/packages/oauthlib/common.py+229 added
1+# -*- coding: utf-8 -*-2+from __future__ import absolute_import3+4+"""5+oauthlib.common6+~~~~~~~~~~~~~~7+8+This module provides data structures and utilities common9+to all implementations of OAuth.10+"""11+12+import random13+import re14+import string15+import time16+import urllib17+import urlparse18+19+UNICODE_ASCII_CHARACTER_SET = (string.ascii_letters.decode('ascii') +20+ string.digits.decode('ascii'))21+22+always_safe = (u'ABCDEFGHIJKLMNOPQRSTUVWXYZ'23+ u'abcdefghijklmnopqrstuvwxyz'24+ u'0123456789' u'_.-')25+26+27+def quote(s, safe=u'/'):28+ encoded = s.encode("utf-8")29+ quoted = urllib.quote(encoded, safe)30+ return quoted.decode("utf-8")31+32+33+def unquote(s):34+ encoded = s.encode("utf-8")35+ unquoted = urllib.unquote(encoded)36+ return unquoted.decode("utf-8")37+38+39+def urlencode(params):40+ utf8_params = encode_params_utf8(params)41+ urlencoded = urllib.urlencode(utf8_params)42+ return urlencoded.decode("utf-8")43+44+45+def encode_params_utf8(params):46+ """Ensures that all parameters in a list of 2-element tuples are encoded to47+ bytestrings using UTF-848+ """49+ encoded = []50+ for k, v in params:51+ encoded.append((52+ k.encode('utf-8') if isinstance(k, unicode) else k,53+ v.encode('utf-8') if isinstance(v, unicode) else v))54+ return encoded55+56+57+def decode_params_utf8(params):58+ """Ensures that all parameters in a list of 2-element tuples are decoded to59+ unicode using UTF-8.60+ """61+ decoded = []62+ for k, v in params:63+ decoded.append((64+ k.decode('utf-8') if isinstance(k, str) else k,65+ v.decode('utf-8') if isinstance(v, str) else v))66+ return decoded67+68+69+urlencoded = set(always_safe) | set(u'=&;%+~')70+71+72+def urldecode(query):73+ """Decode a query string in x-www-form-urlencoded format into a sequence74+ of two-element tuples.75+76+ Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce77+ correct formatting of the query string by validation. If validation fails78+ a ValueError will be raised. urllib.parse_qsl will only raise errors if79+ any of name-value pairs omits the equals sign.80+ """81+ # Check if query contains invalid characters82+ if query and not set(query) <= urlencoded:83+ raise ValueError('Invalid characters in query string.')84+85+ # Check for correctly hex encoded values using a regular expression86+ # All encoded values begin with % followed by two hex characters87+ # correct = %00, %A0, %0A, %FF88+ # invalid = %G0, %5H, %PO89+ invalid_hex = u'%[^0-9A-Fa-f]|%[0-9A-Fa-f][^0-9A-Fa-f]'90+ if len(re.findall(invalid_hex, query)):91+ raise ValueError('Invalid hex encoding in query string.')92+93+ query = query.decode('utf-8') if isinstance(query, str) else query94+ # We want to allow queries such as "c2" whereas urlparse.parse_qsl95+ # with the strict_parsing flag will not.96+ params = urlparse.parse_qsl(query, keep_blank_values=True)97+98+ # unicode all the things99+ return decode_params_utf8(params)100+101+102+def extract_params(raw):103+ """Extract parameters and return them as a list of 2-tuples.104+105+ Will successfully extract parameters from urlencoded query strings,106+ dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an107+ empty list of parameters. Any other input will result in a return108+ value of None.109+ """110+ if isinstance(raw, basestring):111+ try:112+ params = urldecode(raw)113+ except ValueError:114+ params = None115+ elif hasattr(raw, '__iter__'):116+ try:117+ dict(raw)118+ except ValueError:119+ params = None120+ except TypeError:121+ params = None122+ else:123+ params = list(raw.items() if isinstance(raw, dict) else raw)124+ params = decode_params_utf8(params)125+ else:126+ params = None127+128+ return params129+130+131+def generate_nonce():132+ """Generate pseudorandom nonce that is unlikely to repeat.133+134+ Per `section 3.3`_ of the OAuth 1 RFC 5849 spec.135+ Per `section 3.2.1`_ of the MAC Access Authentication spec.136+137+ A random 64-bit number is appended to the epoch timestamp for both138+ randomness and to decrease the likelihood of collisions.139+140+ .. _`section 3.2.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-3.2.1141+ .. _`section 3.3`: http://tools.ietf.org/html/rfc5849#section-3.3142+ """143+ return unicode(unicode(random.getrandbits(64)) + generate_timestamp())144+145+146+def generate_timestamp():147+ """Get seconds since epoch (UTC).148+149+ Per `section 3.3`_ of the OAuth 1 RFC 5849 spec.150+ Per `section 3.2.1`_ of the MAC Access Authentication spec.151+152+ .. _`section 3.2.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-3.2.1153+ .. _`section 3.3`: http://tools.ietf.org/html/rfc5849#section-3.3154+ """155+ return unicode(int(time.time()))156+157+158+def generate_token(length=30, chars=UNICODE_ASCII_CHARACTER_SET):159+ """Generates a non-guessable OAuth token160+161+ OAuth (1 and 2) does not specify the format of tokens except that they162+ should be strings of random characters. Tokens should not be guessable163+ and entropy when generating the random characters is important. Which is164+ why SystemRandom is used instead of the default random.choice method.165+ """166+ rand = random.SystemRandom()167+ return u''.join(rand.choice(chars) for x in range(length))168+169+170+def add_params_to_qs(query, params):171+ """Extend a query with a list of two-tuples."""172+ queryparams = urlparse.parse_qsl(query, keep_blank_values=True)173+ queryparams.extend(params)174+ return urlencode(queryparams)175+176+177+def add_params_to_uri(uri, params):178+ """Add a list of two-tuples to the uri query components."""179+ sch, net, path, par, query, fra = urlparse.urlparse(uri)180+ query = add_params_to_qs(query, params)181+ return urlparse.urlunparse((sch, net, path, par, query, fra))182+183+def safe_string_equals(a, b):184+ """ Near-constant time string comparison. 185+186+ Used in order to avoid timing attacks on sensitive information such187+ as secret keys during request verification (`rootLabs`_).188+189+ .. _`rootLabs`: http://rdist.root.org/2010/01/07/timing-independent-array-comparison/190+ 191+ """192+ if len(a) != len(b):193+ return False194+195+ result = 0196+ for x, y in zip(a, b):197+ result |= ord(x) ^ ord(y)198+ return result == 0199+200+class Request(object):201+ """A malleable representation of a signable HTTP request.202+203+ Body argument may contain any data, but parameters will only be decoded if204+ they are one of:205+206+ * urlencoded query string207+ * dict208+ * list of 2-tuples209+210+ Anything else will be treated as raw body data to be passed through211+ unmolested.212+ """213+214+ def __init__(self, uri, http_method=u'GET', body=None, headers=None):215+ self.uri = uri216+ self.http_method = http_method217+ self.headers = headers or {}218+ self.body = body219+ self.decoded_body = extract_params(body)220+ self.oauth_params = []221+222+ @property223+ def uri_query(self):224+ return urlparse.urlparse(self.uri).query225+226+ @property227+ def uri_query_params(self):228+ return urlparse.parse_qsl(self.uri_query, keep_blank_values=True,229+ strict_parsing=True)modified:Makefile+11 added-2 removed
56 unmodified lines57 58 clean:59 git clean -Xfd60 61-deps:61+deps: urllib3 certs62+63+urllib3:64 rm -fr requests/packages/urllib365 git clone https://github.com/shazow/urllib3.git66 cd urllib3 && git checkout master && cd ..67 mv urllib3/urllib3 requests/packages/68 rm -fr urllib369 70+oauthlib:71+ rm -fr requests/packages/oauthlib72+ git clone https://github.com/idan/oauthlib.git73+ cd oauthlib && git checkout master && cd ..74+ mv oauthlib/oauthlib requests/packages/75+ rm -fr oauthlib76+77 certs:69- cd requests && curl -O http://curl.haxx.se/ca/cacert.pem78+ cd requests && curl -O https://raw.github.com/kennethreitz/certifi/master/certifi/cacert.pem79 80 docs: sitemodified:setup.py+1 added-5 removed
6 unmodified lines7 import os8 import sys9 10 import requests11-from requests.compat import is_py211 12 try:13 from setuptools import setup14 # hush pyflakes11 unmodified lines26 'requests.packages.chardet',27 'requests.packages.chardet2',28 'requests.packages.urllib3',29 'requests.packages.urllib3.packages',31- 'requests.packages.urllib3.packages.ssl_match_hostname',30+ 'requests.packages.urllib3.packages.ssl_match_hostname'31 ]32 33 requires = []34 36-if is_py2:37- requires.append('oauthlib>=0.1.0,<0.2.0')38-35 setup(36 name='requests',37 version=requests.__version__,38 description='Python HTTP for Humans.',24 unmodified lines