http_proxy_digest.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. # -*- coding: utf-8 -*-
  2. """The module containing HTTPProxyDigestAuth."""
  3. import re
  4. from requests import cookies, utils
  5. from . import _digest_auth_compat as auth
  6. class HTTPProxyDigestAuth(auth.HTTPDigestAuth):
  7. """HTTP digest authentication between proxy
  8. :param stale_rejects: The number of rejects indicate that:
  9. the client may wish to simply retry the request
  10. with a new encrypted response, without reprompting the user for a
  11. new username and password. i.e., retry build_digest_header
  12. :type stale_rejects: int
  13. """
  14. _pat = re.compile(r'digest ', flags=re.IGNORECASE)
  15. def __init__(self, *args, **kwargs):
  16. super(HTTPProxyDigestAuth, self).__init__(*args, **kwargs)
  17. self.stale_rejects = 0
  18. self.init_per_thread_state()
  19. @property
  20. def stale_rejects(self):
  21. thread_local = getattr(self, '_thread_local', None)
  22. if thread_local is None:
  23. return self._stale_rejects
  24. return thread_local.stale_rejects
  25. @stale_rejects.setter
  26. def stale_rejects(self, value):
  27. thread_local = getattr(self, '_thread_local', None)
  28. if thread_local is None:
  29. self._stale_rejects = value
  30. else:
  31. thread_local.stale_rejects = value
  32. def init_per_thread_state(self):
  33. try:
  34. super(HTTPProxyDigestAuth, self).init_per_thread_state()
  35. except AttributeError:
  36. # If we're not on requests 2.8.0+ this method does not exist
  37. pass
  38. def handle_407(self, r, **kwargs):
  39. """Handle HTTP 407 only once, otherwise give up
  40. :param r: current response
  41. :returns: responses, along with the new response
  42. """
  43. if r.status_code == 407 and self.stale_rejects < 2:
  44. s_auth = r.headers.get("proxy-authenticate")
  45. if s_auth is None:
  46. raise IOError(
  47. "proxy server violated RFC 7235:"
  48. "407 response MUST contain header proxy-authenticate")
  49. elif not self._pat.match(s_auth):
  50. return r
  51. self.chal = utils.parse_dict_header(
  52. self._pat.sub('', s_auth, count=1))
  53. # if we present the user/passwd and still get rejected
  54. # http://tools.ietf.org/html/rfc2617#section-3.2.1
  55. if ('Proxy-Authorization' in r.request.headers and
  56. 'stale' in self.chal):
  57. if self.chal['stale'].lower() == 'true': # try again
  58. self.stale_rejects += 1
  59. # wrong user/passwd
  60. elif self.chal['stale'].lower() == 'false':
  61. raise IOError("User or password is invalid")
  62. # Consume content and release the original connection
  63. # to allow our new request to reuse the same one.
  64. r.content
  65. r.close()
  66. prep = r.request.copy()
  67. cookies.extract_cookies_to_jar(prep._cookies, r.request, r.raw)
  68. prep.prepare_cookies(prep._cookies)
  69. prep.headers['Proxy-Authorization'] = self.build_digest_header(
  70. prep.method, prep.url)
  71. _r = r.connection.send(prep, **kwargs)
  72. _r.history.append(r)
  73. _r.request = prep
  74. return _r
  75. else: # give up authenticate
  76. return r
  77. def __call__(self, r):
  78. self.init_per_thread_state()
  79. # if we have nonce, then just use it, otherwise server will tell us
  80. if self.last_nonce:
  81. r.headers['Proxy-Authorization'] = self.build_digest_header(
  82. r.method, r.url
  83. )
  84. r.register_hook('response', self.handle_407)
  85. return r