コード例 #1
0
    def test_db_authenticate_threaded(self):

        db = client_context.client.db
        coll = db.test
        coll.drop()
        coll.insert_one({'_id': 1})

        client_context.create_user(
            'db',
            'user',
            'pass',
            roles=['dbOwner'])
        self.addCleanup(db.command, 'dropUser', 'user')

        db = rs_or_single_client_noauth().db
        db.authenticate('user', 'pass')
        # No error.
        db.authenticate('user', 'pass')

        db = rs_or_single_client_noauth().db
        threads = []
        for _ in range(4):
            threads.append(DBAuthenticateThread(db, 'user', 'pass'))
        for thread in threads:
            thread.start()
        for thread in threads:
            thread.join()
            self.assertTrue(thread.success)
コード例 #2
0
    def test_db_authenticate_threaded(self):

        db = client_context.client.db
        coll = db.test
        coll.drop()
        coll.insert_one({'_id': 1})

        client_context.create_user(
            'db',
            'user',
            'pass',
            roles=['dbOwner'])
        self.addCleanup(db.command, 'dropUser', 'user')

        db = rs_or_single_client_noauth().db
        db.authenticate('user', 'pass')
        # No error.
        db.authenticate('user', 'pass')

        db = rs_or_single_client_noauth().db
        threads = []
        for _ in range(4):
            threads.append(DBAuthenticateThread(db, 'user', 'pass'))
        for thread in threads:
            thread.start()
        for thread in threads:
            thread.join()
            self.assertTrue(thread.success)
コード例 #3
0
    def test_scram_skip_empty_exchange(self):
        listener = AllowListEventListener("saslStart", "saslContinue")
        client_context.create_user(
            'testscram', 'sha256', 'pwd', roles=['dbOwner'],
            mechanisms=['SCRAM-SHA-256'])

        client = rs_or_single_client_noauth(
            username='******', password='******', authSource='testscram',
            event_listeners=[listener])
        client.testscram.command('dbstats')

        if client_context.version < (4, 4, -1):
            # Assert we sent the skipEmptyExchange option.
            first_event = listener.results['started'][0]
            self.assertEqual(first_event.command_name, 'saslStart')
            self.assertEqual(
                first_event.command['options'], {'skipEmptyExchange': True})

        # Assert the third exchange was skipped on servers that support it.
        # Note that the first exchange occurs on the connection handshake.
        started = listener.started_command_names()
        if client_context.version.at_least(4, 4, -1):
            self.assertEqual(started, ['saslContinue'])
        else:
            self.assertEqual(
                started, ['saslStart', 'saslContinue', 'saslContinue'])
コード例 #4
0
    def setUp(self):
        super(TestSessionsMultiAuth, self).setUp()

        client_context.create_user('pymongo_test',
                                   'second-user',
                                   'pass',
                                   roles=['readWrite'])
        self.addCleanup(client_context.drop_user, 'pymongo_test',
                        'second-user')
コード例 #5
0
    def setUp(self):
        # Before 2.7.7, SCRAM-SHA-1 had to be enabled from the command line.
        if client_context.version < Version(2, 7, 7):
            cmd_line = client_context.cmd_line
            if 'SCRAM-SHA-1' not in cmd_line.get(
                    'parsed', {}).get('setParameter',
                    {}).get('authenticationMechanisms', ''):
                raise SkipTest('SCRAM-SHA-1 mechanism not enabled')

        client_context.create_user(
            'pymongo_test', 'user', 'pass', roles=['userAdmin', 'readWrite'])
コード例 #6
0
    def setUp(self):
        # Before 2.7.7, SCRAM-SHA-1 had to be enabled from the command line.
        if client_context.version < Version(2, 7, 7):
            cmd_line = client_context.cmd_line
            if 'SCRAM-SHA-1' not in cmd_line.get(
                    'parsed', {}).get('setParameter',
                    {}).get('authenticationMechanisms', ''):
                raise SkipTest('SCRAM-SHA-1 mechanism not enabled')

        client_context.create_user(
            'pymongo_test', 'user', 'pass', roles=['userAdmin', 'readWrite'])
コード例 #7
0
    def test_scram_saslprep(self):
        # Step 4: test SASLprep
        host, port = client_context.host, client_context.port
        # Test the use of SASLprep on passwords. For example,
        # saslprep('\u2136') becomes 'IV' and saslprep('I\u00ADX')
        # becomes 'IX'. SASLprep is only supported when the standard
        # library provides stringprep.
        client_context.create_user(
            'testscram', '\u2168', '\u2163', roles=['dbOwner'],
            mechanisms=['SCRAM-SHA-256'])
        client_context.create_user(
            'testscram', 'IX', 'IX', roles=['dbOwner'],
            mechanisms=['SCRAM-SHA-256'])

        client = rs_or_single_client_noauth(
            username='******', password='******', authSource='testscram')
        client.testscram.command('dbstats')

        client = rs_or_single_client_noauth(
            username='******', password='******', authSource='testscram',
            authMechanism='SCRAM-SHA-256')
        client.testscram.command('dbstats')

        client = rs_or_single_client_noauth(
            username='******', password='******', authSource='testscram')
        client.testscram.command('dbstats')

        client = rs_or_single_client_noauth(
            username='******', password='******', authSource='testscram')
        client.testscram.command('dbstats')

        client = rs_or_single_client_noauth(
            username='******', password='******', authSource='testscram',
            authMechanism='SCRAM-SHA-256')
        client.testscram.command('dbstats')

        client = rs_or_single_client_noauth(
            username='******', password='******', authSource='testscram',
            authMechanism='SCRAM-SHA-256')
        client.testscram.command('dbstats')

        client = rs_or_single_client_noauth(
            'mongodb://\u2168:\u2163@%s:%d/testscram' % (host, port))
        client.testscram.command('dbstats')
        client = rs_or_single_client_noauth(
            'mongodb://\u2168:IV@%s:%d/testscram' % (host, port))
        client.testscram.command('dbstats')

        client = rs_or_single_client_noauth(
            'mongodb://*****:*****@%s:%d/testscram' % (host, port))
        client.testscram.command('dbstats')
        client = rs_or_single_client_noauth(
            'mongodb://*****:*****@%s:%d/testscram' % (host, port))
        client.testscram.command('dbstats')
コード例 #8
0
    def setUp(self):
        super(BulkAuthorizationTestBase, self).setUp()
        client_context.create_user(
            self.db.name, 'readonly', 'pw', ['read'])
        self.db.command(
            'createRole', 'noremove',
            privileges=[{
                'actions': ['insert', 'update', 'find'],
                'resource': {'db': 'pymongo_test', 'collection': 'test'}
            }],
            roles=[])

        client_context.create_user(self.db.name, 'noremove', 'pw', ['noremove'])
コード例 #9
0
    def setUp(self):
        super(BulkAuthorizationTestBase, self).setUp()
        client_context.create_user(
            self.db.name, 'readonly', 'pw', ['read'])
        self.db.command(
            'createRole', 'noremove',
            privileges=[{
                'actions': ['insert', 'update', 'find'],
                'resource': {'db': 'pymongo_test', 'collection': 'test'}
            }],
            roles=[])

        client_context.create_user(self.db.name, 'noremove', 'pw', ['noremove'])
コード例 #10
0
 def setUp(self):
     client_context.create_user('admin', 'admin', 'pass')
     client_context.create_user('pymongo_test', 'user', 'pass',
                                ['userAdmin', 'readWrite'])
コード例 #11
0
    def test_scram(self):
        # Step 1: create users
        client_context.create_user('testscram',
                                   'sha1',
                                   'pwd',
                                   roles=['dbOwner'],
                                   mechanisms=['SCRAM-SHA-1'])
        client_context.create_user('testscram',
                                   'sha256',
                                   'pwd',
                                   roles=['dbOwner'],
                                   mechanisms=['SCRAM-SHA-256'])
        client_context.create_user('testscram',
                                   'both',
                                   'pwd',
                                   roles=['dbOwner'],
                                   mechanisms=['SCRAM-SHA-1', 'SCRAM-SHA-256'])

        # Step 2: verify auth success cases
        client = rs_or_single_client_noauth(username='******',
                                            password='******',
                                            authSource='testscram')
        client.testscram.command('dbstats')

        client = rs_or_single_client_noauth(username='******',
                                            password='******',
                                            authSource='testscram',
                                            authMechanism='SCRAM-SHA-1')
        client.testscram.command('dbstats')

        client = rs_or_single_client_noauth(username='******',
                                            password='******',
                                            authSource='testscram')
        client.testscram.command('dbstats')

        client = rs_or_single_client_noauth(username='******',
                                            password='******',
                                            authSource='testscram',
                                            authMechanism='SCRAM-SHA-256')
        client.testscram.command('dbstats')

        # Step 2: SCRAM-SHA-1 and SCRAM-SHA-256
        client = rs_or_single_client_noauth(username='******',
                                            password='******',
                                            authSource='testscram',
                                            authMechanism='SCRAM-SHA-1')
        client.testscram.command('dbstats')
        client = rs_or_single_client_noauth(username='******',
                                            password='******',
                                            authSource='testscram',
                                            authMechanism='SCRAM-SHA-256')
        client.testscram.command('dbstats')

        self.listener.results.clear()
        client = rs_or_single_client_noauth(username='******',
                                            password='******',
                                            authSource='testscram',
                                            event_listeners=[self.listener])
        client.testscram.command('dbstats')
        if client_context.version.at_least(4, 4, -1):
            # Speculative authentication in 4.4+ sends saslStart with the
            # handshake.
            self.assertEqual(self.listener.results['started'], [])
        else:
            started = self.listener.results['started'][0]
            self.assertEqual(started.command.get('mechanism'), 'SCRAM-SHA-256')

        # Step 3: verify auth failure conditions
        client = rs_or_single_client_noauth(username='******',
                                            password='******',
                                            authSource='testscram',
                                            authMechanism='SCRAM-SHA-256')
        with self.assertRaises(OperationFailure):
            client.testscram.command('dbstats')

        client = rs_or_single_client_noauth(username='******',
                                            password='******',
                                            authSource='testscram',
                                            authMechanism='SCRAM-SHA-1')
        with self.assertRaises(OperationFailure):
            client.testscram.command('dbstats')

        client = rs_or_single_client_noauth(username='******',
                                            password='******',
                                            authSource='testscram')
        with self.assertRaises(OperationFailure):
            client.testscram.command('dbstats')

        if client_context.is_rs:
            host, port = client_context.host, client_context.port
            uri = ('mongodb://*****:*****@%s:%d/testscram'
                   '?replicaSet=%s' %
                   (host, port, client_context.replica_set_name))
            client = single_client_noauth(uri)
            client.testscram.command('dbstats')
            db = client.get_database('testscram',
                                     read_preference=ReadPreference.SECONDARY)
            db.command('dbstats')
コード例 #12
0
    def test_mongodb_x509_auth(self):
        host, port = client_context.host, client_context.port
        ssl_client = MongoClient(
            client_context.pair,
            ssl=True,
            ssl_cert_reqs=ssl.CERT_NONE,
            ssl_certfile=CLIENT_PEM)
        self.addCleanup(remove_all_users, ssl_client['$external'])

        ssl_client.admin.authenticate(db_user, db_pwd)

        # Give x509 user all necessary privileges.
        client_context.create_user('$external', MONGODB_X509_USERNAME, roles=[
            {'role': 'readWriteAnyDatabase', 'db': 'admin'},
            {'role': 'userAdminAnyDatabase', 'db': 'admin'}])

        noauth = MongoClient(
            client_context.pair,
            ssl=True,
            ssl_cert_reqs=ssl.CERT_NONE,
            ssl_certfile=CLIENT_PEM)

        self.assertRaises(OperationFailure, noauth.pymongo_test.test.count)

        auth = MongoClient(
            client_context.pair,
            authMechanism='MONGODB-X509',
            ssl=True,
            ssl_cert_reqs=ssl.CERT_NONE,
            ssl_certfile=CLIENT_PEM)

        if client_context.version.at_least(3, 3, 12):
            # No error
            auth.pymongo_test.test.find_one()
        else:
            # Should require a username
            with self.assertRaises(ConfigurationError):
                auth.pymongo_test.test.find_one()

        uri = ('mongodb://%s@%s:%d/?authMechanism='
               'MONGODB-X509' % (
                   quote_plus(MONGODB_X509_USERNAME), host, port))
        client = MongoClient(uri,
                             ssl=True,
                             ssl_cert_reqs=ssl.CERT_NONE,
                             ssl_certfile=CLIENT_PEM)
        # No error
        client.pymongo_test.test.find_one()

        uri = 'mongodb://%s:%d/?authMechanism=MONGODB-X509' % (host, port)
        client = MongoClient(uri,
                             ssl=True,
                             ssl_cert_reqs=ssl.CERT_NONE,
                             ssl_certfile=CLIENT_PEM)
        if client_context.version.at_least(3, 3, 12):
            # No error
            client.pymongo_test.test.find_one()
        else:
            # Should require a username
            with self.assertRaises(ConfigurationError):
                client.pymongo_test.test.find_one()

        # Auth should fail if username and certificate do not match
        uri = ('mongodb://%s@%s:%d/?authMechanism='
               'MONGODB-X509' % (
                   quote_plus("not the username"), host, port))

        bad_client = MongoClient(
            uri, ssl=True, ssl_cert_reqs="CERT_NONE", ssl_certfile=CLIENT_PEM)

        with self.assertRaises(OperationFailure):
            bad_client.pymongo_test.test.find_one()

        bad_client = MongoClient(
                client_context.pair,
                username="******",
                authMechanism='MONGODB-X509',
                ssl=True,
                ssl_cert_reqs=ssl.CERT_NONE,
                ssl_certfile=CLIENT_PEM)

        with self.assertRaises(OperationFailure):
            bad_client.pymongo_test.test.find_one()

        # Invalid certificate (using CA certificate as client certificate)
        uri = ('mongodb://%s@%s:%d/?authMechanism='
               'MONGODB-X509' % (
                   quote_plus(MONGODB_X509_USERNAME), host, port))
        try:
            connected(MongoClient(uri,
                                  ssl=True,
                                  ssl_cert_reqs=ssl.CERT_NONE,
                                  ssl_certfile=CA_PEM,
                                  serverSelectionTimeoutMS=100))
        except (ConnectionFailure, ConfigurationError):
            pass
        else:
            self.fail("Invalid certificate accepted.")
コード例 #13
0
    def test_mongodb_x509_auth(self):
        host, port = client_context.host, client_context.port
        ssl_client = MongoClient(
            client_context.pair,
            ssl=True,
            ssl_cert_reqs=ssl.CERT_NONE,
            ssl_certfile=CLIENT_PEM)
        self.addCleanup(remove_all_users, ssl_client['$external'])

        ssl_client.admin.authenticate(db_user, db_pwd)

        # Give x509 user all necessary privileges.
        client_context.create_user('$external', MONGODB_X509_USERNAME, roles=[
            {'role': 'readWriteAnyDatabase', 'db': 'admin'},
            {'role': 'userAdminAnyDatabase', 'db': 'admin'}])

        noauth = MongoClient(
            client_context.pair,
            ssl=True,
            ssl_cert_reqs=ssl.CERT_NONE,
            ssl_certfile=CLIENT_PEM)

        self.assertRaises(OperationFailure, noauth.pymongo_test.test.count)

        auth = MongoClient(
            client_context.pair,
            authMechanism='MONGODB-X509',
            ssl=True,
            ssl_cert_reqs=ssl.CERT_NONE,
            ssl_certfile=CLIENT_PEM)

        if client_context.version.at_least(3, 3, 12):
            # No error
            auth.pymongo_test.test.find_one()
        else:
            # Should require a username
            with self.assertRaises(ConfigurationError):
                auth.pymongo_test.test.find_one()

        uri = ('mongodb://%s@%s:%d/?authMechanism='
               'MONGODB-X509' % (
                   quote_plus(MONGODB_X509_USERNAME), host, port))
        client = MongoClient(uri,
                             ssl=True,
                             ssl_cert_reqs=ssl.CERT_NONE,
                             ssl_certfile=CLIENT_PEM)
        # No error
        client.pymongo_test.test.find_one()

        uri = 'mongodb://%s:%d/?authMechanism=MONGODB-X509' % (host, port)
        client = MongoClient(uri,
                             ssl=True,
                             ssl_cert_reqs=ssl.CERT_NONE,
                             ssl_certfile=CLIENT_PEM)
        if client_context.version.at_least(3, 3, 12):
            # No error
            client.pymongo_test.test.find_one()
        else:
            # Should require a username
            with self.assertRaises(ConfigurationError):
                client.pymongo_test.test.find_one()

        # Auth should fail if username and certificate do not match
        uri = ('mongodb://%s@%s:%d/?authMechanism='
               'MONGODB-X509' % (
                   quote_plus("not the username"), host, port))

        bad_client = MongoClient(
            uri, ssl=True, ssl_cert_reqs="CERT_NONE", ssl_certfile=CLIENT_PEM)

        with self.assertRaises(OperationFailure):
            bad_client.pymongo_test.test.find_one()

        bad_client = MongoClient(
                client_context.pair,
                username="******",
                authMechanism='MONGODB-X509',
                ssl=True,
                ssl_cert_reqs=ssl.CERT_NONE,
                ssl_certfile=CLIENT_PEM)

        with self.assertRaises(OperationFailure):
            bad_client.pymongo_test.test.find_one()

        # Invalid certificate (using CA certificate as client certificate)
        uri = ('mongodb://%s@%s:%d/?authMechanism='
               'MONGODB-X509' % (
                   quote_plus(MONGODB_X509_USERNAME), host, port))
        try:
            connected(MongoClient(uri,
                                  ssl=True,
                                  ssl_cert_reqs=ssl.CERT_NONE,
                                  ssl_certfile=CA_PEM,
                                  serverSelectionTimeoutMS=100))
        except (ConnectionFailure, ConfigurationError):
            pass
        else:
            self.fail("Invalid certificate accepted.")
コード例 #14
0
 def setUp(self):
     super(TestAuthURIOptions, self).setUp()
     client_context.create_user('admin', 'admin', 'pass')
     client_context.create_user('pymongo_test', 'user', 'pass',
                                ['userAdmin', 'readWrite'])
コード例 #15
0
 def setUp(self):
     super(TestSCRAMSHA1, self).setUp()
     client_context.create_user(
         'pymongo_test', 'user', 'pass', roles=['userAdmin', 'readWrite'])
コード例 #16
0
    def test_authenticate_multiple(self):
        # "self.client" is logged in as root.
        self.client.drop_database("pymongo_test")
        self.client.drop_database("pymongo_test1")
        users_db_auth = self.client.pymongo_test

        client_context.create_user(
            'admin',
            'ro-admin',
            'pass',
            roles=["userAdmin", "readAnyDatabase"])

        self.addCleanup(client_context.drop_user, 'admin', 'ro-admin')
        client_context.create_user(
            'pymongo_test', 'user', 'pass', roles=["userAdmin", "readWrite"])
        self.addCleanup(remove_all_users, users_db_auth)

        # Non-root client.
        listener = EventListener()
        client = rs_or_single_client_noauth(event_listeners=[listener])
        admin_db = client.admin
        users_db = client.pymongo_test
        other_db = client.pymongo_test1

        self.assertRaises(OperationFailure, users_db.test.find_one)
        self.assertEqual(listener.started_command_names(), ['find'])
        listener.reset()

        # Regular user should be able to query its own db, but
        # no other.
        users_db.authenticate('user', 'pass')
        if client_context.version.at_least(3, 0):
            self.assertEqual(listener.started_command_names()[0], 'saslStart')
        else:
            self.assertEqual(listener.started_command_names()[0], 'getnonce')

        self.assertEqual(0, users_db.test.count_documents({}))
        self.assertRaises(OperationFailure, other_db.test.find_one)

        listener.reset()
        # Admin read-only user should be able to query any db,
        # but not write.
        admin_db.authenticate('ro-admin', 'pass')
        if client_context.version.at_least(3, 0):
            self.assertEqual(listener.started_command_names()[0], 'saslStart')
        else:
            self.assertEqual(listener.started_command_names()[0], 'getnonce')
        self.assertEqual(None, other_db.test.find_one())
        self.assertRaises(OperationFailure,
                          other_db.test.insert_one, {})

        # Close all sockets.
        client.close()

        listener.reset()
        # We should still be able to write to the regular user's db.
        self.assertTrue(users_db.test.delete_many({}))
        names = listener.started_command_names()
        if client_context.version.at_least(4, 4, -1):
            # No speculation with multiple users (but we do skipEmptyExchange).
            self.assertEqual(
                names, ['saslStart', 'saslContinue', 'saslStart',
                        'saslContinue', 'delete'])
        elif client_context.version.at_least(3, 0):
            self.assertEqual(
                names, ['saslStart', 'saslContinue', 'saslContinue',
                        'saslStart', 'saslContinue', 'saslContinue', 'delete'])
        else:
            self.assertEqual(
                names, ['getnonce', 'authenticate',
                        'getnonce', 'authenticate', 'delete'])

        # And read from other dbs...
        self.assertEqual(0, other_db.test.count_documents({}))

        # But still not write to other dbs.
        self.assertRaises(OperationFailure,
                          other_db.test.insert_one, {})
コード例 #17
0
 def setUp(self):
     client_context.create_user('admin', 'admin', 'pass')
     client_context.create_user(
         'pymongo_test', 'user', 'pass', ['userAdmin', 'readWrite'])
     self.client = rs_or_single_client_noauth(
         username='******', password='******')
コード例 #18
0
    def test_scram(self):
        host, port = client_context.host, client_context.port

        client_context.create_user('testscram',
                                   'sha1',
                                   'pwd',
                                   roles=['dbOwner'],
                                   mechanisms=['SCRAM-SHA-1'])

        client_context.create_user('testscram',
                                   'sha256',
                                   'pwd',
                                   roles=['dbOwner'],
                                   mechanisms=['SCRAM-SHA-256'])

        client_context.create_user('testscram',
                                   'both',
                                   'pwd',
                                   roles=['dbOwner'],
                                   mechanisms=['SCRAM-SHA-1', 'SCRAM-SHA-256'])

        client = rs_or_single_client_noauth(event_listeners=[self.listener])
        self.assertTrue(client.testscram.authenticate('sha1', 'pwd'))
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertTrue(
            client.testscram.authenticate('sha1',
                                          'pwd',
                                          mechanism='SCRAM-SHA-1'))
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertRaises(OperationFailure,
                          client.testscram.authenticate,
                          'sha1',
                          'pwd',
                          mechanism='SCRAM-SHA-256')

        self.assertTrue(client.testscram.authenticate('sha256', 'pwd'))
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertTrue(
            client.testscram.authenticate('sha256',
                                          'pwd',
                                          mechanism='SCRAM-SHA-256'))
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertRaises(OperationFailure,
                          client.testscram.authenticate,
                          'sha256',
                          'pwd',
                          mechanism='SCRAM-SHA-1')

        self.listener.results.clear()
        self.assertTrue(client.testscram.authenticate('both', 'pwd'))
        started = self.listener.results['started'][0]
        self.assertEqual(started.command.get('mechanism'), 'SCRAM-SHA-256')
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertTrue(
            client.testscram.authenticate('both',
                                          'pwd',
                                          mechanism='SCRAM-SHA-256'))
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertTrue(
            client.testscram.authenticate('both',
                                          'pwd',
                                          mechanism='SCRAM-SHA-1'))
        client.testscram.command('dbstats')
        client.testscram.logout()

        self.assertRaises(OperationFailure, client.testscram.authenticate,
                          'not-a-user', 'pwd')

        if HAVE_STRINGPREP:
            client_context.create_user('testscram',
                                       saslprep(u'\u2168'),
                                       u'\u2168',
                                       roles=['dbOwner'],
                                       mechanisms=['SCRAM-SHA-256'])

            self.assertTrue(client.testscram.authenticate(
                u'\u2168', u'\u2168'))
            client.testscram.command('dbstats')
            client.testscram.logout()
            self.assertTrue(
                client.testscram.authenticate(u'\u2168',
                                              u'\u2168',
                                              mechanism='SCRAM-SHA-256'))
            client.testscram.command('dbstats')
            client.testscram.logout()
            self.assertRaises(OperationFailure,
                              client.testscram.authenticate,
                              u'\u2168',
                              u'\u2168',
                              mechanism='SCRAM-SHA-1')

            client = rs_or_single_client_noauth(
                u'mongodb://\u2168:\u2168@%s:%d/testscram' % (host, port))
            client.testscram.command('dbstats')

        self.listener.results.clear()
        client = rs_or_single_client_noauth(
            'mongodb://*****:*****@%s:%d/testscram' % (host, port),
            event_listeners=[self.listener])
        client.testscram.command('dbstats')
        started = self.listener.results['started'][0]
        self.assertEqual(started.command.get('mechanism'), 'SCRAM-SHA-256')

        client = rs_or_single_client_noauth(
            'mongodb://*****:*****@%s:%d/testscram?authMechanism=SCRAM-SHA-1' %
            (host, port))
        client.testscram.command('dbstats')

        client = rs_or_single_client_noauth(
            'mongodb://*****:*****@%s:%d/testscram?authMechanism=SCRAM-SHA-256' %
            (host, port))
        client.testscram.command('dbstats')

        if client_context.is_rs:
            uri = ('mongodb://*****:*****@%s:%d/testscram'
                   '?replicaSet=%s' %
                   (host, port, client_context.replica_set_name))
            client = single_client_noauth(uri)
            client.testscram.command('dbstats')
            db = client.get_database('testscram',
                                     read_preference=ReadPreference.SECONDARY)
            db.command('dbstats')
コード例 #19
0
    def test_scram(self):
        host, port = client_context.host, client_context.port

        client_context.create_user(
            'testscram',
            'sha1',
            'pwd',
            roles=['dbOwner'],
            mechanisms=['SCRAM-SHA-1'])

        client_context.create_user(
            'testscram',
            'sha256',
            'pwd',
            roles=['dbOwner'],
            mechanisms=['SCRAM-SHA-256'])

        client_context.create_user(
            'testscram',
            'both',
            'pwd',
            roles=['dbOwner'],
            mechanisms=['SCRAM-SHA-1', 'SCRAM-SHA-256'])

        client = rs_or_single_client_noauth(
            event_listeners=[self.listener])
        self.assertTrue(
            client.testscram.authenticate('sha1', 'pwd'))
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertTrue(
            client.testscram.authenticate(
                'sha1', 'pwd', mechanism='SCRAM-SHA-1'))
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertRaises(
            OperationFailure,
            client.testscram.authenticate,
            'sha1', 'pwd', mechanism='SCRAM-SHA-256')

        self.assertTrue(
            client.testscram.authenticate('sha256', 'pwd'))
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertTrue(
            client.testscram.authenticate(
                'sha256', 'pwd', mechanism='SCRAM-SHA-256'))
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertRaises(
            OperationFailure,
            client.testscram.authenticate,
            'sha256', 'pwd', mechanism='SCRAM-SHA-1')

        self.listener.results.clear()
        self.assertTrue(
            client.testscram.authenticate('both', 'pwd'))
        started = self.listener.results['started'][0]
        self.assertEqual(started.command.get('mechanism'), 'SCRAM-SHA-256')
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertTrue(
            client.testscram.authenticate(
                'both', 'pwd', mechanism='SCRAM-SHA-256'))
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertTrue(
            client.testscram.authenticate(
                'both', 'pwd', mechanism='SCRAM-SHA-1'))
        client.testscram.command('dbstats')
        client.testscram.logout()

        self.assertRaises(
            OperationFailure,
            client.testscram.authenticate,
            'not-a-user', 'pwd')

        if HAVE_STRINGPREP:
            # Test the use of SASLprep on passwords. For example,
            # saslprep(u'\u2136') becomes u'IV' and saslprep(u'I\u00ADX')
            # becomes u'IX'. SASLprep is only supported when the standard
            # library provides stringprep.
            client_context.create_user(
                'testscram',
                u'\u2168',
                u'\u2163',
                roles=['dbOwner'],
                mechanisms=['SCRAM-SHA-256'])

            client_context.create_user(
                'testscram',
                u'IX',
                u'IX',
                roles=['dbOwner'],
                mechanisms=['SCRAM-SHA-256'])

            self.assertTrue(
                client.testscram.authenticate(u'\u2168', u'\u2163'))
            client.testscram.command('dbstats')
            client.testscram.logout()
            self.assertTrue(
                client.testscram.authenticate(
                    u'\u2168', u'\u2163', mechanism='SCRAM-SHA-256'))
            client.testscram.command('dbstats')
            client.testscram.logout()
            self.assertTrue(
                client.testscram.authenticate(u'\u2168', u'IV'))
            client.testscram.command('dbstats')
            client.testscram.logout()

            self.assertTrue(
                client.testscram.authenticate(u'IX', u'I\u00ADX'))
            client.testscram.command('dbstats')
            client.testscram.logout()
            self.assertTrue(
                client.testscram.authenticate(
                    u'IX', u'I\u00ADX', mechanism='SCRAM-SHA-256'))
            client.testscram.command('dbstats')
            client.testscram.logout()
            self.assertTrue(
                client.testscram.authenticate(u'IX', u'IX'))
            client.testscram.command('dbstats')
            client.testscram.logout()

            client = rs_or_single_client_noauth(
                u'mongodb://\u2168:\u2163@%s:%d/testscram' % (host, port))
            client.testscram.command('dbstats')
            client = rs_or_single_client_noauth(
                u'mongodb://\u2168:IV@%s:%d/testscram' % (host, port))
            client.testscram.command('dbstats')

            client = rs_or_single_client_noauth(
                u'mongodb://*****:*****@%s:%d/testscram' % (host, port))
            client.testscram.command('dbstats')
            client = rs_or_single_client_noauth(
                u'mongodb://*****:*****@%s:%d/testscram' % (host, port))
            client.testscram.command('dbstats')

        self.listener.results.clear()
        client = rs_or_single_client_noauth(
            'mongodb://*****:*****@%s:%d/testscram' % (host, port),
            event_listeners=[self.listener])
        client.testscram.command('dbstats')
        started = self.listener.results['started'][0]
        self.assertEqual(started.command.get('mechanism'), 'SCRAM-SHA-256')

        client = rs_or_single_client_noauth(
            'mongodb://*****:*****@%s:%d/testscram?authMechanism=SCRAM-SHA-1'
            % (host, port))
        client.testscram.command('dbstats')

        client = rs_or_single_client_noauth(
            'mongodb://*****:*****@%s:%d/testscram?authMechanism=SCRAM-SHA-256'
            % (host, port))
        client.testscram.command('dbstats')

        if client_context.is_rs:
            uri = ('mongodb://*****:*****@%s:%d/testscram'
                   '?replicaSet=%s' % (host, port,
                                       client_context.replica_set_name))
            client = single_client_noauth(uri)
            client.testscram.command('dbstats')
            db = client.get_database(
                'testscram', read_preference=ReadPreference.SECONDARY)
            db.command('dbstats')
コード例 #20
0
    def test_scram(self):
        host, port = client_context.host, client_context.port

        client_context.create_user('testscram',
                                   'sha1',
                                   'pwd',
                                   roles=['dbOwner'],
                                   mechanisms=['SCRAM-SHA-1'])

        client_context.create_user('testscram',
                                   'sha256',
                                   'pwd',
                                   roles=['dbOwner'],
                                   mechanisms=['SCRAM-SHA-256'])

        client_context.create_user('testscram',
                                   'both',
                                   'pwd',
                                   roles=['dbOwner'],
                                   mechanisms=['SCRAM-SHA-1', 'SCRAM-SHA-256'])

        client = rs_or_single_client_noauth(event_listeners=[self.listener])
        self.assertTrue(client.testscram.authenticate('sha1', 'pwd'))
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertTrue(
            client.testscram.authenticate('sha1',
                                          'pwd',
                                          mechanism='SCRAM-SHA-1'))
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertRaises(OperationFailure,
                          client.testscram.authenticate,
                          'sha1',
                          'pwd',
                          mechanism='SCRAM-SHA-256')

        self.assertTrue(client.testscram.authenticate('sha256', 'pwd'))
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertTrue(
            client.testscram.authenticate('sha256',
                                          'pwd',
                                          mechanism='SCRAM-SHA-256'))
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertRaises(OperationFailure,
                          client.testscram.authenticate,
                          'sha256',
                          'pwd',
                          mechanism='SCRAM-SHA-1')

        self.listener.results.clear()
        self.assertTrue(client.testscram.authenticate('both', 'pwd'))
        started = self.listener.results['started'][0]
        self.assertEqual(started.command.get('mechanism'), 'SCRAM-SHA-256')
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertTrue(
            client.testscram.authenticate('both',
                                          'pwd',
                                          mechanism='SCRAM-SHA-256'))
        client.testscram.command('dbstats')
        client.testscram.logout()
        self.assertTrue(
            client.testscram.authenticate('both',
                                          'pwd',
                                          mechanism='SCRAM-SHA-1'))
        client.testscram.command('dbstats')
        client.testscram.logout()

        self.assertRaises(OperationFailure, client.testscram.authenticate,
                          'not-a-user', 'pwd')

        if HAVE_STRINGPREP:
            # Test the use of SASLprep on passwords. For example,
            # saslprep(u'\u2136') becomes u'IV' and saslprep(u'I\u00ADX')
            # becomes u'IX'. SASLprep is only supported when the standard
            # library provides stringprep.
            client_context.create_user('testscram',
                                       u'\u2168',
                                       u'\u2163',
                                       roles=['dbOwner'],
                                       mechanisms=['SCRAM-SHA-256'])

            client_context.create_user('testscram',
                                       u'IX',
                                       u'IX',
                                       roles=['dbOwner'],
                                       mechanisms=['SCRAM-SHA-256'])

            self.assertTrue(client.testscram.authenticate(
                u'\u2168', u'\u2163'))
            client.testscram.command('dbstats')
            client.testscram.logout()
            self.assertTrue(
                client.testscram.authenticate(u'\u2168',
                                              u'\u2163',
                                              mechanism='SCRAM-SHA-256'))
            client.testscram.command('dbstats')
            client.testscram.logout()
            self.assertTrue(client.testscram.authenticate(u'\u2168', u'IV'))
            client.testscram.command('dbstats')
            client.testscram.logout()

            self.assertTrue(client.testscram.authenticate(u'IX', u'I\u00ADX'))
            client.testscram.command('dbstats')
            client.testscram.logout()
            self.assertTrue(
                client.testscram.authenticate(u'IX',
                                              u'I\u00ADX',
                                              mechanism='SCRAM-SHA-256'))
            client.testscram.command('dbstats')
            client.testscram.logout()
            self.assertTrue(client.testscram.authenticate(u'IX', u'IX'))
            client.testscram.command('dbstats')
            client.testscram.logout()

            client = rs_or_single_client_noauth(
                u'mongodb://\u2168:\u2163@%s:%d/testscram' % (host, port))
            client.testscram.command('dbstats')
            client = rs_or_single_client_noauth(
                u'mongodb://\u2168:IV@%s:%d/testscram' % (host, port))
            client.testscram.command('dbstats')

            client = rs_or_single_client_noauth(
                u'mongodb://*****:*****@%s:%d/testscram' % (host, port))
            client.testscram.command('dbstats')
            client = rs_or_single_client_noauth(
                u'mongodb://*****:*****@%s:%d/testscram' % (host, port))
            client.testscram.command('dbstats')

        self.listener.results.clear()
        client = rs_or_single_client_noauth(
            'mongodb://*****:*****@%s:%d/testscram' % (host, port),
            event_listeners=[self.listener])
        client.testscram.command('dbstats')
        if client_context.version.at_least(4, 4, -1):
            # Speculative authentication in 4.4+ sends saslStart with the
            # handshake.
            self.assertEqual(self.listener.results['started'], [])
        else:
            started = self.listener.results['started'][0]
            self.assertEqual(started.command.get('mechanism'), 'SCRAM-SHA-256')

        client = rs_or_single_client_noauth(
            'mongodb://*****:*****@%s:%d/testscram?authMechanism=SCRAM-SHA-1' %
            (host, port))
        client.testscram.command('dbstats')

        client = rs_or_single_client_noauth(
            'mongodb://*****:*****@%s:%d/testscram?authMechanism=SCRAM-SHA-256' %
            (host, port))
        client.testscram.command('dbstats')

        if client_context.is_rs:
            uri = ('mongodb://*****:*****@%s:%d/testscram'
                   '?replicaSet=%s' %
                   (host, port, client_context.replica_set_name))
            client = single_client_noauth(uri)
            client.testscram.command('dbstats')
            db = client.get_database('testscram',
                                     read_preference=ReadPreference.SECONDARY)
            db.command('dbstats')
コード例 #21
0
    def test_mongodb_x509_auth(self):
        host, port = client_context.host, client_context.port
        self.addCleanup(remove_all_users, client_context.client['$external'])

        # Give x509 user all necessary privileges.
        client_context.create_user('$external',
                                   MONGODB_X509_USERNAME,
                                   roles=[{
                                       'role': 'readWriteAnyDatabase',
                                       'db': 'admin'
                                   }, {
                                       'role': 'userAdminAnyDatabase',
                                       'db': 'admin'
                                   }])

        noauth = MongoClient(client_context.pair,
                             ssl=True,
                             tlsAllowInvalidCertificates=True,
                             tlsCertificateKeyFile=CLIENT_PEM)
        self.addCleanup(noauth.close)

        with self.assertRaises(OperationFailure):
            noauth.pymongo_test.test.find_one()

        listener = EventListener()
        auth = MongoClient(client_context.pair,
                           authMechanism='MONGODB-X509',
                           ssl=True,
                           tlsAllowInvalidCertificates=True,
                           tlsCertificateKeyFile=CLIENT_PEM,
                           event_listeners=[listener])
        self.addCleanup(auth.close)

        # No error
        auth.pymongo_test.test.find_one()
        names = listener.started_command_names()
        if client_context.version.at_least(4, 4, -1):
            # Speculative auth skips the authenticate command.
            self.assertEqual(names, ['find'])
        else:
            self.assertEqual(names, ['authenticate', 'find'])

        uri = ('mongodb://%s@%s:%d/?authMechanism='
               'MONGODB-X509' %
               (quote_plus(MONGODB_X509_USERNAME), host, port))
        client = MongoClient(uri,
                             ssl=True,
                             tlsAllowInvalidCertificates=True,
                             tlsCertificateKeyFile=CLIENT_PEM)
        self.addCleanup(client.close)
        # No error
        client.pymongo_test.test.find_one()

        uri = 'mongodb://%s:%d/?authMechanism=MONGODB-X509' % (host, port)
        client = MongoClient(uri,
                             ssl=True,
                             tlsAllowInvalidCertificates=True,
                             tlsCertificateKeyFile=CLIENT_PEM)
        self.addCleanup(client.close)
        # No error
        client.pymongo_test.test.find_one()
        # Auth should fail if username and certificate do not match
        uri = ('mongodb://%s@%s:%d/?authMechanism='
               'MONGODB-X509' % (quote_plus("not the username"), host, port))

        bad_client = MongoClient(uri,
                                 ssl=True,
                                 tlsAllowInvalidCertificates=True,
                                 tlsCertificateKeyFile=CLIENT_PEM)
        self.addCleanup(bad_client.close)

        with self.assertRaises(OperationFailure):
            bad_client.pymongo_test.test.find_one()

        bad_client = MongoClient(client_context.pair,
                                 username="******",
                                 authMechanism='MONGODB-X509',
                                 ssl=True,
                                 tlsAllowInvalidCertificates=True,
                                 tlsCertificateKeyFile=CLIENT_PEM)
        self.addCleanup(bad_client.close)

        with self.assertRaises(OperationFailure):
            bad_client.pymongo_test.test.find_one()

        # Invalid certificate (using CA certificate as client certificate)
        uri = ('mongodb://%s@%s:%d/?authMechanism='
               'MONGODB-X509' %
               (quote_plus(MONGODB_X509_USERNAME), host, port))
        try:
            connected(
                MongoClient(uri,
                            ssl=True,
                            tlsAllowInvalidCertificates=True,
                            tlsCertificateKeyFile=CA_PEM,
                            serverSelectionTimeoutMS=100))
        except (ConnectionFailure, ConfigurationError):
            pass
        else:
            self.fail("Invalid certificate accepted.")
コード例 #22
0
 def setUp(self):
     client_context.create_user('admin', 'admin', 'pass')
     client_context.create_user('pymongo_test', 'user', 'pass',
                                ['userAdmin', 'readWrite'])
     self.client = rs_or_single_client_noauth(username='******',
                                              password='******')
コード例 #23
0
    def setUp(self):
        super(TestSessionsMultiAuth, self).setUp()

        client_context.create_user(
            'pymongo_test', 'second-user', 'pass', roles=['readWrite'])
        self.addCleanup(client_context.drop_user, 'pymongo_test','second-user')