wrapper.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. # -*- test-case-name: twisted.web.test.test_httpauth -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. A guard implementation which supports HTTP header-based authentication
  6. schemes.
  7. If no I{Authorization} header is supplied, an anonymous login will be
  8. attempted by using a L{Anonymous} credentials object. If such a header is
  9. supplied and does not contain allowed credentials, or if anonymous login is
  10. denied, a 401 will be sent in the response along with I{WWW-Authenticate}
  11. headers for each of the allowed authentication schemes.
  12. """
  13. from __future__ import division, absolute_import
  14. from zope.interface import implementer
  15. from twisted.python import log
  16. from twisted.python.components import proxyForInterface
  17. from twisted.python.compat import networkString
  18. from twisted.web.resource import IResource, ErrorPage
  19. from twisted.web import util
  20. from twisted.cred import error
  21. from twisted.cred.credentials import Anonymous
  22. @implementer(IResource)
  23. class UnauthorizedResource(object):
  24. """
  25. Simple IResource to escape Resource dispatch
  26. """
  27. isLeaf = True
  28. def __init__(self, factories):
  29. self._credentialFactories = factories
  30. def render(self, request):
  31. """
  32. Send www-authenticate headers to the client
  33. """
  34. def generateWWWAuthenticate(scheme, challenge):
  35. l = []
  36. for k,v in challenge.items():
  37. l.append(networkString("%s=%s" % (k, quoteString(v))))
  38. return b" ".join([scheme, b", ".join(l)])
  39. def quoteString(s):
  40. return '"%s"' % (s.replace('\\', '\\\\').replace('"', '\\"'),)
  41. request.setResponseCode(401)
  42. for fact in self._credentialFactories:
  43. challenge = fact.getChallenge(request)
  44. request.responseHeaders.addRawHeader(
  45. b'www-authenticate',
  46. generateWWWAuthenticate(fact.scheme, challenge))
  47. if request.method == b'HEAD':
  48. return b''
  49. return b'Unauthorized'
  50. def getChildWithDefault(self, path, request):
  51. """
  52. Disable resource dispatch
  53. """
  54. return self
  55. @implementer(IResource)
  56. class HTTPAuthSessionWrapper(object):
  57. """
  58. Wrap a portal, enforcing supported header-based authentication schemes.
  59. @ivar _portal: The L{Portal} which will be used to retrieve L{IResource}
  60. avatars.
  61. @ivar _credentialFactories: A list of L{ICredentialFactory} providers which
  62. will be used to decode I{Authorization} headers into L{ICredentials}
  63. providers.
  64. """
  65. isLeaf = False
  66. def __init__(self, portal, credentialFactories):
  67. """
  68. Initialize a session wrapper
  69. @type portal: C{Portal}
  70. @param portal: The portal that will authenticate the remote client
  71. @type credentialFactories: C{Iterable}
  72. @param credentialFactories: The portal that will authenticate the
  73. remote client based on one submitted C{ICredentialFactory}
  74. """
  75. self._portal = portal
  76. self._credentialFactories = credentialFactories
  77. def _authorizedResource(self, request):
  78. """
  79. Get the L{IResource} which the given request is authorized to receive.
  80. If the proper authorization headers are present, the resource will be
  81. requested from the portal. If not, an anonymous login attempt will be
  82. made.
  83. """
  84. authheader = request.getHeader(b'authorization')
  85. if not authheader:
  86. return util.DeferredResource(self._login(Anonymous()))
  87. factory, respString = self._selectParseHeader(authheader)
  88. if factory is None:
  89. return UnauthorizedResource(self._credentialFactories)
  90. try:
  91. credentials = factory.decode(respString, request)
  92. except error.LoginFailed:
  93. return UnauthorizedResource(self._credentialFactories)
  94. except:
  95. log.err(None, "Unexpected failure from credentials factory")
  96. return ErrorPage(500, None, None)
  97. else:
  98. return util.DeferredResource(self._login(credentials))
  99. def render(self, request):
  100. """
  101. Find the L{IResource} avatar suitable for the given request, if
  102. possible, and render it. Otherwise, perhaps render an error page
  103. requiring authorization or describing an internal server failure.
  104. """
  105. return self._authorizedResource(request).render(request)
  106. def getChildWithDefault(self, path, request):
  107. """
  108. Inspect the Authorization HTTP header, and return a deferred which,
  109. when fired after successful authentication, will return an authorized
  110. C{Avatar}. On authentication failure, an C{UnauthorizedResource} will
  111. be returned, essentially halting further dispatch on the wrapped
  112. resource and all children
  113. """
  114. # Don't consume any segments of the request - this class should be
  115. # transparent!
  116. request.postpath.insert(0, request.prepath.pop())
  117. return self._authorizedResource(request)
  118. def _login(self, credentials):
  119. """
  120. Get the L{IResource} avatar for the given credentials.
  121. @return: A L{Deferred} which will be called back with an L{IResource}
  122. avatar or which will errback if authentication fails.
  123. """
  124. d = self._portal.login(credentials, None, IResource)
  125. d.addCallbacks(self._loginSucceeded, self._loginFailed)
  126. return d
  127. def _loginSucceeded(self, args):
  128. """
  129. Handle login success by wrapping the resulting L{IResource} avatar
  130. so that the C{logout} callback will be invoked when rendering is
  131. complete.
  132. """
  133. interface, avatar, logout = args
  134. class ResourceWrapper(proxyForInterface(IResource, 'resource')):
  135. """
  136. Wrap an L{IResource} so that whenever it or a child of it
  137. completes rendering, the cred logout hook will be invoked.
  138. An assumption is made here that exactly one L{IResource} from
  139. among C{avatar} and all of its children will be rendered. If
  140. more than one is rendered, C{logout} will be invoked multiple
  141. times and probably earlier than desired.
  142. """
  143. def getChildWithDefault(self, name, request):
  144. """
  145. Pass through the lookup to the wrapped resource, wrapping
  146. the result in L{ResourceWrapper} to ensure C{logout} is
  147. called when rendering of the child is complete.
  148. """
  149. return ResourceWrapper(self.resource.getChildWithDefault(name, request))
  150. def render(self, request):
  151. """
  152. Hook into response generation so that when rendering has
  153. finished completely (with or without error), C{logout} is
  154. called.
  155. """
  156. request.notifyFinish().addBoth(lambda ign: logout())
  157. return super(ResourceWrapper, self).render(request)
  158. return ResourceWrapper(avatar)
  159. def _loginFailed(self, result):
  160. """
  161. Handle login failure by presenting either another challenge (for
  162. expected authentication/authorization-related failures) or a server
  163. error page (for anything else).
  164. """
  165. if result.check(error.Unauthorized, error.LoginFailed):
  166. return UnauthorizedResource(self._credentialFactories)
  167. else:
  168. log.err(
  169. result,
  170. "HTTPAuthSessionWrapper.getChildWithDefault encountered "
  171. "unexpected error")
  172. return ErrorPage(500, None, None)
  173. def _selectParseHeader(self, header):
  174. """
  175. Choose an C{ICredentialFactory} from C{_credentialFactories}
  176. suitable to use to decode the given I{Authenticate} header.
  177. @return: A two-tuple of a factory and the remaining portion of the
  178. header value to be decoded or a two-tuple of L{None} if no
  179. factory can decode the header value.
  180. """
  181. elements = header.split(b' ')
  182. scheme = elements[0].lower()
  183. for fact in self._credentialFactories:
  184. if fact.scheme == scheme:
  185. return (fact, b' '.join(elements[1:]))
  186. return (None, None)