wrapper.py 8.4 KB

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