Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def test_sanitized_request_non_debug_mode(self):
"""make sure requests are sanitized when in non debug mode.
For the debug mode, the other tests checking sanitization should prove
that debug mode is working.
"""
try:
oauthlib.set_debug(False)
r = Request(URI, headers={'token': 'foobar'}, body='token=banana')
self.assertNotIn('token', repr(r))
self.assertIn('SANITIZED', repr(r))
finally:
# set flag back for other tests
oauthlib.set_debug(True)
def test_get_oauth_params():
"""Verifies oauth_token is added to the list of params when an empty string."""
client = MKMClient(
client_key="app_token",
client_secret="app_secret",
resource_owner_key="",
resource_owner_secret="",
realm="https://sandbox.cardmarket.com",
nonce="0987654321",
timestamp="1234567890",
)
params = client.get_oauth_params(Request(uri="https://sandbox.cardmarket.com"))
assert params[0][0] == "oauth_nonce"
assert params[0][1] == "0987654321"
assert params[1][0] == "oauth_timestamp"
assert params[1][1] == "1234567890"
assert params[2][0] == "oauth_version"
assert params[2][1] == "1.0"
assert params[3][0] == "oauth_signature_method"
assert params[3][1] == "HMAC-SHA1"
assert params[4][0] == "oauth_consumer_key"
assert params[4][1] == "app_token"
assert params[5][0] == "oauth_token"
assert params[5][1] == ""
def oauth_sign_params(cls, url, params):
params.update(
{
"oauth_consumer_key": cls.OAUTH_CONSUMER_KEY,
"oauth_nonce": cls.OAUTH_NONCE,
"oauth_timestamp": str(int(time.time())),
}
)
params["oauth_signature"] = cls.OAUTH_CLIENT.get_oauth_signature(
oauthlib.common.Request(f"http://localhost{url}", "POST", body=params)
)
return params
def verify_request(self, uri, http_method='GET', body=None, headers=None,
scopes=None):
"""Validate client, code etc, return body + headers"""
request = Request(uri, http_method, body, headers)
request.token_type = self.find_token_type(request)
request.scopes = scopes
token_type_handler = self.tokens.get(request.token_type,
self.default_token_type_handler)
log.debug('Dispatching token_type %s request to %r.',
request.token_type, token_type_handler)
return token_type_handler.validate_request(request), request
def create_token_response(self, uri, http_method='POST', body=None,
headers=None, credentials=None, grant_type_for_scope=None,
claims=None):
"""Extract grant_type and route to the designated handler."""
request = Request(
uri, http_method=http_method, body=body, headers=headers)
self.validate_token_request(request)
# 'scope' is an allowed Token Request param in both the "Resource Owner Password Credentials Grant"
# and "Client Credentials Grant" flows
# https://tools.ietf.org/html/rfc6749#section-4.3.2
# https://tools.ietf.org/html/rfc6749#section-4.4.2
request.scopes = utils.scope_to_list(request.scope)
request.extra_credentials = credentials
if grant_type_for_scope:
request.grant_type = grant_type_for_scope
# OpenID Connect claims, if provided. The server using oauthlib might choose
# to implement the claims parameter of the Authorization Request. In this case
# it should retrieve those claims and pass them via the claims argument here,
# as a dict.
verbatim as it is unaffected by the OAuth signing process. Attempting to
sign a request with non-formencoded data using the OAuth body signature
type is invalid and will raise an exception.
If the body does contain parameters, it will be returned as a properly-
formatted formencoded string.
Body may not be included if the http_method is either GET or HEAD as
this changes the semantic meaning of the request.
All string data MUST be unicode or be encoded with the same encoding
scheme supplied to the Client constructor, default utf-8. This includes
strings inside body dicts, for example.
"""
# normalize request data
request = Request(uri, http_method, body, headers,
encoding=self.encoding)
# sanity check
content_type = request.headers.get('Content-Type', None)
multipart = content_type and content_type.startswith('multipart/')
should_have_params = content_type == CONTENT_TYPE_FORM_URLENCODED
has_params = request.decoded_body is not None
# 3.4.1.3.1. Parameter Sources
# [Parameters are collected from the HTTP request entity-body, but only
# if [...]:
# * The entity-body is single-part.
if multipart and has_params:
raise ValueError(
"Headers indicate a multipart body but body contains parameters.")
# * The entity-body follows the encoding requirements of the
# "application/x-www-form-urlencoded" content-type as defined by
verbatim as it is unaffected by the OAuth signing process. Attempting to
sign a request with non-formencoded data using the OAuth body signature
type is invalid and will raise an exception.
If the body does contain parameters, it will be returned as a properly-
formatted formencoded string.
Body may not be included if the http_method is either GET or HEAD as
this changes the semantic meaning of the request.
All string data MUST be unicode or be encoded with the same encoding
scheme supplied to the Client constructor, default utf-8. This includes
strings inside body dicts, for example.
"""
# normalize request data
request = Request(uri, http_method, body, headers,
encoding=self.encoding)
# sanity check
content_type = request.headers.get('Content-Type', None)
multipart = content_type and content_type.startswith('multipart/')
should_have_params = content_type == CONTENT_TYPE_FORM_URLENCODED
has_params = request.decoded_body is not None
# 3.4.1.3.1. Parameter Sources
# [Parameters are collected from the HTTP request entity-body, but only
# if [...]:
# * The entity-body is single-part.
if multipart and has_params:
raise ValueError(
"Headers indicate a multipart body but body contains parameters.")
# * The entity-body follows the encoding requirements of the
# "application/x-www-form-urlencoded" content-type as defined by
def verify_request(self, uri, http_method='GET', body=None, headers=None,
scopes=None):
"""Validate client, code etc, return body + headers"""
request = Request(uri, http_method, body, headers)
request.token_type = self.find_token_type(request)
request.scopes = scopes
token_type_handler = self.tokens.get(request.token_type,
self.default_token_type_handler)
log.debug('Dispatching token_type %s request to %r.',
request.token_type, token_type_handler)
return token_type_handler.validate_request(request), request
create near constant time verification even if an invalid credential
is used. Early exit on invalid credentials would enable attackers
to perform `enumeration attacks`_. Near constant time string comparison
is used to prevent secret key guessing. Note that timing attacks can
only be prevented through near constant time execution, not by adding
a random delay which would only require more samples to be gathered.
.. _`section 3.2`: http://tools.ietf.org/html/rfc5849#section-3.2
.. _`Timing attacks`: http://rdist.root.org/2010/07/19/exploiting-remote-timing-attacks/
.. _`enumeration attacks`: http://www.sans.edu/research/security-laboratory/article/attacks-browsing
"""
# Only include body data from x-www-form-urlencoded requests
headers = headers or {}
if (u"Content-Type" in headers and
headers[u"Content-Type"] == CONTENT_TYPE_FORM_URLENCODED):
request = Request(uri, http_method, body, headers)
else:
request = Request(uri, http_method, u'', headers)
if self.enforce_ssl and not request.uri.lower().startswith("https://"):
raise ValueError("Insecure transport, only HTTPS is allowed.")
signature_type, params, oauth_params = self.get_signature_type_and_params(request)
# The server SHOULD return a 400 (Bad Request) status code when
# receiving a request with duplicated protocol parameters.
if len(dict(oauth_params)) != len(oauth_params):
raise ValueError("Duplicate OAuth entries.")
oauth_params = dict(oauth_params)
request_signature = oauth_params.get(u'oauth_signature')
client_key = oauth_params.get(u'oauth_consumer_key')
def validate_authorization_request(self, uri, http_method='GET', body=None,
headers=None):
"""Extract response_type and route to the designated handler."""
request = Request(
uri, http_method=http_method, body=body, headers=headers)
request.scopes = None
response_type_handler = self.response_types.get(
request.response_type, self.default_response_type_handler)
return response_type_handler.validate_authorization_request(request)