Skip to content
Myr

no more oauth

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 5c1bc20 · Browse files · 13 files+0 added−2875 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

13 files+0 added−2875 removed

  • other:+0 added−2875 removed

13 files+0 added−2875 removed

deleted:requests/packages/oauthlib/oauth1/rfc5849/__init__.py-889 removed
1# -*- coding: utf-8 -*-2from __future__ import absolute_import34"""5oauthlib.oauth1.rfc58496~~~~~~~~~~~~~~78This module is an implementation of various logic needed9for signing and checking OAuth 1.0 RFC 5849 requests.10"""1112import logging13import time14import urlparse1516from oauthlib.common import Request, urlencode, generate_nonce17from oauthlib.common import generate_timestamp18from . import parameters, signature, utils1920logger = logging.getLogger(__name__)2122SIGNATURE_HMAC = u"HMAC-SHA1"23SIGNATURE_RSA = u"RSA-SHA1"24SIGNATURE_PLAINTEXT = u"PLAINTEXT"25SIGNATURE_METHODS = (SIGNATURE_HMAC, SIGNATURE_RSA, SIGNATURE_PLAINTEXT)2627SIGNATURE_TYPE_AUTH_HEADER = u'AUTH_HEADER'28SIGNATURE_TYPE_QUERY = u'QUERY'29SIGNATURE_TYPE_BODY = u'BODY'3031CONTENT_TYPE_FORM_URLENCODED = u'application/x-www-form-urlencoded'323334class Client(object):35 """A client used to sign OAuth 1.0 RFC 5849 requests"""36 def __init__(self, client_key,37 client_secret=None,38 resource_owner_key=None,39 resource_owner_secret=None,40 callback_uri=None,41 signature_method=SIGNATURE_HMAC,42 signature_type=SIGNATURE_TYPE_AUTH_HEADER,43 rsa_key=None, verifier=None):44 self.client_key = client_key45 self.client_secret = client_secret46 self.resource_owner_key = resource_owner_key47 self.resource_owner_secret = resource_owner_secret48 self.signature_method = signature_method49 self.signature_type = signature_type50 self.callback_uri = callback_uri51 self.rsa_key = rsa_key52 self.verifier = verifier5354 if self.signature_method == SIGNATURE_RSA and self.rsa_key is None:55 raise ValueError('rsa_key is required when using RSA signature method.')5657 def get_oauth_signature(self, request):58 """Get an OAuth signature to be used in signing a request59 """60 if self.signature_method == SIGNATURE_PLAINTEXT:61 # fast-path62 return signature.sign_plaintext(self.client_secret,63 self.resource_owner_secret)6465 uri, headers, body = self._render(request)6667 collected_params = signature.collect_parameters(68 uri_query=urlparse.urlparse(uri).query,69 body=body,70 headers=headers)71 logger.debug("Collected params: {0}".format(collected_params))7273 normalized_params = signature.normalize_parameters(collected_params)74 normalized_uri = signature.normalize_base_string_uri(request.uri)75 logger.debug("Normalized params: {0}".format(normalized_params))76 logger.debug("Normalized URI: {0}".format(normalized_uri))7778 base_string = signature.construct_base_string(request.http_method,79 normalized_uri, normalized_params)8081 logger.debug("Base signing string: {0}".format(base_string))8283 if self.signature_method == SIGNATURE_HMAC:84 sig = signature.sign_hmac_sha1(base_string, self.client_secret,85 self.resource_owner_secret)86 elif self.signature_method == SIGNATURE_RSA:87 sig = signature.sign_rsa_sha1(base_string, self.rsa_key)88 else:89 sig = signature.sign_plaintext(self.client_secret,90 self.resource_owner_secret)9192 logger.debug("Signature: {0}".format(sig))93 return sig9495 def get_oauth_params(self):96 """Get the basic OAuth parameters to be used in generating a signature.97 """98 params = [99 (u'oauth_nonce', generate_nonce()),100 (u'oauth_timestamp', generate_timestamp()),101 (u'oauth_version', u'1.0'),102 (u'oauth_signature_method', self.signature_method),103 (u'oauth_consumer_key', self.client_key),104 ]105 if self.resource_owner_key:106 params.append((u'oauth_token', self.resource_owner_key))107 if self.callback_uri:108 params.append((u'oauth_callback', self.callback_uri))109 if self.verifier:110 params.append((u'oauth_verifier', self.verifier))111112 return params113114 def _render(self, request, formencode=False):115 """Render a signed request according to signature type116117 Returns a 3-tuple containing the request URI, headers, and body.118119 If the formencode argument is True and the body contains parameters, it120 is escaped and returned as a valid formencoded string.121 """122 # TODO what if there are body params on a header-type auth?123 # TODO what if there are query params on a body-type auth?124125 uri, headers, body = request.uri, request.headers, request.body126127 # TODO: right now these prepare_* methods are very narrow in scope--they128 # only affect their little thing. In some cases (for example, with129 # header auth) it might be advantageous to allow these methods to touch130 # other parts of the request, like the headers—so the prepare_headers131 # method could also set the Content-Type header to x-www-form-urlencoded132 # like the spec requires. This would be a fundamental change though, and133 # I'm not sure how I feel about it.134 if self.signature_type == SIGNATURE_TYPE_AUTH_HEADER:135 headers = parameters.prepare_headers(request.oauth_params, request.headers)136 elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None:137 body = parameters.prepare_form_encoded_body(request.oauth_params, request.decoded_body)138 if formencode:139 body = urlencode(body)140 headers['Content-Type'] = u'application/x-www-form-urlencoded'141 elif self.signature_type == SIGNATURE_TYPE_QUERY:142 uri = parameters.prepare_request_uri_query(request.oauth_params, request.uri)143 else:144 raise ValueError('Unknown signature type specified.')145146 return uri, headers, body147148 def sign(self, uri, http_method=u'GET', body=None, headers=None):149 """Sign a request150151 Signs an HTTP request with the specified parts.152153 Returns a 3-tuple of the signed request's URI, headers, and body.154 Note that http_method is not returned as it is unaffected by the OAuth155 signing process.156157 The body argument may be a dict, a list of 2-tuples, or a formencoded158 string. The Content-Type header must be 'application/x-www-form-urlencoded'159 if it is present.160161 If the body argument is not one of the above, it will be returned162 verbatim as it is unaffected by the OAuth signing process. Attempting to163 sign a request with non-formencoded data using the OAuth body signature164 type is invalid and will raise an exception.165166 If the body does contain parameters, it will be returned as a properly-167 formatted formencoded string.168169 All string data MUST be unicode. This includes strings inside body170 dicts, for example.171 """172 # normalize request data173 request = Request(uri, http_method, body, headers)174175 # sanity check176 content_type = request.headers.get('Content-Type', None)177 multipart = content_type and content_type.startswith('multipart/')178 should_have_params = content_type == CONTENT_TYPE_FORM_URLENCODED179 has_params = request.decoded_body is not None180 # 3.4.1.3.1. Parameter Sources181 # [Parameters are collected from the HTTP request entity-body, but only182 # if [...]:183 # * The entity-body is single-part.184 if multipart and has_params:185 raise ValueError("Headers indicate a multipart body but body contains parameters.")186 # * The entity-body follows the encoding requirements of the187 # "application/x-www-form-urlencoded" content-type as defined by188 # [W3C.REC-html40-19980424].189 elif should_have_params and not has_params:190 raise ValueError("Headers indicate a formencoded body but body was not decodable.")191 # * The HTTP request entity-header includes the "Content-Type"192 # header field set to "application/x-www-form-urlencoded".193 elif not should_have_params and has_params:194 raise ValueError("Body contains parameters but Content-Type header was not set.")195196 # 3.5.2. Form-Encoded Body197 # Protocol parameters can be transmitted in the HTTP request entity-198 # body, but only if the following REQUIRED conditions are met:199 # o The entity-body is single-part.200 # o The entity-body follows the encoding requirements of the201 # "application/x-www-form-urlencoded" content-type as defined by202 # [W3C.REC-html40-19980424].203 # o The HTTP request entity-header includes the "Content-Type" header204 # field set to "application/x-www-form-urlencoded".205 elif self.signature_type == SIGNATURE_TYPE_BODY and not (206 should_have_params and has_params and not multipart):207 raise ValueError('Body signatures may only be used with form-urlencoded content')208209 # generate the basic OAuth parameters210 request.oauth_params = self.get_oauth_params()211212 # generate the signature213 request.oauth_params.append((u'oauth_signature', self.get_oauth_signature(request)))214215 # render the signed request and return it216 return self._render(request, formencode=True)217218219class Server(object):220 """A server base class used to verify OAuth 1.0 RFC 5849 requests221222 OAuth providers should inherit from Server and implement the methods223 and properties outlined below. Further details are provided in the224 documentation for each method and property.225226 Methods used to check the format of input parameters. Common tests include227 length, character set, membership, range or pattern. These tests are228 referred to as `whitelisting or blacklisting`_. Whitelisting is better229 but blacklisting can be usefull to spot malicious activity.230 The following have methods a default implementation:231232 - check_client_key233 - check_request_token234 - check_access_token235 - check_nonce236 - check_verifier237 - check_realm238239 The methods above default to whitelist input parameters, checking that they240 are alphanumerical and between a minimum and maximum length. Rather than241 overloading the methods a few properties can be used to configure these242 methods.243244 @ safe_characters -> (character set)245 @ client_key_length -> (min, max)246 @ request_token_length -> (min, max)247 @ access_token_length -> (min, max)248 @ nonce_length -> (min, max)249 @ verifier_length -> (min, max)250 @ realms -> [list, of, realms]251252 Methods used to validate input parameters. These checks usually hit either253 persistent or temporary storage such as databases or the filesystem. See254 each methods documentation for detailed usage.255 The following methods must be implemented:256257 - validate_client258 - validate_request_token259 - validate_access_token260 - validate_nonce_and_timestamp261 - validate_redirect_uri262 - validate_requested_realm263 - validate_realm264 - validate_verifier265266 Method used to retrieve sensitive information from storage.267 The following methods must be implemented:268269 - get_client_secret270 - get_request_token_secret271 - get_access_token_secret272 - get_rsa_key273274 To prevent timing attacks it is necessary to not exit early even if the275 client key or resource owner key is invalid. Instead dummy values should276 be used during the remaining verification process. It is very important277 that the dummy client and token are valid input parameters to the methods278 get_client_secret, get_rsa_key and get_(access/request)_token_secret and279 that the running time of those methods when given a dummy value remain280 equivalent to the running time when given a valid client/resource owner.281 The following properties must be implemented:282283 @ dummy_client284 @ dummy_request_token285 @ dummy_access_token286287 .. _`whitelisting or blacklisting`: http://www.schneier.com/blog/archives/2011/01/whitelisting_vs.html288 """289290 def __init__(self):291 pass292293 @property294 def allowed_signature_methods(self):295 return SIGNATURE_METHODS296297 @property298 def safe_characters(self):299 return set(utils.UNICODE_ASCII_CHARACTER_SET)300301 @property302 def client_key_length(self):303 return 20, 30304305 @property306 def request_token_length(self):307 return 20, 30308309 @property310 def access_token_length(self):311 return 20, 30312313 @property314 def timestamp_lifetime(self):315 return 600316317 @property318 def nonce_length(self):319 return 20, 30320321 @property322 def verifier_length(self):323 return 20, 30324325 @property326 def realms(self):327 return []328329 @property330 def enforce_ssl(self):331 return True332333 def check_client_key(self, client_key):334 """Check that the client key only contains safe characters335 and is no shorter than lower and no longer than upper.336 """337 lower, upper = self.client_key_length338 return (set(client_key) <= self.safe_characters and339 lower <= len(client_key) <= upper)340341 def check_request_token(self, request_token):342 """Checks that the request token contains only safe characters343 and is no shorter than lower and no longer than upper.344 """345 lower, upper = self.request_token_length346 return (set(request_token) <= self.safe_characters and347 lower <= len(request_token) <= upper)348349 def check_access_token(self, request_token):350 """Checks that the token contains only safe characters351 and is no shorter than lower and no longer than upper.352 """353 lower, upper = self.access_token_length354 return (set(request_token) <= self.safe_characters and355 lower <= len(request_token) <= upper)356357 def check_nonce(self, nonce):358 """Checks that the nonce only contains only safe characters359 and is no shorter than lower and no longer than upper.360 """361 lower, upper = self.nonce_length362 return (set(nonce) <= self.safe_characters and363 lower <= len(nonce) <= upper)364365 def check_verifier(self, verifier):366 """Checks that the verifier contains only safe characters367 and is no shorter than lower and no longer than upper.368 """369 lower, upper = self.verifier_length370 return (set(verifier) <= self.safe_characters and371 lower <= len(verifier) <= upper)372373 def check_realm(self, realm):374 """Check that the realm is one of a set allowed realms.375 """376 return realm in self.realms377378 def get_client_secret(self, client_key):379 """Retrieves the client secret associated with the client key.380381 This method must allow the use of a dummy client_key value.382 Fetching the secret using the dummy key must take the same amount of383 time as fetching a secret for a valid client.384385 Note that the returned key must be in plaintext.386 """387 raise NotImplementedError("Subclasses must implement this function.")388389 @property390 def dummy_client(self):391 """Dummy client used when an invalid client key is supplied.392393 The dummy client should be associated with either a client secret,394 a rsa key or both depending on which signature methods are supported.395 Providers should make sure that396397 get_client_secret(dummy_client)398 get_rsa_key(dummy_client)399400 return a valid secret or key for the dummy client.401 """402 raise NotImplementedError("Subclasses must implement this function.")403404 def get_request_token_secret(self, client_key, request_token):405 """Retrieves the shared secret associated with the request token.406407 This method must allow the use of a dummy values and the running time408 must be roughly equivalent to that of the running time of valid values.409410 Note that the returned key must be in plaintext.411 """412 raise NotImplementedError("Subclasses must implement this function.")413414 def get_access_token_secret(self, client_key, access_token):415 """Retrieves the shared secret associated with the access token.416417 This method must allow the use of a dummy values and the running time418 must be roughly equivalent to that of the running time of valid values.419420 Note that the returned key must be in plaintext.421 """422 raise NotImplementedError("Subclasses must implement this function.")423424 @property425 def dummy_request_token(self):426 """Dummy request token used when an invalid token was supplied.427428 The dummy request token should be associated with a request token429 secret such that get_request_token_secret(.., dummy_request_token)430 returns a valid secret.431 """432 raise NotImplementedError("Subclasses must implement this function.")433434 @property435 def dummy_access_token(self):436 """Dummy access token used when an invalid token was supplied.437438 The dummy access token should be associated with an access token439 secret such that get_access_token_secret(.., dummy_access_token)440 returns a valid secret.441 """442 raise NotImplementedError("Subclasses must implement this function.")443444 def get_rsa_key(self, client_key):445 """Retrieves a previously stored client provided RSA key.446447 This method must allow the use of a dummy client_key value. Fetching448 the rsa key using the dummy key must take the same aount of time449 as fetching a key for a valid client.450451 Note that the key must be returned in plaintext.452 """453 raise NotImplementedError("Subclasses must implement this function.")454455 def get_signature_type_and_params(self, request):456 """Extracts parameters from query, headers and body. Signature type457 is set to the source in which parameters were found.458 """459 header_params = signature.collect_parameters(headers=request.headers,460 exclude_oauth_signature=False)461 body_params = signature.collect_parameters(body=request.body,462 exclude_oauth_signature=False)463 query_params = signature.collect_parameters(uri_query=request.uri_query,464 exclude_oauth_signature=False)465466 params = []467 params.extend(header_params)468 params.extend(body_params)469 params.extend(query_params)470 signature_types_with_oauth_params = filter(lambda s: s[2], (471 (SIGNATURE_TYPE_AUTH_HEADER, params,472 utils.filter_oauth_params(header_params)),473 (SIGNATURE_TYPE_BODY, params,474 utils.filter_oauth_params(body_params)),475 (SIGNATURE_TYPE_QUERY, params,476 utils.filter_oauth_params(query_params))477 ))478479 if len(signature_types_with_oauth_params) > 1:480 raise ValueError('oauth_ params must come from only 1 signature type but were found in %s' % ', '.join(481 [s[0] for s in signature_types_with_oauth_params]))482 try:483 signature_type, params, oauth_params = signature_types_with_oauth_params[0]484 except IndexError:485 raise ValueError('oauth_ params are missing. Could not determine signature type.')486487 return signature_type, params, oauth_params488489 def validate_client_key(self, client_key):490 """Validates that supplied client key is a registered and valid client.491492 Note that if the dummy client is supplied it should validate in same493 or nearly the same amount of time as a valid one.494495 Bad:496497 if client_key == self.dummy_client:498 return False499 else:500 return storage.has_client(client_key)501502 Good:503504 return storage.has_client(client_key) and client_key != self.dummy_client505 """506 raise NotImplementedError("Subclasses must implement this function.")507508 def validate_request_token(self, client_key, request_token):509 """Validates that supplied request token is registered and valid.510511 Note that if the dummy request_token is supplied it should validate in512 the same nearly the same amount of time as a valid one.513514 Bad:515516 if request_token == self.dummy_request_token:517 return False518 else:519 return storage.has_request_token(request_token)520521 Good:522523 return (storage.has_request_token(request_token) and524 request_token != self.dummy_request_token)525 """526 raise NotImplementedError("Subclasses must implement this function.")527528 def validate_access_token(self, client_key, access_token):529 """Validates that supplied access token is registered and valid.530531 Note that if the dummy access token is supplied it should validate in532 the same or nearly the same amount of time as a valid one.533534 Bad:535536 if access_token == self.dummy_access_token:537 return False538 else:539 return storage.has_access_token(access_token)540541 Good:542543 return (storage.has_access_token(access_token) and544 access_token != self.dummy_access_token)545 """546 raise NotImplementedError("Subclasses must implement this function.")547548 def validate_timestamp_and_nonce(self, client_key, timestamp, nonce,549 request_token=None, access_token=None):550 """Validates that the nonce has not been used before.551552 Per `Section 3.3`_ of the spec.553554 "A nonce is a random string, uniquely generated by the client to allow555 the server to verify that a request has never been made before and556 helps prevent replay attacks when requests are made over a non-secure557 channel. The nonce value MUST be unique across all requests with the558 same timestamp, client credentials, and token combinations."559560 .. _`Section 3.3`: http://tools.ietf.org/html/rfc5849#section-3.3561562 """563 raise NotImplementedError("Subclasses must implement this function.")564565 def validate_redirect_uri(self, client_key, redirect_uri):566 """Validates the client supplied redirection URI.567568 It is highly recommended that OAuth providers require their clients569 to register all redirection URIs prior to using them in requests and570 register them as absolute URIs. See `CWE-601`_ for more information571 about open redirection attacks.572573 By requiring registration of all redirection URIs it should be574 straightforward for the provider to verify whether the supplied575 redirect_uri is valid or not.576577 .. _`CWE-601`: http://cwe.mitre.org/top25/index.html#CWE-601578 """579 raise NotImplementedError("Subclasses must implement this function.")580581582 def validate_requested_realm(self, client_key, realm):583 """Validates that the client may request access to the realm.584585 This method is invoked when obtaining a request token and should586 tie a realm to the request token and after user authorization587 this realm restriction should transfer to the access token.588 """589 raise NotImplementedError("Subclasses must implement this function.")590591 def validate_realm(self, client_key, access_token, uri=None,592 required_realm=None):593 """Validates access to the request realm.594595 How providers choose to use the realm parameter is outside the OAuth596 specification but it is commonly used to restrict access to a subset597 of protected resources such as "photos".598599 required_realm is a convenience parameter which can be used to provide600 a per view method pre-defined list of allowed realms.601 """602 raise NotImplementedError("Subclasses must implement this function.")603604 def validate_verifier(self, client_key, request_token, verifier):605 """Validates a verification code.606607 OAuth providers issue a verification code to clients after the608 resource owner authorizes access. This code is used by the client to609 obtain token credentials and the provider must verify that the610 verifier is valid and associated with the client as well as the611 resource owner.612 """613 raise NotImplementedError("Subclasses must implement this function.")614615 def verify_request(self, uri, http_method=u'GET', body=None,616 headers=None, require_resource_owner=True, require_verifier=False,617 require_realm=False, required_realm=None):618 """Verifies a request ensuring that the following is true:619620 Per `section 3.2`_ of the spec.621622 - all mandated OAuth parameters are supplied623 - parameters are only supplied in one source which may be the URI624 query, the Authorization header or the body625 - all parameters are checked and validated, see comments and the626 methods and properties of this class for further details.627 - the supplied signature is verified against a recalculated one628629 A ValueError will be raised if any parameter is missing,630 supplied twice or invalid. A HTTP 400 Response should be returned631 upon catching an exception.632633 A HTTP 401 Response should be returned if verify_request returns False.634635 `Timing attacks`_ are prevented through the use of dummy credentials to636 create near constant time verification even if an invalid credential637 is used. Early exit on invalid credentials would enable attackers638 to perform `enumeration attacks`_. Near constant time string comparison639 is used to prevent secret key guessing. Note that timing attacks can640 only be prevented through near constant time execution, not by adding641 a random delay which would only require more samples to be gathered.642643 .. _`section 3.2`: http://tools.ietf.org/html/rfc5849#section-3.2644 .. _`Timing attacks`: http://rdist.root.org/2010/07/19/exploiting-remote-timing-attacks/645 .. _`enumeration attacks`: http://www.sans.edu/research/security-laboratory/article/attacks-browsing646 """647 # Only include body data from x-www-form-urlencoded requests648 headers = headers or {}649 if (u"Content-Type" in headers and650 headers[u"Content-Type"] == CONTENT_TYPE_FORM_URLENCODED):651 request = Request(uri, http_method, body, headers)652 else:653 request = Request(uri, http_method, u'', headers)654655 if self.enforce_ssl and not request.uri.lower().startswith("https://"):656 raise ValueError("Insecure transport, only HTTPS is allowed.")657658 signature_type, params, oauth_params = self.get_signature_type_and_params(request)659660 # The server SHOULD return a 400 (Bad Request) status code when661 # receiving a request with duplicated protocol parameters.662 if len(dict(oauth_params)) != len(oauth_params):663 raise ValueError("Duplicate OAuth entries.")664665 oauth_params = dict(oauth_params)666 request_signature = oauth_params.get(u'oauth_signature')667 client_key = oauth_params.get(u'oauth_consumer_key')668 resource_owner_key = oauth_params.get(u'oauth_token')669 nonce = oauth_params.get(u'oauth_nonce')670 timestamp = oauth_params.get(u'oauth_timestamp')671 callback_uri = oauth_params.get(u'oauth_callback')672 verifier = oauth_params.get(u'oauth_verifier')673 signature_method = oauth_params.get(u'oauth_signature_method')674 realm = dict(params).get(u'realm')675676 # The server SHOULD return a 400 (Bad Request) status code when677 # receiving a request with missing parameters.678 if not all((request_signature, client_key, nonce,679 timestamp, signature_method)):680 raise ValueError("Missing OAuth parameters.")681682 # OAuth does not mandate a particular signature method, as each683 # implementation can have its own unique requirements. Servers are684 # free to implement and document their own custom methods.685 # Recommending any particular method is beyond the scope of this686 # specification. Implementers should review the Security687 # Considerations section (`Section 4`_) before deciding on which688 # method to support.689 # .. _`Section 4`: http://tools.ietf.org/html/rfc5849#section-4690 if not signature_method in self.allowed_signature_methods:691 raise ValueError("Invalid signature method.")692693 # Servers receiving an authenticated request MUST validate it by:694 # If the "oauth_version" parameter is present, ensuring its value is695 # "1.0".696 if u'oauth_version' in oauth_params and oauth_params[u'oauth_version'] != u'1.0':697 raise ValueError("Invalid OAuth version.")698699 # The timestamp value MUST be a positive integer. Unless otherwise700 # specified by the server's documentation, the timestamp is expressed701 # in the number of seconds since January 1, 1970 00:00:00 GMT.702 if len(timestamp) != 10:703 raise ValueError("Invalid timestamp size")704 try:705 ts = int(timestamp)706707 except ValueError:708 raise ValueError("Timestamp must be an integer")709710 else:711 # To avoid the need to retain an infinite number of nonce values for712 # future checks, servers MAY choose to restrict the time period after713 # which a request with an old timestamp is rejected.714 if time.time() - ts > self.timestamp_lifetime:715 raise ValueError("Request too old, over 10 minutes.")716717 # Provider specific validation of parameters, used to enforce718 # restrictions such as character set and length.719 if not self.check_client_key(client_key):720 raise ValueError("Invalid client key.")721722 if not resource_owner_key and require_resource_owner:723 raise ValueError("Missing resource owner.")724725 if (require_resource_owner and not require_verifier and726 not self.check_access_token(resource_owner_key)):727 raise ValueError("Invalid resource owner key.")728729 if (require_resource_owner and require_verifier and730 not self.check_request_token(resource_owner_key)):731 raise ValueError("Invalid resource owner key.")732733 if not self.check_nonce(nonce):734 raise ValueError("Invalid nonce.")735736 if realm and not self.check_realm(realm):737 raise ValueError("Invalid realm. Allowed are %s" % self.realms)738739 if not verifier and require_verifier:740 raise ValueError("Missing verifier.")741742 if require_verifier and not self.check_verifier(verifier):743 raise ValueError("Invalid verifier.")744745 # Servers receiving an authenticated request MUST validate it by:746 # If using the "HMAC-SHA1" or "RSA-SHA1" signature methods, ensuring747 # that the combination of nonce/timestamp/token (if present)748 # received from the client has not been used before in a previous749 # request (the server MAY reject requests with stale timestamps as750 # described in `Section 3.3`_).751 # .._`Section 3.3`: http://tools.ietf.org/html/rfc5849#section-3.3752 #753 # We check this before validating client and resource owner for754 # increased security and performance, both gained by doing less work.755 if require_verifier:756 token = {"request_token": resource_owner_key}757 else:758 token = {"access_token": resource_owner_key}759 if not self.validate_timestamp_and_nonce(client_key, timestamp,760 nonce, **token):761 return False762763 # The server SHOULD return a 401 (Unauthorized) status code when764 # receiving a request with invalid client credentials.765 # Note: This is postponed in order to avoid timing attacks, instead766 # a dummy client is assigned and used to maintain near constant767 # time request verification.768 #769 # Note that early exit would enable client enumeration770 valid_client = self.validate_client_key(client_key)771 if not valid_client:772 client_key = self.dummy_client773774 # Ensure a valid redirection uri is used775 valid_redirect = self.validate_redirect_uri(client_key, callback_uri)776777 # The server SHOULD return a 401 (Unauthorized) status code when778 # receiving a request with invalid or expired token.779 # Note: This is postponed in order to avoid timing attacks, instead780 # a dummy token is assigned and used to maintain near constant781 # time request verification.782 #783 # Note that early exit would enable resource owner enumeration784 if resource_owner_key:785 if require_verifier:786 valid_resource_owner = self.validate_request_token(787 client_key, resource_owner_key)788 else:789 valid_resource_owner = self.validate_access_token(790 client_key, resource_owner_key)791 if not valid_resource_owner:792 resource_owner_key = self.dummy_resource_owner793 else:794 valid_resource_owner = True795796 # Note that `realm`_ is only used in authorization headers and how797 # it should be interepreted is not included in the OAuth spec.798 # However they could be seen as a scope or realm to which the799 # client has access and as such every client should be checked800 # to ensure it is authorized access to that scope or realm.801 # .. _`realm`: http://tools.ietf.org/html/rfc2617#section-1.2802 #803 # Note that early exit would enable client realm access enumeration.804 #805 # The require_realm indicates this is the first step in the OAuth806 # workflow where a client requests access to a specific realm.807 #808 # Clients obtaining an access token will not supply a realm and it will809 # not be checked. Instead the previously requested realm should be810 # transferred from the request token to the access token.811 #812 # Access to protected resources will always validate the realm but note813 # that the realm is now tied to the access token and not provided by814 # the client.815 if require_realm and not resource_owner_key:816 valid_realm = self.validate_requested_realm(client_key, realm)817 elif require_verifier:818 valid_realm = True819 else:820 valid_realm = self.validate_realm(client_key, resource_owner_key,821 uri=request.uri, required_realm=required_realm)822823 # The server MUST verify (Section 3.2) the validity of the request,824 # ensure that the resource owner has authorized the provisioning of825 # token credentials to the client, and ensure that the temporary826 # credentials have not expired or been used before. The server MUST827 # also verify the verification code received from the client.828 # .. _`Section 3.2`: http://tools.ietf.org/html/rfc5849#section-3.2829 #830 # Note that early exit would enable resource owner authorization831 # verifier enumertion.832 if verifier:833 valid_verifier = self.validate_verifier(client_key,834 resource_owner_key, verifier)835 else:836 valid_verifier = True837838 # Parameters to Client depend on signature method which may vary839 # for each request. Note that HMAC-SHA1 and PLAINTEXT share parameters840841 request.params = filter(lambda x: x[0] != "oauth_signature", params)842 request.signature = request_signature843844 # ---- RSA Signature verification ----845 if signature_method == SIGNATURE_RSA:846 # The server verifies the signature per `[RFC3447] section 8.2.2`_847 # .. _`[RFC3447] section 8.2.2`: http://tools.ietf.org/html/rfc3447#section-8.2.1848 rsa_key = self.get_rsa_key(client_key)849 valid_signature = signature.verify_rsa_sha1(request, rsa_key)850851 # ---- HMAC or Plaintext Signature verification ----852 else:853 # Servers receiving an authenticated request MUST validate it by:854 # Recalculating the request signature independently as described in855 # `Section 3.4`_ and comparing it to the value received from the856 # client via the "oauth_signature" parameter.857 # .. _`Section 3.4`: http://tools.ietf.org/html/rfc5849#section-3.4858 client_secret = self.get_client_secret(client_key)859 if require_verifier:860 resource_owner_secret = self.get_request_token_secret(861 client_key, resource_owner_key)862 else:863 resource_owner_secret = self.get_access_token_secret(864 client_key, resource_owner_key)865866 if signature_method == SIGNATURE_HMAC:867 valid_signature = signature.verify_hmac_sha1(request,868 client_secret, resource_owner_secret)869 else:870 valid_signature = signature.verify_plaintext(request,871 client_secret, resource_owner_secret)872873 # We delay checking validity until the very end, using dummy values for874 # calculations and fetching secrets/keys to ensure the flow of every875 # request remains almost identical regardless of whether valid values876 # have been supplied. This ensures near constant time execution and877 # prevents malicious users from guessing sensitive information878 v = all((valid_client, valid_resource_owner, valid_realm,879 valid_redirect, valid_verifier, valid_signature))880 logger = logging.getLogger("oauthlib")881 if not v:882 logger.info("[Failure] OAuthLib request verification failed.")883 logger.info("Valid client:\t%s" % valid_client)884 logger.info("Valid token:\t%s\t(Required: %s" % (valid_resource_owner, require_resource_owner))885 logger.info("Valid realm:\t%s\t(Required: %s)" % (valid_realm, require_realm))886 logger.info("Valid callback:\t%s" % valid_redirect)887 logger.info("Valid verifier:\t%s\t(Required: %s)" % (valid_verifier, require_verifier))888 logger.info("Valid signature:\t%s" % valid_signature)889 return v
deleted:requests/packages/oauthlib/oauth1/rfc5849/parameters.py-134 removed
1# -*- coding: utf-8 -*-2from __future__ import absolute_import34"""5oauthlib.parameters6~~~~~~~~~~~~~~~~~~~78This module contains methods related to `section 3.5`_ of the OAuth 1.0a spec.910.. _`section 3.5`: http://tools.ietf.org/html/rfc5849#section-3.511"""1213from urlparse import urlparse, urlunparse14from . import utils15from oauthlib.common import extract_params, urlencode161718# 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_params21def prepare_headers(oauth_params, headers=None, realm=None):22 """**Prepare the Authorization header.**23 Per `section 3.5.1`_ of the spec.2425 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).2829 For example::3031 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"394041 .. _`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 {}4546 # 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)5657 # 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)6162 authorization_header_parameters_parts.append(part)6364 # 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)7071 # 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)7980 # the auth-scheme name set to "OAuth" (case insensitive).81 authorization_header = u'OAuth %s' % authorization_header_parameters8283 # contribute the Authorization header to the given headers84 full_headers = {}85 full_headers.update(headers)86 full_headers[u'Authorization'] = authorization_header87 return full_headers888990def _append_params(oauth_params, params):91 """Append OAuth params to an existing set of parameters.9293 Both params and oauth_params is must be lists of 2-tuples.9495 Per `section 3.5.2`_ and `3.5.3`_ of the spec.9697 .. _`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.399100 """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 merged109110111def prepare_form_encoded_body(oauth_params, body):112 """Prepare the Form-Encoded Body.113114 Per `section 3.5.2`_ of the spec.115116 .. _`section 3.5.2`: http://tools.ietf.org/html/rfc5849#section-3.5.2117118 """119 # append OAuth params to the existing body120 return _append_params(oauth_params, body)121122123def prepare_request_uri_query(oauth_params, uri):124 """Prepare the Request URI Query.125126 Per `section 3.5.3`_ of the spec.127128 .. _`section 3.5.3`: http://tools.ietf.org/html/rfc5849#section-3.5.3129130 """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))
deleted:requests/packages/oauthlib/oauth1/rfc5849/signature.py-551 removed
1# -*- coding: utf-8 -*-2from __future__ import absolute_import3"""4oauthlib.oauth1.rfc5849.signature5~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~67This module represents a direct implementation of `section 3.4`_ of the spec.89Terminology:10 * Client: software interfacing with an OAuth API11 * Server: the API provider12 * Resource Owner: the user who is granting authorization to the client1314Steps for signing a request:15161. Collect parameters from the uri query, auth header, & body172. Normalize those parameters183. Normalize the uri194. Pass the normalized uri, normalized parameters, and http method to20 construct the base string215. Pass the base string and any keys needed to a signing function2223.. _`section 3.4`: http://tools.ietf.org/html/rfc5849#section-3.424"""25import binascii26import hashlib27import hmac28import urlparse29from . import utils30from oauthlib.common import extract_params, safe_string_equals313233def 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.3738 For example, the HTTP request::3940 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"5051 c2&a3=2+q5253 is represented by the following signature base string (line breaks54 are for display purposes only)::5556 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 9d7dh3k39sjv76162 .. _`section 3.4.1.1`: http://tools.ietf.org/html/rfc5849#section-3.4.1.163 """6465 # The signature base string is constructed by concatenating together,66 # in order, the following HTTP request elements:6768 # 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())7475 # 2. An "&" character (ASCII code 38).76 base_string += u'&'7778 # 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)8485 # 4. An "&" character (ASCII code 38).86 base_string += u'&'8788 # 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)9495 return base_string969798def normalize_base_string_uri(uri):99 """**Base String URI**100 Per `section 3.4.1.2`_ of the spec.101102 For example, the HTTP request::103104 GET /r%20v/X?id=123 HTTP/1.1105 Host: EXAMPLE.COM:80106107 is represented by the base string URI: "http://example.com/r%20v/X".108109 In another example, the HTTPS request::110111 GET /?q=1 HTTP/1.1112 Host: www.example.net:8080113114 is represented by the base string URI: "https://www.example.net:8080/".115116 .. _`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.')120121 # FIXME: urlparse does not support unicode122 scheme, netloc, path, params, query, fragment = urlparse.urlparse(uri)123124 # 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/rfc3986129130 # 1. The scheme and host MUST be in lowercase.131 scheme = scheme.lower()132 netloc = netloc.lower()133134 # 2. The host and port values MUST match the content of the HTTP135 # request "Host" header field.136 # TODO: enforce this constraint137138 # 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 = host154155 return urlparse.urlunparse((scheme, netloc, path, u'', u'', u''))156157158# ** 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.3169170def collect_parameters(uri_query='', body=[], headers=None,171 exclude_oauth_signature=True):172 """**Parameter Sources**173174 Parameters starting with `oauth_` will be unescaped.175176 Body parameters must be supplied as a dict, a list of 2-tuples, or a177 formencoded query string.178179 Headers must be supplied as a dict.180181 Per `section 3.4.1.3.1`_ of the spec.182183 For example, the HTTP request::184185 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"195196 c2&a3=2+q197198 contains the following (fully decoded) parameters used in the199 signature base sting::200201 +------------------------+------------------+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 +------------------------+------------------+216217 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).226227 .. _`section 3.4.1.3.1`: http://tools.ietf.org/html/rfc5849#section-3.4.1.3.1228 """229 headers = headers or {}230 params = []231232 # The parameters from the following sources are collected into a single233 # list of name/value pairs:234235 # * 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))246247 # * 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'])259260 # * 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`_.267268 # * 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-19980424272273 # TODO: enforce header param inclusion conditions274 bodyparams = extract_params(body) or []275 params.extend(bodyparams)276277 # 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))283284 # 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)289290 return unescaped_params291292293def normalize_parameters(params):294 """**Parameters Normalization**295 Per `section 3.4.1.3.2`_ of the spec.296297 For example, the list of parameters from the previous section would298 be normalized as follows:299300 Encoded::301302 +------------------------+------------------+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 +------------------------+------------------+317318 Sorted::319320 +------------------------+------------------+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 +------------------------+------------------+335336 Concatenated Pairs::337338 +-------------------------------------+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 +-------------------------------------+353354 and concatenated together into a single string (line breaks are for355 display purposes only)::356357 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=kkk9d7dh3k39sjv7360361 .. _`section 3.4.1.3.2`: http://tools.ietf.org/html/rfc5849#section-3.4.1.3.2362 """363364 # 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.3368369 # 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]374375 # 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()379380 # 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]384385 # 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)389390391def sign_hmac_sha1(base_string, client_secret, resource_owner_secret):392 """**HMAC-SHA1**393394 The "HMAC-SHA1" signature method uses the HMAC-SHA1 signature395 algorithm as defined in `RFC2104`_::396397 digest = HMAC-SHA1 (key, text)398399 Per `section 3.4.2`_ of the spec.400401 .. _`RFC2104`: http://tools.ietf.org/html/rfc2104402 .. _`section 3.4.2`: http://tools.ietf.org/html/rfc5849#section-3.4.2403 """404405 # The HMAC-SHA1 function variables are used in following way:406407 # 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_string412413 # 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'')418419 # 2. An "&" character (ASCII code 38), which MUST be included420 # even when either secret is empty.421 key += u'&'422423 # 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'')427428 # 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)432433 # 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')439440441def sign_rsa_sha1(base_string, rsa_private_key):442 """**RSA-SHA1**443444 Per `section 3.4.3`_ of the spec.445446 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).452453 NOTE: this method requires the python-rsa library.454455 .. _`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.2457458 """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')467468469def sign_plaintext(client_secret, resource_owner_secret):470 """Sign a request using plaintext.471472 Per `section 3.4.4`_ of the spec.473474 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.479480 .. _`section 3.4.4`: http://tools.ietf.org/html/rfc5849#section-3.4.4481482 """483484 # The "oauth_signature" protocol parameter is set to the concatenated485 # value of:486487 # 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'')491492 # 2. An "&" character (ASCII code 38), which MUST be included even493 # when either secret is empty.494 signature += u'&'495496 # 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'')500501 return signature502503504def verify_hmac_sha1(request, client_secret=None, 505 resource_owner_secret=None):506 """Verify a HMAC-SHA1 signature.507508 Per `section 3.4`_ of the spec.509510 .. _`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)518519520def verify_rsa_sha1(request, rsa_public_key):521 """Verify a RSASSA-PKCS #1 v1.5 base64 encoded signature.522523 Per `section 3.4.3`_ of the spec.524525 Note this method requires the PyCrypto library.526527 .. _`section 3.4.3`: http://tools.ietf.org/html/rfc5849#section-3.4.3528529 """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)541542543def verify_plaintext(request, client_secret=None, resource_owner_secret=None):544 """Verify a PLAINTEXT signature.545546 Per `section 3.4`_ of the spec.547548 .. _`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)
deleted:requests/packages/oauthlib/oauth1/rfc5849/utils.py-99 removed
1# -*- coding: utf-8 -*-23"""4oauthlib.utils5~~~~~~~~~~~~~~67This module contains utility methods used by various parts of the OAuth8spec.9"""1011import string12import urllib21314from oauthlib.common import quote, unquote1516UNICODE_ASCII_CHARACTER_SET = (string.ascii_letters.decode('ascii') +17 string.digits.decode('ascii'))181920def filter_params(target):21 """Decorator which filters params to remove non-oauth_* parameters2223 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)2930 wrapper.__doc__ = target.__doc__31 return wrapper323334def 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)414243def escape(u):44 """Escape a unicode string in an OAuth-compatible fashion.4546 Per `section 3.6`_ of the spec.4748 .. _`section 3.6`: http://tools.ietf.org/html/rfc5849#section-3.64950 """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='~')565758def unescape(u):59 if not isinstance(u, unicode):60 raise ValueError('Only unicode objects are unescapable.')61 return unquote(u)626364def urlencode(query):65 """Encode a sequence of two-element tuples or dictionary into a URL query string.6667 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])737475def 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())818283def 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]888990def 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')
deleted:requests/packages/oauthlib/oauth1/__init__.py-13 removed
1# -*- coding: utf-8 -*-2from __future__ import absolute_import34"""5oauthlib.oauth16~~~~~~~~~~~~~~78This module is a wrapper for the most recent implementation of OAuth 1.0 Client9and Server classes.10"""1112from .rfc5849 import Client, Server13
deleted:requests/packages/oauthlib/oauth2/draft25/__init__.py-497 removed
1"""2oauthlib.oauth2.draft_253~~~~~~~~~~~~~~45This module is an implementation of various logic needed6for signing and checking OAuth 2.0 draft 25 requests.7"""8from tokens import prepare_bearer_uri, prepare_bearer_headers9from tokens import prepare_bearer_body, prepare_mac_header10from parameters import prepare_grant_uri, prepare_token_request11from parameters import parse_authorization_code_response12from parameters import parse_implicit_response, parse_token_response131415AUTH_HEADER = u'auth_header'16URI_QUERY = u'query'17BODY = u'body'181920class Client(object):2122 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."""2829 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 }3839 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.4243 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.4849 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:5253 GET /resource/1 HTTP/1.154 Host: example.com55 Authorization: Bearer mF_9.B5f-4.1JqM5657 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:6061 GET /resource/1 HTTP/1.162 Host: example.com63 Authorization: MAC id="h480djs93hd8",64 nonce="274312:dj83hs9s",65 mac="kDZvddkndxvhGRXZhvuDjEWhGeE="6667 .. _`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)7273 def prepare_refresh_body(self, body=u'', refresh_token=None, scope=None):74 """Prepare an access token request, using a refresh token.7576 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:8081 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)9596 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)101102 if token_placement == URI_QUERY:103 uri = prepare_bearer_uri(self.token, uri)104105 if token_placement == BODY:106 body = prepare_bearer_body(self.token, body)107108 return uri, headers, body109110 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, body117118 def _populate_attributes(self, response):119 """Add commonly used values such as access_token to self."""120121 if u'access_token' in response:122 self.access_token = response.get(u'access_token')123124 if u'refresh_token' in response:125 self.refresh_token = response.get(u'refresh_token')126127 if u'token_type' in response:128 self.token_type = response.get(u'token_type')129130 if u'expires_in' in response:131 self.expires_in = response.get(u'expires_in')132133 if u'code' in response:134 self.code = response.get(u'code')135136 def prepare_request_uri(self, *args, **kwargs):137 """Abstract method used to create request URIs."""138 raise NotImplementedError("Must be implemented by inheriting classes.")139140 def prepare_request_body(self, *args, **kwargs):141 """Abstract method used to create request bodies."""142 raise NotImplementedError("Must be implemented by inheriting classes.")143144 def parse_request_uri_response(self, *args, **kwargs):145 """Abstract method used to parse redirection responses."""146147 def parse_request_body_response(self, *args, **kwargs):148 """Abstract method used to parse JSON responses."""149150151class WebApplicationClient(Client):152 """A client utilizing the authorization code grant workflow.153154 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.160161 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 """168169 def prepare_request_uri(self, uri, redirect_uri=None, scope=None,170 state=None, **kwargs):171 """Prepare the authorization code request URI172173 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`_]:177178 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`_.193194 .. _`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)203204 def prepare_request_body(self, code, body=u'', redirect_uri=None, **kwargs):205 """Prepare the access token request body.206207 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:210211 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.220221 .. _`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)227228 def parse_request_uri_response(self, uri, state=None):229 """Parse the URI query for code and state.230231 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:235236 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 response255256 def parse_request_body_response(self, body, scope=None):257 """Parse the JSON response body.258259 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`_.264265 .. `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 response271272273class UserAgentClient(Client):274 """A public client utilizing the implicit code grant workflow.275276 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.283284 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.289290 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.294295 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.298299 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 """305306 def prepare_request_uri(self, uri, redirect_uri=None, scope=None,307 state=None, **kwargs):308 """Prepare the implicit grant request URI.309310 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:313314 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)333334 def parse_request_uri_response(self, uri, state=None, scope=None):335 """Parse the response URI fragment.336337 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:341342 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.361362 .. _`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 response368369370class NativeApplicationClient(Client):371 """A public client utilizing the client credentials grant workflow.372373 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.384385 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).391392 The client credentials grant type MUST only be used by confidential393 clients.394395 Since the client authentication is used as the authorization grant,396 no additional authorization request is needed.397 """398399 def prepare_request_body(self, body=u'', scope=None, **kwargs):400 """Add the client credentials to the request body.401402 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:405406 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`_.411412 .. _`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)416417 def parse_request_body_response(self, body, scope=None):418 """Parse the JSON response body.419420 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`_.425426 .. `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 response432433434class PasswordCredentialsClient(Client):435 """A public client using the resource owner password and username directly.436437 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.443444 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.450451 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 """455456 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.459460 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:463464 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`_.473474 .. _`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)478479 def parse_request_body_response(self, body, scope=None):480 """Parse the JSON response body.481482 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`_.487488 .. `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 response494495496class Server(object):497 pass
deleted:requests/packages/oauthlib/oauth2/draft25/parameters.py-256 removed
1"""2oauthlib.oauth2_draft28.parameters3~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~45This module contains methods related to `Section 4`_ of the OAuth 2 draft.67.. _`Section 4`: http://tools.ietf.org/html/draft-ietf-oauth-v2-28#section-48"""910import json11import urlparse12from oauthlib.common import add_params_to_uri, add_params_to_qs131415def prepare_grant_uri(uri, client_id, response_type, redirect_uri=None,16 scope=None, state=None, **kwargs):17 """Prepare the authorization grant request URI.1819 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]:2324 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`_.3940 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.com4344 .. _`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))]5253 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))5960 for k in kwargs:61 params.append((unicode(k), kwargs[k]))6263 return add_params_to_uri(uri, params)646566def prepare_token_request(grant_type, body=u'', **kwargs):67 """Prepare the access token request.6869 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:7273 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.8283 grant_type=authorization_code&code=SplxlOBeZQQYbYS6WxSbIA84 &redirect_uri=https%3A%2F%2Fclient%2Eexample%2Ecom%2Fcb8586 .. _`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]))9192 return add_params_to_qs(body, params)939495def parse_authorization_code_response(uri, state=None):96 """Parse authorization grant response URI into a dict.9798 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:102103 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.118119 For example, the authorization server redirects the user-agent by120 sending the following HTTP response:121122 HTTP/1.1 302 Found123 Location: https://client.example.com/cb?code=SplxlOBeZQQYbYS6WxSbIA124 &state=xyz125126 """127 query = urlparse.urlparse(uri).query128 params = dict(urlparse.parse_qsl(query))129130 if not u'code' in params:131 raise KeyError("Missing code parameter in response.")132133 if state and params.get(u'state', None) != state:134 raise ValueError("Mismatching or missing state in response.")135136 return params137138139def parse_implicit_response(uri, state=None, scope=None):140 """Parse the implicit token response URI into a dict.141142 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:146147 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.166167 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)174175 if state and params.get(u'state', None) != state:176 raise ValueError("Mismatching or missing state in params.")177178 return params179180181def parse_token_response(body, scope=None):182 """Parse the JSON token response body into a dict.183184 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:187188 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`_.207208 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.215216 For example:217218 HTTP/1.1 200 OK219 Content-Type: application/json;charset=UTF-8220 Cache-Control: no-store221 Pragma: no-cache222223 {224 "access_token":"2YotnFZFEjr1zCsicMWpAA",225 "token_type":"example",226 "expires_in":3600,227 "refresh_token":"tGzv3JOkF0XG5Qx2TlKWIA",228 "example_parameter":"example_value"229 }230231 .. _`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 params239240241def validate_token_parameters(params, scope=None):242 """Ensures token precence, token type, expiration and scope in params."""243244 if not u'access_token' in params:245 raise KeyError("Missing access token parameter.")246247 if not u'token_type' in params:248 raise KeyError("Missing token type parameter.")249250 # 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)
deleted:requests/packages/oauthlib/oauth2/draft25/tokens.py-132 removed
1from __future__ import absolute_import2"""3oauthlib.oauth2.draft25.tokens4~~~~~~~~~~~~~~~~~~~~~~~~~~~~~56This module contains methods for adding two types of access tokens to requests.78- Bearer http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-089- MAC http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-001011"""12from binascii import b2a_base6413import hashlib14import hmac15from urlparse import urlparse1617from oauthlib.common import add_params_to_uri, add_params_to_qs18from . import utils192021def 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.2425 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.2829 Currently two algorithms are supported, "hmac-sha-1" and "hmac-sha-256",30 `extension algorithms`_ are not supported.3132 Example MAC Authorization header, linebreaks added for clarity3334 Authorization: MAC id="h480djs93hd8",35 nonce="1336363200:dj83hs9s",36 mac="bhCQXTVyfj5cmA9uKkPFx1zeOXM="3738 .. _`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.14041 :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)5051 if hash_algorithm.lower() == u'hmac-sha-1':52 h = hashlib.sha153 else:54 h = hashlib.sha2565556 nonce = nonce or u'{0}:{1}'.format(utils.generate_nonce(), utils.generate_timestamp())57 sch, net, path, par, query, fra = urlparse(uri)5859 if query:60 request_uri = path + u'?' + query61 else:62 request_uri = path6364 # 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''6970 # 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'8081 # 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')8687 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)9596 headers = headers or {}97 headers[u'Authorization'] = u', '.join(header)98 return headers99100101def 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.104105 http://www.example.com/path?access_token=h480djs93hd8106107 .. _`Bearer Token`: http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-18108 """109 return add_params_to_uri(uri, [((u'access_token', token))])110111112def prepare_bearer_headers(token, headers=None):113 """Add a `Bearer Token`_ to the request URI.114 Recommended method of passing bearer tokens.115116 Authorization: Bearer h480djs93hd8117118 .. _`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 headers123124125def prepare_bearer_body(token, body=u''):126 """Add a `Bearer Token`_ to the request body.127128 access_token=h480djs93hd8129130 .. _`Bearer Token`: http://tools.ietf.org/html/draft-ietf-oauth-v2-bearer-18131 """132 return add_params_to_qs(body, [((u'access_token', token))])
deleted:requests/packages/oauthlib/oauth2/draft25/utils.py-39 removed
1"""2oauthlib.utils3~~~~~~~~~~~~~~45This module contains utility methods used by various parts of the OAuth 2 spec.6"""78import urllib9import urlparse101112def host_from_uri(uri):13 """Extract hostname and port from URI.1415 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 }2122 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())2728 return netloc, port293031def escape(u):32 """Escape a string in an OAuth-compatible fashion.3334 TODO: verify whether this can in fact be used for OAuth 23536 """37 if not isinstance(u, unicode):38 raise ValueError('Only unicode objects are escapable.')39 return urllib.quote(u.encode('utf-8'), safe='~')
deleted:requests/packages/oauthlib/oauth2/__init__.py-13 removed
1# -*- coding: utf-8 -*-2from __future__ import absolute_import34"""5oauthlib.oauth26~~~~~~~~~~~~~~78This module is a wrapper for the most recent implementation of OAuth 2.0 Client9and Server classes.10"""1112from .draft25 import Client, Server13
deleted:requests/packages/oauthlib/__init__.py
deleted:requests/packages/oauthlib/common.py-229 removed
1# -*- coding: utf-8 -*-2from __future__ import absolute_import34"""5oauthlib.common6~~~~~~~~~~~~~~78This module provides data structures and utilities common9to all implementations of OAuth.10"""1112import random13import re14import string15import time16import urllib17import urlparse1819UNICODE_ASCII_CHARACTER_SET = (string.ascii_letters.decode('ascii') +20 string.digits.decode('ascii'))2122always_safe = (u'ABCDEFGHIJKLMNOPQRSTUVWXYZ'23 u'abcdefghijklmnopqrstuvwxyz'24 u'0123456789' u'_.-')252627def quote(s, safe=u'/'):28 encoded = s.encode("utf-8")29 quoted = urllib.quote(encoded, safe)30 return quoted.decode("utf-8")313233def unquote(s):34 encoded = s.encode("utf-8")35 unquoted = urllib.unquote(encoded)36 return unquoted.decode("utf-8")373839def urlencode(params):40 utf8_params = encode_params_utf8(params)41 urlencoded = urllib.urlencode(utf8_params)42 return urlencoded.decode("utf-8")434445def 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 encoded555657def 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 decoded676869urlencoded = set(always_safe) | set(u'=&;%+~')707172def urldecode(query):73 """Decode a query string in x-www-form-urlencoded format into a sequence74 of two-element tuples.7576 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.')8485 # 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.')9293 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)9798 # unicode all the things99 return decode_params_utf8(params)100101102def extract_params(raw):103 """Extract parameters and return them as a list of 2-tuples.104105 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 = None127128 return params129130131def generate_nonce():132 """Generate pseudorandom nonce that is unlikely to repeat.133134 Per `section 3.3`_ of the OAuth 1 RFC 5849 spec.135 Per `section 3.2.1`_ of the MAC Access Authentication spec.136137 A random 64-bit number is appended to the epoch timestamp for both138 randomness and to decrease the likelihood of collisions.139140 .. _`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())144145146def generate_timestamp():147 """Get seconds since epoch (UTC).148149 Per `section 3.3`_ of the OAuth 1 RFC 5849 spec.150 Per `section 3.2.1`_ of the MAC Access Authentication spec.151152 .. _`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()))156157158def generate_token(length=30, chars=UNICODE_ASCII_CHARACTER_SET):159 """Generates a non-guessable OAuth token160161 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))168169170def 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)175176177def 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))182183def safe_string_equals(a, b):184 """ Near-constant time string comparison. 185186 Used in order to avoid timing attacks on sensitive information such187 as secret keys during request verification (`rootLabs`_).188189 .. _`rootLabs`: http://rdist.root.org/2010/01/07/timing-independent-array-comparison/190 191 """192 if len(a) != len(b):193 return False194195 result = 0196 for x, y in zip(a, b):197 result |= ord(x) ^ ord(y)198 return result == 0199200class Request(object):201 """A malleable representation of a signable HTTP request.202203 Body argument may contain any data, but parameters will only be decoded if204 they are one of:205206 * urlencoded query string207 * dict208 * list of 2-tuples209210 Anything else will be treated as raw body data to be passed through211 unmolested.212 """213214 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 = []221222 @property223 def uri_query(self):224 return urlparse.urlparse(self.uri).query225226 @property227 def uri_query_params(self):228 return urlparse.parse_qsl(self.uri_query, keep_blank_values=True,229 strict_parsing=True)
deleted:requests/_oauth.py-23 removed
1# -*- coding: utf-8 -*-23"""4requests._oauth5~~~~~~~~~~~~~~~67This module contains the path hack necessary for oauthlib to be vendored into8requests while allowing upstream changes.9"""1011import os12import sys1314try:15 from oauthlib.oauth1 import rfc584916 from oauthlib.common import extract_params17 from oauthlib.oauth1.rfc5849 import (Client, SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER)18except ImportError:19 from .packages import oauthlib20 sys.modules['oauthlib'] = oauthlib21 from oauthlib.oauth1 import rfc584922 from oauthlib.common import extract_params23 from oauthlib.oauth1.rfc5849 import (Client, SIGNATURE_HMAC, SIGNATURE_TYPE_AUTH_HEADER)