def setUp(self): root = Data(b'El toro!', 'text/plain') root.putChild(b"cookiemirror", CookieMirrorResource()) root.putChild(b"rawcookiemirror", RawCookieMirrorResource()) site = server.Site(root, timeout=None) self.port = self._listen(site) self.portno = self.port.getHost().port
def setUp(self): market_factory = WebSocketServerFactory( 'ws://localhost:8080/market_stream') user_factory = WebSocketServerFactory( 'ws://localhost:8080/user_stream') market_factory.protocol = MarketStreamServerProtocol user_factory.protocol = UserStreamServerProtocol market_factory.startFactory() user_factory.startFactory() root = Data('', 'text/plain') root.putChild(b'market_stream', WebSocketResource(market_factory)) root.putChild(b'user_stream', WebSocketResource(user_factory)) site = Site(root) reactor.listenTCP(8080, site) def run_server(): reactor.run(installSignalHandlers=False) Thread(target=run_server).start() def run_client(): from examples import simple_trading self.client_process = Process(target=run_client) self.client_process.start()
def test_getChild(self): """ L{_HostResource.getChild} returns the proper I{Resource} for the vhost embedded in the URL. Verify that returning the proper I{Resource} required changing the I{Host} in the header. """ bazroot = Data(b"root data", "") bazuri = Data(b"uri data", "") baztest = Data(b"test data", "") bazuri.putChild(b"test", baztest) bazroot.putChild(b"uri", bazuri) hr = _HostResource() root = NameVirtualHost() root.default = Data(b"default data", "") root.addHost(b"baz.com", bazroot) request = DummyRequest([b"uri", b"test"]) request.prepath = [b"bar", b"http", b"baz.com"] request.site = Site(root) request.isSecure = lambda: False request.host = b"" step = hr.getChild(b"baz.com", request) # Consumes rest of path self.assertIsInstance(step, Data) request = DummyRequest([b"uri", b"test"]) step = root.getChild(b"uri", request) self.assertIsInstance(step, NoResource)
def test_getChild(self): """ L{_HostResource.getChild} returns the proper I{Resource} for the vhost embedded in the URL. Verify that returning the proper I{Resource} required changing the I{Host} in the header. """ bazroot = Data(b'root data', "") bazuri = Data(b'uri data', "") baztest = Data(b'test data', "") bazuri.putChild(b'test', baztest) bazroot.putChild(b'uri', bazuri) hr = _HostResource() root = NameVirtualHost() root.default = Data(b'default data', "") root.addHost(b'baz.com', bazroot) request = DummyRequest([b'uri', b'test']) request.prepath = [b'bar', b'http', b'baz.com'] request.site = Site(root) request.isSecure = lambda: False request.host = b'' step = hr.getChild(b'baz.com', request) # Consumes rest of path self.assertIsInstance(step, Data) request = DummyRequest([b'uri', b'test']) step = root.getChild(b'uri', request) self.assertIsInstance(step, NoResource)
def get_client_resource(self, configuration): """ :return: A static data resource that produces the given configuration when rendered, as an aid to testing. """ items = configuration.items(self._client_section_name, []) resource = Data( dumps(dict(items)), b"text/json", ) # Give it some dynamic stuff too. resource.putChild(b"counter", GetCounter()) return resource
def go(self, reactor): data = Data("Hello world\n", "text/plain") data.putChild("", data) factory = Site(data) # TODO: adoptStreamConnection should really support AF_UNIX protocol = ConnectionFromManager(reactor, factory) skt = fromfd(MAGIC_FILE_DESCRIPTOR, AF_UNIX, SOCK_STREAM) os.close(MAGIC_FILE_DESCRIPTOR) serverTransport = UNIXServer(skt, protocol, None, None, 1234, reactor) protocol.makeConnection(serverTransport) serverTransport.startReading() globalLogBeginner.beginLoggingTo([protocol.sendLog]) factory.doStart() return Deferred()
def get_provider_factory(): """ Instantiates a Site that serves the resources that we expect from a valid provider. Listens on: * port 8000 for http connections * port 8443 for https connections :rparam: factory for a site :rtype: Site instance """ root = Data("", "") root.putChild("", root) root.putChild("provider.json", FileModified( os.path.join(_here, "test_provider.json"))) config = Resource() config.putChild( "eip-service.json", FileModified( os.path.join(_here, "eip-service.json"))) apiv1 = Resource() apiv1.putChild("config", config) apiv1.putChild("sessions", API_Sessions()) apiv1.putChild("users", FakeUsers(None)) apiv1.putChild("cert", FileModified( os.path.join(_here, 'openvpn.pem'))) root.putChild("1", apiv1) factory = Site(root) return factory
def get_provider_factory(): """ Instantiates a Site that serves the resources that we expect from a valid provider. Listens on: * port 8000 for http connections * port 8443 for https connections :rparam: factory for a site :rtype: Site instance """ root = Data("", "") root.putChild("", root) root.putChild("provider.json", FileModified(os.path.join(_here, "test_provider.json"))) config = Resource() config.putChild("eip-service.json", FileModified(os.path.join(_here, "eip-service.json"))) apiv1 = Resource() apiv1.putChild("config", config) apiv1.putChild("sessions", API_Sessions()) apiv1.putChild("users", FakeUsers(None)) apiv1.putChild("cert", FileModified(os.path.join(_here, 'openvpn.pem'))) root.putChild("1", apiv1) factory = Site(root) return factory
def test_resource_tree(self): """ The agent should traverse the resource tree correctly """ class R(Resource): def __init__(self, response): Resource.__init__(self) self._response = response def render_GET(self, request): return self._response a = Data('a', 'text/plain') c = Data('c', 'text/plain') a.putChild('b', Data('b', 'text/plain')) a.putChild('c', c) c.putChild('d', Data('d', 'text/plain')) agent = self.getAgent(a) # are these assertions correct? yield self.assertBody(agent, 'a', 'GET', 'http://example.com') yield self.assertBody(agent, 'a', 'GET', 'http://example.com/') yield self.assertBody(agent, 'b', 'GET', 'http://example.com/b') yield self.assertBody(agent, 'c', 'GET', 'http://example.com/c') yield self.assertBody(agent, 'd', 'GET', 'http://example.com/c/d')
def setUp(self): self.avatar_content = b"avatar content" self.child_content = b"child content" self.grandchild_content = b"grandchild content" grandchild = Data(self.grandchild_content, b"text/plain") child = Data(self.child_content, b"text/plain") child.putChild(b"grandchild", grandchild) self.avatar = Data(self.avatar_content, b"text/plain") self.avatar.putChild(b"child", child) self.realm = OneIResourceAvatarRealm(self.avatar) self.portal = Portal( self.realm, [AllowAnonymousAccess()], ) self.guard = HTTPAuthSessionWrapper( self.portal, [BasicCredentialFactory("example.com")], )
def setUp(self): plainRoot = Data(b'not me', 'text/plain') tlsRoot = Data(b'me neither', 'text/plain') plainSite = server.Site(plainRoot, timeout=None) tlsSite = server.Site(tlsRoot, timeout=None) self.tlsPort = reactor.listenSSL( 0, tlsSite, contextFactory=ssl.DefaultOpenSSLContextFactory( serverPEMPath, serverPEMPath), interface="127.0.0.1") self.plainPort = reactor.listenTCP(0, plainSite, interface="127.0.0.1") self.plainPortno = self.plainPort.getHost().port self.tlsPortno = self.tlsPort.getHost().port plainRoot.putChild(b'one', Redirect(self.getHTTPS('two'))) tlsRoot.putChild(b'two', Redirect(self.getHTTP('three'))) plainRoot.putChild(b'three', Redirect(self.getHTTPS('four'))) tlsRoot.putChild(b'four', Data(b'FOUND IT!', 'text/plain'))
def start(): log.startLogging(sys.stdout) fileFactory = WebSocketServerFactory() fileFactory.protocol = GetFiles fileFactory.startFactory() fResource = WebSocketResource(fileFactory) textFactory = WebSocketServerFactory() textFactory.protocol = GetText textFactory.startFactory() gResource = WebSocketResource(textFactory) submitTextFactory = WebSocketServerFactory() submitTextFactory.protocol = SubmitText submitTextFactory.startFactory() sResource = WebSocketResource(submitTextFactory) AudioFactory = WebSocketServerFactory() AudioFactory.protocol = Audio AudioFactory.startFactory() aResource = WebSocketResource(AudioFactory) # Establish a dummy root resource root = Data("", "text/plain") root.putChild(b"gettext", gResource) root.putChild(b"submittext", sResource) root.putChild(b"getfiles", fResource) root.putChild(b"audio", aResource) # both under one Twisted Web Site site = Site(root) reactor.listenTCP(9000, site) reactor.run()
class SoledadSessionTestCase(unittest.TestCase): """ Tests adapted from for L{twisted.web.test.test_httpauth.HTTPAuthSessionWrapper}. """ def makeRequest(self, *args, **kwargs): request = DummyRequest(*args, **kwargs) request.path = '/' return request def setUp(self): self.username = b'foo bar' self.password = b'bar baz' self.avatarContent = b"contents of the avatar resource itself" self.childName = b"foo-child" self.childContent = b"contents of the foo child of the avatar" self.checker = InMemoryUsernamePasswordDatabaseDontUse() self.checker.addUser(self.username, self.password) self.avatar = Data(self.avatarContent, 'text/plain') self.avatar.putChild( self.childName, Data(self.childContent, 'text/plain')) self.avatars = {self.username: self.avatar} self.realm = Realm(self.avatars.get) self.portal = portal.Portal(self.realm, [self.checker]) self.wrapper = SoledadSession(self.portal) def _authorizedTokenLogin(self, request): authorization = b64encode( self.username + b':' + self.password) request.requestHeaders.addRawHeader(b'authorization', b'Token ' + authorization) return getChildForRequest(self.wrapper, request) def test_getChildWithDefault(self): request = self.makeRequest([self.childName]) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(result): self.assertEqual(request.responseCode, 401) d.addCallback(cbFinished) request.render(child) return d def _invalidAuthorizationTest(self, response): request = self.makeRequest([self.childName]) request.requestHeaders.addRawHeader(b'authorization', response) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(result): self.assertEqual(request.responseCode, 401) d.addCallback(cbFinished) request.render(child) return d def test_getChildWithDefaultUnauthorizedUser(self): return self._invalidAuthorizationTest( b'Basic ' + b64encode(b'foo:bar')) def test_getChildWithDefaultUnauthorizedPassword(self): return self._invalidAuthorizationTest( b'Basic ' + b64encode(self.username + b':bar')) def test_getChildWithDefaultUnrecognizedScheme(self): return self._invalidAuthorizationTest(b'Quux foo bar baz') def test_getChildWithDefaultAuthorized(self): request = self.makeRequest([self.childName]) child = self._authorizedTokenLogin(request) d = request.notifyFinish() def cbFinished(ignored): self.assertEqual(request.written, [self.childContent]) d.addCallback(cbFinished) request.render(child) return d def test_renderAuthorized(self): # Request it exactly, not any of its children. request = self.makeRequest([]) child = self._authorizedTokenLogin(request) d = request.notifyFinish() def cbFinished(ignored): self.assertEqual(request.written, [self.avatarContent]) d.addCallback(cbFinished) request.render(child) return d def test_decodeRaises(self): request = self.makeRequest([self.childName]) request.requestHeaders.addRawHeader(b'authorization', b'Token decode should fail') child = getChildForRequest(self.wrapper, request) self.assertIsInstance(child, UnauthorizedResource) def test_parseResponse(self): basicAuthorization = b'Basic abcdef123456' self.assertEqual( self.wrapper._parseHeader(basicAuthorization), None) tokenAuthorization = b'Token abcdef123456' self.assertEqual( self.wrapper._parseHeader(tokenAuthorization), b'abcdef123456') def test_unexpectedDecodeError(self): class UnexpectedException(Exception): pass class BadFactory(object): scheme = b'bad' def getChallenge(self, client): return {} def decode(self, response, request): print("decode raised") raise UnexpectedException() self.wrapper._credentialFactory = BadFactory() request = self.makeRequest([self.childName]) request.requestHeaders.addRawHeader(b'authorization', b'Bad abc') child = getChildForRequest(self.wrapper, request) request.render(child) self.assertEqual(request.responseCode, 500) errors = self.flushLoggedErrors(UnexpectedException) self.assertEqual(len(errors), 1) def test_unexpectedLoginError(self): class UnexpectedException(Exception): pass class BrokenChecker(object): credentialInterfaces = (IUsernamePassword,) def requestAvatarId(self, credentials): raise UnexpectedException() self.portal.registerChecker(BrokenChecker()) request = self.makeRequest([self.childName]) child = self._authorizedTokenLogin(request) request.render(child) self.assertEqual(request.responseCode, 500) self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1) def test_cantAccessOtherUserPathByDefault(self): request = self.makeRequest([]) # valid url_mapper path, but for another user request.path = '/blobs/another-user/' child = self._authorizedTokenLogin(request) request.render(child) self.assertEqual(request.responseCode, 500)
if __name__ == '__main__': log.startLogging(sys.stdout) transcribeFactory = WebSocketServerFactory() transcribeFactory.protocol = Transcribe transcribeFactory.startFactory() tResource = WebSocketResource(transcribeFactory) streamFactory = WebSocketServerFactory() streamFactory.protocol = Stream streamFactory.startFactory() sResource = WebSocketResource(streamFactory) modelFactory = WebSocketServerFactory() modelFactory.protocol = Model modelFactory.startFactory() mResource = WebSocketResource(modelFactory) # Establish a dummy root resource root = Data("", "text/plain") root.putChild(b"transcribe", tResource) root.putChild(b"stream", sResource) root.putChild(b"model", mResource) # both under one Twisted Web Site site = Site(root) reactor.listenTCP(9000, site) reactor.run()
class HTTPAuthHeaderTests(unittest.TestCase): """ Tests for L{HTTPAuthSessionWrapper}. """ makeRequest = DummyRequest def setUp(self): """ Create a realm, portal, and L{HTTPAuthSessionWrapper} to use in the tests. """ self.username = b'foo bar' self.password = b'bar baz' self.avatarContent = b"contents of the avatar resource itself" self.childName = b"foo-child" self.childContent = b"contents of the foo child of the avatar" self.checker = InMemoryUsernamePasswordDatabaseDontUse() self.checker.addUser(self.username, self.password) self.avatar = Data(self.avatarContent, 'text/plain') self.avatar.putChild(self.childName, Data(self.childContent, 'text/plain')) self.avatars = {self.username: self.avatar} self.realm = Realm(self.avatars.get) self.portal = portal.Portal(self.realm, [self.checker]) self.credentialFactories = [] self.wrapper = HTTPAuthSessionWrapper(self.portal, self.credentialFactories) def _authorizedBasicLogin(self, request): """ Add an I{basic authorization} header to the given request and then dispatch it, starting from C{self.wrapper} and returning the resulting L{IResource}. """ authorization = b64encode(self.username + b':' + self.password) request.requestHeaders.addRawHeader(b'authorization', b'Basic ' + authorization) return getChildForRequest(self.wrapper, request) def test_getChildWithDefault(self): """ Resource traversal which encounters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} instance when the request does not have the required I{Authorization} headers. """ request = self.makeRequest([self.childName]) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(result): self.assertEqual(request.responseCode, 401) d.addCallback(cbFinished) request.render(child) return d def _invalidAuthorizationTest(self, response): """ Create a request with the given value as the value of an I{Authorization} header and perform resource traversal with it, starting at C{self.wrapper}. Assert that the result is a 401 response code. Return a L{Deferred} which fires when this is all done. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) request.requestHeaders.addRawHeader(b'authorization', response) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(result): self.assertEqual(request.responseCode, 401) d.addCallback(cbFinished) request.render(child) return d def test_getChildWithDefaultUnauthorizedUser(self): """ Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has an I{Authorization} header with a user which does not exist. """ return self._invalidAuthorizationTest(b'Basic ' + b64encode(b'foo:bar')) def test_getChildWithDefaultUnauthorizedPassword(self): """ Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has an I{Authorization} header with a user which exists and the wrong password. """ return self._invalidAuthorizationTest(b'Basic ' + b64encode(self.username + b':bar')) def test_getChildWithDefaultUnrecognizedScheme(self): """ Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has an I{Authorization} header with an unrecognized scheme. """ return self._invalidAuthorizationTest(b'Quux foo bar baz') def test_getChildWithDefaultAuthorized(self): """ Resource traversal which encounters an L{HTTPAuthSessionWrapper} results in an L{IResource} which renders the L{IResource} avatar retrieved from the portal when the request has a valid I{Authorization} header. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) child = self._authorizedBasicLogin(request) d = request.notifyFinish() def cbFinished(ignored): self.assertEqual(request.written, [self.childContent]) d.addCallback(cbFinished) request.render(child) return d def test_renderAuthorized(self): """ Resource traversal which terminates at an L{HTTPAuthSessionWrapper} and includes correct authentication headers results in the L{IResource} avatar (not one of its children) retrieved from the portal being rendered. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) # Request it exactly, not any of its children. request = self.makeRequest([]) child = self._authorizedBasicLogin(request) d = request.notifyFinish() def cbFinished(ignored): self.assertEqual(request.written, [self.avatarContent]) d.addCallback(cbFinished) request.render(child) return d def test_getChallengeCalledWithRequest(self): """ When L{HTTPAuthSessionWrapper} finds an L{ICredentialFactory} to issue a challenge, it calls the C{getChallenge} method with the request as an argument. """ @implementer(ICredentialFactory) class DumbCredentialFactory: scheme = b'dumb' def __init__(self): self.requests = [] def getChallenge(self, request): self.requests.append(request) return {} factory = DumbCredentialFactory() self.credentialFactories.append(factory) request = self.makeRequest([self.childName]) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(ignored): self.assertEqual(factory.requests, [request]) d.addCallback(cbFinished) request.render(child) return d def _logoutTest(self): """ Issue a request for an authentication-protected resource using valid credentials and then return the C{DummyRequest} instance which was used. This is a helper for tests about the behavior of the logout callback. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) class SlowerResource(Resource): def render(self, request): return NOT_DONE_YET self.avatar.putChild(self.childName, SlowerResource()) request = self.makeRequest([self.childName]) child = self._authorizedBasicLogin(request) request.render(child) self.assertEqual(self.realm.loggedOut, 0) return request def test_logout(self): """ The realm's logout callback is invoked after the resource is rendered. """ request = self._logoutTest() request.finish() self.assertEqual(self.realm.loggedOut, 1) def test_logoutOnError(self): """ The realm's logout callback is also invoked if there is an error generating the response (for example, if the client disconnects early). """ request = self._logoutTest() request.processingFailed( Failure(ConnectionDone("Simulated disconnect"))) self.assertEqual(self.realm.loggedOut, 1) def test_decodeRaises(self): """ Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has a I{Basic Authorization} header which cannot be decoded using base64. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) request.requestHeaders.addRawHeader(b'authorization', b'Basic decode should fail') child = getChildForRequest(self.wrapper, request) self.assertIsInstance(child, UnauthorizedResource) def test_selectParseResponse(self): """ L{HTTPAuthSessionWrapper._selectParseHeader} returns a two-tuple giving the L{ICredentialFactory} to use to parse the header and a string containing the portion of the header which remains to be parsed. """ basicAuthorization = b'Basic abcdef123456' self.assertEqual(self.wrapper._selectParseHeader(basicAuthorization), (None, None)) factory = BasicCredentialFactory('example.com') self.credentialFactories.append(factory) self.assertEqual(self.wrapper._selectParseHeader(basicAuthorization), (factory, b'abcdef123456')) def test_unexpectedDecodeError(self): """ Any unexpected exception raised by the credential factory's C{decode} method results in a 500 response code and causes the exception to be logged. """ logObserver = EventLoggingObserver.createWithCleanup( self, globalLogPublisher) class UnexpectedException(Exception): pass class BadFactory: scheme = b'bad' def getChallenge(self, client): return {} def decode(self, response, request): raise UnexpectedException() self.credentialFactories.append(BadFactory()) request = self.makeRequest([self.childName]) request.requestHeaders.addRawHeader(b'authorization', b'Bad abc') child = getChildForRequest(self.wrapper, request) request.render(child) self.assertEqual(request.responseCode, 500) self.assertEquals(1, len(logObserver)) self.assertIsInstance(logObserver[0]["log_failure"].value, UnexpectedException) self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1) def test_unexpectedLoginError(self): """ Any unexpected failure from L{Portal.login} results in a 500 response code and causes the failure to be logged. """ logObserver = EventLoggingObserver.createWithCleanup( self, globalLogPublisher) class UnexpectedException(Exception): pass class BrokenChecker: credentialInterfaces = (IUsernamePassword, ) def requestAvatarId(self, credentials): raise UnexpectedException() self.portal.registerChecker(BrokenChecker()) self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) child = self._authorizedBasicLogin(request) request.render(child) self.assertEqual(request.responseCode, 500) self.assertEquals(1, len(logObserver)) self.assertIsInstance(logObserver[0]["log_failure"].value, UnexpectedException) self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1) def test_anonymousAccess(self): """ Anonymous requests are allowed if a L{Portal} has an anonymous checker registered. """ unprotectedContents = b"contents of the unprotected child resource" self.avatars[ANONYMOUS] = Resource() self.avatars[ANONYMOUS].putChild( self.childName, Data(unprotectedContents, 'text/plain')) self.portal.registerChecker(AllowAnonymousAccess()) self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(ignored): self.assertEqual(request.written, [unprotectedContents]) d.addCallback(cbFinished) request.render(child) return d
def makeResource(expected): resource = Data(expected, b"text/plain") intermediate = Data(b"incorrect intermediate", b"text/plain") intermediate.putChild(b"child", resource) return DeferredResource(succeed(intermediate))
class GuardTests(TestCase): """ Tests for interaction with L{twisted.web.guard}. """ def setUp(self): self.avatar_content = b"avatar content" self.child_content = b"child content" self.grandchild_content = b"grandchild content" grandchild = Data(self.grandchild_content, b"text/plain") child = Data(self.child_content, b"text/plain") child.putChild(b"grandchild", grandchild) self.avatar = Data(self.avatar_content, b"text/plain") self.avatar.putChild(b"child", child) self.realm = OneIResourceAvatarRealm(self.avatar) self.portal = Portal( self.realm, [AllowAnonymousAccess()], ) self.guard = HTTPAuthSessionWrapper( self.portal, [BasicCredentialFactory("example.com")], ) def test_avatar(self): """ A request for exactly the guarded resource results in the avatar returned by cred. """ root = Page() root.child_guarded = self.guard actual = self.successResultOf( renderResourceReturnTransport( root, b"/guarded", b"GET", ), ) self.assertIn(self.avatar_content, actual) def test_child(self): """ A request for a direct child of the guarded resource results in that child of the avatar returned by cred. """ root = Page() root.child_guarded = self.guard actual = self.successResultOf( renderResourceReturnTransport( root, b"/guarded/child", b"GET", ), ) self.assertIn(self.child_content, actual) def test_grandchild(self): """ A request for a grandchild of the guarded resource results in that grandchild of the avatar returned by cred. Ideally this test would be redundant with L{test_child} but the implementation of L{IResource} support results in different codepaths for the 1st descendant vs the Nth descendant. """ root = Page() root.child_guarded = self.guard actual = self.successResultOf( renderResourceReturnTransport( root, b"/guarded/child/grandchild", b"GET", ), ) self.assertIn(self.grandchild_content, actual)
if len(sys.argv) > 1 and sys.argv[1] == 'debug': log.startLogging(sys.stdout) debug = True else: debug = False factory1 = WebSocketServerFactory("ws://localhost:9000", debug = debug, debugCodePaths = debug) factory1.protocol = Echo1ServerProtocol resource1 = WebSocketResource(factory1) factory2 = WebSocketServerFactory("ws://localhost:9000", debug = debug, debugCodePaths = debug) factory2.protocol = Echo2ServerProtocol resource2 = WebSocketResource(factory2) ## Establish a dummy root resource root = Data("", "text/plain") ## and our WebSocket servers under different paths .. root.putChild("echo1", resource1) root.putChild("echo2", resource2) ## both under one Twisted Web Site site = Site(root) reactor.listenTCP(9000, site) reactor.run()
class HTTPAuthHeaderTests(unittest.TestCase): """ Tests for L{HTTPAuthSessionWrapper}. """ makeRequest = DummyRequest def setUp(self): """ Create a realm, portal, and L{HTTPAuthSessionWrapper} to use in the tests. """ self.username = '******' self.password = '******' self.avatarContent = "contents of the avatar resource itself" self.childName = "foo-child" self.childContent = "contents of the foo child of the avatar" self.checker = InMemoryUsernamePasswordDatabaseDontUse() self.checker.addUser(self.username, self.password) self.avatar = Data(self.avatarContent, 'text/plain') self.avatar.putChild( self.childName, Data(self.childContent, 'text/plain')) self.avatars = {self.username: self.avatar} self.realm = Realm(self.avatars.get) self.portal = portal.Portal(self.realm, [self.checker]) self.credentialFactories = [] self.wrapper = HTTPAuthSessionWrapper( self.portal, self.credentialFactories) def _authorizedBasicLogin(self, request): """ Add an I{basic authorization} header to the given request and then dispatch it, starting from C{self.wrapper} and returning the resulting L{IResource}. """ authorization = b64encode(self.username + ':' + self.password) request.headers['authorization'] = 'Basic ' + authorization return getChildForRequest(self.wrapper, request) def test_getChildWithDefault(self): """ Resource traversal which encounters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} instance when the request does not have the required I{Authorization} headers. """ request = self.makeRequest([self.childName]) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(result): self.assertEquals(request.responseCode, 401) d.addCallback(cbFinished) request.render(child) return d def _invalidAuthorizationTest(self, response): """ Create a request with the given value as the value of an I{Authorization} header and perform resource traversal with it, starting at C{self.wrapper}. Assert that the result is a 401 response code. Return a L{Deferred} which fires when this is all done. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) request.headers['authorization'] = response child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(result): self.assertEqual(request.responseCode, 401) d.addCallback(cbFinished) request.render(child) return d def test_getChildWithDefaultUnauthorizedUser(self): """ Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has an I{Authorization} header with a user which does not exist. """ return self._invalidAuthorizationTest('Basic ' + b64encode('foo:bar')) def test_getChildWithDefaultUnauthorizedPassword(self): """ Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has an I{Authorization} header with a user which exists and the wrong password. """ return self._invalidAuthorizationTest( 'Basic ' + b64encode(self.username + ':bar')) def test_getChildWithDefaultUnrecognizedScheme(self): """ Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has an I{Authorization} header with an unrecognized scheme. """ return self._invalidAuthorizationTest('Quux foo bar baz') def test_getChildWithDefaultAuthorized(self): """ Resource traversal which encounters an L{HTTPAuthSessionWrapper} results in an L{IResource} which renders the L{IResource} avatar retrieved from the portal when the request has a valid I{Authorization} header. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) child = self._authorizedBasicLogin(request) d = request.notifyFinish() def cbFinished(ignored): self.assertEquals(request.written, [self.childContent]) d.addCallback(cbFinished) request.render(child) return d def test_renderAuthorized(self): """ Resource traversal which terminates at an L{HTTPAuthSessionWrapper} and includes correct authentication headers results in the L{IResource} avatar (not one of its children) retrieved from the portal being rendered. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) # Request it exactly, not any of its children. request = self.makeRequest([]) child = self._authorizedBasicLogin(request) d = request.notifyFinish() def cbFinished(ignored): self.assertEquals(request.written, [self.avatarContent]) d.addCallback(cbFinished) request.render(child) return d def test_getChallengeCalledWithRequest(self): """ When L{HTTPAuthSessionWrapper} finds an L{ICredentialFactory} to issue a challenge, it calls the C{getChallenge} method with the request as an argument. """ class DumbCredentialFactory(object): implements(ICredentialFactory) scheme = 'dumb' def __init__(self): self.requests = [] def getChallenge(self, request): self.requests.append(request) return {} factory = DumbCredentialFactory() self.credentialFactories.append(factory) request = self.makeRequest([self.childName]) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(ignored): self.assertEqual(factory.requests, [request]) d.addCallback(cbFinished) request.render(child) return d def test_logout(self): """ The realm's logout callback is invoked after the resource is rendered. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) class SlowerResource(Resource): def render(self, request): return NOT_DONE_YET self.avatar.putChild(self.childName, SlowerResource()) request = self.makeRequest([self.childName]) child = self._authorizedBasicLogin(request) request.render(child) self.assertEqual(self.realm.loggedOut, 0) request.finish() self.assertEqual(self.realm.loggedOut, 1) def test_decodeRaises(self): """ Resource traversal which enouncters an L{HTTPAuthSessionWrapper} results in an L{UnauthorizedResource} when the request has a I{Basic Authorization} header which cannot be decoded using base64. """ self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) request.headers['authorization'] = 'Basic decode should fail' child = getChildForRequest(self.wrapper, request) self.assertIsInstance(child, UnauthorizedResource) def test_selectParseResponse(self): """ L{HTTPAuthSessionWrapper._selectParseHeader} returns a two-tuple giving the L{ICredentialFactory} to use to parse the header and a string containing the portion of the header which remains to be parsed. """ basicAuthorization = 'Basic abcdef123456' self.assertEqual( self.wrapper._selectParseHeader(basicAuthorization), (None, None)) factory = BasicCredentialFactory('example.com') self.credentialFactories.append(factory) self.assertEqual( self.wrapper._selectParseHeader(basicAuthorization), (factory, 'abcdef123456')) def test_unexpectedDecodeError(self): """ Any unexpected exception raised by the credential factory's C{decode} method results in a 500 response code and causes the exception to be logged. """ class UnexpectedException(Exception): pass class BadFactory(object): scheme = 'bad' def getChallenge(self, client): return {} def decode(self, response, request): raise UnexpectedException() self.credentialFactories.append(BadFactory()) request = self.makeRequest([self.childName]) request.headers['authorization'] = 'Bad abc' child = getChildForRequest(self.wrapper, request) request.render(child) self.assertEqual(request.responseCode, 500) self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1) def test_unexpectedLoginError(self): """ Any unexpected failure from L{Portal.login} results in a 500 response code and causes the failure to be logged. """ class UnexpectedException(Exception): pass class BrokenChecker(object): credentialInterfaces = (IUsernamePassword,) def requestAvatarId(self, credentials): raise UnexpectedException() self.portal.registerChecker(BrokenChecker()) self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) child = self._authorizedBasicLogin(request) request.render(child) self.assertEqual(request.responseCode, 500) self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1) def test_anonymousAccess(self): """ Anonymous requests are allowed if a L{Portal} has an anonymous checker registered. """ unprotectedContents = "contents of the unprotected child resource" self.avatars[ANONYMOUS] = Resource() self.avatars[ANONYMOUS].putChild( self.childName, Data(unprotectedContents, 'text/plain')) self.portal.registerChecker(AllowAnonymousAccess()) self.credentialFactories.append(BasicCredentialFactory('example.com')) request = self.makeRequest([self.childName]) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(ignored): self.assertEquals(request.written, [unprotectedContents]) d.addCallback(cbFinished) request.render(child) return d
if __name__ == '__main__': log.startLogging(sys.stdout) factory1 = WebSocketServerFactory() factory1.protocol = Echo1ServerProtocol factory1.startFactory( ) # when wrapped as a Twisted Web resource, start the underlying factory manually resource1 = WebSocketResource(factory1) factory2 = WebSocketServerFactory() factory2.protocol = Echo2ServerProtocol factory2.startFactory( ) # when wrapped as a Twisted Web resource, start the underlying factory manually resource2 = WebSocketResource(factory2) # Establish a dummy root resource root = Data("", "text/plain") # and our WebSocket servers under different paths .. root.putChild("echo1", resource1) root.putChild("echo2", resource2) # both under one Twisted Web Site site = Site(root) reactor.listenTCP(9000, site) reactor.run()
self.sendClose() if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'debug': log.startLogging(sys.stdout) debug = True else: debug = False factorySave = WebSocketServerFactory("ws://localhost:{0}".format(LOCAL_PROXY_PORT), debug = debug) factorySave.protocol = RemoteControlSaveProtocol resourceSave = WebSocketResource(factorySave) factoryLoad = WebSocketServerFactory("ws://localhost:{0}".format(LOCAL_PROXY_PORT), debug = debug) factoryLoad.protocol = RemoteControlLoadProtocol resourceLoad = WebSocketResource(factoryLoad) # Establish a dummy root resource root = Data("", "text/plain") # and our WebSocket servers under different paths .. root.putChild("save", resourceSave) root.putChild("load", resourceLoad) # both under one Twisted Web Site site = Site(root) reactor.listenTCP(LOCAL_PROXY_PORT, site) reactor.run()
class SoledadSessionTestCase(unittest.TestCase): """ Tests adapted from for L{twisted.web.test.test_httpauth.HTTPAuthSessionWrapper}. """ def makeRequest(self, *args, **kwargs): request = DummyRequest(*args, **kwargs) request.path = '/' return request def setUp(self): self.username = b'foo bar' self.password = b'bar baz' self.avatarContent = b"contents of the avatar resource itself" self.childName = b"foo-child" self.childContent = b"contents of the foo child of the avatar" self.checker = InMemoryUsernamePasswordDatabaseDontUse() self.checker.addUser(self.username, self.password) self.avatar = Data(self.avatarContent, 'text/plain') self.avatar.putChild(self.childName, Data(self.childContent, 'text/plain')) self.avatars = {self.username: self.avatar} self.realm = Realm(self.avatars.get) self.portal = portal.Portal(self.realm, [self.checker]) self.wrapper = SoledadSession(self.portal) def _authorizedTokenLogin(self, request): authorization = b64encode(self.username + b':' + self.password) request.requestHeaders.addRawHeader(b'authorization', b'Token ' + authorization) return getChildForRequest(self.wrapper, request) def test_getChildWithDefault(self): request = self.makeRequest([self.childName]) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(result): self.assertEqual(request.responseCode, 401) d.addCallback(cbFinished) request.render(child) return d def _invalidAuthorizationTest(self, response): request = self.makeRequest([self.childName]) request.requestHeaders.addRawHeader(b'authorization', response) child = getChildForRequest(self.wrapper, request) d = request.notifyFinish() def cbFinished(result): self.assertEqual(request.responseCode, 401) d.addCallback(cbFinished) request.render(child) return d def test_getChildWithDefaultUnauthorizedUser(self): return self._invalidAuthorizationTest(b'Basic ' + b64encode(b'foo:bar')) def test_getChildWithDefaultUnauthorizedPassword(self): return self._invalidAuthorizationTest(b'Basic ' + b64encode(self.username + b':bar')) def test_getChildWithDefaultUnrecognizedScheme(self): return self._invalidAuthorizationTest(b'Quux foo bar baz') def test_getChildWithDefaultAuthorized(self): request = self.makeRequest([self.childName]) child = self._authorizedTokenLogin(request) d = request.notifyFinish() def cbFinished(ignored): self.assertEqual(request.written, [self.childContent]) d.addCallback(cbFinished) request.render(child) return d def test_renderAuthorized(self): # Request it exactly, not any of its children. request = self.makeRequest([]) child = self._authorizedTokenLogin(request) d = request.notifyFinish() def cbFinished(ignored): self.assertEqual(request.written, [self.avatarContent]) d.addCallback(cbFinished) request.render(child) return d def test_decodeRaises(self): request = self.makeRequest([self.childName]) request.requestHeaders.addRawHeader(b'authorization', b'Token decode should fail') child = getChildForRequest(self.wrapper, request) self.assertIsInstance(child, UnauthorizedResource) def test_parseResponse(self): basicAuthorization = b'Basic abcdef123456' self.assertEqual(self.wrapper._parseHeader(basicAuthorization), None) tokenAuthorization = b'Token abcdef123456' self.assertEqual(self.wrapper._parseHeader(tokenAuthorization), b'abcdef123456') def test_unexpectedDecodeError(self): class UnexpectedException(Exception): pass class BadFactory(object): scheme = b'bad' def getChallenge(self, client): return {} def decode(self, response, request): print("decode raised") raise UnexpectedException() self.wrapper._credentialFactory = BadFactory() request = self.makeRequest([self.childName]) request.requestHeaders.addRawHeader(b'authorization', b'Bad abc') child = getChildForRequest(self.wrapper, request) request.render(child) self.assertEqual(request.responseCode, 500) errors = self.flushLoggedErrors(UnexpectedException) self.assertEqual(len(errors), 1) def test_unexpectedLoginError(self): class UnexpectedException(Exception): pass class BrokenChecker(object): credentialInterfaces = (IUsernamePassword, ) def requestAvatarId(self, credentials): raise UnexpectedException() self.portal.registerChecker(BrokenChecker()) request = self.makeRequest([self.childName]) child = self._authorizedTokenLogin(request) request.render(child) self.assertEqual(request.responseCode, 500) self.assertEqual(len(self.flushLoggedErrors(UnexpectedException)), 1)
if __name__ == '__main__': if len(sys.argv) > 1 and sys.argv[1] == 'debug': log.startLogging(sys.stdout) debug = True else: debug = False factorySave = WebSocketServerFactory( "ws://localhost:{0}".format(LOCAL_PROXY_PORT), debug=debug) factorySave.protocol = RemoteControlSaveProtocol resourceSave = WebSocketResource(factorySave) factoryLoad = WebSocketServerFactory( "ws://localhost:{0}".format(LOCAL_PROXY_PORT), debug=debug) factoryLoad.protocol = RemoteControlLoadProtocol resourceLoad = WebSocketResource(factoryLoad) # Establish a dummy root resource root = Data("", "text/plain") # and our WebSocket servers under different paths .. root.putChild("save", resourceSave) root.putChild("load", resourceLoad) # both under one Twisted Web Site site = Site(root) reactor.listenTCP(LOCAL_PROXY_PORT, site) reactor.run()