Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.11/site-packages/oauthlib/common.py: 36%
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
Shortcuts on this page
r m x toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1"""
2oauthlib.common
3~~~~~~~~~~~~~~
5This module provides data structures and utilities common
6to all implementations of OAuth.
7"""
8import collections
9import datetime
10import hashlib
11import hmac
12import logging
13import os
14import re
15import secrets
16import time
17import urllib.parse as urlparse
18from urllib.parse import (
19 quote as _quote, unquote as _unquote, urlencode as _urlencode,
20)
22from . import get_debug
24try:
25 from secrets import SystemRandom, randbits
26except ImportError:
27 from random import SystemRandom, getrandbits as randbits
29UNICODE_ASCII_CHARACTER_SET = ('abcdefghijklmnopqrstuvwxyz'
30 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
31 '0123456789')
33CLIENT_ID_CHARACTER_SET = (r' !"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMN'
34 'OPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}')
36SANITIZE_KEY_PATTERN = re.compile(r'password|token', re.IGNORECASE)
37INVALID_HEX_PATTERN = re.compile(r'%[^0-9A-Fa-f]|%[0-9A-Fa-f][^0-9A-Fa-f]')
39always_safe = ('ABCDEFGHIJKLMNOPQRSTUVWXYZ'
40 'abcdefghijklmnopqrstuvwxyz'
41 '0123456789_.-')
43log = logging.getLogger('oauthlib')
45LOG_SAFE_PREFIX_LENGTH = 4
46LOG_SAFE_HASH_LENGTH = 12
48LOG_SAFE_KEY = os.environ.get('OAUTHLIB_LOG_SAFE_KEY') or secrets.token_bytes(32)
51def set_log_safe_key(key):
52 """Set the key used by log_safe to fingerprint secrets in log output.
54 Set a stable key to make log_safe fingerprints reproducible across
55 processes and restarts, so log lines can be correlated against known
56 values. By default a random per-process key is used, which prevents
57 offline brute-force of low-entropy values from log output but only
58 allows correlation within a single process run.
60 Passing None resets the key to a fresh random per-process key.
61 """
62 global LOG_SAFE_KEY # noqa: PLW0603
63 LOG_SAFE_KEY = key if key is not None else secrets.token_bytes(32)
66def _get_log_safe_key():
67 """Return the current log_safe key, encoded to bytes for hmac.new()."""
68 key = LOG_SAFE_KEY
69 if isinstance(key, str):
70 key = key.encode('utf-8')
71 return key
74def log_safe(value):
75 """Return a non-reversible representation of a secret suitable for logging.
77 The returned string contains a short prefix (for correlation with other
78 log lines or known values) plus a truncated HMAC-SHA256 of the value
79 (for exact matching of the same secret across log lines), never exposing
80 enough of the secret to be replayed. The HMAC is keyed with LOG_SAFE_KEY:
81 with a stable key the fingerprints are reproducible, with the default
82 random per-process key they are not computable outside the process.
84 Mappings are returned as a new dict with every value passed through
85 ``log_safe``, so structured details (e.g. token field names) remain
86 visible while their values are sanitized.
87 """
88 if isinstance(value, dict):
89 return {k: log_safe(v) for k, v in value.items()}
90 if isinstance(value, (list, tuple)):
91 return [log_safe(v) for v in value]
92 if value is None:
93 return None
94 value = str(value)
95 digest = hmac.new(_get_log_safe_key(), value.encode('utf-8'), hashlib.sha256).hexdigest()[:LOG_SAFE_HASH_LENGTH]
96 prefix = value[:LOG_SAFE_PREFIX_LENGTH] if len(value) > LOG_SAFE_PREFIX_LENGTH else value
97 return '%s..%s' % (prefix, digest)
100# 'safe' must be bytes (Python 2.6 requires bytes, other versions allow either)
101def quote(s, safe=b'/'):
102 s = s.encode('utf-8') if isinstance(s, str) else s
103 s = _quote(s, safe)
104 # PY3 always returns unicode. PY2 may return either, depending on whether
105 # it had to modify the string.
106 if isinstance(s, bytes):
107 s = s.decode('utf-8')
108 return s
111def unquote(s):
112 s = _unquote(s)
113 # PY3 always returns unicode. PY2 seems to always return what you give it,
114 # which differs from quote's behavior. Just to be safe, make sure it is
115 # unicode before we return.
116 if isinstance(s, bytes):
117 s = s.decode('utf-8')
118 return s
121def urlencode(params):
122 utf8_params = encode_params_utf8(params)
123 urlencoded = _urlencode(utf8_params)
124 if isinstance(urlencoded, str):
125 return urlencoded
126 else:
127 return urlencoded.decode("utf-8")
130def encode_params_utf8(params):
131 """Ensures that all parameters in a list of 2-element tuples are encoded to
132 bytestrings using UTF-8
133 """
134 encoded = []
135 for k, v in params:
136 encoded.append((
137 k.encode('utf-8') if isinstance(k, str) else k,
138 v.encode('utf-8') if isinstance(v, str) else v))
139 return encoded
142def decode_params_utf8(params):
143 """Ensures that all parameters in a list of 2-element tuples are decoded to
144 unicode using UTF-8.
145 """
146 decoded = []
147 for k, v in params:
148 decoded.append((
149 k.decode('utf-8') if isinstance(k, bytes) else k,
150 v.decode('utf-8') if isinstance(v, bytes) else v))
151 return decoded
154urlencoded = set(always_safe) | set('=&;:%+~,*@!()/?\'$')
157def urldecode(query):
158 """Decode a query string in x-www-form-urlencoded format into a sequence
159 of two-element tuples.
161 Unlike urlparse.parse_qsl(..., strict_parsing=True) urldecode will enforce
162 correct formatting of the query string by validation. If validation fails
163 a ValueError will be raised. urllib.parse_qsl will only raise errors if
164 any of name-value pairs omits the equals sign.
165 """
166 # Check if query contains invalid characters
167 if query and not set(query) <= urlencoded:
168 error = ("Error trying to decode a non urlencoded string. "
169 "Found invalid characters: %s "
170 "in the string: '%s'. "
171 "Please ensure the request/response body is "
172 "x-www-form-urlencoded.")
173 raise ValueError(error % (set(query) - urlencoded, query))
175 # Check for correctly hex encoded values using a regular expression
176 # All encoded values begin with % followed by two hex characters
177 # correct = %00, %A0, %0A, %FF
178 # invalid = %G0, %5H, %PO
179 if INVALID_HEX_PATTERN.search(query):
180 raise ValueError('Invalid hex encoding in query string.')
182 # We want to allow queries such as "c2" whereas urlparse.parse_qsl
183 # with the strict_parsing flag will not.
184 params = urlparse.parse_qsl(query, keep_blank_values=True)
186 # unicode all the things
187 return decode_params_utf8(params)
190def extract_params(raw):
191 """Extract parameters and return them as a list of 2-tuples.
193 Will successfully extract parameters from urlencoded query strings,
194 dicts, or lists of 2-tuples. Empty strings/dicts/lists will return an
195 empty list of parameters. Any other input will result in a return
196 value of None.
197 """
198 if isinstance(raw, (bytes, str)):
199 try:
200 params = urldecode(raw)
201 except ValueError:
202 params = None
203 elif hasattr(raw, '__iter__'):
204 try:
205 dict(raw)
206 except ValueError:
207 params = None
208 except TypeError:
209 params = None
210 else:
211 params = list(raw.items() if isinstance(raw, dict) else raw)
212 params = decode_params_utf8(params)
213 else:
214 params = None
216 return params
219def generate_nonce():
220 """Generate pseudorandom nonce that is unlikely to repeat.
222 Per `section 3.3`_ of the OAuth 1 RFC 5849 spec.
223 Per `section 3.2.1`_ of the MAC Access Authentication spec.
225 RFC 5849 section 3.3 requires the nonce to be unique "across all requests
226 with the same timestamp, client credentials, and token combinations". The
227 ``oauth_timestamp`` parameter is sent separately, so embedding the epoch
228 time in the nonce does nothing to distinguish requests that share a
229 timestamp: within a given second the collision resistance comes entirely
230 from the random component. This uses 96 bits drawn from the system CSPRNG
231 (up from the previous 64 bits appended to the timestamp), which keeps the
232 birthday-bound collision probability negligible while the decimal encoding
233 stays within the default nonce length limits.
235 .. _`section 3.2.1`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-3.2.1
236 .. _`section 3.3`: https://tools.ietf.org/html/rfc5849#section-3.3
237 """
238 return str(randbits(96))
241def generate_timestamp():
242 """Get seconds since epoch (UTC).
244 Per `section 3.3`_ of the OAuth 1 RFC 5849 spec.
245 Per `section 3.2.1`_ of the MAC Access Authentication spec.
247 .. _`section 3.2.1`: https://tools.ietf.org/html/draft-ietf-oauth-v2-http-mac-01#section-3.2.1
248 .. _`section 3.3`: https://tools.ietf.org/html/rfc5849#section-3.3
249 """
250 return str(int(time.time()))
253def generate_token(length=30, chars=UNICODE_ASCII_CHARACTER_SET):
254 """Generates a non-guessable OAuth token
256 OAuth (1 and 2) does not specify the format of tokens except that they
257 should be strings of random characters. Tokens should not be guessable
258 and entropy when generating the random characters is important. Which is
259 why SystemRandom is used instead of the default random.choice method.
260 """
261 rand = SystemRandom()
262 return ''.join(rand.choice(chars) for x in range(length))
265def generate_signed_token(private_pem, request):
266 import jwt # noqa: PLC0415
268 now = datetime.datetime.utcnow()
270 claims = {
271 'scope': request.scope,
272 'exp': now + datetime.timedelta(seconds=request.expires_in)
273 }
275 claims.update(request.claims)
277 token = jwt.encode(claims, private_pem, 'RS256')
278 token = to_unicode(token, "UTF-8")
280 return token
283def verify_signed_token(public_pem, token):
284 import jwt # noqa: PLC0415
286 return jwt.decode(token, public_pem, algorithms=['RS256'])
289def generate_client_id(length=30, chars=CLIENT_ID_CHARACTER_SET):
290 """Generates an OAuth client_id
292 OAuth 2 specify the format of client_id in
293 https://tools.ietf.org/html/rfc6749#appendix-A.
294 """
295 return generate_token(length, chars)
298def add_params_to_qs(query, params):
299 """Extend a query with a list of two-tuples."""
300 if isinstance(params, dict):
301 params = params.items()
302 queryparams = urlparse.parse_qsl(query, keep_blank_values=True)
303 queryparams.extend(params)
304 return urlencode(queryparams)
307def add_params_to_uri(uri, params, fragment=False):
308 """Add a list of two-tuples to the uri query components."""
309 sch, net, path, par, query, fra = urlparse.urlparse(uri)
310 if fragment:
311 fra = add_params_to_qs(fra, params)
312 else:
313 query = add_params_to_qs(query, params)
314 return urlparse.urlunparse((sch, net, path, par, query, fra))
317def safe_string_equals(a, b):
318 """ Near-constant time string comparison.
320 Used in order to avoid timing attacks on sensitive information such
321 as secret keys during request verification (`rootLabs`_).
323 Both operands are digested with SHA-256 before being compared with
324 :func:`hmac.compare_digest`. Comparing fixed-length digests removes
325 any dependency of the comparison's timing (and control flow) on the
326 length or content of either operand, so callers do not leak the
327 length of server-side secrets such as OAuth1 PLAINTEXT signatures.
329 .. _`rootLabs`: http://rdist.root.org/2010/01/07/timing-independent-array-comparison/
331 """
332 if isinstance(a, str):
333 a = a.encode('utf-8')
334 if isinstance(b, str):
335 b = b.encode('utf-8')
336 a_digest = hashlib.sha256(a).digest()
337 b_digest = hashlib.sha256(b).digest()
338 return hmac.compare_digest(a_digest, b_digest)
341def check_http_header_value(name, value):
342 """Validate that a value is safe to embed in an HTTP header field value.
344 Prevents header injection by rejecting characters that allow the value
345 to break out of its header field, per RFC 9110 section 5.5:
347 - CR and LF characters, which enable header splitting/injection;
348 - other control characters (CTLs, including NUL), which may corrupt
349 or terminate parsing of the header by downstream intermediaries;
350 - double quotes, which allow a quoted-string parameter in a header
351 value (such as the MAC Authorization header) to break out and
352 inject arbitrary parameters;
353 - non-ASCII characters, which are mangled inconsistently by proxies
354 and gateways and may be re-interpreted as control characters.
356 :param name: Name of the parameter, used in error messages.
357 :param value: Candidate header value. ``None`` is allowed and ignored.
358 :raises ValueError: if the value contains unsafe characters.
359 """
360 if value is None:
361 return
362 if not isinstance(value, str):
363 raise ValueError('%s must be a string' % name)
364 for char in value:
365 if char in '\r\n':
366 raise ValueError('%s must not contain CR or LF characters' % name)
367 if ord(char) < 0x20 or ord(char) == 0x7f:
368 raise ValueError('%s must not contain control characters' % name)
369 if char == '"':
370 raise ValueError('%s must not contain double quotes' % name)
371 if ord(char) > 0x7e:
372 raise ValueError('%s must contain ASCII characters only' % name)
375def to_unicode(data, encoding='UTF-8'):
376 """Convert a number of different types of objects to unicode."""
377 if isinstance(data, str):
378 return data
380 if isinstance(data, bytes):
381 return str(data, encoding=encoding)
383 if hasattr(data, '__iter__'):
384 try:
385 dict(data)
386 except TypeError:
387 pass
388 except ValueError:
389 # Assume it's a one dimensional data structure
390 return (to_unicode(i, encoding) for i in data)
391 else:
392 # We support 2.6 which lacks dict comprehensions
393 if hasattr(data, 'items'):
394 data = data.items()
395 return {to_unicode(k, encoding): to_unicode(v, encoding) for k, v in data}
397 return data
400def _sanitize_body(body):
401 """Redact values of parameters whose name mentions password or token.
403 Linear-time replacement for the former SANITIZE_PATTERN regex, whose
404 backtracking made ``repr(Request)`` pathological on adversarial bodies
405 when debug mode is enabled.
406 """
407 parts = re.split(r'([&;])', body)
408 for i in range(0, len(parts), 2):
409 name, sep, value = parts[i].partition('=')
410 if sep and value and SANITIZE_KEY_PATTERN.search(name):
411 parts[i] = name + '=<SANITIZED>'
412 return ''.join(parts)
415class CaseInsensitiveDict(dict):
417 """Basic case insensitive dict with strings only keys."""
419 proxy = {}
421 def __init__(self, data):
422 self.proxy = {k.lower(): k for k in data}
423 for k in data:
424 self[k] = data[k]
426 def __contains__(self, k):
427 return k.lower() in self.proxy
429 def __delitem__(self, k):
430 key = self.proxy[k.lower()]
431 super().__delitem__(key)
432 del self.proxy[k.lower()]
434 def __getitem__(self, k):
435 key = self.proxy[k.lower()]
436 return super().__getitem__(key)
438 def get(self, k, default=None):
439 return self[k] if k in self else default # noqa: SIM401
441 def __setitem__(self, k, v):
442 super().__setitem__(k, v)
443 self.proxy[k.lower()] = k
445 def update(self, *args, **kwargs):
446 super().update(*args, **kwargs)
447 for k in dict(*args, **kwargs):
448 self.proxy[k.lower()] = k
451class Request:
453 """A malleable representation of a signable HTTP request.
455 Body argument may contain any data, but parameters will only be decoded if
456 they are one of:
458 * urlencoded query string
459 * dict
460 * list of 2-tuples
462 Anything else will be treated as raw body data to be passed through
463 unmolested.
464 """
466 def __init__(self, uri, http_method='GET', body=None, headers=None,
467 encoding='utf-8'):
468 # Convert to unicode using encoding if given, else assume unicode
469 def encode(x):
470 return to_unicode(x, encoding) if encoding else x
472 self.uri = encode(uri)
473 self.http_method = encode(http_method)
474 self.headers = CaseInsensitiveDict(encode(headers or {}))
475 self.body = encode(body)
476 self.decoded_body = extract_params(self.body)
477 self.oauth_params = []
478 self.validator_log = {}
480 self._params = {
481 "access_token": None,
482 "client": None,
483 "client_id": None,
484 "client_secret": None,
485 "code": None,
486 "code_challenge": None,
487 "code_challenge_method": None,
488 "code_verifier": None,
489 "device_code": None,
490 "extra_credentials": None,
491 "grant_type": None,
492 "redirect_uri": None,
493 "refresh_token": None,
494 "request_token": None,
495 "resource": None,
496 "response_type": None,
497 "scope": None,
498 "scopes": None,
499 "state": None,
500 "token": None,
501 "user": None,
502 "token_type_hint": None,
504 # OpenID Connect
505 "response_mode": None,
506 "nonce": None,
507 "display": None,
508 "prompt": None,
509 "claims": None,
510 "max_age": None,
511 "ui_locales": None,
512 "id_token_hint": None,
513 "login_hint": None,
514 "acr_values": None
515 }
516 self._params.update(dict(urldecode(self.uri_query)))
517 self._params.update(dict(self.decoded_body or []))
519 def __getattr__(self, name):
520 if name in self._params:
521 return self._params[name]
522 else:
523 raise AttributeError(name)
525 def __repr__(self):
526 if not get_debug():
527 return "<oauthlib.Request SANITIZED>"
528 body = self.body
529 headers = self.headers.copy()
530 if body:
531 body = _sanitize_body(str(body))
532 if 'Authorization' in headers:
533 headers['Authorization'] = '<SANITIZED>'
534 return '<oauthlib.Request url="{}", http_method="{}", headers="{}", body="{}">'.format(
535 self.uri, self.http_method, headers, body)
537 @property
538 def uri_query(self):
539 return urlparse.urlparse(self.uri).query
541 @property
542 def uri_query_params(self):
543 if not self.uri_query:
544 return []
545 return urlparse.parse_qsl(self.uri_query, keep_blank_values=True,
546 strict_parsing=True)
548 @property
549 def duplicate_params(self):
550 seen_keys = collections.defaultdict(int)
551 all_keys = (p[0]
552 for p in (self.decoded_body or []) + self.uri_query_params)
553 for k in all_keys:
554 seen_keys[k] += 1
555 return [k for k, c in seen_keys.items() if c > 1]