__init__.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. # -*- coding: utf-8 -*-
  2. """
  3. oauthlib.oauth1.rfc5849
  4. ~~~~~~~~~~~~~~
  5. This module is an implementation of various logic needed
  6. for signing and checking OAuth 1.0 RFC 5849 requests.
  7. """
  8. from __future__ import absolute_import, unicode_literals
  9. import base64
  10. import hashlib
  11. import logging
  12. log = logging.getLogger(__name__)
  13. import sys
  14. try:
  15. import urlparse
  16. except ImportError:
  17. import urllib.parse as urlparse
  18. if sys.version_info[0] == 3:
  19. bytes_type = bytes
  20. else:
  21. bytes_type = str
  22. from oauthlib.common import Request, urlencode, generate_nonce
  23. from oauthlib.common import generate_timestamp, to_unicode
  24. from . import parameters, signature
  25. SIGNATURE_HMAC = "HMAC-SHA1"
  26. SIGNATURE_RSA = "RSA-SHA1"
  27. SIGNATURE_PLAINTEXT = "PLAINTEXT"
  28. SIGNATURE_METHODS = (SIGNATURE_HMAC, SIGNATURE_RSA, SIGNATURE_PLAINTEXT)
  29. SIGNATURE_TYPE_AUTH_HEADER = 'AUTH_HEADER'
  30. SIGNATURE_TYPE_QUERY = 'QUERY'
  31. SIGNATURE_TYPE_BODY = 'BODY'
  32. CONTENT_TYPE_FORM_URLENCODED = 'application/x-www-form-urlencoded'
  33. class Client(object):
  34. """A client used to sign OAuth 1.0 RFC 5849 requests."""
  35. SIGNATURE_METHODS = {
  36. SIGNATURE_HMAC: signature.sign_hmac_sha1_with_client,
  37. SIGNATURE_RSA: signature.sign_rsa_sha1_with_client,
  38. SIGNATURE_PLAINTEXT: signature.sign_plaintext_with_client
  39. }
  40. @classmethod
  41. def register_signature_method(cls, method_name, method_callback):
  42. cls.SIGNATURE_METHODS[method_name] = method_callback
  43. def __init__(self, client_key,
  44. client_secret=None,
  45. resource_owner_key=None,
  46. resource_owner_secret=None,
  47. callback_uri=None,
  48. signature_method=SIGNATURE_HMAC,
  49. signature_type=SIGNATURE_TYPE_AUTH_HEADER,
  50. rsa_key=None, verifier=None, realm=None,
  51. encoding='utf-8', decoding=None,
  52. nonce=None, timestamp=None):
  53. """Create an OAuth 1 client.
  54. :param client_key: Client key (consumer key), mandatory.
  55. :param resource_owner_key: Resource owner key (oauth token).
  56. :param resource_owner_secret: Resource owner secret (oauth token secret).
  57. :param callback_uri: Callback used when obtaining request token.
  58. :param signature_method: SIGNATURE_HMAC, SIGNATURE_RSA or SIGNATURE_PLAINTEXT.
  59. :param signature_type: SIGNATURE_TYPE_AUTH_HEADER (default),
  60. SIGNATURE_TYPE_QUERY or SIGNATURE_TYPE_BODY
  61. depending on where you want to embed the oauth
  62. credentials.
  63. :param rsa_key: RSA key used with SIGNATURE_RSA.
  64. :param verifier: Verifier used when obtaining an access token.
  65. :param realm: Realm (scope) to which access is being requested.
  66. :param encoding: If you provide non-unicode input you may use this
  67. to have oauthlib automatically convert.
  68. :param decoding: If you wish that the returned uri, headers and body
  69. from sign be encoded back from unicode, then set
  70. decoding to your preferred encoding, i.e. utf-8.
  71. :param nonce: Use this nonce instead of generating one. (Mainly for testing)
  72. :param timestamp: Use this timestamp instead of using current. (Mainly for testing)
  73. """
  74. # Convert to unicode using encoding if given, else assume unicode
  75. encode = lambda x: to_unicode(x, encoding) if encoding else x
  76. self.client_key = encode(client_key)
  77. self.client_secret = encode(client_secret)
  78. self.resource_owner_key = encode(resource_owner_key)
  79. self.resource_owner_secret = encode(resource_owner_secret)
  80. self.signature_method = encode(signature_method)
  81. self.signature_type = encode(signature_type)
  82. self.callback_uri = encode(callback_uri)
  83. self.rsa_key = encode(rsa_key)
  84. self.verifier = encode(verifier)
  85. self.realm = encode(realm)
  86. self.encoding = encode(encoding)
  87. self.decoding = encode(decoding)
  88. self.nonce = encode(nonce)
  89. self.timestamp = encode(timestamp)
  90. def __repr__(self):
  91. attrs = vars(self).copy()
  92. attrs['client_secret'] = '****' if attrs['client_secret'] else None
  93. attrs['rsa_key'] = '****' if attrs['rsa_key'] else None
  94. attrs[
  95. 'resource_owner_secret'] = '****' if attrs['resource_owner_secret'] else None
  96. attribute_str = ', '.join('%s=%s' % (k, v) for k, v in attrs.items())
  97. return '<%s %s>' % (self.__class__.__name__, attribute_str)
  98. def get_oauth_signature(self, request):
  99. """Get an OAuth signature to be used in signing a request
  100. To satisfy `section 3.4.1.2`_ item 2, if the request argument's
  101. headers dict attribute contains a Host item, its value will
  102. replace any netloc part of the request argument's uri attribute
  103. value.
  104. .. _`section 3.4.1.2`: http://tools.ietf.org/html/rfc5849#section-3.4.1.2
  105. """
  106. if self.signature_method == SIGNATURE_PLAINTEXT:
  107. # fast-path
  108. return signature.sign_plaintext(self.client_secret,
  109. self.resource_owner_secret)
  110. uri, headers, body = self._render(request)
  111. collected_params = signature.collect_parameters(
  112. uri_query=urlparse.urlparse(uri).query,
  113. body=body,
  114. headers=headers)
  115. log.debug("Collected params: {0}".format(collected_params))
  116. normalized_params = signature.normalize_parameters(collected_params)
  117. normalized_uri = signature.normalize_base_string_uri(uri,
  118. headers.get('Host', None))
  119. log.debug("Normalized params: {0}".format(normalized_params))
  120. log.debug("Normalized URI: {0}".format(normalized_uri))
  121. base_string = signature.construct_base_string(request.http_method,
  122. normalized_uri, normalized_params)
  123. log.debug("Base signing string: {0}".format(base_string))
  124. if self.signature_method not in self.SIGNATURE_METHODS:
  125. raise ValueError('Invalid signature method.')
  126. sig = self.SIGNATURE_METHODS[self.signature_method](base_string, self)
  127. log.debug("Signature: {0}".format(sig))
  128. return sig
  129. def get_oauth_params(self, request):
  130. """Get the basic OAuth parameters to be used in generating a signature.
  131. """
  132. nonce = (generate_nonce()
  133. if self.nonce is None else self.nonce)
  134. timestamp = (generate_timestamp()
  135. if self.timestamp is None else self.timestamp)
  136. params = [
  137. ('oauth_nonce', nonce),
  138. ('oauth_timestamp', timestamp),
  139. ('oauth_version', '1.0'),
  140. ('oauth_signature_method', self.signature_method),
  141. ('oauth_consumer_key', self.client_key),
  142. ]
  143. if self.resource_owner_key:
  144. params.append(('oauth_token', self.resource_owner_key))
  145. if self.callback_uri:
  146. params.append(('oauth_callback', self.callback_uri))
  147. if self.verifier:
  148. params.append(('oauth_verifier', self.verifier))
  149. # providing body hash for requests other than x-www-form-urlencoded
  150. # as described in http://oauth.googlecode.com/svn/spec/ext/body_hash/1.0/oauth-bodyhash.html
  151. # 4.1.1. When to include the body hash
  152. # * [...] MUST NOT include an oauth_body_hash parameter on requests with form-encoded request bodies
  153. # * [...] SHOULD include the oauth_body_hash parameter on all other requests.
  154. content_type = request.headers.get('Content-Type', None)
  155. content_type_eligible = content_type and content_type.find('application/x-www-form-urlencoded') < 0
  156. if request.body is not None and content_type_eligible:
  157. params.append(('oauth_body_hash', base64.b64encode(hashlib.sha1(request.body.encode('utf-8')).digest()).decode('utf-8')))
  158. return params
  159. def _render(self, request, formencode=False, realm=None):
  160. """Render a signed request according to signature type
  161. Returns a 3-tuple containing the request URI, headers, and body.
  162. If the formencode argument is True and the body contains parameters, it
  163. is escaped and returned as a valid formencoded string.
  164. """
  165. # TODO what if there are body params on a header-type auth?
  166. # TODO what if there are query params on a body-type auth?
  167. uri, headers, body = request.uri, request.headers, request.body
  168. # TODO: right now these prepare_* methods are very narrow in scope--they
  169. # only affect their little thing. In some cases (for example, with
  170. # header auth) it might be advantageous to allow these methods to touch
  171. # other parts of the request, like the headers—so the prepare_headers
  172. # method could also set the Content-Type header to x-www-form-urlencoded
  173. # like the spec requires. This would be a fundamental change though, and
  174. # I'm not sure how I feel about it.
  175. if self.signature_type == SIGNATURE_TYPE_AUTH_HEADER:
  176. headers = parameters.prepare_headers(
  177. request.oauth_params, request.headers, realm=realm)
  178. elif self.signature_type == SIGNATURE_TYPE_BODY and request.decoded_body is not None:
  179. body = parameters.prepare_form_encoded_body(
  180. request.oauth_params, request.decoded_body)
  181. if formencode:
  182. body = urlencode(body)
  183. headers['Content-Type'] = 'application/x-www-form-urlencoded'
  184. elif self.signature_type == SIGNATURE_TYPE_QUERY:
  185. uri = parameters.prepare_request_uri_query(
  186. request.oauth_params, request.uri)
  187. else:
  188. raise ValueError('Unknown signature type specified.')
  189. return uri, headers, body
  190. def sign(self, uri, http_method='GET', body=None, headers=None, realm=None):
  191. """Sign a request
  192. Signs an HTTP request with the specified parts.
  193. Returns a 3-tuple of the signed request's URI, headers, and body.
  194. Note that http_method is not returned as it is unaffected by the OAuth
  195. signing process. Also worth noting is that duplicate parameters
  196. will be included in the signature, regardless of where they are
  197. specified (query, body).
  198. The body argument may be a dict, a list of 2-tuples, or a formencoded
  199. string. The Content-Type header must be 'application/x-www-form-urlencoded'
  200. if it is present.
  201. If the body argument is not one of the above, it will be returned
  202. verbatim as it is unaffected by the OAuth signing process. Attempting to
  203. sign a request with non-formencoded data using the OAuth body signature
  204. type is invalid and will raise an exception.
  205. If the body does contain parameters, it will be returned as a properly-
  206. formatted formencoded string.
  207. Body may not be included if the http_method is either GET or HEAD as
  208. this changes the semantic meaning of the request.
  209. All string data MUST be unicode or be encoded with the same encoding
  210. scheme supplied to the Client constructor, default utf-8. This includes
  211. strings inside body dicts, for example.
  212. """
  213. # normalize request data
  214. request = Request(uri, http_method, body, headers,
  215. encoding=self.encoding)
  216. # sanity check
  217. content_type = request.headers.get('Content-Type', None)
  218. multipart = content_type and content_type.startswith('multipart/')
  219. should_have_params = content_type == CONTENT_TYPE_FORM_URLENCODED
  220. has_params = request.decoded_body is not None
  221. # 3.4.1.3.1. Parameter Sources
  222. # [Parameters are collected from the HTTP request entity-body, but only
  223. # if [...]:
  224. # * The entity-body is single-part.
  225. if multipart and has_params:
  226. raise ValueError(
  227. "Headers indicate a multipart body but body contains parameters.")
  228. # * The entity-body follows the encoding requirements of the
  229. # "application/x-www-form-urlencoded" content-type as defined by
  230. # [W3C.REC-html40-19980424].
  231. elif should_have_params and not has_params:
  232. raise ValueError(
  233. "Headers indicate a formencoded body but body was not decodable.")
  234. # * The HTTP request entity-header includes the "Content-Type"
  235. # header field set to "application/x-www-form-urlencoded".
  236. elif not should_have_params and has_params:
  237. raise ValueError(
  238. "Body contains parameters but Content-Type header was {0} "
  239. "instead of {1}".format(content_type or "not set",
  240. CONTENT_TYPE_FORM_URLENCODED))
  241. # 3.5.2. Form-Encoded Body
  242. # Protocol parameters can be transmitted in the HTTP request entity-
  243. # body, but only if the following REQUIRED conditions are met:
  244. # o The entity-body is single-part.
  245. # o The entity-body follows the encoding requirements of the
  246. # "application/x-www-form-urlencoded" content-type as defined by
  247. # [W3C.REC-html40-19980424].
  248. # o The HTTP request entity-header includes the "Content-Type" header
  249. # field set to "application/x-www-form-urlencoded".
  250. elif self.signature_type == SIGNATURE_TYPE_BODY and not (
  251. should_have_params and has_params and not multipart):
  252. raise ValueError(
  253. 'Body signatures may only be used with form-urlencoded content')
  254. # We amend http://tools.ietf.org/html/rfc5849#section-3.4.1.3.1
  255. # with the clause that parameters from body should only be included
  256. # in non GET or HEAD requests. Extracting the request body parameters
  257. # and including them in the signature base string would give semantic
  258. # meaning to the body, which it should not have according to the
  259. # HTTP 1.1 spec.
  260. elif http_method.upper() in ('GET', 'HEAD') and has_params:
  261. raise ValueError('GET/HEAD requests should not include body.')
  262. # generate the basic OAuth parameters
  263. request.oauth_params = self.get_oauth_params(request)
  264. # generate the signature
  265. request.oauth_params.append(
  266. ('oauth_signature', self.get_oauth_signature(request)))
  267. # render the signed request and return it
  268. uri, headers, body = self._render(request, formencode=True,
  269. realm=(realm or self.realm))
  270. if self.decoding:
  271. log.debug('Encoding URI, headers and body to %s.', self.decoding)
  272. uri = uri.encode(self.decoding)
  273. body = body.encode(self.decoding) if body else body
  274. new_headers = {}
  275. for k, v in headers.items():
  276. new_headers[k.encode(self.decoding)] = v.encode(self.decoding)
  277. headers = new_headers
  278. return uri, headers, body