common.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  1. # -*- coding: utf-8 -*-
  2. """
  3. oauthlib.common
  4. ~~~~~~~~~~~~~~
  5. This module provides data structures and utilities common
  6. to all implementations of OAuth.
  7. """
  8. from __future__ import absolute_import, unicode_literals
  9. import collections
  10. import datetime
  11. import logging
  12. import random
  13. import re
  14. import sys
  15. import time
  16. try:
  17. from urllib import quote as _quote
  18. from urllib import unquote as _unquote
  19. from urllib import urlencode as _urlencode
  20. except ImportError:
  21. from urllib.parse import quote as _quote
  22. from urllib.parse import unquote as _unquote
  23. from urllib.parse import urlencode as _urlencode
  24. try:
  25. import urlparse
  26. except ImportError:
  27. import urllib.parse as urlparse
  28. UNICODE_ASCII_CHARACTER_SET = ('abcdefghijklmnopqrstuvwxyz'
  29. 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  30. '0123456789')
  31. CLIENT_ID_CHARACTER_SET = (r' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMN'
  32. 'OPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}')
  33. SANITIZE_PATTERN = re.compile(r'([^&;]*(?:password|token)[^=]*=)[^&;]+', re.IGNORECASE)
  34. INVALID_HEX_PATTERN = re.compile(r'%[^0-9A-Fa-f]|%[0-9A-Fa-f][^0-9A-Fa-f]')
  35. always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  36. 'abcdefghijklmnopqrstuvwxyz'
  37. '0123456789' '_.-')
  38. log = logging.getLogger('oauthlib')
  39. PY3 = sys.version_info[0] == 3
  40. if PY3:
  41. unicode_type = str
  42. bytes_type = bytes
  43. else:
  44. unicode_type = unicode
  45. bytes_type = str
  46. # 'safe' must be bytes (Python 2.6 requires bytes, other versions allow either)
  47. def quote(s, safe=b'/'):
  48. s = s.encode('utf-8') if isinstance(s, unicode_type) else s
  49. s = _quote(s, safe)
  50. # PY3 always returns unicode. PY2 may return either, depending on whether
  51. # it had to modify the string.
  52. if isinstance(s, bytes_type):
  53. s = s.decode('utf-8')
  54. return s
  55. def unquote(s):
  56. s = _unquote(s)
  57. # PY3 always returns unicode. PY2 seems to always return what you give it,
  58. # which differs from quote's behavior. Just to be safe, make sure it is
  59. # unicode before we return.
  60. if isinstance(s, bytes_type):
  61. s = s.decode('utf-8')
  62. return s
  63. def urlencode(params):
  64. utf8_params = encode_params_utf8(params)
  65. urlencoded = _urlencode(utf8_params)
  66. if isinstance(urlencoded, unicode_type): # PY3 returns unicode
  67. return urlencoded
  68. else:
  69. return urlencoded.decode("utf-8")
  70. def encode_params_utf8(params):
  71. """Ensures that all parameters in a list of 2-element tuples are encoded to
  72. bytestrings using UTF-8
  73. """
  74. encoded = []
  75. for k, v in params:
  76. encoded.append((
  77. k.encode('utf-8') if isinstance(k, unicode_type) else k,
  78. v.encode('utf-8') if isinstance(v, unicode_type) else v))
  79. return encoded
  80. def decode_params_utf8(params):
  81. """Ensures that all parameters in a list of 2-element tuples are decoded to
  82. unicode using UTF-8.
  83. """
  84. decoded = []
  85. for k, v in params:
  86. decoded.append((
  87. k.decode('utf-8') if isinstance(k, bytes_type) else k,
  88. v.decode('utf-8') if isinstance(v, bytes_type) else v))
  89. return decoded
  90. urlencoded = set(always_safe) | set('=&;:%+~,*@!()/?')
  91. def urldecode(query):
  92. """Decode a query string in x-www-form-urlencoded format into a sequence
  93. of two-element tuples.
  94. Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce
  95. correct formatting of the query string by validation. If validation fails
  96. a ValueError will be raised. urllib.parse_qsl will only raise errors if
  97. any of name-value pairs omits the equals sign.
  98. """
  99. # Check if query contains invalid characters
  100. if query and not set(query) <= urlencoded:
  101. error = ("Error trying to decode a non urlencoded string. "
  102. "Found invalid characters: %s "
  103. "in the string: '%s'. "
  104. "Please ensure the request/response body is "
  105. "x-www-form-urlencoded.")
  106. raise ValueError(error % (set(query) - urlencoded, query))
  107. # Check for correctly hex encoded values using a regular expression
  108. # All encoded values begin with % followed by two hex characters
  109. # correct = %00, %A0, %0A, %FF
  110. # invalid = %G0, %5H, %PO
  111. if INVALID_HEX_PATTERN.search(query):
  112. raise ValueError('Invalid hex encoding in query string.')
  113. # We encode to utf-8 prior to parsing because parse_qsl behaves
  114. # differently on unicode input in python 2 and 3.
  115. # Python 2.7
  116. # >>> urlparse.parse_qsl(u'%E5%95%A6%E5%95%A6')
  117. # u'\xe5\x95\xa6\xe5\x95\xa6'
  118. # Python 2.7, non unicode input gives the same
  119. # >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6')
  120. # '\xe5\x95\xa6\xe5\x95\xa6'
  121. # but now we can decode it to unicode
  122. # >>> urlparse.parse_qsl('%E5%95%A6%E5%95%A6').decode('utf-8')
  123. # u'\u5566\u5566'
  124. # Python 3.3 however
  125. # >>> urllib.parse.parse_qsl(u'%E5%95%A6%E5%95%A6')
  126. # u'\u5566\u5566'
  127. query = query.encode(
  128. 'utf-8') if not PY3 and isinstance(query, unicode_type) else query
  129. # We want to allow queries such as "c2" whereas urlparse.parse_qsl
  130. # with the strict_parsing flag will not.
  131. params = urlparse.parse_qsl(query, keep_blank_values=True)
  132. # unicode all the things
  133. return decode_params_utf8(params)
  134. def extract_params(raw):
  135. """Extract parameters and return them as a list of 2-tuples.
  136. Will successfully extract parameters from urlencoded query strings,
  137. dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an
  138. empty list of parameters. Any other input will result in a return
  139. value of None.
  140. """
  141. if isinstance(raw, bytes_type) or isinstance(raw, unicode_type):
  142. try:
  143. params = urldecode(raw)
  144. except ValueError:
  145. params = None
  146. elif hasattr(raw, '__iter__'):
  147. try:
  148. dict(raw)
  149. except ValueError:
  150. params = None
  151. except TypeError:
  152. params = None
  153. else:
  154. params = list(raw.items() if isinstance(raw, dict) else raw)
  155. params = decode_params_utf8(params)
  156. else:
  157. params = None
  158. return params
  159. def generate_nonce():
  160. """Generate pseudorandom nonce that is unlikely to repeat.
  161. Per `section 3.3`_ of the OAuth 1 RFC 5849 spec.
  162. Per `section 3.2.1`_ of the MAC Access Authentication spec.
  163. A random 64-bit number is appended to the epoch timestamp for both
  164. randomness and to decrease the likelihood of collisions.
  165. .. _`section 3.2.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-3.2.1
  166. .. _`section 3.3`: http://tools.ietf.org/html/rfc5849#section-3.3
  167. """
  168. return unicode_type(unicode_type(random.getrandbits(64)) + generate_timestamp())
  169. def generate_timestamp():
  170. """Get seconds since epoch (UTC).
  171. Per `section 3.3`_ of the OAuth 1 RFC 5849 spec.
  172. Per `section 3.2.1`_ of the MAC Access Authentication spec.
  173. .. _`section 3.2.1`: http://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-3.2.1
  174. .. _`section 3.3`: http://tools.ietf.org/html/rfc5849#section-3.3
  175. """
  176. return unicode_type(int(time.time()))
  177. def generate_token(length=30, chars=UNICODE_ASCII_CHARACTER_SET):
  178. """Generates a non-guessable OAuth token
  179. OAuth (1 and 2) does not specify the format of tokens except that they
  180. should be strings of random characters. Tokens should not be guessable
  181. and entropy when generating the random characters is important. Which is
  182. why SystemRandom is used instead of the default random.choice method.
  183. """
  184. rand = random.SystemRandom()
  185. return ''.join(rand.choice(chars) for x in range(length))
  186. def generate_signed_token(private_pem, request):
  187. import jwt
  188. now = datetime.datetime.utcnow()
  189. claims = {
  190. 'scope': request.scope,
  191. 'exp': now + datetime.timedelta(seconds=request.expires_in)
  192. }
  193. claims.update(request.claims)
  194. token = jwt.encode(claims, private_pem, 'RS256')
  195. token = to_unicode(token, "UTF-8")
  196. return token
  197. def verify_signed_token(public_pem, token):
  198. import jwt
  199. return jwt.decode(token, public_pem, algorithms=['RS256'])
  200. def generate_client_id(length=30, chars=CLIENT_ID_CHARACTER_SET):
  201. """Generates an OAuth client_id
  202. OAuth 2 specify the format of client_id in
  203. http://tools.ietf.org/html/rfc6749#appendix-A.
  204. """
  205. return generate_token(length, chars)
  206. def add_params_to_qs(query, params):
  207. """Extend a query with a list of two-tuples."""
  208. if isinstance(params, dict):
  209. params = params.items()
  210. queryparams = urlparse.parse_qsl(query, keep_blank_values=True)
  211. queryparams.extend(params)
  212. return urlencode(queryparams)
  213. def add_params_to_uri(uri, params, fragment=False):
  214. """Add a list of two-tuples to the uri query components."""
  215. sch, net, path, par, query, fra = urlparse.urlparse(uri)
  216. if fragment:
  217. fra = add_params_to_qs(fra, params)
  218. else:
  219. query = add_params_to_qs(query, params)
  220. return urlparse.urlunparse((sch, net, path, par, query, fra))
  221. def safe_string_equals(a, b):
  222. """ Near-constant time string comparison.
  223. Used in order to avoid timing attacks on sensitive information such
  224. as secret keys during request verification (`rootLabs`_).
  225. .. _`rootLabs`: http://rdist.root.org/2010/01/07/timing-independent-array-comparison/
  226. """
  227. if len(a) != len(b):
  228. return False
  229. result = 0
  230. for x, y in zip(a, b):
  231. result |= ord(x) ^ ord(y)
  232. return result == 0
  233. def to_unicode(data, encoding='UTF-8'):
  234. """Convert a number of different types of objects to unicode."""
  235. if isinstance(data, unicode_type):
  236. return data
  237. if isinstance(data, bytes_type):
  238. return unicode_type(data, encoding=encoding)
  239. if hasattr(data, '__iter__'):
  240. try:
  241. dict(data)
  242. except TypeError:
  243. pass
  244. except ValueError:
  245. # Assume it's a one dimensional data structure
  246. return (to_unicode(i, encoding) for i in data)
  247. else:
  248. # We support 2.6 which lacks dict comprehensions
  249. if hasattr(data, 'items'):
  250. data = data.items()
  251. return dict(((to_unicode(k, encoding), to_unicode(v, encoding)) for k, v in data))
  252. return data
  253. class CaseInsensitiveDict(dict):
  254. """Basic case insensitive dict with strings only keys."""
  255. proxy = {}
  256. def __init__(self, data):
  257. self.proxy = dict((k.lower(), k) for k in data)
  258. for k in data:
  259. self[k] = data[k]
  260. def __contains__(self, k):
  261. return k.lower() in self.proxy
  262. def __delitem__(self, k):
  263. key = self.proxy[k.lower()]
  264. super(CaseInsensitiveDict, self).__delitem__(key)
  265. del self.proxy[k.lower()]
  266. def __getitem__(self, k):
  267. key = self.proxy[k.lower()]
  268. return super(CaseInsensitiveDict, self).__getitem__(key)
  269. def get(self, k, default=None):
  270. return self[k] if k in self else default
  271. def __setitem__(self, k, v):
  272. super(CaseInsensitiveDict, self).__setitem__(k, v)
  273. self.proxy[k.lower()] = k
  274. class Request(object):
  275. """A malleable representation of a signable HTTP request.
  276. Body argument may contain any data, but parameters will only be decoded if
  277. they are one of:
  278. * urlencoded query string
  279. * dict
  280. * list of 2-tuples
  281. Anything else will be treated as raw body data to be passed through
  282. unmolested.
  283. """
  284. def __init__(self, uri, http_method='GET', body=None, headers=None,
  285. encoding='utf-8'):
  286. # Convert to unicode using encoding if given, else assume unicode
  287. encode = lambda x: to_unicode(x, encoding) if encoding else x
  288. self.uri = encode(uri)
  289. self.http_method = encode(http_method)
  290. self.headers = CaseInsensitiveDict(encode(headers or {}))
  291. self.body = encode(body)
  292. self.decoded_body = extract_params(self.body)
  293. self.oauth_params = []
  294. self.validator_log = {}
  295. self._params = {
  296. "access_token": None,
  297. "client": None,
  298. "client_id": None,
  299. "client_secret": None,
  300. "code": None,
  301. "extra_credentials": None,
  302. "grant_type": None,
  303. "redirect_uri": None,
  304. "refresh_token": None,
  305. "request_token": None,
  306. "response_type": None,
  307. "scope": None,
  308. "scopes": None,
  309. "state": None,
  310. "token": None,
  311. "user": None,
  312. "token_type_hint": None,
  313. # OpenID Connect
  314. "response_mode": None,
  315. "nonce": None,
  316. "display": None,
  317. "prompt": None,
  318. "claims": None,
  319. "max_age": None,
  320. "ui_locales": None,
  321. "id_token_hint": None,
  322. "login_hint": None,
  323. "acr_values": None
  324. }
  325. self._params.update(dict(urldecode(self.uri_query)))
  326. self._params.update(dict(self.decoded_body or []))
  327. self._params.update(self.headers)
  328. def __getattr__(self, name):
  329. if name in self._params:
  330. return self._params[name]
  331. else:
  332. raise AttributeError(name)
  333. def __repr__(self):
  334. body = self.body
  335. headers = self.headers.copy()
  336. if body:
  337. body = SANITIZE_PATTERN.sub('\1<SANITIZED>', str(body))
  338. if 'Authorization' in headers:
  339. headers['Authorization'] = '<SANITIZED>'
  340. return '<oauthlib.Request url="%s", http_method="%s", headers="%s", body="%s">' % (
  341. self.uri, self.http_method, headers, body)
  342. @property
  343. def uri_query(self):
  344. return urlparse.urlparse(self.uri).query
  345. @property
  346. def uri_query_params(self):
  347. if not self.uri_query:
  348. return []
  349. return urlparse.parse_qsl(self.uri_query, keep_blank_values=True,
  350. strict_parsing=True)
  351. @property
  352. def duplicate_params(self):
  353. seen_keys = collections.defaultdict(int)
  354. all_keys = (p[0]
  355. for p in (self.decoded_body or []) + self.uri_query_params)
  356. for k in all_keys:
  357. seen_keys[k] += 1
  358. return [k for k, c in seen_keys.items() if c > 1]