Beispiel #1
0
def manhole_factory(namespace, username, password):
    """
    Produces a factory object which can be used to listen for telnet
    connections to the manhole.
    """
    assert isinstance(namespace, dict)
    assert isinstance(username, STRING_TYPES)
    assert isinstance(password, STRING_TYPES)
    assert TelnetRealm.NAMESPACE is None, "namespace already set"

    # TODO: we should try to use the system to authorize users instead
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser(username, password)

    # Setup the namespace
    namespace = namespace.copy()
    namespace.setdefault("pp", pprint)
    namespace.setdefault("show", show)

    realm = TelnetRealm()
    TelnetRealm.NAMESPACE = namespace
    portal = Portal(realm, [checker])
    factory = ServerFactory()
    factory.protocol = TransportProtocolFactory(portal)
    return factory
    def setUp(self):
        yield SMPPClientTestCases.setUp(self)

        # Init SMPPServerPB
        SMPPServerPBConfigInstance = SMPPServerPBConfig()
        SMPPServerPBInstance = SMPPServerPB(SMPPServerPBConfigInstance)
        SMPPServerPBInstance.addSmpps(self.smpps_factory)

        p = portal.Portal(JasminPBRealm(SMPPServerPBInstance))
        c = InMemoryUsernamePasswordDatabaseDontUse()
        c.addUser('smppsadmin', md5('smppspwd').digest())
        p.registerChecker(c)
        jPBPortalRoot = JasminPBPortalRoot(p)
        self.SMPPServerPBInstanceServer = reactor.listenTCP(SMPPServerPBConfigInstance.port,
                                                            pb.PBServerFactory(jPBPortalRoot))

        # Init SMPPServerPBClient and connect it to SMPPServerPB
        SMPPServerPBClientConfigInstance = SMPPServerPBClientConfig()
        self.SMPPServerPBProxyInstance = SMPPServerPBProxy()
        yield self.SMPPServerPBProxyInstance.connect(
            SMPPServerPBClientConfigInstance.host,
            SMPPServerPBClientConfigInstance.port,
            SMPPServerPBClientConfigInstance.username,
            SMPPServerPBClientConfigInstance.password,
            retry=False)

        # Lower the timeout config to pass the timeout tests quickly
        self.DLRThrower.config.timeout = 2
        self.DLRThrower.config.retry_delay = 1
        self.DLRThrower.config.max_retries = 2

        # Most important thing:
        # Swap default direct smpps access to perspectivebroker smpps access:
        self.DLRThrower.addSmpps(self.SMPPServerPBProxyInstance)
Beispiel #3
0
    def startRouterPBService(self):
        "Start Router PB server"

        RouterPBConfigInstance = RouterPBConfig(self.options['config'])
        self.components['router-pb-factory'] = RouterPB()
        self.components['router-pb-factory'].setConfig(RouterPBConfigInstance)

        # Set authentication portal
        p = portal.Portal(JasminPBRealm(self.components['router-pb-factory']))
        if RouterPBConfigInstance.authentication:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser(RouterPBConfigInstance.admin_username,
                      RouterPBConfigInstance.admin_password)
            p.registerChecker(c)
        else:
            p.registerChecker(AllowAnonymousAccess())
        jPBPortalRoot = JasminPBPortalRoot(p)

        # Add service
        self.components['router-pb-server'] = reactor.listenTCP(
            RouterPBConfigInstance.port,
            pb.PBServerFactory(jPBPortalRoot),
            interface=RouterPBConfigInstance.bind)

        # AMQP Broker is used to listen to deliver_sm/dlr queues
        return self.components['router-pb-factory'].addAmqpBroker(self.components['amqp-broker-factory'])
Beispiel #4
0
    def startSMPPClientManagerPBService(self):
        "Start SMPP Client Manager PB server"

        SMPPClientPBConfigInstance = SMPPClientPBConfig(self.options["config"])
        self.components["smppcm-pb-factory"] = SMPPClientManagerPB()
        self.components["smppcm-pb-factory"].setConfig(SMPPClientPBConfigInstance)

        # Set authentication portal
        p = portal.Portal(JasminPBRealm(self.components["smppcm-pb-factory"]))
        if SMPPClientPBConfigInstance.authentication:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser(SMPPClientPBConfigInstance.admin_username, SMPPClientPBConfigInstance.admin_password)
            p.registerChecker(c)
        else:
            p.registerChecker(AllowAnonymousAccess())
        jPBPortalRoot = JasminPBPortalRoot(p)

        # Add service
        self.components["smppcm-pb-server"] = reactor.listenTCP(
            SMPPClientPBConfigInstance.port,
            pb.PBServerFactory(jPBPortalRoot),
            interface=SMPPClientPBConfigInstance.bind,
        )

        # AMQP Broker is used to listen to submit_sm queues and publish to deliver_sm/dlr queues
        self.components["smppcm-pb-factory"].addAmqpBroker(self.components["amqp-broker-factory"])
        self.components["smppcm-pb-factory"].addRedisClient(self.components["rc"])
    def setUp(self, authentication=False):
        "This will launch InterceptorPB and provide a client connected to it."
        # Launch a client in a disconnected state
        # it will be connected on demand through the self.ipb_connect() method
        self.ipb_client = InterceptorPBProxy()

        yield ProvisionWithoutInterceptorPB.setUp(self)

        # Initiating config objects without any filename
        # will lead to setting defaults and that's what we
        # need to run the tests
        InterceptorPBConfigInstance = InterceptorPBConfig()

        # Launch the interceptor server
        pbInterceptor_factory = InterceptorPB()
        pbInterceptor_factory.setConfig(InterceptorPBConfigInstance)

        # Configure portal
        p = portal.Portal(JasminPBRealm(pbInterceptor_factory))
        if not authentication:
            p.registerChecker(AllowAnonymousAccess())
        else:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser("test_user", md5("test_password").digest())
            p.registerChecker(c)
        jPBPortalRoot = JasminPBPortalRoot(p)
        self.pbInterceptor_server = reactor.listenTCP(0, pb.PBServerFactory(jPBPortalRoot))
        self.pbInterceptor_port = self.pbInterceptor_server.getHost().port
def main(reactor, duration):
    chunkSize = 16384

    server = BenchmarkSSHFactory()
    server.portal = Portal(BenchmarkRealm())

    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.users = {b"username": b"password"}

    server.portal.registerChecker(checker)

    port = reactor.listenTCP(0, server)
    tcpServer = TCP4ClientEndpoint(reactor, '127.0.0.1', port.getHost().port)
    sshServer = SSHCommandClientEndpoint(
        b'chargen', tcpServer,
        lambda command:
            SSHPasswordUserAuth(b'username', b'password', command))

    client = Client(reactor, sshServer)
    d = client.run(duration, chunkSize)
    def cleanup(passthrough):
        d = port.stopListening()
        d.addCallback(lambda ignored: passthrough)
        return d
    d.addCallback(cleanup)
    return d
Beispiel #7
0
 def setUp(self, authentication = False):
     # Initiating config objects without any filename
     # will lead to setting defaults and that's what we
     # need to run the tests
     self.RouterPBConfigInstance = RouterPBConfig()
     
     # Launch the router server
     self.pbRoot_f = RouterPB()
     
     # Mock callbacks
     # will be used for assertions
     self.pbRoot_f.bill_request_submit_sm_resp_callback = mock.Mock(wraps = self.pbRoot_f.bill_request_submit_sm_resp_callback)
     self.pbRoot_f.deliver_sm_callback = mock.Mock(wraps = self.pbRoot_f.deliver_sm_callback)
     
     self.pbRoot_f.setConfig(self.RouterPBConfigInstance)
     p = portal.Portal(JasminPBRealm(self.pbRoot_f))
     if not authentication:
         p.registerChecker(AllowAnonymousAccess())
     else:
         c = InMemoryUsernamePasswordDatabaseDontUse()
         c.addUser('test_user', md5('test_password').digest())
         p.registerChecker(c)
     jPBPortalRoot = JasminPBPortalRoot(p)
     self.PBServer = reactor.listenTCP(0, pb.PBServerFactory(jPBPortalRoot))
     self.pbPort = self.PBServer.getHost().port
Beispiel #8
0
def create_portal(a):
    """I'm responsible for creating the authenticated portal"""
    realm = AggregatorRealm(a)
    portal = Portal(realm)
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser(version.apiversion, a.getPassword())
    portal.registerChecker(checker)
    return portal
def StartServices(username,password):
    from md5 import md5
    password = md5(password).digest()
    
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser(username,password)
    portal.registerChecker(checker)
    reactor.listenTCP(7001,pb.PBServerFactory(portal))
Beispiel #10
0
def main():
    from twisted.cred.portal import Portal
    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("benchmark", "benchmark")
    portal.registerChecker(checker)
    reactor.listenTCP(8787, pb.PBServerFactory(portal))
    reactor.run()
def StartServices():
    #fire up the World Stuff
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    from md5 import md5
    password = md5("daemon").digest()
    for x in range(0,100):
        checker.addUser(str(x), password)
    portal.registerChecker(checker)
    reactor.listenTCP(7000,pb.PBServerFactory(portal))
Beispiel #12
0
def main():
    from twisted.internet import reactor
    from twisted.cred.portal import Portal
    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("guest", "guest")
    portal.registerChecker(checker)
    reactor.listenTCP(pb.portno, pb.PBServerFactory(portal))
    reactor.run()
Beispiel #13
0
    def setServiceParent(self, parent):
        service.MultiService.setServiceParent(self, parent)

        portal = Portal(PbRealm(parent))

        checker = InMemoryUsernamePasswordDatabaseDontUse()
        checker.addUser("guest", "guest")
        portal.registerChecker(checker)

        s = strports.service("unix:%s" % self.socket, pb.PBServerFactory(portal))
        s.setServiceParent(self)
Beispiel #14
0
def setup():
    from twisted.internet import reactor
    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse


    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("guest", "password")
    portal.registerChecker(checker)

    reactor.listenTCP(7777, ConsoleSMTPFactory(portal))
Beispiel #15
0
class WrapResourceTestCase(TestCase):

    def setUp(self):
        self.checker = InMemoryUsernamePasswordDatabaseDontUse()
        self.checker.addUser("joe", "blow")

    def test_wrapResourceWeb(self):
        from twisted.web.resource import IResource, Resource
        root = Resource()
        wrapped = wrapResource(root, [self.checker])
        self.assertTrue(IResource.providedBy(wrapped))
Beispiel #16
0
def main():
    """
    Start the AMP server and the reactor.
    """
    startLogging(stdout)
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("testuser", "examplepass")
    realm = AdditionRealm()
    factory = CredAMPServerFactory(Portal(realm, [checker]))
    reactor.listenTCP(7805, factory)
    reactor.run()
    def test_setupSiteWithProtectedHook(self):
        checker = InMemoryUsernamePasswordDatabaseDontUse()
        checker.addUser("guest", "password")

        self.svc.setupSite(self.makeConfig(change_hook_dialects={"base": True}, change_hook_auth=[checker]))
        site = self.svc.site

        # check that it has the right kind of resources attached to its
        # root
        root = site.resource
        req = mock.Mock()
        self.assertIsInstance(root.getChildWithDefault("change_hook", req), HTTPAuthSessionWrapper)
Beispiel #18
0
    def __init__(self, port=8787):
        BaseService.__init__(self)

        boiler = None
        portal = Portal(PbRealm(boiler))

        checker = InMemoryUsernamePasswordDatabaseDontUse()
        checker.addUser("guest", "guest")
        portal.registerChecker(checker)

        service = strports.service("tcp:%d" % port, pb.PBServerFactory(portal))
        service.setServiceParent(self)
Beispiel #19
0
def StartServices(callback):
    global IMPCONNECTED_CALLBACK
    IMPCONNECTED_CALLBACK = callback
    # fire up the World Stuff
    portal = Portal(SimpleRealm())
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    from md5 import md5

    password = md5("imp").digest()
    for x in range(0, 100):
        checker.addUser(str(x), password)
    portal.registerChecker(checker)
    reactor.listenTCP(7005, pb.PBServerFactory(portal))
 def test_requestAvatarId(self):
     """
     L{SSHProtocolChecker.requestAvatarId} should defer to one if its
     registered checkers to authenticate a user.
     """
     checker = SSHProtocolChecker()
     passwordDatabase = InMemoryUsernamePasswordDatabaseDontUse()
     passwordDatabase.addUser('test', 'test')
     checker.registerChecker(passwordDatabase)
     d = checker.requestAvatarId(UsernamePassword('test', 'test'))
     def _callback(avatarId):
         self.assertEquals(avatarId, 'test')
     return d.addCallback(_callback)
Beispiel #21
0
def protectResource(resource, accessKey, secretKey, realm=None):

    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
    from twisted.web.guard import HTTPAuthSessionWrapper
    from twisted.cred.portal import Portal

    portal_realm = _SingleResourceRealm(resource)

    cred_checker = InMemoryUsernamePasswordDatabaseDontUse()
    cred_checker.addUser(accessKey, secretKey)
    portal = Portal(portal_realm, [cred_checker])

    cred_factory = AuthHMACCredentialFactory(realm or 'twoost-app')
    return HTTPAuthSessionWrapper(portal, [cred_factory])
def main():
    from twisted.application import internet
    from twisted.application import service    
    
    portal = Portal(SimpleRealm())
    # initiate a simple checker
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("guest", "password")
    portal.registerChecker(checker)
    
    a = service.Application("Console SMTP Server")
    internet.TCPServer(2500, ConsoleSMTPFactory(portal)).setServiceParent(a)
    
    return a
 def setUp(self):
     self.service_calls = []
     self.encoder = pdu_encoding.PDUEncoder()
     self.smpp_config = SMPPServerConfig(msgHandler=self._serviceHandler,
                                         systems={'userA': {"max_bindings": 2}}
                                         )
     portal = Portal(self.SmppRealm())
     credential_checker = InMemoryUsernamePasswordDatabaseDontUse()
     credential_checker.addUser('userA', 'valid')
     portal.registerChecker(credential_checker)
     self.factory = SMPPServerFactory(self.smpp_config, auth_portal=portal)
     self.proto = self.factory.buildProtocol(('127.0.0.1', 0))
     self.tr = proto_helpers.StringTransport()
     self.proto.makeConnection(self.tr)
    def test_requestAvatarIdWithNotEnoughAuthentication(self):
        """
        If the client indicates that it is never satisfied, by always returning
        False from _areDone, then L{SSHProtocolChecker} should raise
        L{NotEnoughAuthentication}.
        """
        checker = SSHProtocolChecker()
        def _areDone(avatarId):
            return False
        self.patch(checker, 'areDone', _areDone)

        passwordDatabase = InMemoryUsernamePasswordDatabaseDontUse()
        passwordDatabase.addUser('test', 'test')
        checker.registerChecker(passwordDatabase)
        d = checker.requestAvatarId(UsernamePassword('test', 'test'))
        return self.assertFailure(d, NotEnoughAuthentication)
Beispiel #25
0
def new_restricted_server_resource(app, dhcp_request_processing_service,
                                   credentials, realm_name=REALM_NAME):
    """Create and return a new server resource that will be accessible only
    if the given credentials are present in the HTTP requests.
    
    credentials is a (username, password) tuple.
    
    """
    server_resource = ServerResource(app, dhcp_request_processing_service)
    pwd_checker = InMemoryUsernamePasswordDatabaseDontUse()
    pwd_checker.addUser(*credentials)
    realm = _SimpleRealm(server_resource)
    portal = Portal(realm, [pwd_checker])
    credentialFactory = DigestCredentialFactory('MD5', realm_name)
    wrapper = HTTPAuthSessionWrapper(portal, [credentialFactory])
    return wrapper
Beispiel #26
0
    def setUp(self, authentication = False):
        # Initiating config objects without any filename
        # will lead to setting defaults and that's what we
        # need to run the tests
        self.SMPPClientPBConfigInstance = SMPPClientPBConfig()
        self.SMPPClientPBConfigInstance.authentication = authentication
        AMQPServiceConfigInstance = AmqpConfig()
        AMQPServiceConfigInstance.reconnectOnConnectionLoss = False

        # Launch AMQP Broker
        self.amqpBroker = AmqpFactory(AMQPServiceConfigInstance)
        self.amqpBroker.preConnect()
        self.amqpClient = reactor.connectTCP(AMQPServiceConfigInstance.host, AMQPServiceConfigInstance.port, self.amqpBroker)

        # Wait for AMQP Broker connection to get ready
        yield self.amqpBroker.getChannelReadyDeferred()

        # Launch the client manager server
        pbRoot = SMPPClientManagerPB()
        pbRoot.setConfig(self.SMPPClientPBConfigInstance)

        yield pbRoot.addAmqpBroker(self.amqpBroker)
        p = portal.Portal(JasminPBRealm(pbRoot))
        if not authentication:
            p.registerChecker(AllowAnonymousAccess())
        else:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser('test_user', md5('test_password').digest())
            p.registerChecker(c)
        jPBPortalRoot = JasminPBPortalRoot(p)
        self.PBServer = reactor.listenTCP(0, pb.PBServerFactory(jPBPortalRoot))
        self.pbPort = self.PBServer.getHost().port

        # Launch the router server
        self.RouterPBInstance = RouterPB()
        self.RouterPBInstance.setConfig(RouterPBConfig())
        pbRoot.addRouterPB(self.RouterPBInstance)

        # Default SMPPClientConfig
        defaultSMPPClientId = '001-testconnector'

        self.defaultConfig = SMPPClientConfig(id=defaultSMPPClientId,
                                              username='******',
                                              reconnectOnConnectionFailure=True,
                                              port=9002,
                                              )
Beispiel #27
0
	def runConcurrentThread(self):
		
		port = int(self.pluginPrefs.get('smtpPort', '2525'))
		user = self.pluginPrefs.get('smtpUser', 'guest')
		password = self.pluginPrefs.get('smtpPassword', 'password')
							
		portal = Portal(SimpleRealm())
		checker = InMemoryUsernamePasswordDatabaseDontUse()
		checker.addUser(user, password)
		portal.registerChecker(checker)

		try:
			self.smtpFactory = MySMTPFactory(portal)
			self.listeningPort = reactor.listenTCP(port, self.smtpFactory)
			reactor.run()
		except self.StopThread:
			pass	# Optionally catch the StopThread exception and do any needed cleanup.
Beispiel #28
0
    def __init__(self, config):
        self._config = config
        self._emails = deque([])
        self._authorisedHelo = config.get("AuthorisedHosts", ["127.0.0.1"])
        self.noisy = config.get("LogNoisy", True)

        self.portal = Portal(SimpleRealm(self))

        if self._config.get("Authentication", False):
            checker = InMemoryUsernamePasswordDatabaseDontUse()
            checker.addUser("guest", "password")
            print "Checking Authentication"
        else:
            checker = AllowAnonymousAccess()
            print "Allowing anonymous access"

        self.portal.registerChecker(checker)
Beispiel #29
0
    def get_service(self):
        """
        Creates a service object that can be used by twistd init code to start the server
        """
        realm = ClusterRealm()
        realm.server = self

        # create security - Twisted does not support ssh in the pb so were doing our
        # own authentication until it is implmented, leaving in the memory
        # checker just so we dont have to rip out the authentication code
        from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
        checker =   InMemoryUsernamePasswordDatabaseDontUse()
        checker.addUser('master','1234')
        p = portal.Portal(realm, [checker])

        factory = pb.PBServerFactory(p)
        return internet.TCPServer(self.port, factory)
Beispiel #30
0
    def setUp(self, authentication = False):
        # Initiating config objects without any filename
        # will lead to setting defaults and that's what we
        # need to run the tests
        self.InterceptorPBConfigInstance = InterceptorPBConfig()
        self.InterceptorPBConfigInstance.authentication = authentication

        # Launch the interceptor pb server
        pbRoot = InterceptorPB()
        pbRoot.setConfig(self.InterceptorPBConfigInstance)

        p = portal.Portal(JasminPBRealm(pbRoot))
        if not authentication:
            p.registerChecker(AllowAnonymousAccess())
        else:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser('test_user', md5('test_password').digest())
            p.registerChecker(c)
        jPBPortalRoot = JasminPBPortalRoot(p)
        self.IPBServer = reactor.listenTCP(0, pb.PBServerFactory(jPBPortalRoot))
        self.ipbPort = self.IPBServer.getHost().port

        # Test fixtures
        self.SubmitSMPDU = SubmitSM(
            source_addr='20203060',
            destination_addr='20203060',
            short_message='MT hello world',
        )
        self.DeliverSMPDU = DeliverSM(
            source_addr='20203060',
            destination_addr='20203060',
            short_message='MO hello world',
        )
        self.connector = Connector('abc')
        self.user = User(1, Group(100), 'username', 'password')

        # Routables fixtures
        self.routable_simple = SimpleRoutablePDU(self.connector, self.SubmitSMPDU, self.user, datetime.now())

        # Scripts fixtures
        self.script_generic = InterceptorScript('somevar = "something in MOIS"')
        self.script_3_second = InterceptorScript('import time;time.sleep(3)')
        self.script_syntax_error = InterceptorScript('somevar = sssss')
        self.script_http_status = InterceptorScript('http_status = 404')
        self.script_smpp_status = InterceptorScript('smpp_status = 64')
Beispiel #31
0
    def testGetLoggedInRoot_httpAuthLogin(self):

        p = self.createPortal(realmFactory=GetLoggedInRealm)
        p.registerChecker(InMemoryUsernamePasswordDatabaseDontUse(test='test'),
                          IUsernamePassword)
        chan = self.createGuard(p)
        for x in range(4):
            req = chan.makeFakeRequest('%s/' % self.getGuardPath(), "test",
                                       "test")
            self.assertEquals(req.written.getvalue(), "GetLoggedInAvatar")
        self.assertEquals(len(self.sessions), 1)
Beispiel #32
0
def main(root):
    log.startLogging(sys.stdout)
    checkers = [InMemoryUsernamePasswordDatabaseDontUse(**USERS)]

    wrapper = guard.HTTPAuthSessionWrapper(
        Portal(SimpleRealm(root), checkers),
        [guard.DigestCredentialFactory('md5', 'whatever.com')])

    reactor.listenSSL(443, server.Site(resource=wrapper),
                      contextFactory=sslContext)
    reactor.run()
Beispiel #33
0
 def setUp(self):
     self.service_calls = []
     self.clock = task.Clock()
     self.encoder = pdu_encoding.PDUEncoder()
     self.smpp_config = SMPPServerConfig(
         msgHandler=self._serviceHandler,
         systems={'userA': {
             "max_bindings": 2
         }},
         enquireLinkTimerSecs=0.1,
         responseTimerSecs=0.1)
     portal = Portal(self.SmppRealm())
     credential_checker = InMemoryUsernamePasswordDatabaseDontUse()
     credential_checker.addUser('userA', 'valid')
     portal.registerChecker(credential_checker)
     self.factory = SMPPServerFactory(self.smpp_config, auth_portal=portal)
     self.proto = self.factory.buildProtocol(('127.0.0.1', 0))
     self.proto.callLater = self.clock.callLater
     self.tr = proto_helpers.StringTransport()
     self.proto.makeConnection(self.tr)
Beispiel #34
0
 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)
Beispiel #35
0
    def testLoginExtraPath_withSlash(self):
        p = self.createPortal()
        p.registerChecker(InMemoryUsernamePasswordDatabaseDontUse(test='test'),
                          IUsernamePassword)
        chan = self.createGuard(p)

        req = chan.makeFakeRequest(
            '%s/__login__/sub/path/?username=test&password=test' %
            self.getGuardPath()).followAllRedirects()
        self.assertEquals(req.written.getvalue(), "Yes")
        self.assertEquals(req.path, '%s/sub/path/' % self.getGuardPath())
Beispiel #36
0
    def setupProtectedResource(self, resource_obj):
        class SimpleRealm(object):
            """
            A realm which gives out L{ChangeHookResource} instances for authenticated
            users.
            """
            implements(IRealm)

            def requestAvatar(self, avatarId, mind, *interfaces):
                if resource.IResource in interfaces:
                    return (resource.IResource, resource_obj, lambda: None)
                raise NotImplementedError()

        login, password = self.change_hook_auth
        checker = InMemoryUsernamePasswordDatabaseDontUse()
        checker.addUser(login, password)
        portal = Portal(SimpleRealm(), [checker])
        credentialFactory = guard.BasicCredentialFactory('Protected area')
        wrapper = guard.HTTPAuthSessionWrapper(portal, [credentialFactory])
        return wrapper
Beispiel #37
0
 def __init__(self, users, **kwargs):
     if isinstance(users, dict):
         users = {user: unicode2bytes(pw) for user, pw in users.items()}
     elif isinstance(users, list):
         users = [(user, unicode2bytes(pw)) for user, pw in users]
     TwistedICredAuthBase.__init__(
         self,
         [DigestCredentialFactory(b"md5", b"buildbot"),
          BasicCredentialFactory(b"buildbot")],
         [InMemoryUsernamePasswordDatabaseDontUse(**dict(users))],
         **kwargs)
    def setUp(self, authentication=False):
        SMPPServerTestCases.setUp(self)

        # Initiating config objects without any filename
        self.SMPPServerPBConfigInstance = SMPPServerPBConfig()
        self.SMPPServerPBConfigInstance.authentication = authentication

        # Launch the SMPPServerPB
        pbRoot = SMPPServerPB(self.SMPPServerPBConfigInstance)
        pbRoot.addSmpps(self.smpps_factory)

        p = portal.Portal(JasminPBRealm(pbRoot))
        if not authentication:
            p.registerChecker(AllowAnonymousAccess())
        else:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser('test_user', md5('test_password').digest())
            p.registerChecker(c)
        jPBPortalRoot = JasminPBPortalRoot(p)
        self.PBServer = reactor.listenTCP(0, pb.PBServerFactory(jPBPortalRoot))
        self.pbPort = self.PBServer.getHost().port
Beispiel #39
0
def makeManholeService(ns, options):
    from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
    checker = InMemoryUsernamePasswordDatabaseDontUse(admin="admin")

    def chainProtocolFactory():
        return insults.ServerProtocol(ColoredManhole, namespace=ns)

    rlm = TerminalRealm()
    rlm.chainedProtocolFactory = chainProtocolFactory
    ptl = portal.Portal(rlm, [checker])
    f = ConchFactory(ptl)
    return internet.TCPServer(options['manhole-port'], f)
Beispiel #40
0
    def testErrorPage_getLogin_deep(self):
        """Failed normal login results in anonymous view of the same page."""
        p = self.createPortal()
        p.registerChecker(InMemoryUsernamePasswordDatabaseDontUse(test='test'),
                          IUsernamePassword)
        chan = self.createGuard(p)

        req = chan.makeFakeRequest(
            '%s/__login__/quux/thud?username=test&password=invalid-password' %
            self.getGuardPath()).followAllRedirects()
        self.assertEquals(req.written.getvalue(), 'No')
        self.assertEquals(req.path, '%s/quux/thud' % self.getGuardPath())
Beispiel #41
0
    def test_init(self):
        """
        It should accept a UserStore on init
        """
        checker = InMemoryUsernamePasswordDatabaseDontUse()
        realm = UserRealm()

        app = ServerApp(None, realm, [checker], 'services')
        self.assertEqual(app.ticket_store, None)
        self.assertEqual(app.portal.realm, realm)
        self.assertIn(checker, app.portal.checkers.values())
        self.assertEqual(app.validService, 'services')
Beispiel #42
0
    def setUp(self, authentication = False):
        # Initiating config objects without any filename
        # will lead to setting defaults and that's what we
        # need to run the tests
        self.SMPPClientPBConfigInstance = SMPPClientPBConfig()
        self.SMPPClientPBConfigInstance.authentication = authentication
        AMQPServiceConfigInstance = AmqpConfig()
        AMQPServiceConfigInstance.reconnectOnConnectionLoss = False

        # Launch AMQP Broker
        self.amqpBroker = AmqpFactory(AMQPServiceConfigInstance)
        self.amqpBroker.preConnect()
        self.amqpClient = reactor.connectTCP(AMQPServiceConfigInstance.host, AMQPServiceConfigInstance.port, self.amqpBroker)

        # Wait for AMQP Broker connection to get ready
        yield self.amqpBroker.getChannelReadyDeferred()

        # Launch the client manager server
        pbRoot = SMPPClientManagerPB()
        pbRoot.setConfig(self.SMPPClientPBConfigInstance)
        yield pbRoot.addAmqpBroker(self.amqpBroker)
        p = portal.Portal(JasminPBRealm(pbRoot))
        if not authentication:
            p.registerChecker(AllowAnonymousAccess())
        else:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser('test_user', md5('test_password').digest())
            p.registerChecker(c)
        jPBPortalRoot = JasminPBPortalRoot(p)
        self.PBServer = reactor.listenTCP(0, pb.PBServerFactory(jPBPortalRoot))
        self.pbPort = self.PBServer.getHost().port

        # Default SMPPClientConfig
        defaultSMPPClientId = '001-testconnector'

        self.defaultConfig = SMPPClientConfig(id=defaultSMPPClientId,
                                              username='******',
                                              reconnectOnConnectionFailure=True,
                                              port=9002,
                                              )
def main():
    realm = TradeRealm()
    realm.server = TradeEngine(realm)
    
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("guest", "guest")
    checker.addUser("admin","123")
    checker.addUser("0017aca","1")
    checker.addUser('0017cac','1')
    portal = Portal(realm, [checker])  
    
    factory = pb.PBServerFactory(portal)
    reactor.listenTCP(pb.portno, factory)
    reactor.run()
Beispiel #44
0
    def startInterceptorPBService(self):
        """Start Interceptor PB server"""

        InterceptorPBConfigInstance = InterceptorPBConfig(self.options['config'])
        self.components['interceptor-pb-factory'] = InterceptorPB(InterceptorPBConfigInstance)

        # Set authentication portal
        p = portal.Portal(JasminPBRealm(self.components['interceptor-pb-factory']))
        if InterceptorPBConfigInstance.authentication:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser(InterceptorPBConfigInstance.admin_username,
                      InterceptorPBConfigInstance.admin_password)
            p.registerChecker(c)
        else:
            p.registerChecker(AllowAnonymousAccess())
        jPBPortalRoot = JasminPBPortalRoot(p)

        # Add service
        self.components['interceptor-pb-server'] = reactor.listenTCP(
            InterceptorPBConfigInstance.port,
            pb.PBServerFactory(jPBPortalRoot),
            interface=InterceptorPBConfigInstance.bind)
Beispiel #45
0
def main():
	log.startLogging(sys.stdout)

	# TBD: get the admin password from an environment variable

	credCheckers = [InMemoryUsernamePasswordDatabaseDontUse(admin='secret')]

	wrapper = guard.HTTPAuthSessionWrapper(
		Portal(AdministrativeRealm(), credCheckers),
		[guard.DigestCredentialFactory('md5', 'suse.com')])

	reactor.listenTCP(8889, server.Site(resource = wrapper))
	reactor.run()
Beispiel #46
0
    def startSMPPClientManagerPBService(self):
        "Start SMPP Client Manager PB server"

        SMPPClientPBConfigInstance = SMPPClientPBConfig(self.options['config'])
        self.components['smppcm-pb-factory'] = SMPPClientManagerPB()
        self.components['smppcm-pb-factory'].setConfig(
            SMPPClientPBConfigInstance)

        # Set authentication portal
        p = portal.Portal(JasminPBRealm(self.components['smppcm-pb-factory']))
        if SMPPClientPBConfigInstance.authentication:
            c = InMemoryUsernamePasswordDatabaseDontUse()
            c.addUser(SMPPClientPBConfigInstance.admin_username,
                      SMPPClientPBConfigInstance.admin_password)
            p.registerChecker(c)
        else:
            p.registerChecker(AllowAnonymousAccess())
        jPBPortalRoot = JasminPBPortalRoot(p)

        # Add service
        self.components['smppcm-pb-server'] = reactor.listenTCP(
            SMPPClientPBConfigInstance.port,
            pb.PBServerFactory(jPBPortalRoot),
            interface=SMPPClientPBConfigInstance.bind)

        # AMQP Broker is used to listen to submit_sm queues and publish to deliver_sm/dlr queues
        self.components['smppcm-pb-factory'].addAmqpBroker(
            self.components['amqp-broker-factory'])
        self.components['smppcm-pb-factory'].addRedisClient(
            self.components['rc'])
        self.components['smppcm-pb-factory'].addRouterPB(
            self.components['router-pb-factory'])

        # Add interceptor if enabled:
        if 'interceptor-pb-client' in self.components:
            self.components['smppcm-pb-factory'].addInterceptorPBClient(
                self.components['interceptor-pb-client'])
Beispiel #47
0
    def __init__(self, map, total_players):
        import player

        players = [player.PlayerCacheable(i) for i in range(total_players)]
        import game

        self.game = game.Game(players=players, server=self)
        map.setup()
        self.game.set_map(map)
        self.ai_players = []

        from twisted.cred.portal import Portal
        from twisted.cred.checkers import (
            AllowAnonymousAccess,
            InMemoryUsernamePasswordDatabaseDontUse,
        )

        portal = Portal(RequestClientRealm(self))
        checker = InMemoryUsernamePasswordDatabaseDontUse()
        checker.addUser("guest", "guest")
        # 	checker = AllowAnonymousAccess()
        portal.registerChecker(checker)
        self.listening_port = reactor.listenTCP(pb.portno,
                                                pb.PBServerFactory(portal))
Beispiel #48
0
    def make_manhole_server(self, port, username, password):
        from twisted.application.internet import TCPServer
        from twisted.cred.portal import Portal
        from twisted.cred.checkers import InMemoryUsernamePasswordDatabaseDontUse
        from twisted.conch.manhole import ColoredManhole
        from twisted.conch.manhole_ssh import ConchFactory, TerminalRealm
        from twisted.conch.insults.insults import ServerProtocol

        rlm = TerminalRealm()
        rlm.chainedProtocolFactory = lambda: ServerProtocol(
            ColoredManhole, None)

        auth_checker = InMemoryUsernamePasswordDatabaseDontUse(
            **{username: password})

        return TCPServer(port, ConchFactory(Portal(rlm, [auth_checker])))
Beispiel #49
0
    def testErrorPage_httpAuth_deep(self):
        """Failed HTTP Auth results in a 403 error."""
        p = self.createPortal()
        p.registerChecker(InMemoryUsernamePasswordDatabaseDontUse(test='test'),
                          IUsernamePassword)
        chan = self.createGuard(p)

        req = chan.makeFakeRequest('%s/quux/thud' % self.getGuardPath(),
                                   "test", "invalid-password")
        self.assertFalse(req.responseHeaders.hasHeader('location'))
        self.assertEquals(req.code, 403)
        self.assertEquals(req.written.getvalue(),
                          '<html><head><title>Forbidden</title></head>'
                          +'<body><h1>Forbidden</h1>Request was forbidden.'
                          +'</body></html>')
        self.assertEquals(req.path, '%s/quux/thud' % self.getGuardPath())
Beispiel #50
0
    def test_httpAuthInit(self):
        """
        A request for a guarded URL which includes HTTP AUTH headers giving
        valid credentials is responded to with the resource given back by the
        realm for the avatar identified by those credentials and a single
        session is created for that avatar.
        """
        p = self.createPortal()
        chan = self.createGuard(p)
        p.registerChecker(InMemoryUsernamePasswordDatabaseDontUse(test='test'), IUsernamePassword)

        # Make the request three times.  The same resource should come back
        # each time, and there should only ever be one session.
        for x in range(3):
            req = chan.makeFakeRequest('%s/' % self.getGuardPath(), "test", "test")
            self.assertEquals(req.written.getvalue(), "Yes")
            self.assertEquals(len(self.sessions), 1)
Beispiel #51
0
 def _leaky(self):
     p = self.createPortal(LeakyRealm)
     sw = self.createSessionWrapper(p)
     p.registerChecker(
         InMemoryUsernamePasswordDatabaseDontUse(test0='test0',
                                                 test1='test1',
                                                 test2='test2',
                                                 test3='test3',
                                                 test4='test4',
                                                 test5='test5',
                                                 test6='test6',
                                                 test7='test7',
                                                 test8='test8',
                                                 test9='test9'),
         IUsernamePassword)
     for x in range(10):
         self.makeRequest(sw, p, 'test%s' % x)
Beispiel #52
0
def main():
    """
    Create a PB server using MyRealm and run it on port 8800.
    """
    startLogging(stdout)

    p = Portal(MyRealm())

    # Here the username/password checker is registered.
    c1 = InMemoryUsernamePasswordDatabaseDontUse(user1="pass1", user2="pass2")
    p.registerChecker(c1)

    # Here the anonymous checker is registered.
    c2 = AllowAnonymousAccess()
    p.registerChecker(c2)

    reactor.listenTCP(8800, PBServerFactory(p))
    reactor.run()
Beispiel #53
0
    def testUsernamePassword(self):
        p = self.createPortal()
        p.registerChecker(InMemoryUsernamePasswordDatabaseDontUse(test='test'), IUsernamePassword)
        chan = self.createGuard(p)

        # Check the anonymous page
        req = chan.makeFakeRequest('%s/' % self.getGuardPath()).followAllRedirects()
        self.assertEquals(req.written.getvalue(), "No")

        # Check the logged in page
        req = chan.makeFakeRequest('%s/__login__/?username=test&password=test' % self.getGuardPath()).followAllRedirects()
        self.assertEquals(req.written.getvalue(), "Yes")

        # Log out
        chan.makeFakeRequest("%s/__logout__" % self.getGuardPath()).followRedirect()

        # Get the anonymous page again
        k = chan.makeFakeRequest("%s/" % self.getGuardPath())
        self.assertEquals(k.written.getvalue(), "No")
Beispiel #54
0
    def __init__(self, port, pws, **kw):
        kw.update(globals())
        kw['pp'] = pprint

        realm = manhole_ssh.TerminalRealm()
        manhole = ManholeWithCompleter(kw)

        def windowChanged(_, win_size):
            manhole.terminalSize(*reversed(win_size[:2]))

        realm.sessionFactory.windowChanged = windowChanged
        realm.chainedProtocolFactory.protocolFactory = lambda _: manhole
        portal = Portal(realm)
        portal.registerChecker(InMemoryUsernamePasswordDatabaseDontUse(**pws))
        factory = manhole_ssh.ConchFactory(portal)
        public_key_str, private_key_str = get_rsa_keys()
        factory.publicKeys = {'ssh-rsa': keys.Key.fromString(public_key_str)}
        factory.privateKeys = {'ssh-rsa': keys.Key.fromString(private_key_str)}
        reactor.listenTCP(port, factory, interface='localhost')
Beispiel #55
0
    def test_loginRestoresRequestParameters(self):
        """
        After login has succeeded, the GET arguments, POST arguments, body,
        method, and headers from the request which triggered the login are set
        on the request which will be responded to with the guarded resource.
        """
        renders = []
        portal = self.createPortal(lambda: SillyRealm(
            authenticatedAvatarFactory=lambda: InspectfulPage(renders)))
        portal.registerChecker(
            InMemoryUsernamePasswordDatabaseDontUse(test='test'),
            IUsernamePassword)
        channel = self.createGuard(portal)

        # Negotiate a session.
        request = channel.makeFakeRequest(self.getGuardPath())
        request = request.followAllRedirects()

        # Pretend to be a resource before login which requires login and saves
        # request state.
        request.session.args = {'foo': ['1'], 'bar': ['2']}
        request.session.fields = None
        request.session.method = 'GET'
        request.session.content = None
        request.session._requestHeaders = Headers({
            'host': ['fake.com'],
            'extra': ['bar']
        })

        # Perform the login.
        request = channel.makeFakeRequest(
            self.getGuardPath() + '/__login__?username=test&password=test')
        request = request.followAllRedirects()

        self.assertEqual(request.written.getvalue(), '')
        self.assertEqual(renders, [({
            'foo': ['1'],
            'bar': ['2']
        }, None, None, 'GET', Headers({
            'host': ['fake.com'],
            'extra': ['bar']
        }))])
Beispiel #56
0
def getResource(rest_cfg, service):
    checkers = []
    if "users" in rest_cfg:
        checkers.append(
            InMemoryUsernamePasswordDatabaseDontUse(**rest_cfg["users"])
        )

    res = Resource()
    res.putChild("uuid", ByUUID(service))
    res.putChild("id", ByID(service))
    res.putChild("merge", Merge(service))


    #realm = TildeRESTRealm()
    #realm.root = res
    #portal = Portal(realm, checkers)
    #credFactory = DigestCredentialFactory("md5", "localhost:8081")

    #res = HTTPAuthSessionWrapper(portal, [credFactory])
    return res
def main():
    # log
    log.startLogging(sys.stdout)

    checkers = [InMemoryUsernamePasswordDatabaseDontUse(joe='blow')]

    portal = Portal(SimpleRealm(), checkers)

    credFactory = [guard.DigestCredentialFactory('md5', 'example.com')]

    wrapper = guard.HTTPAuthSessionWrapper(portal, credFactory)

    # guard.HTTPAuthSessionWrapper(
    #     Portal(SimpleRealm(), checkers),
    #     [guard.DigestCredentialFactory('md5', 'example.com')])

    factory = server.Site(resource=wrapper)

    reactor.listenTCP(8889, factory)

    reactor.run()
Beispiel #58
0
        b'ssh-userauth': myClass,
        b'ssh-connection': connection.SSHConnection
    }

    def getPrimes(self):
        """
        See: L{factory.SSHFactory}
        """
        return PRIMES


class ClientUserAuth(userauth.SSHUserAuthClient):
    def __init__(self):
        super().__init__()

    def auth_password(self):
        #normal password authentication
        return False


portal = portal.Portal(ExampleRealm())
passwdDB = InMemoryUsernamePasswordDatabaseDontUse()
portal.registerChecker(passwdDB)

ExampleFactory.portal = portal

if __name__ == '__main__':
    print("ssh started")
    reactor.listenTCP(2222, ExampleFactory())
    reactor.run()
Beispiel #59
0
    # Server's host keys.
    # To simplify the example this server is defined only with a host key of
    # type RSA.
    publicKeys = {'ssh-rsa': keys.Key.fromFile(SERVER_RSA_PUBLIC)}
    privateKeys = {'ssh-rsa': keys.Key.fromFile(SERVER_RSA_PRIVATE)}
    # Service handlers.
    services = {
        'ssh-userauth': userauth.SSHUserAuthServer,
        'ssh-connection': connection.SSHConnection
    }

    def getPrimes(self):
        """
        See: L{factory.SSHFactory}
        """
        return PRIMES


portal = portal.Portal(ExampleRealm())
passwdDB = InMemoryUsernamePasswordDatabaseDontUse()
passwdDB.addUser('user', 'password')
sshDB = SSHPublicKeyChecker(
    InMemorySSHKeyDB({'user': [keys.Key.fromFile(CLIENT_RSA_PUBLIC)]}))
portal.registerChecker(passwdDB)
portal.registerChecker(sshDB)
ExampleFactory.portal = portal

if __name__ == '__main__':
    reactor.listenTCP(5022, ExampleFactory())
    reactor.run()
Beispiel #60
0
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