def test_failOnKeyError(self): """ If the getpwnam function raises a KeyError, the login fails with an L{UnauthorizedLogin} exception. """ def getpwnam(username): raise KeyError(username) checker = checkers.UNIXPasswordDatabase([getpwnam]) credential = UsernamePassword(b"username", b"username") self.assertUnauthorizedLogin(checker.requestAvatarId(credential))
def testUpgrade(self): p = Portal(IRealm(self.store), [ICredentialsChecker(self.store)]) def loggedIn((ifc, av, lgo)): assert av.garbage == 7 # Bug in cooperator? this triggers an exception. # return svc.stopService() d = p.login(UsernamePassword('*****@*****.**', SECRET), None, IGarbage) return d.addCallback(loggedIn)
def test_failOnSpecial(self): """ If the password returned by any function is C{""}, C{"x"}, or C{"*"} it is not compared against the supplied password. Instead it is skipped. """ pwd = UserDatabase() pwd.addUser('alice', '', 1, 2, '', 'foo', 'bar') pwd.addUser('bob', 'x', 1, 2, '', 'foo', 'bar') pwd.addUser('carol', '*', 1, 2, '', 'foo', 'bar') self.patch(checkers, 'pwd', pwd) checker = checkers.UNIXPasswordDatabase([checkers._pwdGetByName]) cred = UsernamePassword('alice', '') self.assertUnauthorizedLogin(checker.requestAvatarId(cred)) cred = UsernamePassword('bob', 'x') self.assertUnauthorizedLogin(checker.requestAvatarId(cred)) cred = UsernamePassword('carol', '*') self.assertUnauthorizedLogin(checker.requestAvatarId(cred))
def test_good_creds(self): # set up a dummy server which always return a *valid* token document token = {'user_id': 'user', 'type': 'Token'} server = dummy_server(token) # setup the checker with the custom server checker = CouchDBTokenChecker() auth_module.couch_server = lambda url: server # assert the checker *can* verify the creds creds = UsernamePassword('user', 'pass') avatarId = yield checker.requestAvatarId(creds) self.assertEqual('user', avatarId)
def test_bad_creds(self): # set up a dummy server which always return an *invalid* token document token = None server = dummy_server(token) # setup the checker with the custom server checker = CouchDBTokenChecker() auth_module.couch_server = lambda url: server # assert the checker *cannot* verify the creds creds = UsernamePassword('user', '') with self.assertRaises(UnauthorizedLogin): yield checker.requestAvatarId(creds)
def test_good_creds(self): auth_file_path = os.path.join(self.tempdir, 'auth.file') with open(auth_file_path, 'w') as tempfile: tempfile.write('goodservice:goodtoken') # setup the checker with the auth tokens file conf = {'services_tokens_file': auth_file_path} checker = FileTokenChecker(conf) # assert the checker *can* verify the creds creds = UsernamePassword('goodservice', 'goodtoken') avatarId = yield checker.requestAvatarId(creds) self.assertEqual('goodservice', avatarId)
def test_bad_creds(self): auth_file_path = os.path.join(self.tempdir, 'auth.file') with open(auth_file_path, 'w') as tempfile: tempfile.write('service:token') # setup the checker with the auth tokens file conf = {'services_tokens_file': auth_file_path} checker = FileTokenChecker(conf) # assert the checker *cannot* verify the creds creds = UsernamePassword('service', 'wrongtoken') with self.assertRaises(UnauthorizedLogin): yield checker.requestAvatarId(creds)
def test_portal(self): """ L{AMPConfiguration.getFactory} returns a factory which creates protocols which have a C{portal} attribute which is a L{Portal} which authenticates and authorizes using L{axiom.userbase}. """ return self._testPortalLogin( UsernamePassword( '%s@%s' % (self.localpart.encode('ascii'), self.domain.encode('ascii')), self.password), )
def decode(self, response, request): try: creds = binascii.a2b_base64(response + b'===') except binascii.Error: raise error.LoginFailed('Invalid credentials') creds = creds.split(b':', 1) if len(creds) == 2: return UsernamePassword(*creds) else: raise error.LoginFailed('Invalid credentials')
def test_failOnSpecial(self): """ If the password returned by any function is C{""}, C{"x"}, or C{"*"} it is not compared against the supplied password. Instead it is skipped. """ pwd = UserDatabase() pwd.addUser("alice", "", 1, 2, "", "foo", "bar") pwd.addUser("bob", "x", 1, 2, "", "foo", "bar") pwd.addUser("carol", "*", 1, 2, "", "foo", "bar") self.patch(checkers, "pwd", pwd) checker = checkers.UNIXPasswordDatabase([checkers._pwdGetByName]) cred = UsernamePassword(b"alice", b"") self.assertUnauthorizedLogin(checker.requestAvatarId(cred)) cred = UsernamePassword(b"bob", b"x") self.assertUnauthorizedLogin(checker.requestAvatarId(cred)) cred = UsernamePassword(b"carol", b"*") self.assertUnauthorizedLogin(checker.requestAvatarId(cred))
def run(self, local_players): self.local_players = local_players self.wait_for_server_state = WaitForSeverState() factory = ClientFactory() factory.client = self reactor.connectTCP(self.server_name, pb.portno, factory) # factory.login(Anonymous()).addCallbacks(connected, failure) d = factory.login(UsernamePassword("guest", "guest"), ClientMind(self)) d.addCallbacks(self.connected_callback, self.failure_callback)
def test_connect_withUsernamePassword_valid(self): """ Connect with UsernamePassword credentials. """ credentials = UsernamePassword( u"uid=wsanchez,cn=user,{0}".format(self.baseDN), u"zehcnasw") service = self.service(credentials=credentials) with TestService.Connection(service, "query") as connection: self.assertEquals(connection.methods_called(), ["initialize", "simple_bind_s"])
def main(reactor, username, password): startLogging(stdout) router = Router() proto = AMP(router) router.bindRoute(proto, None).connectTo(None) cc = ClientCreator(reactor, lambda: proto) d = cc.connectTCP(username.split('@')[1], 7805) d.addCallback(login, UsernamePassword(username, password)) d.addCallback(connectRoute, router, BoxPrinter(), u'http://divmod.org/ns/echo') d.addCallback(sendBox) return d
def test_passwd(self): """ The C{--passwd} command-line option will load a passwd-like file. """ self.options.parseOptions( ['--telnetPort', 'tcp:22', '--passwd', self.filename]) service = manhole_tap.makeService(self.options) portal = service.services[0].factory.protocol.portal self.assertEqual(len(portal.checkers.keys()), 2) # Ensure it's the passwd file we wanted by trying to authenticate self.assertTrue( self.successResultOf( portal.login(UsernamePassword(*self.usernamePassword), None, telnet.ITelnetProtocol))) self.assertIsInstance( self.failureResultOf( portal.login(UsernamePassword(b"wrong", b"user"), None, telnet.ITelnetProtocol)).value, error.UnauthorizedLogin)
def testUpgrade(self): p = Portal(IRealm(self.store), [ICredentialsChecker(self.store)]) def loggedIn(xxx_todo_changeme): # if we can login, i guess everything is fine (interface, avatarAspect, logout) = xxx_todo_changeme self.assertEqual(avatarAspect.garbage, GARBAGE_LEVEL) creds = UsernamePassword('@'.join(CREDENTIALS[:-1]), CREDENTIALS[-1]) d = p.login(creds, None, IGarbage) return d.addCallback(loggedIn)
def test_usernamepasswordInvalid(self): """ L{LoginSystem.requestAvatarId} fails with L{UnauthorizedLogin} if the password supplied with the L{UsernamePassword} credentials is not valid for the provided username. """ account = self.realm.addAccount( self.localpart, self.domain, self.password) username = '******' % (self.localpart, self.domain) d = self._requestAvatarId(UsernamePassword(username, 'blahblah')) self.assertFailure(d, UnauthorizedLogin) return d
def test_usernamepassword(self): """ L{LoginSystem.requestAvatarId} returns the store identifier of the L{LoginAccount} associated with a L{UsernamePassword} credentials object if the username and password identify an existing account. """ account = self.realm.addAccount( self.localpart, self.domain, self.password) username = '******' % (self.localpart, self.domain) d = self._requestAvatarId(UsernamePassword(username, self.password)) d.addCallback(self.assertEqual, account.storeID) return d
def test_passInCheckers(self): """ L{UNIXPasswordDatabase} takes a list of functions to check for UNIX user information. """ password = crypt.crypt('secret', 'secret') userdb = UserDatabase() userdb.addUser('anybody', password, 1, 2, 'foo', '/bar', '/bin/sh') checker = checkers.UNIXPasswordDatabase([userdb.getpwnam]) self.assertLoggedIn( checker.requestAvatarId(UsernamePassword('anybody', 'secret')), 'anybody')
def connect(self, host, port, username=None, password=None): # Launch a client self.pbClientFactory = pb.PBClientFactory() reactor.connectTCP(host, port, self.pbClientFactory) if username is None and password is None: return self.pbClientFactory.login(Anonymous()).addCallback( self._connected) else: return self.pbClientFactory.login( UsernamePassword(username, password)).addCallback(self._connected)
def test_authFailure(self): """ The checker created by the C{--auth} command-line option returns a L{Deferred} that fails with L{UnauthorizedLogin} when presented with credentials that are unknown to that checker. """ self.options.parseOptions(['--auth', 'file:' + self.filename]) checker = self.options['credCheckers'][-1] invalid = UsernamePassword(self.usernamePassword[0], 'fake') # Wrong password should raise error return self.assertFailure(checker.requestAvatarId(invalid), error.UnauthorizedLogin)
def test_passInCheckers(self): """ L{UNIXPasswordDatabase} takes a list of functions to check for UNIX user information. """ password = crypt.crypt("secret", "secret") userdb = UserDatabase() userdb.addUser("anybody", password, 1, 2, "foo", "/bar", "/bin/sh") checker = checkers.UNIXPasswordDatabase([userdb.getpwnam]) self.assertLoggedIn( checker.requestAvatarId(UsernamePassword(b"anybody", b"secret")), b"anybody")
def _get_session(self, provider, full_id, password=""): if full_id in self._sessions: return self._sessions[full_id] # TODO if password/username null, then pass AnonymousCreds username, provider_id = config.get_username_and_provider(full_id) credentials = UsernamePassword(username, password) api = self._get_api(provider) provider_pem = _get_provider_ca_path(provider_id) session = Session(credentials, api, provider_pem) self._sessions[full_id] = session return session
def testRequestAvatarId(self): """ L{FacadeChecker.requestAvatarId} when passed credentials creates a L{FluidinfoSession} for the authenticated user only if credentials are correct. """ user = createUser(u'user', u'pass', u'User', u'*****@*****.**') self.store.commit() credentials = UsernamePassword('user', 'pass') session = yield self.checker.requestAvatarId(credentials) self.assertEqual(user.username, session.auth.username) self.assertEqual(user.objectID, session.auth.objectID)
def render(self, request): log.info('Incoming authentication request from %s' % request.getClientIP()) authentication_utility = getUtility(IHttpRestAuthenticationUtility) # enable basic auth only if explicitly requested basic_auth = request.args.get('basic_auth', [self.BASIC_AUTH_DEFAULT])[0] != 'false' body = request.content.getvalue() if request.args.get('username') and request.args.get('password'): credentials = UsernamePassword( request.args.get('username')[0], request.args.get('password')[0]) elif body: try: params = json.loads(body) except ValueError: raise BadRequest("The request body not JSON-parsable") # cannot be unicode username = str(params['username']) password = str(params['password']) credentials = UsernamePassword(username, password) else: credentials = authentication_utility.get_basic_auth_credentials( request) # if already authenticated, return success even if the request didn't provide auth credentials if not credentials and request.interaction.checkPermission( 'rest', object): return {'status': 'success'} # XXX: refactor HttpRestServer.handle_request so that it's not a db.transact # so that we can use a defer.inlineCallback here return blocking_yield( authentication_utility.authenticate(request, credentials, basic_auth))
def doLogin(self): host = self._hostEntry.get_text() port = int(self._portEntry.get_text()) userName = self._userNameEntry.get_text() password = self._passwordEntry.get_text() client_factory = pb.PBClientFactory() reactor.connectTCP(host, port, client_factory) creds = UsernamePassword(userName, password) client_factory.login(creds).addCallbacks(self._cbGotPerspective, self._ebFailedLogin) self.statusMsg("Contacting server...")
def on_buttonLogin_mouseClick(self, event): result = loginDialog(self, port=pb.portno) if result.accepted: # verify input here? host = result.host port = result.port username = result.username password = result.password reactor.connectTCP(host, port, self.pbfactory) self.pbfactory.login( UsernamePassword(username, password) ).addCallbacks(self.loginsuccess, self.loginfailure)
def test_failOnBadPassword(self): """ If the verifyCryptedPassword function doesn't verify the password, the login fails with an L{UnauthorizedLogin} exception. """ def verifyCryptedPassword(crypted, pw): return False def getpwnam(username): return [username, username] self.patch(checkers, 'verifyCryptedPassword', verifyCryptedPassword) checker = checkers.UNIXPasswordDatabase([getpwnam]) credential = UsernamePassword(b'username', b'username') self.assertUnauthorizedLogin(checker.requestAvatarId(credential))
def test_requestAvatarId(self): """ L{SSHProtocolChecker.requestAvatarId} should defer to one if its registered checkers to authenticate a user. """ checker = checkers.SSHProtocolChecker() passwordDatabase = InMemoryUsernamePasswordDatabaseDontUse() passwordDatabase.addUser(b'test', b'test') checker.registerChecker(passwordDatabase) d = checker.requestAvatarId(UsernamePassword(b'test', b'test')) def _callback(avatarId): self.assertEqual(avatarId, b'test') return d.addCallback(_callback)
def test_loginWrongUser(self): addr = 'http://localhost:%s' % self.portNumber credentials = UsernamePassword('wrong user', 'password1') proxy = Proxy(addr, credentials=credentials) d = proxy.callRemote('echo', '') e = self.assertFailure(d, jsonrpc.JSONRPCError) def finished(result): self.assertEquals(result.strerror, 'Unauthorized') self.assertEquals(result.errno, jsonrpc.INVALID_REQUEST) e.addCallback(finished) return d
def test_noAvatar(self): """ L{login} returns a L{Deferred} which fires with L{NotImplementedError} if the realm raises L{NotImplementedError} when asked for the avatar. """ def noAvatar(avatarId, mind, *interfaces): raise NotImplementedError() self.realm.requestAvatar = noAvatar loginDeferred = login(self.client, UsernamePassword(self.username, self.password)) return self.assertFailure(loginDeferred, NotImplementedError)