예제 #1
0
    def setUp(self):
        client = MongoClient(host, port)
        # Sharded auth not supported before MongoDB 2.0
        if is_mongos(client) and not version.at_least(client, (2, 0, 0)):
            raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")
        if not server_started_with_auth(client):
            raise SkipTest('Authentication is not enabled on server')
        response = client.admin.command('ismaster')
        self.set_name = str(response.get('setName', ''))
        client.admin.add_user('admin', 'pass', roles=['userAdminAnyDatabase',
                                                      'dbAdminAnyDatabase',
                                                      'readWriteAnyDatabase',
                                                      'clusterAdmin'])
        client.admin.authenticate('admin', 'pass')
        client.pymongo_test.add_user('user', 'pass',
                                     roles=['userAdmin', 'readWrite'])

        if self.set_name:
            # GLE requires authentication.
            client.admin.authenticate('admin', 'pass')
            # Make sure the admin user is replicated after calling add_user
            # above. This avoids a race in the MRSC tests below. Adding a
            # user is just an insert into system.users.
            client.admin.command('getLastError', w=len(response['hosts']))
        self.client = client
    def test_profiling_info(self):
        db = self.connection.pymongo_test

        db.set_profiling_level(ALL)
        db.test.find()
        db.set_profiling_level(OFF)

        info = db.profiling_info()
        self.assert_(isinstance(info, list))

        # Check if we're going to fail because of SERVER-4754, in which
        # profiling info isn't collected if mongod was started with --auth
        if server_started_with_auth(self.connection):
            raise SkipTest(
                "We need SERVER-4754 fixed for the rest of this test to pass"
            )

        self.assert_(len(info) >= 1)
        # These basically clue us in to server changes.
        if version.at_least(db.connection, (1, 9, 1, -1)):
            self.assert_(isinstance(info[0]['responseLength'], int))
            self.assert_(isinstance(info[0]['millis'], int))
            self.assert_(isinstance(info[0]['client'], basestring))
            self.assert_(isinstance(info[0]['user'], basestring))
            self.assert_(isinstance(info[0]['ntoreturn'], int))
            self.assert_(isinstance(info[0]['ns'], basestring))
            self.assert_(isinstance(info[0]['op'], basestring))
        else:
            self.assert_(isinstance(info[0]["info"], basestring))
            self.assert_(isinstance(info[0]["millis"], float))
        self.assert_(isinstance(info[0]["ts"], datetime.datetime))
예제 #3
0
    def setUp(self):
        client = MongoClient(host, port)
        # Sharded auth not supported before MongoDB 2.0
        if is_mongos(client) and not version.at_least(client, (2, 0, 0)):
            raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")
        if not server_started_with_auth(client):
            raise SkipTest('Authentication is not enabled on server')
        response = client.admin.command('ismaster')
        self.set_name = str(response.get('setName', ''))
        client.admin.add_user('admin', 'pass', roles=['userAdminAnyDatabase',
                                                      'dbAdminAnyDatabase',
                                                      'readWriteAnyDatabase',
                                                      'clusterAdmin'])
        client.admin.authenticate('admin', 'pass')
        client.pymongo_test.add_user('user', 'pass',
                                     roles=['userAdmin', 'readWrite'])

        if self.set_name:
            # GLE requires authentication.
            client.admin.authenticate('admin', 'pass')
            # Make sure the admin user is replicated after calling add_user
            # above. This avoids a race in the MRSC tests below. Adding a
            # user is just an insert into system.users.
            client.admin.command('getLastError', w=len(response['hosts']))
        self.client = client
    def test_profiling_info(self):
        if is_mongos(self.connection):
            raise SkipTest('profile is not supported by mongos')
        db = self.connection.pymongo_test

        db.set_profiling_level(ALL)
        db.test.find()
        db.set_profiling_level(OFF)

        info = db.profiling_info()
        self.assertTrue(isinstance(info, list))

        # Check if we're going to fail because of SERVER-4754, in which
        # profiling info isn't collected if mongod was started with --auth
        if server_started_with_auth(self.connection):
            raise SkipTest(
                "We need SERVER-4754 fixed for the rest of this test to pass")

        self.assertTrue(len(info) >= 1)
        # These basically clue us in to server changes.
        if version.at_least(db.connection, (1, 9, 1, -1)):
            self.assertTrue(isinstance(info[0]['responseLength'], int))
            self.assertTrue(isinstance(info[0]['millis'], int))
            self.assertTrue(isinstance(info[0]['client'], basestring))
            self.assertTrue(isinstance(info[0]['user'], basestring))
            self.assertTrue(isinstance(info[0]['ntoreturn'], int))
            self.assertTrue(isinstance(info[0]['ns'], basestring))
            self.assertTrue(isinstance(info[0]['op'], basestring))
        else:
            self.assertTrue(isinstance(info[0]["info"], basestring))
            self.assertTrue(isinstance(info[0]["millis"], float))
        self.assertTrue(isinstance(info[0]["ts"], datetime.datetime))
예제 #5
0
    def test_fsync_lock_unlock(self):
        c = get_client()
        if is_mongos(c):
            raise SkipTest('fsync/lock not supported by mongos')
        if not version.at_least(c, (2, 0)) and server_started_with_auth(c):
            raise SkipTest('Requires server >= 2.0 to test with auth')

        res = c.admin.command('getCmdLineOpts')
        if '--master' in res['argv'] and version.at_least(c, (2, 3, 0)):
            raise SkipTest('SERVER-7714')

        self.assertFalse(c.is_locked)
        # async flushing not supported on windows...
        if sys.platform not in ('cygwin', 'win32'):
            c.fsync(async=True)
            self.assertFalse(c.is_locked)
        c.fsync(lock=True)
        self.assertTrue(c.is_locked)
        locked = True
        c.unlock()
        for _ in xrange(5):
            locked = c.is_locked
            if not locked:
                break
            time.sleep(1)
        self.assertFalse(locked)
예제 #6
0
    def test_init_disconnected_with_auth(self):
        c = self._get_client()
        if not server_started_with_auth(c):
            raise SkipTest('Authentication is not enabled on server')

        c.admin.add_user("admin", "pass")
        c.admin.authenticate("admin", "pass")
        try:
            c.pymongo_test.add_user("user", "pass", roles=['readWrite', 'userAdmin'])

            # Auth with lazy connection.
            host = one(self.hosts)
            uri = "mongodb://*****:*****@%s:%d/pymongo_test?replicaSet=%s" % (
                host[0], host[1], self.name)

            authenticated_client = MongoReplicaSetClient(uri, _connect=False)
            authenticated_client.pymongo_test.test.find_one()

            # Wrong password.
            bad_uri = "mongodb://*****:*****@%s:%d/pymongo_test?replicaSet=%s" % (
                host[0], host[1], self.name)

            bad_client = MongoReplicaSetClient(bad_uri, _connect=False)
            self.assertRaises(
                OperationFailure, bad_client.pymongo_test.test.find_one)

        finally:
            # Clean up.
            remove_all_users(c.pymongo_test)
            remove_all_users(c.admin)
예제 #7
0
    def test_mongodb_x509_auth(self):
        # Expects the server to be running with the server.pem, ca.pem
        # and crl.pem provided in mongodb and the server tests as well as
        # --auth
        #
        #   --sslPEMKeyFile=jstests/libs/server.pem
        #   --sslCAFile=jstests/libs/ca.pem
        #   --sslCRLFile=jstests/libs/crl.pem
        #   --auth
        if not CERT_SSL:
            raise SkipTest("No mongod available over SSL with certs")

        client = MongoClient(host, port, ssl=True, ssl_certfile=CLIENT_PEM)
        if not version.at_least(client, (2, 5, 3, -1)):
            raise SkipTest("MONGODB-X509 tests require MongoDB 2.5.3 or newer")
        if not server_started_with_auth(client):
            raise SkipTest('Authentication is not enabled on server')
        # Give admin all necessary privileges.
        client['$external'].add_user(MONGODB_X509_USERNAME, roles=[
            {'role': 'readWriteAnyDatabase', 'db': 'admin'},
            {'role': 'userAdminAnyDatabase', 'db': 'admin'}])
        coll = client.pymongo_test.test
        self.assertRaises(OperationFailure, coll.count)
        self.assertTrue(client.admin.authenticate(MONGODB_X509_USERNAME,
                                                  mechanism='MONGODB-X509'))
        self.assertTrue(coll.remove())
        uri = ('mongodb://%s@%s:%d/?authMechanism='
               'MONGODB-X509' % (quote_plus(MONGODB_X509_USERNAME), host, port))
        # SSL options aren't supported in the URI...
        self.assertTrue(MongoClient(uri, ssl=True, ssl_certfile=CLIENT_PEM))
        # Cleanup
        remove_all_users(client['$external'])
        client['$external'].logout()
예제 #8
0
    def test_authenticate_and_request(self):
        if (is_mongos(self.client) and not
            version.at_least(self.client, (2, 0, 0))):
            raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")
        if not server_started_with_auth(self.client):
            raise SkipTest('Authentication is not enabled on server')

        # Database.authenticate() needs to be in a request - check that it
        # always runs in a request, and that it restores the request state
        # (in or not in a request) properly when it's finished.
        self.assertFalse(self.client.auto_start_request)
        db = self.client.pymongo_test
        db.add_user("mike", "password",
                    roles=["userAdmin", "dbAdmin", "readWrite"])
        try:
            self.assertFalse(self.client.in_request())
            self.assertTrue(db.authenticate("mike", "password"))
            self.assertFalse(self.client.in_request())

            request_cx = get_client(auto_start_request=True)
            request_db = request_cx.pymongo_test
            self.assertTrue(request_db.authenticate("mike", "password"))
            self.assertTrue(request_cx.in_request())
        finally:
            db.authenticate("mike", "password")
            db.remove_user("mike")
            db.logout()
            request_db.logout()
예제 #9
0
    def test_unix_socket(self):
        if not hasattr(socket, "AF_UNIX"):
            raise SkipTest("UNIX-sockets are not supported on this system")

        if (sys.platform == 'darwin'
                and server_started_with_auth(self.sync_cx)):
            raise SkipTest("SERVER-8492")

        mongodb_socket = '/tmp/mongodb-27017.sock'
        if not os.access(mongodb_socket, os.R_OK):
            raise SkipTest("Socket file is not accessible")

        yield motor.MotorClient("mongodb://%s" % mongodb_socket,
                                io_loop=self.io_loop).open()

        client = yield motor.MotorClient("mongodb://%s" % mongodb_socket,
                                         io_loop=self.io_loop).open()

        yield client.pymongo_test.test.save({"dummy": "object"})

        # Confirm we can read via the socket.
        dbs = yield client.database_names()
        self.assertTrue("pymongo_test" in dbs)
        client.close()

        # Confirm it fails with a missing socket.
        client = motor.MotorClient("mongodb:///tmp/non-existent.sock",
                                   io_loop=self.io_loop)

        with assert_raises(ConnectionFailure):
            yield client.open()
예제 #10
0
    def test_authenticate_and_safe(self):
        if (is_mongos(self.client) and not
            version.at_least(self.client, (2, 0, 0))):
            raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")
        if not server_started_with_auth(self.client):
            raise SkipTest('Authentication is not enabled on server')
        db = self.client.auth_test

        db.add_user("bernie", "password",
                    roles=["userAdmin", "dbAdmin", "readWrite"])
        db.authenticate("bernie", "password")
        try:
            db.test.remove({})
            self.assertTrue(db.test.insert({"bim": "baz"}))
            self.assertEqual(1, db.test.count())

            self.assertEqual(1,
                             db.test.update({"bim": "baz"},
                                            {"$set": {"bim": "bar"}}).get('n'))

            self.assertEqual(1,
                             db.test.remove({}).get('n'))

            self.assertEqual(0, db.test.count())
        finally:
            db.remove_user("bernie")
            db.logout()
예제 #11
0
    def test_authenticate_and_safe(self):
        if (is_mongos(self.client) and not
            version.at_least(self.client, (2, 0, 0))):
            raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")
        if not server_started_with_auth(self.client):
            raise SkipTest('Authentication is not enabled on server')
        db = self.client.auth_test

        db.add_user("bernie", "password",
                    roles=["userAdmin", "dbAdmin", "readWrite"])
        db.authenticate("bernie", "password")
        try:
            db.test.remove({})
            self.assertTrue(db.test.insert({"bim": "baz"}))
            self.assertEqual(1, db.test.count())

            self.assertEqual(1,
                             db.test.update({"bim": "baz"},
                                            {"$set": {"bim": "bar"}}).get('n'))

            self.assertEqual(1,
                             db.test.remove({}).get('n'))

            self.assertEqual(0, db.test.count())
        finally:
            db.remove_user("bernie")
            db.logout()
예제 #12
0
    def test_authenticate_and_request(self):
        if (is_mongos(self.client) and not
            version.at_least(self.client, (2, 0, 0))):
            raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")
        if not server_started_with_auth(self.client):
            raise SkipTest('Authentication is not enabled on server')

        # Database.authenticate() needs to be in a request - check that it
        # always runs in a request, and that it restores the request state
        # (in or not in a request) properly when it's finished.
        self.assertFalse(self.client.auto_start_request)
        db = self.client.pymongo_test
        db.add_user("mike", "password",
                    roles=["userAdmin", "dbAdmin", "readWrite"])
        try:
            self.assertFalse(self.client.in_request())
            self.assertTrue(db.authenticate("mike", "password"))
            self.assertFalse(self.client.in_request())

            request_cx = get_client(auto_start_request=True)
            request_db = request_cx.pymongo_test
            self.assertTrue(request_cx.in_request())
            self.assertTrue(request_db.authenticate("mike", "password"))
            self.assertTrue(request_cx.in_request())
        finally:
            db.authenticate("mike", "password")
            db.remove_user("mike")
            db.logout()
            request_db.logout()
    def test_auth_network_error(self):
        # Make sure there's no semaphore leak if we get a network error
        # when authenticating a new socket with cached credentials.
        auth_client = self._get_client()
        if not server_started_with_auth(auth_client):
            raise SkipTest('Authentication is not enabled on server')

        auth_client.admin.add_user('admin', 'password')
        auth_client.admin.authenticate('admin', 'password')
        try:
            # Get a client with one socket so we detect if it's leaked.
            c = self._get_client(max_pool_size=1, waitQueueTimeoutMS=1)

            # Simulate an authenticate() call on a different socket.
            credentials = auth._build_credentials_tuple(
                'MONGODB-CR', 'admin', unicode('admin'), unicode('password'),
                {})

            c._cache_credentials('test', credentials, connect=False)

            # Cause a network error on the actual socket.
            pool = get_pool(c)
            socket_info = one(pool.sockets)
            socket_info.sock.close()

            # In __check_auth, the client authenticates its socket with the
            # new credential, but gets a socket.error. Should be reraised as
            # AutoReconnect.
            self.assertRaises(AutoReconnect, c.test.collection.find_one)

            # No semaphore leak, the pool is allowed to make a new socket.
            c.test.collection.find_one()
        finally:
            remove_all_users(auth_client.admin)
    def test_init_disconnected_with_auth(self):
        c = self._get_client()
        if not server_started_with_auth(c):
            raise SkipTest('Authentication is not enabled on server')

        c.admin.add_user("admin", "pass")
        c.admin.authenticate("admin", "pass")
        try:
            c.pymongo_test.add_user("user",
                                    "pass",
                                    roles=['readWrite', 'userAdmin'])

            # Auth with lazy connection.
            host = one(self.hosts)
            uri = "mongodb://*****:*****@%s:%d/pymongo_test?replicaSet=%s" % (
                host[0], host[1], self.name)

            authenticated_client = MongoReplicaSetClient(uri, _connect=False)
            authenticated_client.pymongo_test.test.find_one()

            # Wrong password.
            bad_uri = "mongodb://*****:*****@%s:%d/pymongo_test?replicaSet=%s" % (
                host[0], host[1], self.name)

            bad_client = MongoReplicaSetClient(bad_uri, _connect=False)
            self.assertRaises(OperationFailure,
                              bad_client.pymongo_test.test.find_one)

        finally:
            # Clean up.
            remove_all_users(c.pymongo_test)
            remove_all_users(c.admin)
예제 #15
0
    def test_unix_socket(self):
        if not hasattr(socket, "AF_UNIX"):
            raise SkipTest("UNIX-sockets are not supported on this system")

        if (sys.platform == 'darwin' and
                server_started_with_auth(self.sync_cx)):
            raise SkipTest("SERVER-8492")

        mongodb_socket = '/tmp/mongodb-27017.sock'
        if not os.access(mongodb_socket, os.R_OK):
            raise SkipTest("Socket file is not accessible")

        yield motor.MotorClient(
            "mongodb://%s" % mongodb_socket, io_loop=self.io_loop).open()

        client = yield motor.MotorClient(
            "mongodb://%s" % mongodb_socket, io_loop=self.io_loop).open()

        yield client.pymongo_test.test.save({"dummy": "object"})

        # Confirm we can read via the socket
        dbs = yield client.database_names()
        self.assertTrue("pymongo_test" in dbs)
        client.close()

        # Confirm it fails with a missing socket
        client = motor.MotorClient(
            "mongodb:///tmp/non-existent.sock", io_loop=self.io_loop)

        with assert_raises(ConnectionFailure):
            yield client.open()
예제 #16
0
    def test_auth_network_error(self):
        # Make sure there's no semaphore leak if we get a network error
        # when authenticating a new socket with cached credentials.
        auth_client = self._get_client()
        if not server_started_with_auth(auth_client):
            raise SkipTest('Authentication is not enabled on server')

        auth_client.admin.add_user('admin', 'password')
        auth_client.admin.authenticate('admin', 'password')
        try:
            # Get a client with one socket so we detect if it's leaked.
            c = self._get_client(max_pool_size=1, waitQueueTimeoutMS=1)

            # Simulate an authenticate() call on a different socket.
            credentials = auth._build_credentials_tuple(
                'MONGODB-CR', 'admin',
                unicode('admin'), unicode('password'),
                {})

            c._cache_credentials('test', credentials, connect=False)

            # Cause a network error on the actual socket.
            pool = get_pool(c)
            socket_info = one(pool.sockets)
            socket_info.sock.close()

            # In __check_auth, the client authenticates its socket with the
            # new credential, but gets a socket.error. Should be reraised as
            # AutoReconnect.
            self.assertRaises(AutoReconnect, c.test.collection.find_one)

            # No semaphore leak, the pool is allowed to make a new socket.
            c.test.collection.find_one()
        finally:
            remove_all_users(auth_client.admin)
예제 #17
0
    def test_profiling_info(self):
        db = self.client.pymongo_test

        db.system.profile.drop()
        db.set_profiling_level(ALL)
        db.test.find_one()
        db.set_profiling_level(OFF)

        info = db.profiling_info()
        self.assertTrue(isinstance(info, list))

        # Check if we're going to fail because of SERVER-4754, in which
        # profiling info isn't collected if mongod was started with --auth
        if server_started_with_auth(self.client):
            raise SkipTest(
                "We need SERVER-4754 fixed for the rest of this test to pass"
            )

        self.assertTrue(len(info) >= 1)
        # These basically clue us in to server changes.
        self.assertTrue(isinstance(info[0]['responseLength'], int))
        self.assertTrue(isinstance(info[0]['millis'], int))
        self.assertTrue(isinstance(info[0]['client'], string_type))
        self.assertTrue(isinstance(info[0]['user'], string_type))
        self.assertTrue(isinstance(info[0]['ns'], string_type))
        self.assertTrue(isinstance(info[0]['op'], string_type))
        self.assertTrue(isinstance(info[0]["ts"], datetime.datetime))
예제 #18
0
    def setUp(self):
        super(TestBulkAuthorization, self).setUp()
        self.client = client = get_client()
        if (not server_started_with_auth(client)
                or not version.at_least(client, (2, 5, 3))):
            raise SkipTest('Need at least MongoDB 2.5.3 with auth')

        db = client.pymongo_test
        self.coll = db.test
        self.coll.remove()

        db.add_user('dbOwner', 'pw', roles=['dbOwner'])
        db.authenticate('dbOwner', 'pw')
        db.add_user('readonly', 'pw', roles=['read'])
        db.command('createRole',
                   'noremove',
                   privileges=[{
                       'actions': ['insert', 'update', 'find'],
                       'resource': {
                           'db': 'pymongo_test',
                           'collection': 'test'
                       }
                   }],
                   roles=[])

        db.add_user('noremove', 'pw', roles=['noremove'])
        db.logout()
예제 #19
0
    def test_profiling_info(self):
        if is_mongos(self.client):
            raise SkipTest("profile is not supported by mongos")
        db = self.client.pymongo_test

        db.set_profiling_level(ALL)
        db.test.find_one()
        db.set_profiling_level(OFF)

        info = db.profiling_info()
        self.assertTrue(isinstance(info, list))

        # Check if we're going to fail because of SERVER-4754, in which
        # profiling info isn't collected if mongod was started with --auth
        if server_started_with_auth(self.client):
            raise SkipTest("We need SERVER-4754 fixed for the rest of this test to pass")

        self.assertTrue(len(info) >= 1)
        # These basically clue us in to server changes.
        if version.at_least(db.connection, (1, 9, 1, -1)):
            self.assertTrue(isinstance(info[0]["responseLength"], int))
            self.assertTrue(isinstance(info[0]["millis"], int))
            self.assertTrue(isinstance(info[0]["client"], basestring))
            self.assertTrue(isinstance(info[0]["user"], basestring))
            self.assertTrue(isinstance(info[0]["ns"], basestring))
            self.assertTrue(isinstance(info[0]["op"], basestring))
        else:
            self.assertTrue(isinstance(info[0]["info"], basestring))
            self.assertTrue(isinstance(info[0]["millis"], float))
        self.assertTrue(isinstance(info[0]["ts"], datetime.datetime))
    def test_unix_socket(self):
        if not hasattr(socket, "AF_UNIX"):
            raise SkipTest("UNIX-sockets are not supported on this system")
        client = MongoClient(host, port)
        if (sys.platform == 'darwin' and
                server_started_with_auth(client) and
                not version.at_least(client, (2, 7, 1))):
            raise SkipTest("SERVER-8492")

        mongodb_socket = '/tmp/mongodb-27017.sock'
        if not os.access(mongodb_socket, os.R_OK):
            raise SkipTest("Socket file is not accessable")

        self.assertTrue(MongoClient("mongodb://%s" % mongodb_socket))

        client = MongoClient("mongodb://%s" % mongodb_socket)
        client.pymongo_test.test.save({"dummy": "object"})

        # Confirm we can read via the socket
        dbs = client.database_names()
        self.assertTrue("pymongo_test" in dbs)

        # Confirm it fails with a missing socket
        self.assertRaises(ConnectionFailure, MongoClient,
                          "mongodb:///tmp/none-existent.sock")
    def test_profiling_info(self):
        db = self.client.pymongo_test

        db.system.profile.drop()
        db.set_profiling_level(ALL)
        db.test.find_one()
        db.set_profiling_level(OFF)

        info = db.profiling_info()
        self.assertTrue(isinstance(info, list))

        # Check if we're going to fail because of SERVER-4754, in which
        # profiling info isn't collected if mongod was started with --auth
        if server_started_with_auth(self.client):
            raise SkipTest(
                "We need SERVER-4754 fixed for the rest of this test to pass"
            )

        self.assertTrue(len(info) >= 1)
        # These basically clue us in to server changes.
        self.assertTrue(isinstance(info[0]['responseLength'], int))
        self.assertTrue(isinstance(info[0]['millis'], int))
        self.assertTrue(isinstance(info[0]['client'], string_type))
        self.assertTrue(isinstance(info[0]['user'], string_type))
        self.assertTrue(isinstance(info[0]['ns'], string_type))
        self.assertTrue(isinstance(info[0]['op'], string_type))
        self.assertTrue(isinstance(info[0]["ts"], datetime.datetime))
예제 #22
0
    def test_fsync_lock_unlock(self):
        c = get_client()
        if is_mongos(c):
            raise SkipTest('fsync/lock not supported by mongos')
        if not version.at_least(c, (2, 0)) and server_started_with_auth(c):
            raise SkipTest('Requires server >= 2.0 to test with auth')

        res = c.admin.command('getCmdLineOpts')
        if '--master' in res['argv'] and version.at_least(c, (2, 3, 0)):
            raise SkipTest('SERVER-7714')

        self.assertFalse(c.is_locked)
        # async flushing not supported on windows...
        if sys.platform not in ('cygwin', 'win32'):
            c.fsync(async=True)
            self.assertFalse(c.is_locked)
        c.fsync(lock=True)
        self.assertTrue(c.is_locked)
        locked = True
        c.unlock()
        for _ in xrange(5):
            locked = c.is_locked
            if not locked:
                break
            time.sleep(1)
        self.assertFalse(locked)
예제 #23
0
    def test_authenticate_multiple(self):
        client = get_client()
        if is_mongos(client) and not version.at_least(self.client, (2, 2, 0)):
            raise SkipTest("Need mongos >= 2.2.0")
        if not server_started_with_auth(client):
            raise SkipTest("Authentication is not enabled on server")

        # Setup
        users_db = client.pymongo_test
        admin_db = client.admin
        other_db = client.pymongo_test1
        users_db.test.remove()
        other_db.test.remove()

        admin_db.add_user("admin", "pass", roles=["userAdminAnyDatabase", "dbAdmin", "clusterAdmin", "readWrite"])
        try:
            self.assertTrue(admin_db.authenticate("admin", "pass"))

            if version.at_least(self.client, (2, 5, 3, -1)):
                admin_db.add_user("ro-admin", "pass", roles=["userAdmin", "readAnyDatabase"])
            else:
                admin_db.add_user("ro-admin", "pass", read_only=True)

            users_db.add_user("user", "pass", roles=["userAdmin", "readWrite"])

            admin_db.logout()
            self.assertRaises(OperationFailure, users_db.test.find_one)

            # Regular user should be able to query its own db, but
            # no other.
            users_db.authenticate("user", "pass")
            self.assertEqual(0, users_db.test.count())
            self.assertRaises(OperationFailure, other_db.test.find_one)

            # Admin read-only user should be able to query any db,
            # but not write.
            admin_db.authenticate("ro-admin", "pass")
            self.assertEqual(0, other_db.test.count())
            self.assertRaises(OperationFailure, other_db.test.insert, {})

            # Force close all sockets
            client.disconnect()

            # We should still be able to write to the regular user's db
            self.assertTrue(users_db.test.remove())
            # And read from other dbs...
            self.assertEqual(0, other_db.test.count())
            # But still not write to other dbs...
            self.assertRaises(OperationFailure, other_db.test.insert, {})

        # Cleanup
        finally:
            admin_db.logout()
            users_db.logout()
            admin_db.authenticate("admin", "pass")
            remove_all_users(users_db)
            remove_all_users(admin_db)
예제 #24
0
 def setUp(self):
     self.conn = self._get_connection()
     if not server_started_with_auth(self.conn):
         raise SkipTest("Authentication is not enabled on server")
     self.conn.admin.system.users.remove({})
     self.conn.admin.add_user('admin-user', 'password')
     self.conn.admin.authenticate("admin-user", "password")
     self.conn.auth_test.system.users.remove({})
     self.conn.auth_test.add_user("test-user", "password")
예제 #25
0
    def test_authenticate_multiple(self):
        client = get_client()
        if (is_mongos(client) and not
            version.at_least(self.client, (2, 0, 0))):
            raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")
        if not server_started_with_auth(client):
            raise SkipTest("Authentication is not enabled on server")

        # Setup
        users_db = client.pymongo_test
        admin_db = client.admin
        other_db = client.pymongo_test1
        users_db.system.users.remove()
        admin_db.system.users.remove()
        users_db.test.remove()
        other_db.test.remove()

        admin_db.add_user('admin', 'pass')
        self.assertTrue(admin_db.authenticate('admin', 'pass'))

        admin_db.add_user('ro-admin', 'pass', read_only=True)
        users_db.add_user('user', 'pass')

        admin_db.logout()
        self.assertRaises(OperationFailure, users_db.test.find_one)

        # Regular user should be able to query its own db, but
        # no other.
        users_db.authenticate('user', 'pass')
        self.assertEqual(0, users_db.test.count())
        self.assertRaises(OperationFailure, other_db.test.find_one)

        # Admin read-only user should be able to query any db,
        # but not write.
        admin_db.authenticate('ro-admin', 'pass')
        self.assertEqual(0, other_db.test.count())
        self.assertRaises(OperationFailure,
                          other_db.test.insert, {})

        # Force close all sockets
        client.disconnect()

        # We should still be able to write to the regular user's db
        self.assertTrue(users_db.test.remove())
        # And read from other dbs...
        self.assertEqual(0, other_db.test.count())
        # But still not write to other dbs...
        self.assertRaises(OperationFailure,
                          other_db.test.insert, {})

        # Cleanup
        admin_db.logout()
        users_db.logout()
        self.assertTrue(admin_db.authenticate('admin', 'pass'))
        self.assertTrue(admin_db.system.users.remove())
        self.assertEqual(0, admin_db.system.users.count())
        self.assertTrue(users_db.system.users.remove())
예제 #26
0
 def setUp(self):
     self.conn = self._get_connection()
     if not server_started_with_auth(self.conn):
         raise SkipTest("Authentication is not enabled on server")
     self.conn.admin.system.users.remove({})
     self.conn.admin.add_user('admin-user', 'password')
     self.conn.admin.authenticate("admin-user", "password")
     self.conn.auth_test.system.users.remove({})
     self.conn.auth_test.add_user("test-user", "password")
예제 #27
0
    def test_comment(self):
        if is_mongos(self.client):
            raise SkipTest("profile is not supported by mongos")
        if not version.at_least(self.db.connection, (2, 0)):
            raise SkipTest("Requires server >= 2.0")
        if server_started_with_auth(self.db.connection):
            raise SkipTest("SERVER-4754 - This test uses profiling.")

        def run_with_profiling(func):
            self.db.set_profiling_level(OFF)
            self.db.system.profile.drop()
            self.db.set_profiling_level(ALL)
            func()
            self.db.set_profiling_level(OFF)

        def find():
            list(self.db.test.find().comment('foo'))
            op = self.db.system.profile.find({
                'ns': 'pymongo_test.test',
                'op': 'query',
                'query.$comment': 'foo'
            })
            self.assertEqual(op.count(), 1)

        run_with_profiling(find)

        def count():
            self.db.test.find().comment('foo').count()
            op = self.db.system.profile.find({
                'ns': 'pymongo_test.$cmd',
                'op': 'command',
                'command.count': 'test',
                'command.$comment': 'foo'
            })
            self.assertEqual(op.count(), 1)

        run_with_profiling(count)

        def distinct():
            self.db.test.find().comment('foo').distinct('type')
            op = self.db.system.profile.find({
                'ns': 'pymongo_test.$cmd',
                'op': 'command',
                'command.distinct': 'test',
                'command.$comment': 'foo'
            })
            self.assertEqual(op.count(), 1)

        run_with_profiling(distinct)

        self.db.test.insert([{}, {}])
        cursor = self.db.test.find()
        cursor.next()
        self.assertRaises(InvalidOperation, cursor.comment, 'hello')

        self.db.system.profile.drop()
예제 #28
0
    def test_mongodb_x509_auth(self):
        # Expects the server to be running with the server.pem, ca.pem
        # and crl.pem provided in mongodb and the server tests as well as
        # --auth
        #
        #   --sslPEMKeyFile=jstests/libs/server.pem
        #   --sslCAFile=jstests/libs/ca.pem
        #   --sslCRLFile=jstests/libs/crl.pem
        #   --auth
        if not CERT_SSL:
            raise SkipTest("No mongod available over SSL with certs")

        client = MongoClient(host, port, ssl=True, ssl_certfile=CLIENT_PEM)
        if not version.at_least(client, (2, 5, 3, -1)):
            raise SkipTest("MONGODB-X509 tests require MongoDB 2.5.3 or newer")
        if not server_started_with_auth(client):
            raise SkipTest('Authentication is not enabled on server')
        # Give admin all necessary privileges.
        client['$external'].add_user(MONGODB_X509_USERNAME, roles=[
            {'role': 'readWriteAnyDatabase', 'db': 'admin'},
            {'role': 'userAdminAnyDatabase', 'db': 'admin'}])
        coll = client.pymongo_test.test
        self.assertRaises(OperationFailure, coll.count)
        self.assertTrue(client.admin.authenticate(MONGODB_X509_USERNAME,
                                                  mechanism='MONGODB-X509'))
        self.assertTrue(coll.remove())
        uri = ('mongodb://%s@%s:%d/?authMechanism='
               'MONGODB-X509' % (quote_plus(MONGODB_X509_USERNAME), host, port))
        # SSL options aren't supported in the URI...
        self.assertTrue(MongoClient(uri, ssl=True, ssl_certfile=CLIENT_PEM))

        # Should require a username
        uri = ('mongodb://%s:%d/?authMechanism=MONGODB-X509' % (host, port))
        client_bad = MongoClient(uri, ssl=True, ssl_certfile=CLIENT_PEM)
        self.assertRaises(OperationFailure, client_bad.pymongo_test.test.remove)

        # 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))
        self.assertRaises(ConfigurationError, MongoClient, uri,
                          ssl=True, ssl_certfile=CLIENT_PEM)
        self.assertRaises(OperationFailure, client.admin.authenticate,
                          "not the username",
                          mechanism="MONGODB-X509")

        # Invalid certificate (using CA certificate as client certificate)
        uri = ('mongodb://%s@%s:%d/?authMechanism='
               'MONGODB-X509' % (quote_plus(MONGODB_X509_USERNAME), host, port))
        self.assertRaises(ConnectionFailure, MongoClient, uri,
                          ssl=True, ssl_certfile=CA_PEM)
        self.assertRaises(ConnectionFailure, MongoClient, pair,
                          ssl=True, ssl_certfile=CA_PEM)

        # Cleanup
        remove_all_users(client['$external'])
        client['$external'].logout()
예제 #29
0
    def test_comment(self):
        if server_started_with_auth(self.db.client):
            raise SkipTest("SERVER-4754 - This test uses profiling.")

        def run_with_profiling(func):
            self.db.set_profiling_level(OFF)
            self.db.system.profile.drop()
            self.db.set_profiling_level(ALL)
            func()
            self.db.set_profiling_level(OFF)

        def find():
            list(self.db.test.find().comment('foo'))
            op = self.db.system.profile.find({
                'ns': 'pymongo_test.test',
                'op': 'query',
                'query.$comment': 'foo'
            })
            self.assertEqual(op.count(), 1)

        run_with_profiling(find)

        # MongoDB 3.1.5 changed the ns for commands.
        regex = {'$regex': 'pymongo_test.(\$cmd|test)'}

        def count():
            self.db.test.find().comment('foo').count()
            op = self.db.system.profile.find({
                'ns': regex,
                'op': 'command',
                'command.count': 'test',
                'command.$comment': 'foo'
            })
            self.assertEqual(op.count(), 1)

        run_with_profiling(count)

        def distinct():
            self.db.test.find().comment('foo').distinct('type')
            op = self.db.system.profile.find({
                'ns': regex,
                'op': 'command',
                'command.distinct': 'test',
                'command.$comment': 'foo'
            })
            self.assertEqual(op.count(), 1)

        run_with_profiling(distinct)

        self.db.test.insert_many([{}, {}])
        cursor = self.db.test.find()
        next(cursor)
        self.assertRaises(InvalidOperation, cursor.comment, 'hello')

        self.db.system.profile.drop()
예제 #30
0
 def setUp(self):
     client = MongoClient(HOST, PORT)
     # Sharded auth not supported before MongoDB 2.0
     if is_mongos(client) and not version.at_least(client, (2, 0, 0)):
         raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")
     if not server_started_with_auth(client):
         raise SkipTest('Authentication is not enabled on server')
     self.set_name = client.admin.command('ismaster').get('setName')
     client.pymongo_test.add_user('user', 'pass')
     client.admin.add_user('admin', 'pass')
     self.client = client
    def test_lazy_auth_raises_operation_failure(self):
        # Check if we have the prerequisites to run this test.
        c = self._get_client()
        if not server_started_with_auth(c):
            raise SkipTest("Authentication is not enabled on server")

        lazy_client = MongoReplicaSetClient(
            "mongodb://*****:*****@%s/pymongo_test" % pair, replicaSet=self.name, _connect=False
        )

        assertRaisesExactly(OperationFailure, lazy_client.test.collection.find_one)
    def test_lazy_auth_raises_operation_failure(self):
        # Check if we have the prerequisites to run this test.
        c = MongoClient(host, port)
        if not server_started_with_auth(c):
            raise SkipTest("Authentication is not enabled on server")

        if is_mongos(c) and not version.at_least(c, (2, 0, 0)):
            raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")

        lazy_client = MongoClient("mongodb://*****:*****@%s:%d/pymongo_test" % (host, port), _connect=False)

        assertRaisesExactly(OperationFailure, lazy_client.test.collection.find_one)
예제 #33
0
 def setUp(self):
     client = self._get_client()
     if not server_started_with_auth(client):
         raise SkipTest("Authentication is not enabled on server")
     self.client = client
     self.client.admin.add_user(
         "admin-user",
         "password",
         roles=["clusterAdmin", "dbAdminAnyDatabase", "readWriteAnyDatabase", "userAdminAnyDatabase"],
     )
     self.client.admin.authenticate("admin-user", "password")
     self.client.auth_test.add_user("test-user", "password", roles=["readWrite"])
예제 #34
0
    def test_auth_from_uri(self):
        c = MongoClient(host, port)
        # Sharded auth not supported before MongoDB 2.0
        if is_mongos(c) and not version.at_least(c, (2, 0, 0)):
            raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")
        if not server_started_with_auth(c):
            raise SkipTest('Authentication is not enabled on server')

        c.admin.add_user("admin", "pass")
        c.admin.authenticate("admin", "pass")
        try:
            c.pymongo_test.add_user("user",
                                    "pass",
                                    roles=['userAdmin', 'readWrite'])

            self.assertRaises(ConfigurationError, MongoClient,
                              "mongodb://*****:*****@%s:%d" % (host, port))
            self.assertRaises(ConfigurationError, MongoClient,
                              "mongodb://*****:*****@%s:%d" % (host, port))
            self.assertRaises(ConfigurationError, MongoClient,
                              "mongodb://*****:*****@%s:%d" % (host, port))
            MongoClient("mongodb://*****:*****@%s:%d" % (host, port))

            self.assertRaises(
                ConfigurationError, MongoClient,
                "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port))
            self.assertRaises(
                ConfigurationError, MongoClient,
                "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port))
            MongoClient("mongodb://*****:*****@%s:%d/pymongo_test" %
                        (host, port))

            # Auth with lazy connection.
            MongoClient("mongodb://*****:*****@%s:%d/pymongo_test" %
                        (host, port),
                        _connect=False).pymongo_test.test.find_one()

            # Wrong password.
            bad_client = MongoClient(
                "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port),
                _connect=False)

            # If auth fails with lazy connection, MongoClient raises
            # AutoReconnect instead of the more appropriate OperationFailure,
            # PYTHON-517.
            self.assertRaises(PyMongoError,
                              bad_client.pymongo_test.test.find_one)

        finally:
            # Clean up.
            remove_all_users(c.pymongo_test)
            remove_all_users(c.admin)
예제 #35
0
 def setUp(self):
     self.client = MongoClient(host, port)
     if not version.at_least(self.client, (2, 4, 0)):
         raise SkipTest('Delegated authentication requires MongoDB >= 2.4.0')
     if not server_started_with_auth(self.client):
         raise SkipTest('Authentication is not enabled on server')
     # Give admin all priviledges.
     self.client.admin.add_user('admin', 'pass',
                                roles=['readAnyDatabase',
                                       'readWriteAnyDatabase',
                                       'userAdminAnyDatabase',
                                       'dbAdminAnyDatabase',
                                       'clusterAdmin'])
예제 #36
0
 def setUp(self):
     self.client = MongoClient(host, port)
     if not version.at_least(self.client, (2, 4, 0)):
         raise SkipTest('Delegated authentication requires MongoDB >= 2.4.0')
     if not server_started_with_auth(self.client):
         raise SkipTest('Authentication is not enabled on server')
     # Give admin all priviledges.
     self.client.admin.add_user('admin', 'pass',
                                roles=['readAnyDatabase',
                                       'readWriteAnyDatabase',
                                       'userAdminAnyDatabase',
                                       'dbAdminAnyDatabase',
                                       'clusterAdmin'])
    def test_lazy_auth_raises_operation_failure(self):
        # Check if we have the prerequisites to run this test.
        c = self._get_client()
        if not server_started_with_auth(c):
            raise SkipTest('Authentication is not enabled on server')

        lazy_client = MongoReplicaSetClient(
            "mongodb://*****:*****@%s/pymongo_test" % pair,
            replicaSet=self.name,
            _connect=False)

        assertRaisesExactly(OperationFailure,
                            lazy_client.test.collection.find_one)
예제 #38
0
 def setUp(self):
     client = self._get_client()
     if not server_started_with_auth(client):
         raise SkipTest("Authentication is not enabled on server")
     self.client = client
     self.client.admin.add_user('admin-user', 'password',
                                roles=['clusterAdmin',
                                       'dbAdminAnyDatabase',
                                       'readWriteAnyDatabase',
                                       'userAdminAnyDatabase'])
     self.client.admin.authenticate("admin-user", "password")
     self.client.auth_test.add_user("test-user", "password",
                                    roles=['readWrite'])
예제 #39
0
    def test_default_roles(self):
        if not version.at_least(self.client, (2, 5, 3, -1)):
            raise SkipTest("Default roles only exist in MongoDB >= 2.5.3")
        if not server_started_with_auth(self.client):
            raise SkipTest('Authentication is not enabled on server')

        # "Admin" user
        db = self.client.admin
        db.add_user('admin', 'pass')
        try:
            db.authenticate('admin', 'pass')
            info = db.command('usersInfo', 'admin')['users'][0]
            self.assertEqual("root", info['roles'][0]['role'])

            # Read only "admin" user
            db.add_user('ro-admin', 'pass', read_only=True)
            db.logout()
            db.authenticate('ro-admin', 'pass')
            info = db.command('usersInfo', 'ro-admin')['users'][0]
            self.assertEqual("readAnyDatabase", info['roles'][0]['role'])
            db.logout()

        # Cleanup
        finally:
            db.authenticate('admin', 'pass')
            remove_all_users(db)
            db.logout()

        db.connection.disconnect()

        # "Non-admin" user
        db = self.client.pymongo_test
        db.add_user('user', 'pass')
        try:
            db.authenticate('user', 'pass')
            info = db.command('usersInfo', 'user')['users'][0]
            self.assertEqual("dbOwner", info['roles'][0]['role'])

            # Read only "Non-admin" user
            db.add_user('ro-user', 'pass', read_only=True)
            db.logout()
            db.authenticate('ro-user', 'pass')
            info = db.command('usersInfo', 'ro-user')['users'][0]
            self.assertEqual("read", info['roles'][0]['role'])
            db.logout()

        # Cleanup
        finally:
            db.authenticate('user', 'pass')
            remove_all_users(db)
            db.logout()
예제 #40
0
    def test_default_roles(self):
        if not version.at_least(self.client, (2, 5, 3, -1)):
            raise SkipTest("Default roles only exist in MongoDB >= 2.5.3")
        if not server_started_with_auth(self.client):
            raise SkipTest('Authentication is not enabled on server')

        # "Admin" user
        db = self.client.admin
        db.add_user('admin', 'pass')
        try:
            db.authenticate('admin', 'pass')
            info = db.command('usersInfo', 'admin')['users'][0]
            self.assertEqual("root", info['roles'][0]['role'])

            # Read only "admin" user
            db.add_user('ro-admin', 'pass', read_only=True)
            db.logout()
            db.authenticate('ro-admin', 'pass')
            info = db.command('usersInfo', 'ro-admin')['users'][0]
            self.assertEqual("readAnyDatabase", info['roles'][0]['role'])
            db.logout()

        # Cleanup
        finally:
            db.authenticate('admin', 'pass')
            remove_all_users(db)
            db.logout()

        db.connection.disconnect()

        # "Non-admin" user
        db = self.client.pymongo_test
        db.add_user('user', 'pass')
        try:
            db.authenticate('user', 'pass')
            info = db.command('usersInfo', 'user')['users'][0]
            self.assertEqual("dbOwner", info['roles'][0]['role'])

            # Read only "Non-admin" user
            db.add_user('ro-user', 'pass', read_only=True)
            db.logout()
            db.authenticate('ro-user', 'pass')
            info = db.command('usersInfo', 'ro-user')['users'][0]
            self.assertEqual("read", info['roles'][0]['role'])
            db.logout()

        # Cleanup
        finally:
            db.authenticate('user', 'pass')
            remove_all_users(db)
            db.logout()
예제 #41
0
    def test_auth_from_uri(self):
        c = MongoClient(host, port)
        # Sharded auth not supported before MongoDB 2.0
        if is_mongos(c) and not version.at_least(c, (2, 0, 0)):
            raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")
        if not server_started_with_auth(c):
            raise SkipTest('Authentication is not enabled on server')

        c.admin.add_user("admin", "pass")
        c.admin.authenticate("admin", "pass")
        try:
            c.pymongo_test.add_user("user", "pass", roles=['userAdmin', 'readWrite'])

            self.assertRaises(ConfigurationError, MongoClient,
                              "mongodb://*****:*****@%s:%d" % (host, port))
            self.assertRaises(ConfigurationError, MongoClient,
                              "mongodb://*****:*****@%s:%d" % (host, port))
            self.assertRaises(ConfigurationError, MongoClient,
                              "mongodb://*****:*****@%s:%d" % (host, port))
            MongoClient("mongodb://*****:*****@%s:%d" % (host, port))

            self.assertRaises(ConfigurationError, MongoClient,
                              "mongodb://*****:*****@%s:%d/pymongo_test" %
                              (host, port))
            self.assertRaises(ConfigurationError, MongoClient,
                              "mongodb://*****:*****@%s:%d/pymongo_test" %
                              (host, port))
            MongoClient("mongodb://*****:*****@%s:%d/pymongo_test" %
                       (host, port))

            # Auth with lazy connection.
            MongoClient(
                "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port),
                _connect=False).pymongo_test.test.find_one()

            # Wrong password.
            bad_client = MongoClient(
                "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port),
                _connect=False)

            # If auth fails with lazy connection, MongoClient raises
            # AutoReconnect instead of the more appropriate OperationFailure,
            # PYTHON-517.
            self.assertRaises(
                PyMongoError, bad_client.pymongo_test.test.find_one)

        finally:
            # Clean up.
            remove_all_users(c.pymongo_test)
            remove_all_users(c.admin)
예제 #42
0
    def test_comment(self):
        if is_mongos(self.client):
            raise SkipTest("profile is not supported by mongos")
        if not version.at_least(self.db.connection, (2, 0)):
            raise SkipTest("Requires server >= 2.0")
        if server_started_with_auth(self.db.connection):
            raise SkipTest("SERVER-4754 - This test uses profiling.")

        def run_with_profiling(func):
            self.db.set_profiling_level(OFF)
            self.db.system.profile.drop()
            self.db.set_profiling_level(ALL)
            func()
            self.db.set_profiling_level(OFF)

        def find():
            list(self.db.test.find().comment('foo'))
            op = self.db.system.profile.find({'ns': 'pymongo_test.test',
                                              'op': 'query',
                                              'query.$comment': 'foo'})
            self.assertEqual(op.count(), 1)

        run_with_profiling(find)

        def count():
            self.db.test.find().comment('foo').count()
            op = self.db.system.profile.find({'ns': 'pymongo_test.$cmd',
                                              'op': 'command',
                                              'command.count': 'test',
                                              'command.$comment': 'foo'})
            self.assertEqual(op.count(), 1)

        run_with_profiling(count)

        def distinct():
            self.db.test.find().comment('foo').distinct('type')
            op = self.db.system.profile.find({'ns': 'pymongo_test.$cmd',
                                              'op': 'command',
                                              'command.distinct': 'test',
                                              'command.$comment': 'foo'})
            self.assertEqual(op.count(), 1)

        run_with_profiling(distinct)

        self.db.test.insert([{}, {}])
        cursor = self.db.test.find()
        cursor.next()
        self.assertRaises(InvalidOperation, cursor.comment, 'hello')

        self.db.system.profile.drop()
예제 #43
0
    def test_comment(self):
        if server_started_with_auth(self.db.client):
            raise SkipTest("SERVER-4754 - This test uses profiling.")

        def run_with_profiling(func):
            self.db.set_profiling_level(OFF)
            self.db.system.profile.drop()
            self.db.set_profiling_level(ALL)
            func()
            self.db.set_profiling_level(OFF)

        def find():
            list(self.db.test.find().comment('foo'))
            op = self.db.system.profile.find({'ns': 'pymongo_test.test',
                                              'op': 'query',
                                              'query.$comment': 'foo'})
            self.assertEqual(op.count(), 1)

        run_with_profiling(find)

        # MongoDB 3.1.5 changed the ns for commands.
        regex = {'$regex': 'pymongo_test.(\$cmd|test)'}

        def count():
            self.db.test.find().comment('foo').count()
            op = self.db.system.profile.find({'ns': regex,
                                              'op': 'command',
                                              'command.count': 'test',
                                              'command.$comment': 'foo'})
            self.assertEqual(op.count(), 1)

        run_with_profiling(count)

        def distinct():
            self.db.test.find().comment('foo').distinct('type')
            op = self.db.system.profile.find({'ns': regex,
                                              'op': 'command',
                                              'command.distinct': 'test',
                                              'command.$comment': 'foo'})
            self.assertEqual(op.count(), 1)

        run_with_profiling(distinct)

        self.db.test.insert_many([{}, {}])
        cursor = self.db.test.find()
        next(cursor)
        self.assertRaises(InvalidOperation, cursor.comment, 'hello')

        self.db.system.profile.drop()
예제 #44
0
 def setUp(self):
     client = self._get_client()
     if not server_started_with_auth(client):
         raise SkipTest("Authentication is not enabled on server")
     self.client = client
     remove_all_users(self.client.admin)
     self.client.admin.add_user('admin-user', 'password',
                                roles=['clusterAdmin',
                                       'dbAdminAnyDatabase',
                                       'readWriteAnyDatabase',
                                       'userAdminAnyDatabase'])
     self.client.admin.authenticate("admin-user", "password")
     remove_all_users(self.client.auth_test)
     self.client.auth_test.add_user("test-user", "password",
                                    roles=['readWrite'])
 def setUp(self):
     conn = self._get_connection()
     if not server_started_with_auth(conn):
         raise SkipTest("Authentication is not enabled on server")
     self.conn = conn
     self.conn.admin.system.users.remove({})
     try:
         # First admin user add fails gle in MongoDB >= 2.1.2
         # See SERVER-4225 for more information.
         self.conn.admin.add_user("admin-user", "password")
     except OperationFailure:
         pass
     self.conn.admin.authenticate("admin-user", "password")
     self.conn.auth_test.system.users.remove({})
     self.conn.auth_test.add_user("test-user", "password")
예제 #46
0
 def setUp(self):
     conn = self._get_connection()
     if not server_started_with_auth(conn):
         raise SkipTest("Authentication is not enabled on server")
     self.conn = conn
     self.conn.admin.system.users.remove({})
     try:
         # First admin user add fails gle in MongoDB >= 2.1.2
         # See SERVER-4225 for more information.
         self.conn.admin.add_user('admin-user', 'password')
     except OperationFailure:
         pass
     self.conn.admin.authenticate("admin-user", "password")
     self.conn.auth_test.system.users.remove({})
     self.conn.auth_test.add_user("test-user", "password")
예제 #47
0
    def test_lazy_auth_raises_operation_failure(self):
        # Check if we have the prerequisites to run this test.
        c = MongoClient(host, port)
        if not server_started_with_auth(c):
            raise SkipTest('Authentication is not enabled on server')

        if is_mongos(c) and not version.at_least(c, (2, 0, 0)):
            raise SkipTest("Auth with sharding requires MongoDB >= 2.0.0")

        lazy_client = MongoClient("mongodb://*****:*****@%s:%d/pymongo_test" %
                                  (host, port),
                                  _connect=False)

        assertRaisesExactly(OperationFailure,
                            lazy_client.test.collection.find_one)
예제 #48
0
    def test_open_sync_auth_from_uri(self):
        if not server_started_with_auth(self.sync_cx):
            raise SkipTest("Server not started with auth")

        self.sync_cx.admin.system.users.remove({})
        self.sync_cx.pymongo_test.system.users.remove({})
        self.sync_cx.admin.add_user("admin", "pass")
        self.sync_cx.admin.authenticate("admin", "pass")
        self.sync_cx.pymongo_test.add_user("user", "pass")

        try:
            uri = "mongodb://*****:*****@%s:%d" % (host, port)
            self.assertRaises(
                ConfigurationError,
                motor.MotorClient(uri, io_loop=self.io_loop).open_sync)

            uri = "mongodb://*****:*****@%s:%d" % (host, port)
            self.assertRaises(
                ConfigurationError,
                motor.MotorClient(uri, io_loop=self.io_loop).open_sync)

            uri = "mongodb://*****:*****@%s:%d" % (host, port)
            self.assertRaises(
                ConfigurationError,
                motor.MotorClient(uri, io_loop=self.io_loop).open_sync)

            # Works
            uri = "mongodb://*****:*****@%s:%d" % (host, port)
            cx = motor.MotorClient(uri, io_loop=self.io_loop).open_sync()
            cx.close()

            uri = "mongodb://*****:*****@%s:%d/pymongo_test"
            self.assertRaises(
                ConfigurationError,
                motor.MotorClient(uri, io_loop=self.io_loop).open_sync)

            uri = "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)
            self.assertRaises(
                ConfigurationError,
                motor.MotorClient(uri, io_loop=self.io_loop).open_sync)

            uri = "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)
            cx = motor.MotorClient(uri, io_loop=self.io_loop).open_sync()
            cx.close()

        finally:
            self.sync_cx.admin.system.users.remove({})
            self.sync_cx.pymongo_test.system.users.remove({})
예제 #49
0
    def test_comment(self):
        if server_started_with_auth(self.db.client):
            raise SkipTest("SERVER-4754 - This test uses profiling.")

        # MongoDB 3.1.5 changed the ns for commands.
        regex = {'$regex': 'pymongo_test.(\$cmd|test)'}

        if client_context.version.at_least(3, 1, 8, -1):
            query_key = "query.comment"
        else:
            query_key = "query.$comment"

        self.client.drop_database(self.db)
        self.db.set_profiling_level(ALL)
        try:
            list(self.db.test.find().comment('foo'))
            op = self.db.system.profile.find({
                'ns': 'pymongo_test.test',
                'op': 'query',
                query_key: 'foo'
            })
            self.assertEqual(op.count(), 1)

            self.db.test.find().comment('foo').count()
            op = self.db.system.profile.find({
                'ns': regex,
                'op': 'command',
                'command.count': 'test',
                'command.$comment': 'foo'
            })
            self.assertEqual(op.count(), 1)

            self.db.test.find().comment('foo').distinct('type')
            op = self.db.system.profile.find({
                'ns': regex,
                'op': 'command',
                'command.distinct': 'test',
                'command.$comment': 'foo'
            })
            self.assertEqual(op.count(), 1)
        finally:
            self.db.set_profiling_level(OFF)
            self.db.system.profile.drop()

        self.db.test.insert_many([{}, {}])
        cursor = self.db.test.find()
        next(cursor)
        self.assertRaises(InvalidOperation, cursor.comment, 'hello')
예제 #50
0
    def test_mongodb_x509_auth(self):
        # Expects the server to be running with the server.pem, ca.pem
        # and crl.pem provided in mongodb and the server tests as well as
        # --auth
        #
        #   --sslPEMKeyFile=/path/to/pymongo/test/certificates/server.pem
        #   --sslCAFile=/path/to/pymongo/test/certificates/ca.pem
        #   --sslCRLFile=/path/to/pymongo/test/certificates/crl.pem
        #   --auth
        if not CERT_SSL:
            raise SkipTest("No mongod available over SSL with certs")

        client = MongoClient(host, port, ssl=True, ssl_certfile=CLIENT_PEM)
        if not version.at_least(client, (2, 5, 3, -1)):
            raise SkipTest("MONGODB-X509 tests require MongoDB 2.5.3 or newer")
        if not server_started_with_auth(client):
            raise SkipTest("Authentication is not enabled on server")
        # Give admin all necessary privileges.
        client["$external"].add_user(
            MONGODB_X509_USERNAME,
            roles=[{"role": "readWriteAnyDatabase", "db": "admin"}, {"role": "userAdminAnyDatabase", "db": "admin"}],
        )
        coll = client.pymongo_test.test
        self.assertRaises(OperationFailure, coll.count)
        self.assertTrue(client.admin.authenticate(MONGODB_X509_USERNAME, mechanism="MONGODB-X509"))
        self.assertTrue(coll.remove())
        uri = "mongodb://%s@%s:%d/?authMechanism=" "MONGODB-X509" % (quote_plus(MONGODB_X509_USERNAME), host, port)
        # SSL options aren't supported in the URI...
        self.assertTrue(MongoClient(uri, ssl=True, ssl_certfile=CLIENT_PEM))

        # Should require a username
        uri = "mongodb://%s:%d/?authMechanism=MONGODB-X509" % (host, port)
        client_bad = MongoClient(uri, ssl=True, ssl_certfile=CLIENT_PEM)
        self.assertRaises(OperationFailure, client_bad.pymongo_test.test.remove)

        # 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)
        self.assertRaises(ConfigurationError, MongoClient, uri, ssl=True, ssl_certfile=CLIENT_PEM)
        self.assertRaises(OperationFailure, client.admin.authenticate, "not the username", mechanism="MONGODB-X509")

        # Invalid certificate (using CA certificate as client certificate)
        uri = "mongodb://%s@%s:%d/?authMechanism=" "MONGODB-X509" % (quote_plus(MONGODB_X509_USERNAME), host, port)
        self.assertRaises(ConnectionFailure, MongoClient, uri, ssl=True, ssl_certfile=CA_PEM)
        self.assertRaises(ConnectionFailure, MongoClient, pair, ssl=True, ssl_certfile=CA_PEM)

        # Cleanup
        remove_all_users(client["$external"])
        client["$external"].logout()
예제 #51
0
    def test_mongodb_x509_auth(self):
        # Expects the server to be running with the server.pem, ca.pem
        # and crl.pem provided in mongodb and the server tests as well as
        # --auth:
        #
        #   --sslPEMKeyFile=jstests/libs/server.pem
        #   --sslCAFile=jstests/libs/ca.pem
        #   --sslCRLFile=jstests/libs/crl.pem
        #   --auth
        if not test.mongod_validates_client_cert:
            raise SkipTest("No mongod available over SSL with certs")

        client = motor.MotorClient(host, port, ssl_certfile=CLIENT_PEM)
        if not (yield version.at_least(client, (2, 5, 3, -1))):
            raise SkipTest("MONGODB-X509 tests require MongoDB 2.5.3 or newer")

        if not (yield server_started_with_auth(client)):
            raise SkipTest('Authentication is not enabled on server')

        # Give admin all necessary privileges.
        yield client['$external'].add_user(MONGODB_X509_USERNAME,
                                           roles=[{
                                               'role': 'readWriteAnyDatabase',
                                               'db': 'admin'
                                           }, {
                                               'role': 'userAdminAnyDatabase',
                                               'db': 'admin'
                                           }])

        collection = client.motor_test.test
        with test.assert_raises(OperationFailure):
            yield collection.count()

        yield client.admin.authenticate(MONGODB_X509_USERNAME,
                                        mechanism='MONGODB-X509')

        yield collection.remove()
        uri = ('mongodb://%s@%s:%d/?authMechanism='
               'MONGODB-X509' %
               (quote_plus(MONGODB_X509_USERNAME), host, port))

        # SSL options aren't supported in the URI....
        auth_uri_client = motor.MotorClient(uri, ssl_certfile=CLIENT_PEM)
        yield auth_uri_client.db.collection.find_one()

        # Cleanup.
        yield remove_all_users(client['$external'])
        yield client['$external'].logout()
    def test_comment(self):
        if is_mongos(self.client):
            raise SkipTest("profile is not supported by mongos")
        if not version.at_least(self.db.connection, (2, 0)):
            raise SkipTest("Requires server >= 2.0")
        if server_started_with_auth(self.db.connection):
            raise SkipTest("SERVER-4754 - This test uses profiling.")

        # MongoDB 3.1.5 changed the ns for commands.
        regex = {'$regex': 'pymongo_test.(\$cmd|test)'}

        if version.at_least(self.db.connection, (3, 1, 8, -1)):
            query_key = "query.comment"
        else:
            query_key = "query.$comment"

        self.client.drop_database(self.db)
        self.db.set_profiling_level(ALL)
        try:
            list(self.db.test.find().comment('foo'))
            op = self.db.system.profile.find({'ns': 'pymongo_test.test',
                                              'op': 'query',
                                              query_key: 'foo'})
            self.assertEqual(op.count(), 1)

            self.db.test.find().comment('foo').count()
            op = self.db.system.profile.find({'ns': regex,
                                              'op': 'command',
                                              'command.count': 'test',
                                              'command.$comment': 'foo'})
            self.assertEqual(op.count(), 1)

            self.db.test.find().comment('foo').distinct('type')
            op = self.db.system.profile.find({'ns': regex,
                                              'op': 'command',
                                              'command.distinct': 'test',
                                              'command.$comment': 'foo'})
            self.assertEqual(op.count(), 1)
        finally:
            self.db.set_profiling_level(OFF)
            self.db.system.profile.drop()

        self.db.test.insert([{}, {}])
        cursor = self.db.test.find()
        cursor.next()
        self.assertRaises(InvalidOperation, cursor.comment, 'hello')
예제 #53
0
    def test_mongodb_x509_auth(self):
        # Expects the server to be running with the server.pem, ca.pem
        # and crl.pem provided in mongodb and the server tests as well as
        # --auth:
        #
        #   --sslPEMKeyFile=jstests/libs/server.pem
        #   --sslCAFile=jstests/libs/ca.pem
        #   --sslCRLFile=jstests/libs/crl.pem
        #   --auth
        if not test.mongod_validates_client_cert:
            raise SkipTest("No mongod available over SSL with certs")

        client = motor.MotorClient(host, port, ssl_certfile=CLIENT_PEM)
        if not (yield version.at_least(client, (2, 5, 3, -1))):
            raise SkipTest("MONGODB-X509 tests require MongoDB 2.5.3 or newer")

        if not (yield server_started_with_auth(client)):
            raise SkipTest('Authentication is not enabled on server')

        # Give admin all necessary privileges.
        yield client['$external'].add_user(MONGODB_X509_USERNAME, roles=[
            {'role': 'readWriteAnyDatabase', 'db': 'admin'},
            {'role': 'userAdminAnyDatabase', 'db': 'admin'}])

        collection = client.motor_test.test
        with test.assert_raises(OperationFailure):
            yield collection.count()

        yield client.admin.authenticate(
            MONGODB_X509_USERNAME, mechanism='MONGODB-X509')

        yield collection.remove()
        uri = ('mongodb://%s@%s:%d/?authMechanism='
               'MONGODB-X509' % (
               quote_plus(MONGODB_X509_USERNAME), host, port))

        # SSL options aren't supported in the URI....
        auth_uri_client = motor.MotorClient(uri, ssl_certfile=CLIENT_PEM)
        yield auth_uri_client.db.collection.find_one()

        # Cleanup.
        yield remove_all_users(client['$external'])
        yield client['$external'].logout()
예제 #54
0
    def test_open_sync_auth_from_uri(self):
        if not server_started_with_auth(self.sync_cx):
            raise SkipTest("Server not started with auth")

        self.sync_cx.admin.system.users.remove({})
        self.sync_cx.pymongo_test.system.users.remove({})
        self.sync_cx.admin.add_user("admin", "pass")
        self.sync_cx.admin.authenticate("admin", "pass")
        self.sync_cx.pymongo_test.add_user("user", "pass")

        try:
            uri = "mongodb://*****:*****@%s:%d" % (host, port)
            self.assertRaises(ConfigurationError, motor.MotorClient(
                uri, io_loop=self.io_loop).open_sync)

            uri = "mongodb://*****:*****@%s:%d" % (host, port)
            self.assertRaises(ConfigurationError, motor.MotorClient(
                uri, io_loop=self.io_loop).open_sync)

            uri = "mongodb://*****:*****@%s:%d" % (host, port)
            self.assertRaises(ConfigurationError, motor.MotorClient(
                uri, io_loop=self.io_loop).open_sync)

            # Works
            uri = "mongodb://*****:*****@%s:%d" % (host, port)
            cx = motor.MotorClient(uri, io_loop=self.io_loop).open_sync()
            cx.close()

            uri = "mongodb://*****:*****@%s:%d/pymongo_test"
            self.assertRaises(ConfigurationError, motor.MotorClient(
                uri, io_loop=self.io_loop).open_sync)

            uri = "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)
            self.assertRaises(ConfigurationError, motor.MotorClient(
                uri, io_loop=self.io_loop).open_sync)

            uri = "mongodb://*****:*****@%s:%d/pymongo_test" % (host, port)
            cx = motor.MotorClient(uri, io_loop=self.io_loop).open_sync()
            cx.close()

        finally:
            self.sync_cx.admin.system.users.remove({})
            self.sync_cx.pymongo_test.system.users.remove({})
예제 #55
0
    def test_auth_from_uri(self):
        if not (yield server_started_with_auth(self.cx)):
            raise SkipTest('Authentication is not enabled on server')

        yield remove_all_users(self.db)
        yield remove_all_users(self.cx.admin)
        yield self.cx.admin.add_user('admin', 'pass')
        yield self.cx.admin.authenticate('admin', 'pass')

        db = self.db
        try:
            yield db.add_user('mike',
                              'password',
                              roles=['userAdmin', 'readWrite'])

            client = motor.MotorClient('mongodb://*****:*****@%s:%d' %
                                       (host, port))

            # Note: open() only calls ismaster, doesn't throw auth errors.
            yield client.open()

            with assert_raises(OperationFailure):
                yield client.db.collection.find_one()

            client.close()

            client = motor.MotorClient('mongodb://*****:*****@%s:%d/%s' %
                                       (host, port, db.name))

            yield client.open()
            client.close()

            client = motor.MotorClient('mongodb://*****:*****@%s:%d/%s' %
                                       (host, port, db.name))

            yield client[db.name].collection.find_one()
            client.close()

        finally:
            yield db.remove_user('mike')
            yield self.cx.admin.remove_user('admin')
예제 #56
0
    def test_new_user_cmds(self):
        if not version.at_least(self.client, (2, 5, 3, -1)):
            raise SkipTest("User manipulation through commands "
                           "requires MongoDB >= 2.5.3")
        if not server_started_with_auth(self.client):
            raise SkipTest('Authentication is not enabled on server')

        db = self.client.pymongo_test
        db.add_user("amalia", "password", roles=["userAdmin"])
        db.authenticate("amalia", "password")
        try:
            # This tests the ability to update user attributes.
            db.add_user("amalia", "new_password",
                        customData={"secret": "koalas"})

            user_info = db.command("usersInfo", "amalia")
            self.assertTrue(user_info["users"])
            amalia_user = user_info["users"][0]
            self.assertEqual(amalia_user["user"], "amalia")
            self.assertEqual(amalia_user["customData"], {"secret": "koalas"})
        finally:
            db.remove_user("amalia")
            db.logout()
예제 #57
0
    def test_unix_socket(self):
        if not hasattr(socket, "AF_UNIX"):
            raise SkipTest("UNIX-sockets are not supported on this system")
        if (sys.platform == 'darwin'
                and server_started_with_auth(MongoClient(host, port))):
            raise SkipTest("SERVER-8492")

        mongodb_socket = '/tmp/mongodb-27017.sock'
        if not os.access(mongodb_socket, os.R_OK):
            raise SkipTest("Socket file is not accessable")

        self.assertTrue(MongoClient("mongodb://%s" % mongodb_socket))

        client = MongoClient("mongodb://%s" % mongodb_socket)
        client.pymongo_test.test.save({"dummy": "object"})

        # Confirm we can read via the socket
        dbs = client.database_names()
        self.assertTrue("pymongo_test" in dbs)

        # Confirm it fails with a missing socket
        self.assertRaises(ConnectionFailure, MongoClient,
                          "mongodb:///tmp/none-existent.sock")
예제 #58
0
    def test_make_user_readonly(self):
        if (is_mongos(self.client)
                and not version.at_least(self.client, (2, 0, 0))):
            raise SkipTest('Auth with sharding requires MongoDB >= 2.0.0')

        if not server_started_with_auth(self.client):
            raise SkipTest('Authentication is not enabled on server')

        admin = self.client.admin
        admin.add_user('admin', 'pw')
        admin.authenticate('admin', 'pw')

        db = self.client.pymongo_test

        try:
            # Make a read-write user.
            db.add_user('jesse', 'pw')
            admin.logout()

            # Check that we're read-write by default.
            db.authenticate('jesse', 'pw')
            db.collection.insert({})
            db.logout()

            # Make the user read-only.
            admin.authenticate('admin', 'pw')
            db.add_user('jesse', 'pw', read_only=True)
            admin.logout()

            db.authenticate('jesse', 'pw')
            self.assertRaises(OperationFailure, db.collection.insert, {})
        finally:
            # Cleanup
            admin.authenticate('admin', 'pw')
            remove_all_users(db)
            admin.remove_user("admin")
            admin.logout()
    def test_copy_db(self):
        c = self._get_client()
        # We test copy twice; once starting in a request and once not. In
        # either case the copy should succeed (because it starts a request
        # internally) and should leave us in the same state as before the copy.
        c.start_request()

        self.assertRaises(TypeError, c.copy_database, 4, "foo")
        self.assertRaises(TypeError, c.copy_database, "foo", 4)

        self.assertRaises(InvalidName, c.copy_database, "foo", "$foo")

        c.pymongo_test.test.drop()
        c.drop_database("pymongo_test1")
        c.drop_database("pymongo_test2")

        c.pymongo_test.test.insert({"foo": "bar"})

        self.assertFalse("pymongo_test1" in c.database_names())
        self.assertFalse("pymongo_test2" in c.database_names())

        c.copy_database("pymongo_test", "pymongo_test1")
        # copy_database() didn't accidentally end the request
        self.assertTrue(c.in_request())

        self.assertTrue("pymongo_test1" in c.database_names())
        self.assertEqual("bar", c.pymongo_test1.test.find_one()["foo"])

        c.end_request()

        self.assertFalse(c.in_request())
        c.copy_database("pymongo_test", "pymongo_test2", pair)
        # copy_database() didn't accidentally restart the request
        self.assertFalse(c.in_request())

        time.sleep(1)

        self.assertTrue("pymongo_test2" in c.database_names())
        self.assertEqual("bar", c.pymongo_test2.test.find_one()["foo"])

        if version.at_least(c, (1, 3, 3, 1)) and server_started_with_auth(c):
            c.drop_database("pymongo_test1")

            c.admin.add_user("admin", "password")
            c.admin.authenticate("admin", "password")
            try:
                c.pymongo_test.add_user("mike", "password")

                self.assertRaises(OperationFailure,
                                  c.copy_database,
                                  "pymongo_test",
                                  "pymongo_test1",
                                  username="******",
                                  password="******")
                self.assertFalse("pymongo_test1" in c.database_names())

                self.assertRaises(OperationFailure,
                                  c.copy_database,
                                  "pymongo_test",
                                  "pymongo_test1",
                                  username="******",
                                  password="******")
                self.assertFalse("pymongo_test1" in c.database_names())

                c.copy_database("pymongo_test",
                                "pymongo_test1",
                                username="******",
                                password="******")
                self.assertTrue("pymongo_test1" in c.database_names())
                res = c.pymongo_test1.test.find_one(_must_use_master=True)
                self.assertEqual("bar", res["foo"])
            finally:
                # Cleanup
                remove_all_users(c.pymongo_test)
                c.admin.remove_user("admin")
        c.close()