diff options
author | Jonathan Abrahams <jonathan@mongodb.com> | 2016-03-09 12:17:50 -0500 |
---|---|---|
committer | Jonathan Abrahams <jonathan@mongodb.com> | 2016-03-09 12:18:14 -0500 |
commit | 4ae691e8edc87d0e3cfb633bb91c328426be007b (patch) | |
tree | 52079a593f54382ca13a2e741633eab1b6271893 /jstests/auth | |
parent | a025d43f3ce2efc1fb1282a718f5d286fa0a4dc1 (diff) | |
download | mongo-4ae691e8edc87d0e3cfb633bb91c328426be007b.tar.gz |
SERVER-22468 Format JS code with approved style in jstests/
Diffstat (limited to 'jstests/auth')
51 files changed, 5654 insertions, 5809 deletions
diff --git a/jstests/auth/access_control_with_unreachable_configs.js b/jstests/auth/access_control_with_unreachable_configs.js index 23a38502301..6c833d5c844 100644 --- a/jstests/auth/access_control_with_unreachable_configs.js +++ b/jstests/auth/access_control_with_unreachable_configs.js @@ -3,14 +3,18 @@ // are user documents stored in the configuration information, it must assume that // there are. -var dopts = { smallfiles: "", nopreallocj: ""}; -var st = new ShardingTest( - { shards: 1, - mongos: 1, - config: 1, - keyFile: 'jstests/libs/key1', - useHostname: false, // Needed when relying on the localhost exception - other: { shardOptions: dopts, configOptions: dopts, mongosOptions: { verbose: 1 } } } ); +var dopts = { + smallfiles: "", + nopreallocj: "" +}; +var st = new ShardingTest({ + shards: 1, + mongos: 1, + config: 1, + keyFile: 'jstests/libs/key1', + useHostname: false, // Needed when relying on the localhost exception + other: {shardOptions: dopts, configOptions: dopts, mongosOptions: {verbose: 1}} +}); var mongos = st.s; var config = st.config0; var authzErrorCode = 13; @@ -35,7 +39,7 @@ assert.commandWorked(db.adminCommand('serverStatus')); jsTest.log('repeat without config server'); // shut down only config server -MongoRunner.stopMongod(config.port, /*signal*/15); +MongoRunner.stopMongod(config.port, /*signal*/ 15); // open a new connection to mongos (unauthorized) var conn2 = new Mongo(mongos.host); diff --git a/jstests/auth/arbiter.js b/jstests/auth/arbiter.js index 9e7f048e1df..75b7b67a9ad 100644 --- a/jstests/auth/arbiter.js +++ b/jstests/auth/arbiter.js @@ -3,24 +3,32 @@ var name = "arbiter_localhost_test"; var key = "jstests/libs/key1"; -var replTest = new ReplSetTest({ name: name, nodes: 3, keyFile: key }); +var replTest = new ReplSetTest({name: name, nodes: 3, keyFile: key}); var nodes = replTest.nodeList(); replTest.startSet(); -replTest.initiate({_id: name, - members: [ - { "_id": 0, "host": nodes[0], priority: 3 }, - { "_id": 1, "host": nodes[1] }, - { "_id": 2, "host": nodes[2], arbiterOnly: true } - ], - }); +replTest.initiate({ + _id: name, + members: [ + {"_id": 0, "host": nodes[0], priority: 3}, + {"_id": 1, "host": nodes[1]}, + {"_id": 2, "host": nodes[2], arbiterOnly: true} + ], +}); var primaryAdmin = replTest.nodes[0].getDB("admin"); var arbiterAdmin = replTest.nodes[2].getDB("admin"); -var cmd0 = { getCmdLineOpts: 1 }; -var cmd1 = { getParameter: 1, logLevel: 1 }; -var cmd2 = { serverStatus: 1 }; +var cmd0 = { + getCmdLineOpts: 1 +}; +var cmd1 = { + getParameter: 1, + logLevel: 1 +}; +var cmd2 = { + serverStatus: 1 +}; assert.commandFailedWithCode(primaryAdmin.runCommand(cmd0), 13); assert.commandFailedWithCode(primaryAdmin.runCommand(cmd1), 13); diff --git a/jstests/auth/auth1.js b/jstests/auth/auth1.js index 560d54828fc..c90765ffb02 100644 --- a/jstests/auth/auth1.js +++ b/jstests/auth/auth1.js @@ -5,42 +5,42 @@ function setupTest() { print("START auth1.js"); baseName = "jstests_auth_auth1"; - m = MongoRunner.runMongod({auth: "", - nohttpinterface: "", - bind_ip: "127.0.0.1", - useHostname: false}); + m = MongoRunner.runMongod( + {auth: "", nohttpinterface: "", bind_ip: "127.0.0.1", useHostname: false}); return m; } function runTest(m) { // these are used by read-only user - db = m.getDB( "test" ); + db = m.getDB("test"); mro = new Mongo(m.host); - dbRO = mro.getDB( "test" ); - tRO = dbRO[ baseName ]; + dbRO = mro.getDB("test"); + tRO = dbRO[baseName]; db.getSisterDB("admin").createUser({user: "root", pwd: "root", roles: ["root"]}); db.getSisterDB("admin").auth("root", "root"); - t = db[ baseName ]; + t = db[baseName]; t.drop(); db.dropAllUsers(); db.logout(); - db.getSisterDB( "admin" ).createUser({user: "super", pwd: "super", roles: ["__system"] }); + db.getSisterDB("admin").createUser({user: "super", pwd: "super", roles: ["__system"]}); db.getSisterDB("admin").auth("super", "super"); - db.createUser({user: "eliot" , pwd: "eliot", roles: jsTest.basicUserRoles }); - db.createUser({user: "guest" , pwd: "guest", roles: jsTest.readOnlyUserRoles}); + db.createUser({user: "eliot", pwd: "eliot", roles: jsTest.basicUserRoles}); + db.createUser({user: "guest", pwd: "guest", roles: jsTest.readOnlyUserRoles}); db.getSisterDB("admin").logout(); - assert.throws( function() { t.findOne(); }, [], "read without login" ); + assert.throws(function() { + t.findOne(); + }, [], "read without login"); print("make sure we can't run certain commands w/out auth"); var codeUnauthorized = 13; - var rslt = db.runCommand({eval : "function() { return 1; }"}); + var rslt = db.runCommand({eval: "function() { return 1; }"}); assert.eq(rslt.code, codeUnauthorized, tojson(rslt)); - var rslt = db.runCommand({getLog : "global"}); + var rslt = db.runCommand({getLog: "global"}); assert.eq(rslt.code, codeUnauthorized, tojson(rslt)); assert(!db.auth("eliot", "eliot2"), "auth succeeded with wrong password"); @@ -50,51 +50,68 @@ function runTest(m) { assert(!db.auth("eliot", "eliot"), "auth succeeded with wrong password"); assert(db.auth("eliot", "eliot2"), "auth failed"); - for( i = 0; i < 1000; ++i ) { - t.save( {i:i} ); + for (i = 0; i < 1000; ++i) { + t.save({i: i}); } - assert.eq( 1000, t.count() , "A1" ); - assert.eq( 1000, t.find().toArray().length , "A2" ); + assert.eq(1000, t.count(), "A1"); + assert.eq(1000, t.find().toArray().length, "A2"); - db.setProfilingLevel( 2 ); + db.setProfilingLevel(2); t.count(); - db.setProfilingLevel( 0 ); - assert.lt( 0 , db.system.profile.find( { user : "eliot@test" } ).count() , "AP1" ); - - var p = { key : { i : true } , - reduce : function(obj,prev) { prev.count++; }, - initial: { count: 0 } + db.setProfilingLevel(0); + assert.lt(0, db.system.profile.find({user: "eliot@test"}).count(), "AP1"); + + var p = { + key: {i: true}, + reduce: function(obj, prev) { + prev.count++; + }, + initial: {count: 0} }; - assert.eq( 1000, t.group( p ).length , "A5" ); + assert.eq(1000, t.group(p).length, "A5"); - assert( dbRO.auth( "guest", "guest" ), "auth failed 2" ); + assert(dbRO.auth("guest", "guest"), "auth failed 2"); - assert.eq( 1000, tRO.count() , "B1" ); - assert.eq( 1000, tRO.find().toArray().length , "B2" ); // make sure we have a getMore in play - assert.commandWorked( dbRO.runCommand( {ismaster:1} ) , "B3" ); + assert.eq(1000, tRO.count(), "B1"); + assert.eq(1000, tRO.find().toArray().length, "B2"); // make sure we have a getMore in play + assert.commandWorked(dbRO.runCommand({ismaster: 1}), "B3"); assert.writeError(tRO.save({})); - assert.eq( 1000, tRO.count() , "B6" ); - - assert.eq( 1000, tRO.group( p ).length , "C1" ); + assert.eq(1000, tRO.count(), "B6"); - var p = { key : { i : true } , - reduce : function(obj,prev) { db.jstests_auth_auth1.save( {i:10000} ); prev.count++; }, - initial: { count: 0 } - }; + assert.eq(1000, tRO.group(p).length, "C1"); + var p = { + key: {i: true}, + reduce: function(obj, prev) { + db.jstests_auth_auth1.save({i: 10000}); + prev.count++; + }, + initial: {count: 0} + }; - assert.throws( function() { return t.group( p ); }, null , "write reduce didn't fail" ); - assert.eq( 1000, dbRO.jstests_auth_auth1.count() , "C3" ); - + assert.throws(function() { + return t.group(p); + }, null, "write reduce didn't fail"); + assert.eq(1000, dbRO.jstests_auth_auth1.count(), "C3"); db.getSiblingDB('admin').auth('super', 'super'); - assert.eq( 1000, db.eval( function() { return db[ "jstests_auth_auth1" ].count(); } ) , "D1" ); - db.eval( function() { db[ "jstests_auth_auth1" ].save( {i:1000} ); } ); - assert.eq( 1001, db.eval( function() { return db[ "jstests_auth_auth1" ].count(); } ) , "D2" ); + assert.eq(1000, + db.eval(function() { + return db["jstests_auth_auth1"].count(); + }), + "D1"); + db.eval(function() { + db["jstests_auth_auth1"].save({i: 1000}); + }); + assert.eq(1001, + db.eval(function() { + return db["jstests_auth_auth1"].count(); + }), + "D2"); print("SUCCESS auth1.js"); } diff --git a/jstests/auth/auth2.js b/jstests/auth/auth2.js index 52d1fac084b..f09d87d7275 100644 --- a/jstests/auth/auth2.js +++ b/jstests/auth/auth2.js @@ -1,24 +1,32 @@ // test read/write permissions m = MongoRunner.runMongod({auth: "", bind_ip: "127.0.0.1", nojournal: "", smallfiles: ""}); -db = m.getDB( "admin" ); +db = m.getDB("admin"); // These statements throw because the localhost exception does not allow // these operations: it only allows the creation of the first admin user // and necessary setup operations. -assert.throws( function(){ db.users.count(); } ); -assert.throws( function() { db.shutdownServer(); } ); +assert.throws(function() { + db.users.count(); +}); +assert.throws(function() { + db.shutdownServer(); +}); -db.createUser( { user: "eliot", pwd: "eliot", roles: [ "root" ] } ); +db.createUser({user: "eliot", pwd: "eliot", roles: ["root"]}); // These statements throw because we have a user but have not authenticated // as that user. -assert.throws( function(){ db.users.count(); } ); -assert.throws( function() { db.shutdownServer(); } ); +assert.throws(function() { + db.users.count(); +}); +assert.throws(function() { + db.shutdownServer(); +}); -db.auth( "eliot", "eliot" ); +db.auth("eliot", "eliot"); -users = db.getCollection( "system.users" ); -assert.eq( 1, users.count() ); +users = db.getCollection("system.users"); +assert.eq(1, users.count()); db.shutdownServer(); diff --git a/jstests/auth/auth3.js b/jstests/auth/auth3.js index 9ec028aca21..dd87ea2448a 100644 --- a/jstests/auth/auth3.js +++ b/jstests/auth/auth3.js @@ -1,32 +1,32 @@ (function() { -'use strict'; + 'use strict'; -var conn = MongoRunner.runMongod({ auth: "" }); + var conn = MongoRunner.runMongod({auth: ""}); -var admin = conn.getDB("admin"); -var errorCodeUnauthorized = 13; + var admin = conn.getDB("admin"); + var errorCodeUnauthorized = 13; -admin.createUser({user:"foo",pwd: "bar", roles: jsTest.adminUserRoles}); + admin.createUser({user: "foo", pwd: "bar", roles: jsTest.adminUserRoles}); -print("make sure curop, killop, and unlock fail"); + print("make sure curop, killop, and unlock fail"); -var x = admin.$cmd.sys.inprog.findOne(); -assert(!("inprog" in x), tojson(x)); -assert.eq(x.code, errorCodeUnauthorized, tojson(x)); + var x = admin.$cmd.sys.inprog.findOne(); + assert(!("inprog" in x), tojson(x)); + assert.eq(x.code, errorCodeUnauthorized, tojson(x)); -x = admin.killOp(123); -assert(!("info" in x), tojson(x)); -assert.eq(x.code, errorCodeUnauthorized, tojson(x)); + x = admin.killOp(123); + assert(!("info" in x), tojson(x)); + assert.eq(x.code, errorCodeUnauthorized, tojson(x)); -x = admin.fsyncUnlock(); -assert(x.errmsg != "not locked", tojson(x)); -assert.eq(x.code, errorCodeUnauthorized, tojson(x)); + x = admin.fsyncUnlock(); + assert(x.errmsg != "not locked", tojson(x)); + assert.eq(x.code, errorCodeUnauthorized, tojson(x)); -conn.getDB("admin").auth("foo","bar"); + conn.getDB("admin").auth("foo", "bar"); -assert("inprog" in admin.currentOp()); -assert("info" in admin.killOp(123)); -assert.eq(admin.fsyncUnlock().errmsg, "not locked"); + assert("inprog" in admin.currentOp()); + assert("info" in admin.killOp(123)); + assert.eq(admin.fsyncUnlock().errmsg, "not locked"); })(); diff --git a/jstests/auth/auth_helpers.js b/jstests/auth/auth_helpers.js index f35f2f579af..94131821784 100644 --- a/jstests/auth/auth_helpers.js +++ b/jstests/auth/auth_helpers.js @@ -3,33 +3,33 @@ // This test requires users to persist across a restart. // @tags: [requires_persistence] -var conn = MongoRunner.runMongod({ smallfiles: ""}); +var conn = MongoRunner.runMongod({smallfiles: ""}); var mechanisms, hasCR, hasCramMd5; var admin = conn.getDB('admin'); // In order to test MONGODB-CR we need to "reset" the authSchemaVersion to // 26Final "3" or else the user won't get MONGODB-CR credentials. -admin.system.version.save({ "_id" : "authSchema", "currentVersion" : 3 }); -admin.createUser({user:'andy', pwd: 'a', roles: jsTest.adminUserRoles}); +admin.system.version.save({"_id": "authSchema", "currentVersion": 3}); +admin.createUser({user: 'andy', pwd: 'a', roles: jsTest.adminUserRoles}); admin.auth({user: 'andy', pwd: 'a'}); // Attempt to start with CRAM-MD5 enabled // If this fails the build only supports default auth mechanisms MongoRunner.stopMongod(conn); -var restartedConn = MongoRunner.runMongod({ - auth: "", - restart: conn, - setParameter: "authenticationMechanisms=SCRAM-SHA-1,MONGODB-CR,CRAM-MD5"}); +var restartedConn = MongoRunner.runMongod({ + auth: "", + restart: conn, + setParameter: "authenticationMechanisms=SCRAM-SHA-1,MONGODB-CR,CRAM-MD5" +}); if (restartedConn != null) { - mechanisms = [ "SCRAM-SHA-1", "MONGODB-CR", "CRAM-MD5" ]; + mechanisms = ["SCRAM-SHA-1", "MONGODB-CR", "CRAM-MD5"]; hasCR = true; hasCramMd5 = true; print("test info: Enabling non-default authentication mechanisms."); -} -else { - restartedConn = MongoRunner.runMongod({ restart: conn }); - mechanisms = [ "SCRAM-SHA-1", "MONGODB-CR" ]; +} else { + restartedConn = MongoRunner.runMongod({restart: conn}); + mechanisms = ["SCRAM-SHA-1", "MONGODB-CR"]; hasCR = true; hasCramMd5 = false; print("test info: Using only default password authentication mechanisms."); diff --git a/jstests/auth/auth_options.js b/jstests/auth/auth_options.js index 1a38821fa03..d2f89d12a0f 100644 --- a/jstests/auth/auth_options.js +++ b/jstests/auth/auth_options.js @@ -4,63 +4,49 @@ load('jstests/libs/command_line/test_parsed_options.js'); jsTest.log("Testing \"auth\" command line option"); var expectedResult = { - "parsed" : { - "security" : { - "authorization" : "enabled" - } - } + "parsed": {"security": {"authorization": "enabled"}} }; -testGetCmdLineOptsMongod({ auth : "" }, expectedResult); +testGetCmdLineOptsMongod({auth: ""}, expectedResult); jsTest.log("Testing \"noauth\" command line option"); expectedResult = { - "parsed" : { - "security" : { - "authorization" : "disabled" - } - } + "parsed": {"security": {"authorization": "disabled"}} }; -testGetCmdLineOptsMongod({ noauth : "" }, expectedResult); +testGetCmdLineOptsMongod({noauth: ""}, expectedResult); jsTest.log("Testing \"security.authorization\" config file option"); expectedResult = { - "parsed" : { - "config" : "jstests/libs/config_files/enable_auth.json", - "security" : { - "authorization" : "enabled" - } + "parsed": { + "config": "jstests/libs/config_files/enable_auth.json", + "security": {"authorization": "enabled"} } }; -testGetCmdLineOptsMongod({ config : "jstests/libs/config_files/enable_auth.json" }, expectedResult); +testGetCmdLineOptsMongod({config: "jstests/libs/config_files/enable_auth.json"}, expectedResult); jsTest.log("Testing with no explicit object check setting"); expectedResult = { - "parsed" : { } + "parsed": {} }; testGetCmdLineOptsMongod({}, expectedResult); // Test that we preserve switches explicitly set to false in config files. See SERVER-13439. jsTest.log("Testing explicitly disabled \"auth\" config file option"); expectedResult = { - "parsed" : { - "config" : "jstests/libs/config_files/disable_auth.ini", - "security" : { - "authorization" : "disabled" - } + "parsed": { + "config": "jstests/libs/config_files/disable_auth.ini", + "security": {"authorization": "disabled"} } }; -testGetCmdLineOptsMongod({ config : "jstests/libs/config_files/disable_auth.ini" }, expectedResult); +testGetCmdLineOptsMongod({config: "jstests/libs/config_files/disable_auth.ini"}, expectedResult); jsTest.log("Testing explicitly disabled \"noauth\" config file option"); expectedResult = { - "parsed" : { - "config" : "jstests/libs/config_files/disable_noauth.ini", - "security" : { - "authorization" : "enabled" - } + "parsed": { + "config": "jstests/libs/config_files/disable_noauth.ini", + "security": {"authorization": "enabled"} } }; -testGetCmdLineOptsMongod({ config : "jstests/libs/config_files/disable_noauth.ini" }, expectedResult); +testGetCmdLineOptsMongod({config: "jstests/libs/config_files/disable_noauth.ini"}, expectedResult); print(baseName + " succeeded."); diff --git a/jstests/auth/auth_schema_upgrade.js b/jstests/auth/auth_schema_upgrade.js index 95dcaad70eb..d80fbe6bbad 100644 --- a/jstests/auth/auth_schema_upgrade.js +++ b/jstests/auth/auth_schema_upgrade.js @@ -1,21 +1,17 @@ // Standalone test of authSchemaUpgrade load('./jstests/multiVersion/libs/auth_helpers.js'); -var setupCRUsers = function(conn){ +var setupCRUsers = function(conn) { jsTest.log("setting up legacy users"); var adminDB = conn.getDB('admin'); - adminDB.system.version.update({_id:"authSchema"},{"currentVersion":3},{upsert:true}); + adminDB.system.version.update({_id: "authSchema"}, {"currentVersion": 3}, {upsert: true}); - adminDB.createUser({user: 'user1', pwd: 'pass', - roles: jsTest.adminUserRoles}); - assert(adminDB.auth({mechanism: 'MONGODB-CR', - user: 'user1', pwd: 'pass'})); + adminDB.createUser({user: 'user1', pwd: 'pass', roles: jsTest.adminUserRoles}); + assert(adminDB.auth({mechanism: 'MONGODB-CR', user: 'user1', pwd: 'pass'})); - adminDB.createUser({user: 'user2', pwd: 'pass', - roles: jsTest.adminUserRoles}); - assert(adminDB.auth({mechanism: 'MONGODB-CR', - user: 'user2', pwd: 'pass'})); + adminDB.createUser({user: 'user2', pwd: 'pass', roles: jsTest.adminUserRoles}); + assert(adminDB.auth({mechanism: 'MONGODB-CR', user: 'user2', pwd: 'pass'})); // Add $external no-op user to verify that it does not affect // authSchemaUpgrade SERVER-18475 @@ -29,8 +25,7 @@ var setupCRUsers = function(conn){ verifyUserDoc(adminDB, 'user2', true, false); verifyUserDoc(adminDB.getSiblingDB('$external'), "evil", false, false, true); - adminDB.updateUser('user1', {pwd: 'newpass', - roles: jsTest.adminUserRoles}); + adminDB.updateUser('user1', {pwd: 'newpass', roles: jsTest.adminUserRoles}); verifyAuth(adminDB, 'user1', 'newpass', true, true); verifyUserDoc(adminDB, 'user1', true, false); @@ -47,7 +42,7 @@ var verifySchemaUpgrade = function(adminDB) { verifyAuth(adminDB, 'user2', 'pass', false, true); }; -var runAndVerifySchemaUpgrade = function(conn){ +var runAndVerifySchemaUpgrade = function(conn) { jsTest.log("run authSchemaUpgrade"); var adminDB = conn.getDB('admin'); @@ -64,7 +59,7 @@ var testAuthSchemaUpgrade = function(conn) { var testUpgradeShards = function(mongos, shard) { setupCRUsers(shard); - assert.commandWorked(mongos.adminCommand({"authSchemaUpgrade":1,"upgradeShards":1})); + assert.commandWorked(mongos.adminCommand({"authSchemaUpgrade": 1, "upgradeShards": 1})); verifySchemaUpgrade(shard.getDB('admin')); }; @@ -74,13 +69,17 @@ testAuthSchemaUpgrade(conn); MongoRunner.stopMongod(conn); jsTest.log('Test authSchemUpgrade sharded'); -var dopts = { smallfiles: "", nopreallocj: ""}; -var st = new ShardingTest( - { shards: 1, - mongos: 1, - config: 1, - useHostname: false, // Needed when relying on the localhost exception - other: { shardOptions: dopts, configOptions: dopts, mongosOptions: { verbose: 1 } } } ); +var dopts = { + smallfiles: "", + nopreallocj: "" +}; +var st = new ShardingTest({ + shards: 1, + mongos: 1, + config: 1, + useHostname: false, // Needed when relying on the localhost exception + other: {shardOptions: dopts, configOptions: dopts, mongosOptions: {verbose: 1}} +}); testAuthSchemaUpgrade(st.s); testUpgradeShards(st.s, st.shard0); st.stop(); diff --git a/jstests/auth/authz_modifications_access_control.js b/jstests/auth/authz_modifications_access_control.js index 69e9b2b2c6e..bb294796a7f 100644 --- a/jstests/auth/authz_modifications_access_control.js +++ b/jstests/auth/authz_modifications_access_control.js @@ -5,19 +5,17 @@ function runTest(conn) { var authzErrorCode = 13; - conn.getDB('admin').createUser({user: 'userAdmin', - pwd: 'pwd', - roles: ['userAdminAnyDatabase']}); + conn.getDB('admin') + .createUser({user: 'userAdmin', pwd: 'pwd', roles: ['userAdminAnyDatabase']}); var userAdminConn = new Mongo(conn.host); userAdminConn.getDB('admin').auth('userAdmin', 'pwd'); var testUserAdmin = userAdminConn.getDB('test'); var adminUserAdmin = userAdminConn.getDB('admin'); - testUserAdmin.createRole({role: 'testRole', roles:[], privileges:[]}); - adminUserAdmin.createRole({role: 'adminRole', roles:[], privileges:[]}); - testUserAdmin.createUser({user: 'spencer', - pwd: 'pwd', - roles: ['testRole', {role: 'adminRole', db: 'admin'}]}); + testUserAdmin.createRole({role: 'testRole', roles: [], privileges: []}); + adminUserAdmin.createRole({role: 'adminRole', roles: [], privileges: []}); + testUserAdmin.createUser( + {user: 'spencer', pwd: 'pwd', roles: ['testRole', {role: 'adminRole', db: 'admin'}]}); adminUserAdmin.createUser({user: 'otherUser', pwd: 'pwd', roles: []}); var db = conn.getDB('test'); @@ -32,43 +30,43 @@ function runTest(conn) { // while "db" and "admindb" will be used for the actual permission checks that are being tested. (function testCreateUser() { - jsTestLog("Testing user creation"); + jsTestLog("Testing user creation"); - var res = db.runCommand({createUser: 'andy', pwd: 'pwd', roles: []}); - assert.commandFailedWithCode(res, authzErrorCode); + var res = db.runCommand({createUser: 'andy', pwd: 'pwd', roles: []}); + assert.commandFailedWithCode(res, authzErrorCode); + testUserAdmin.grantPrivilegesToRole( + 'testRole', [{resource: {db: 'test', collection: ''}, actions: ['createUser']}]); - testUserAdmin.grantPrivilegesToRole('testRole', [{resource: {db: 'test', collection: ''}, - actions: ['createUser']}]); + assert.commandWorked(db.runCommand({createUser: 'andy', pwd: 'pwd', roles: []})); - - assert.commandWorked(db.runCommand({createUser: 'andy', pwd: 'pwd', roles: []})); - - res = admindb.runCommand({createUser: 'andy', pwd: 'pwd', roles: []}); - assert.commandFailedWithCode(res, authzErrorCode); - })(); + res = admindb.runCommand({createUser: 'andy', pwd: 'pwd', roles: []}); + assert.commandFailedWithCode(res, authzErrorCode); + })(); (function testCreateRole() { - jsTestLog("Testing role creation"); - - var res = db.runCommand({createRole: 'testRole2', roles: [], privileges: []}); - assert.commandFailedWithCode(res, authzErrorCode); + jsTestLog("Testing role creation"); + var res = db.runCommand({createRole: 'testRole2', roles: [], privileges: []}); + assert.commandFailedWithCode(res, authzErrorCode); - testUserAdmin.grantPrivilegesToRole('testRole', [{resource: {db: 'test', collection: ''}, - actions: ['createRole']}]); + testUserAdmin.grantPrivilegesToRole( + 'testRole', [{resource: {db: 'test', collection: ''}, actions: ['createRole']}]); + assert.commandWorked(db.runCommand({createRole: 'testRole2', roles: [], privileges: []})); - assert.commandWorked(db.runCommand({createRole: 'testRole2', roles: [], privileges: []})); - - res = admindb.runCommand({createRole: 'testRole2', roles: [], privileges: []}); - assert.commandFailedWithCode(res, authzErrorCode); - })(); + res = admindb.runCommand({createRole: 'testRole2', roles: [], privileges: []}); + assert.commandFailedWithCode(res, authzErrorCode); + })(); - (function () { + (function() { jsTestLog("Testing role creation, of user-defined roles with same name as built-in roles"); - var cmdObj = {createRole: "readWrite", roles: [], privileges: []}; + var cmdObj = { + createRole: "readWrite", + roles: [], + privileges: [] + }; var res = adminUserAdmin.runCommand(cmdObj); assert.commandFailed(res, tojson(cmdObj)); @@ -79,242 +77,232 @@ function runTest(conn) { })(); (function testViewUser() { - jsTestLog("Testing viewing user information"); - - var res = db.runCommand({usersInfo: 'andy'}); - assert.commandFailedWithCode(res, authzErrorCode); + jsTestLog("Testing viewing user information"); + var res = db.runCommand({usersInfo: 'andy'}); + assert.commandFailedWithCode(res, authzErrorCode); - testUserAdmin.grantPrivilegesToRole('testRole', [{resource: {db: 'test', collection: ''}, - actions: ['viewUser']}]); + testUserAdmin.grantPrivilegesToRole( + 'testRole', [{resource: {db: 'test', collection: ''}, actions: ['viewUser']}]); + assert.commandWorked(db.runCommand({usersInfo: 'andy'})); - assert.commandWorked(db.runCommand({usersInfo: 'andy'})); - - res = admindb.runCommand({usersInfo: 'andy'}); - assert.commandFailedWithCode(res, authzErrorCode); - })(); + res = admindb.runCommand({usersInfo: 'andy'}); + assert.commandFailedWithCode(res, authzErrorCode); + })(); (function testViewRole() { - jsTestLog("Testing viewing role information"); - - var res = db.runCommand({rolesInfo: 'testRole2'}); - assert.commandFailedWithCode(res, authzErrorCode); + jsTestLog("Testing viewing role information"); + var res = db.runCommand({rolesInfo: 'testRole2'}); + assert.commandFailedWithCode(res, authzErrorCode); - testUserAdmin.grantPrivilegesToRole('testRole', [{resource: {db: 'test', collection: ''}, - actions: ['viewRole']}]); + testUserAdmin.grantPrivilegesToRole( + 'testRole', [{resource: {db: 'test', collection: ''}, actions: ['viewRole']}]); + assert.commandWorked(db.runCommand({rolesInfo: 'testRole2'})); - assert.commandWorked(db.runCommand({rolesInfo: 'testRole2'})); - - res = admindb.runCommand({rolesInfo: 'testRole2'}); - assert.commandFailedWithCode(res, authzErrorCode); - })(); + res = admindb.runCommand({rolesInfo: 'testRole2'}); + assert.commandFailedWithCode(res, authzErrorCode); + })(); (function testDropUser() { - jsTestLog("Testing dropping user"); - - var res = db.runCommand({dropUser: 'andy'}); - assert.commandFailedWithCode(res, authzErrorCode); + jsTestLog("Testing dropping user"); + var res = db.runCommand({dropUser: 'andy'}); + assert.commandFailedWithCode(res, authzErrorCode); - testUserAdmin.grantPrivilegesToRole('testRole', [{resource: {db: 'test', collection: ''}, - actions: ['dropUser']}]); + testUserAdmin.grantPrivilegesToRole( + 'testRole', [{resource: {db: 'test', collection: ''}, actions: ['dropUser']}]); + assert.commandWorked(db.runCommand({dropUser: 'andy'})); - assert.commandWorked(db.runCommand({dropUser: 'andy'})); - - res = admindb.runCommand({dropUser: 'andy'}); - assert.commandFailedWithCode(res, authzErrorCode); - })(); + res = admindb.runCommand({dropUser: 'andy'}); + assert.commandFailedWithCode(res, authzErrorCode); + })(); (function testDropRole() { - jsTestLog("Testing dropping role"); - - var res = db.runCommand({dropRole: 'testRole2'}); - assert.commandFailedWithCode(res, authzErrorCode); + jsTestLog("Testing dropping role"); + var res = db.runCommand({dropRole: 'testRole2'}); + assert.commandFailedWithCode(res, authzErrorCode); - testUserAdmin.grantPrivilegesToRole('testRole', [{resource: {db: 'test', collection: ''}, - actions: ['dropRole']}]); + testUserAdmin.grantPrivilegesToRole( + 'testRole', [{resource: {db: 'test', collection: ''}, actions: ['dropRole']}]); + assert.commandWorked(db.runCommand({dropRole: 'testRole2'})); - assert.commandWorked(db.runCommand({dropRole: 'testRole2'})); - - res = admindb.runCommand({dropRole: 'testRole2'}); - assert.commandFailedWithCode(res, authzErrorCode); - })(); + res = admindb.runCommand({dropRole: 'testRole2'}); + assert.commandFailedWithCode(res, authzErrorCode); + })(); (function testGrantRole() { - jsTestLog("Testing granting roles"); - - var res = db.runCommand({createUser: 'andy', pwd: 'pwd', roles: ['read']}); - assert.commandFailedWithCode(res, authzErrorCode); + jsTestLog("Testing granting roles"); - res = db.runCommand({grantRolesToUser: 'spencer', roles: ['read']}); - assert.commandFailedWithCode(res, authzErrorCode); + var res = db.runCommand({createUser: 'andy', pwd: 'pwd', roles: ['read']}); + assert.commandFailedWithCode(res, authzErrorCode); - res = db.runCommand({grantRolesToRole: 'testRole', roles: ['read']}); - assert.commandFailedWithCode(res, authzErrorCode); + res = db.runCommand({grantRolesToUser: 'spencer', roles: ['read']}); + assert.commandFailedWithCode(res, authzErrorCode); - res = admindb.runCommand({grantRolesToUser: 'otherUser', - roles: [{role: 'read', db: 'test'}]}); - assert.commandFailedWithCode(res, authzErrorCode); + res = db.runCommand({grantRolesToRole: 'testRole', roles: ['read']}); + assert.commandFailedWithCode(res, authzErrorCode); + res = admindb.runCommand( + {grantRolesToUser: 'otherUser', roles: [{role: 'read', db: 'test'}]}); + assert.commandFailedWithCode(res, authzErrorCode); - testUserAdmin.grantPrivilegesToRole('testRole', [{resource: {db: 'test', collection: ''}, - actions: ['grantRole']}]); + testUserAdmin.grantPrivilegesToRole( + 'testRole', [{resource: {db: 'test', collection: ''}, actions: ['grantRole']}]); + assert.commandWorked(db.runCommand({createUser: 'andy', pwd: 'pwd', roles: ['read']})); + assert.commandWorked(db.runCommand({grantRolesToUser: 'spencer', roles: ['read']})); + assert.commandWorked(db.runCommand({grantRolesToRole: 'testRole', roles: ['read']})); - assert.commandWorked(db.runCommand({createUser: 'andy', pwd: 'pwd', roles: ['read']})); - assert.commandWorked(db.runCommand({grantRolesToUser: 'spencer', roles: ['read']})); - assert.commandWorked(db.runCommand({grantRolesToRole: 'testRole', roles: ['read']})); + // Granting roles from other dbs should fail + res = db.runCommand({grantRolesToUser: 'spencer', roles: [{role: 'read', db: 'other'}]}); + assert.commandFailedWithCode(res, authzErrorCode); - // Granting roles from other dbs should fail - res = db.runCommand({grantRolesToUser: 'spencer', roles: [{role: 'read', db: 'other'}]}); - assert.commandFailedWithCode(res, authzErrorCode); - - // Granting roles from this db to users in another db, however, should work - res = admindb.runCommand({grantRolesToUser: 'otherUser', - roles: [{role: 'read', db: 'test'}]}); - assert.commandWorked(res); - })(); + // Granting roles from this db to users in another db, however, should work + res = admindb.runCommand( + {grantRolesToUser: 'otherUser', roles: [{role: 'read', db: 'test'}]}); + assert.commandWorked(res); + })(); (function testRevokeRole() { - jsTestLog("Testing revoking roles"); - - var res = db.runCommand({revokeRolesFromUser: 'spencer', roles: ['read']}); - assert.commandFailedWithCode(res, authzErrorCode); + jsTestLog("Testing revoking roles"); - res = db.runCommand({revokeRolesFromRole: 'testRole', roles: ['read']}); - assert.commandFailedWithCode(res, authzErrorCode); + var res = db.runCommand({revokeRolesFromUser: 'spencer', roles: ['read']}); + assert.commandFailedWithCode(res, authzErrorCode); - res = admindb.runCommand({revokeRolesFromUser: 'otherUser', - roles: [{role: 'read', db: 'test'}]}); - assert.commandFailedWithCode(res, authzErrorCode); + res = db.runCommand({revokeRolesFromRole: 'testRole', roles: ['read']}); + assert.commandFailedWithCode(res, authzErrorCode); + res = admindb.runCommand( + {revokeRolesFromUser: 'otherUser', roles: [{role: 'read', db: 'test'}]}); + assert.commandFailedWithCode(res, authzErrorCode); - testUserAdmin.grantPrivilegesToRole('testRole', [{resource: {db: 'test', collection: ''}, - actions: ['revokeRole']}]); + testUserAdmin.grantPrivilegesToRole( + 'testRole', [{resource: {db: 'test', collection: ''}, actions: ['revokeRole']}]); + assert.commandWorked(db.runCommand({revokeRolesFromUser: 'spencer', roles: ['read']})); + assert.commandWorked(db.runCommand({revokeRolesFromRole: 'testRole', roles: ['read']})); - assert.commandWorked(db.runCommand({revokeRolesFromUser: 'spencer', roles: ['read']})); - assert.commandWorked(db.runCommand({revokeRolesFromRole: 'testRole', roles: ['read']})); + // Revoking roles from other dbs should fail + res = db.runCommand({revokeRolesFromUser: 'spencer', roles: [{role: 'read', db: 'other'}]}); + assert.commandFailedWithCode(res, authzErrorCode); - // Revoking roles from other dbs should fail - res = db.runCommand({revokeRolesFromUser: 'spencer', - roles: [{role: 'read', db: 'other'}]}); - assert.commandFailedWithCode(res, authzErrorCode); - - // Revoking roles from this db from users in another db, however, should work - res = admindb.runCommand({revokeRolesFromUser: 'otherUser', - roles: [{role: 'read', db: 'test'}]}); - assert.commandWorked(res); - })(); + // Revoking roles from this db from users in another db, however, should work + res = admindb.runCommand( + {revokeRolesFromUser: 'otherUser', roles: [{role: 'read', db: 'test'}]}); + assert.commandWorked(res); + })(); (function testGrantPrivileges() { - jsTestLog("Testing granting privileges"); - - testUserAdmin.revokePrivilegesFromRole('testRole', - [{resource: {db: 'test', collection: ''}, - actions: ['grantRole']}]); - - - var res = db.runCommand({createRole: 'testRole2', - roles: [], - privileges: [{resource: {db: 'test', collection: ''}, - actions: ['find']}]}); - assert.commandFailedWithCode(res, authzErrorCode); - - res = db.runCommand({grantPrivilegesToRole: 'testRole', - privileges: [{resource: {db: 'test', collection: ''}, - actions: ['find']}]}); - assert.commandFailedWithCode(res, authzErrorCode); - - res = admindb.runCommand({grantPrivilegesToRole: 'adminRole', - privileges: [{resource: {db: 'test', collection: ''}, - actions: ['find']}]}); - assert.commandFailedWithCode(res, authzErrorCode); - - - testUserAdmin.grantPrivilegesToRole('testRole', [{resource: {db: 'test', collection: ''}, - actions: ['grantRole']}]); - - - res = db.runCommand({createRole: 'testRole2', - roles: [], - privileges: [{resource: {db: 'test', collection: ''}, - actions: ['find']}]}); - assert.commandWorked(res); - - res = db.runCommand({grantPrivilegesToRole: 'testRole', - privileges: [{resource: {db: 'test', collection: ''}, - actions: ['find']}]}); - assert.commandWorked(res); - - // Granting privileges from other dbs should fail - res = db.runCommand({grantPrivilegesToRole: 'testRole', - privileges: [{resource: {db: 'other', collection: ''}, - actions: ['find']}]}); - assert.commandFailedWithCode(res, authzErrorCode); - - // Granting privileges from this db to users in another db, however, should work - res = admindb.runCommand({grantPrivilegesToRole: 'adminRole', - privileges: [{resource: {db: 'test', collection: ''}, - actions: ['find']}]}); - assert.commandWorked(res); - })(); + jsTestLog("Testing granting privileges"); + + testUserAdmin.revokePrivilegesFromRole( + 'testRole', [{resource: {db: 'test', collection: ''}, actions: ['grantRole']}]); + + var res = db.runCommand({ + createRole: 'testRole2', + roles: [], + privileges: [{resource: {db: 'test', collection: ''}, actions: ['find']}] + }); + assert.commandFailedWithCode(res, authzErrorCode); + + res = db.runCommand({ + grantPrivilegesToRole: 'testRole', + privileges: [{resource: {db: 'test', collection: ''}, actions: ['find']}] + }); + assert.commandFailedWithCode(res, authzErrorCode); + + res = admindb.runCommand({ + grantPrivilegesToRole: 'adminRole', + privileges: [{resource: {db: 'test', collection: ''}, actions: ['find']}] + }); + assert.commandFailedWithCode(res, authzErrorCode); + + testUserAdmin.grantPrivilegesToRole( + 'testRole', [{resource: {db: 'test', collection: ''}, actions: ['grantRole']}]); + + res = db.runCommand({ + createRole: 'testRole2', + roles: [], + privileges: [{resource: {db: 'test', collection: ''}, actions: ['find']}] + }); + assert.commandWorked(res); + + res = db.runCommand({ + grantPrivilegesToRole: 'testRole', + privileges: [{resource: {db: 'test', collection: ''}, actions: ['find']}] + }); + assert.commandWorked(res); + + // Granting privileges from other dbs should fail + res = db.runCommand({ + grantPrivilegesToRole: 'testRole', + privileges: [{resource: {db: 'other', collection: ''}, actions: ['find']}] + }); + assert.commandFailedWithCode(res, authzErrorCode); + + // Granting privileges from this db to users in another db, however, should work + res = admindb.runCommand({ + grantPrivilegesToRole: 'adminRole', + privileges: [{resource: {db: 'test', collection: ''}, actions: ['find']}] + }); + assert.commandWorked(res); + })(); (function testRevokePrivileges() { - jsTestLog("Testing revoking privileges"); - - testUserAdmin.revokePrivilegesFromRole('testRole', - [{resource: {db: 'test', collection: ''}, - actions: ['revokeRole']}]); - - - var res = db.runCommand({revokePrivilegesFromRole: 'testRole', - privileges: [{resource: {db: 'test', collection: ''}, - actions: ['find']}]}); - assert.commandFailedWithCode(res, authzErrorCode); - - res = admindb.runCommand({revokePrivilegesFromRole: 'adminRole', - privileges: [{resource: {db: 'test', collection: ''}, - actions: ['find']}]}); - assert.commandFailedWithCode(res, authzErrorCode); - - - testUserAdmin.grantPrivilegesToRole('testRole', [{resource: {db: 'test', collection: ''}, - actions: ['revokeRole']}]); - - - res = db.runCommand({revokePrivilegesFromRole: 'testRole', - privileges: [{resource: {db: 'test', collection: ''}, - actions: ['find']}]}); - assert.commandWorked(res); - - // Revoking privileges from other dbs should fail - res = db.runCommand({revokePrivilegesFromRole: 'testRole', - privileges: [{resource: {db: 'other', collection: ''}, - actions: ['find']}]}); - assert.commandFailedWithCode(res, authzErrorCode); - - // Granting privileges from this db to users in another db, however, should work - res = admindb.runCommand({revokePrivilegesFromRole: 'adminRole', - privileges: [{resource: {db: 'test', collection: ''}, - actions: ['find']}]}); - assert.commandWorked(res); - })(); + jsTestLog("Testing revoking privileges"); + + testUserAdmin.revokePrivilegesFromRole( + 'testRole', [{resource: {db: 'test', collection: ''}, actions: ['revokeRole']}]); + + var res = db.runCommand({ + revokePrivilegesFromRole: 'testRole', + privileges: [{resource: {db: 'test', collection: ''}, actions: ['find']}] + }); + assert.commandFailedWithCode(res, authzErrorCode); + + res = admindb.runCommand({ + revokePrivilegesFromRole: 'adminRole', + privileges: [{resource: {db: 'test', collection: ''}, actions: ['find']}] + }); + assert.commandFailedWithCode(res, authzErrorCode); + + testUserAdmin.grantPrivilegesToRole( + 'testRole', [{resource: {db: 'test', collection: ''}, actions: ['revokeRole']}]); + + res = db.runCommand({ + revokePrivilegesFromRole: 'testRole', + privileges: [{resource: {db: 'test', collection: ''}, actions: ['find']}] + }); + assert.commandWorked(res); + + // Revoking privileges from other dbs should fail + res = db.runCommand({ + revokePrivilegesFromRole: 'testRole', + privileges: [{resource: {db: 'other', collection: ''}, actions: ['find']}] + }); + assert.commandFailedWithCode(res, authzErrorCode); + + // Granting privileges from this db to users in another db, however, should work + res = admindb.runCommand({ + revokePrivilegesFromRole: 'adminRole', + privileges: [{resource: {db: 'test', collection: ''}, actions: ['find']}] + }); + assert.commandWorked(res); + })(); } - jsTest.log('Test standalone'); -var conn = MongoRunner.runMongod({ auth: '' }); +var conn = MongoRunner.runMongod({auth: ''}); runTest(conn); MongoRunner.stopMongod(conn.port); jsTest.log('Test sharding'); -var st = new ShardingTest({ shards: 2, config: 3, keyFile: 'jstests/libs/key1' }); +var st = new ShardingTest({shards: 2, config: 3, keyFile: 'jstests/libs/key1'}); runTest(st.s); st.stop(); diff --git a/jstests/auth/basic_role_auth.js b/jstests/auth/basic_role_auth.js index 8b50f70671b..f44a331fa95 100644 --- a/jstests/auth/basic_role_auth.js +++ b/jstests/auth/basic_role_auth.js @@ -13,86 +13,59 @@ */ var AUTH_INFO = { admin: { - root: { - pwd: 'root', - roles: [ 'root' ] - }, - cluster: { - pwd: 'cluster', - roles: [ 'clusterAdmin' ] - }, - anone: { - pwd: 'none', - roles: [] - }, - aro: { - pwd: 'ro', - roles: [ 'read' ] - }, - arw: { - pwd: 'rw', - roles: [ 'readWrite' ] - }, - aadmin: { - pwd: 'admin', - roles: [ 'dbAdmin' ] - }, - auadmin: { - pwd: 'uadmin', - roles: [ 'userAdmin' ] - }, - any_ro: { - pwd: 'ro', - roles: [ 'readAnyDatabase' ] - }, - any_rw: { - pwd: 'rw', - roles: [ 'readWriteAnyDatabase' ] - }, - any_admin: { - pwd: 'admin', - roles: [ 'dbAdminAnyDatabase' ] - }, - any_uadmin: { - pwd: 'uadmin', - roles: [ 'userAdminAnyDatabase' ] - } + root: {pwd: 'root', roles: ['root']}, + cluster: {pwd: 'cluster', roles: ['clusterAdmin']}, + anone: {pwd: 'none', roles: []}, + aro: {pwd: 'ro', roles: ['read']}, + arw: {pwd: 'rw', roles: ['readWrite']}, + aadmin: {pwd: 'admin', roles: ['dbAdmin']}, + auadmin: {pwd: 'uadmin', roles: ['userAdmin']}, + any_ro: {pwd: 'ro', roles: ['readAnyDatabase']}, + any_rw: {pwd: 'rw', roles: ['readWriteAnyDatabase']}, + any_admin: {pwd: 'admin', roles: ['dbAdminAnyDatabase']}, + any_uadmin: {pwd: 'uadmin', roles: ['userAdminAnyDatabase']} }, test: { - none: { - pwd: 'none', - roles: [] - }, - ro: { - pwd: 'ro', - roles: [ 'read' ] - }, - rw: { - pwd: 'rw', - roles: [ 'readWrite' ] - }, - roadmin: { - pwd: 'roadmin', - roles: [ 'read', 'dbAdmin' ] - }, - admin: { - pwd: 'admin', - roles: [ 'dbAdmin' ] - }, - uadmin: { - pwd: 'uadmin', - roles: [ 'userAdmin' ] - } + none: {pwd: 'none', roles: []}, + ro: {pwd: 'ro', roles: ['read']}, + rw: {pwd: 'rw', roles: ['readWrite']}, + roadmin: {pwd: 'roadmin', roles: ['read', 'dbAdmin']}, + admin: {pwd: 'admin', roles: ['dbAdmin']}, + uadmin: {pwd: 'uadmin', roles: ['userAdmin']} } }; // Constants that lists the privileges of a given role. -var READ_PERM = { query: 1, index_r: 1, killCursor: 1 }; -var READ_WRITE_PERM = { insert: 1, update: 1, remove: 1, query: 1, - index_r: 1, index_w: 1, killCursor: 1 }; -var ADMIN_PERM = { index_r: 1, index_w: 1, profile_r: 1 }; -var UADMIN_PERM = { user_r: 1, user_w: 1 }; -var CLUSTER_PERM = { killOp: 1, currentOp: 1, fsync_unlock: 1, killCursor: 1, profile_r: 1 }; +var READ_PERM = { + query: 1, + index_r: 1, + killCursor: 1 +}; +var READ_WRITE_PERM = { + insert: 1, + update: 1, + remove: 1, + query: 1, + index_r: 1, + index_w: 1, + killCursor: 1 +}; +var ADMIN_PERM = { + index_r: 1, + index_w: 1, + profile_r: 1 +}; +var UADMIN_PERM = { + user_r: 1, + user_w: 1 +}; +var CLUSTER_PERM = { + killOp: 1, + currentOp: 1, + fsync_unlock: 1, + killCursor: 1, + profile_r: 1 +}; /** * Checks whether an error occurs after running an operation. @@ -111,10 +84,9 @@ var checkErr = function(shouldPass, opFunc) { success = false; } - assert(success == shouldPass, 'expected shouldPass: ' + shouldPass + - ', got: ' + success + - ', op: ' + tojson(opFunc) + - ', exception: ' + tojson(exception)); + assert(success == shouldPass, + 'expected shouldPass: ' + shouldPass + ', got: ' + success + ', op: ' + tojson(opFunc) + + ', exception: ' + tojson(exception)); }; /** @@ -129,76 +101,91 @@ var checkErr = function(shouldPass, opFunc) { * fsync_unlock. */ var testOps = function(db, allowedActions) { - checkErr(allowedActions.hasOwnProperty('insert'), function() { - var res = db.user.insert({ y: 1 }); - if (res.hasWriteError()) throw Error("insert failed: " + tojson(res.getRawResponse())); - }); - - checkErr(allowedActions.hasOwnProperty('update'), function() { - var res = db.user.update({ y: 1 }, { z: 3 }); - if (res.hasWriteError()) throw Error("update failed: " + tojson(res.getRawResponse())); - }); - - checkErr(allowedActions.hasOwnProperty('remove'), function() { - var res = db.user.remove({ y: 1 }); - if (res.hasWriteError()) throw Error("remove failed: " + tojson(res.getRawResponse())); - }); - - checkErr(allowedActions.hasOwnProperty('query'), function() { - db.user.findOne({ y: 1 }); - }); - - checkErr(allowedActions.hasOwnProperty('killOp'), function() { - var errorCodeUnauthorized = 13; - var res = db.killOp(1); - - if (res.code == errorCodeUnauthorized) { - throw Error("unauthorized killOp"); - } - }); - - checkErr(allowedActions.hasOwnProperty('currentOp'), function() { - var errorCodeUnauthorized = 13; - var res = db.currentOp(); - - if (res.code == errorCodeUnauthorized) { - throw Error("unauthorized currentOp"); - } - }); - - checkErr(allowedActions.hasOwnProperty('index_r'), function() { - db.system.indexes.findOne(); - }); - - checkErr(allowedActions.hasOwnProperty('index_w'), function() { - var res = db.user.ensureIndex({ x: 1 }); - if (res.code == 13) { // Unauthorized - throw Error("unauthorized currentOp"); - } - }); - - checkErr(allowedActions.hasOwnProperty('profile_r'), function() { - db.system.profile.findOne(); - }); - - checkErr(allowedActions.hasOwnProperty('profile_w'), function() { - var res = db.system.profile.insert({ x: 1 }); - if (res.hasWriteError()) { - throw Error("profile insert failed: " + tojson(res.getRawResponse())); - } - }); - - checkErr(allowedActions.hasOwnProperty('user_r'), function() { - var result = db.runCommand({usersInfo: 1}); - if (!result.ok) { - throw new Error(tojson(result)); - } - }); - - checkErr(allowedActions.hasOwnProperty('user_w'), function() { - db.createUser({user:'a', pwd: 'a', roles: jsTest.basicUserRoles}); - assert(db.dropUser('a')); - }); + checkErr(allowedActions.hasOwnProperty('insert'), + function() { + var res = db.user.insert({y: 1}); + if (res.hasWriteError()) + throw Error("insert failed: " + tojson(res.getRawResponse())); + }); + + checkErr(allowedActions.hasOwnProperty('update'), + function() { + var res = db.user.update({y: 1}, {z: 3}); + if (res.hasWriteError()) + throw Error("update failed: " + tojson(res.getRawResponse())); + }); + + checkErr(allowedActions.hasOwnProperty('remove'), + function() { + var res = db.user.remove({y: 1}); + if (res.hasWriteError()) + throw Error("remove failed: " + tojson(res.getRawResponse())); + }); + + checkErr(allowedActions.hasOwnProperty('query'), + function() { + db.user.findOne({y: 1}); + }); + + checkErr(allowedActions.hasOwnProperty('killOp'), + function() { + var errorCodeUnauthorized = 13; + var res = db.killOp(1); + + if (res.code == errorCodeUnauthorized) { + throw Error("unauthorized killOp"); + } + }); + + checkErr(allowedActions.hasOwnProperty('currentOp'), + function() { + var errorCodeUnauthorized = 13; + var res = db.currentOp(); + + if (res.code == errorCodeUnauthorized) { + throw Error("unauthorized currentOp"); + } + }); + + checkErr(allowedActions.hasOwnProperty('index_r'), + function() { + db.system.indexes.findOne(); + }); + + checkErr(allowedActions.hasOwnProperty('index_w'), + function() { + var res = db.user.ensureIndex({x: 1}); + if (res.code == 13) { // Unauthorized + throw Error("unauthorized currentOp"); + } + }); + + checkErr(allowedActions.hasOwnProperty('profile_r'), + function() { + db.system.profile.findOne(); + }); + + checkErr(allowedActions.hasOwnProperty('profile_w'), + function() { + var res = db.system.profile.insert({x: 1}); + if (res.hasWriteError()) { + throw Error("profile insert failed: " + tojson(res.getRawResponse())); + } + }); + + checkErr(allowedActions.hasOwnProperty('user_r'), + function() { + var result = db.runCommand({usersInfo: 1}); + if (!result.ok) { + throw new Error(tojson(result)); + } + }); + + checkErr(allowedActions.hasOwnProperty('user_w'), + function() { + db.createUser({user: 'a', pwd: 'a', roles: jsTest.basicUserRoles}); + assert(db.dropUser('a')); + }); // Test for kill cursor (function() { @@ -208,8 +195,7 @@ var testOps = function(db, allowedActions) { if (db2 == 'admin') { assert.eq(1, db2.auth('aro', AUTH_INFO.admin.aro.pwd)); - } - else { + } else { assert.eq(1, db2.auth('ro', AUTH_INFO.test.ro.pwd)); } @@ -218,33 +204,35 @@ var testOps = function(db, allowedActions) { db.killCursor(cursor.id()); // Send a synchronous message to make sure that kill cursor was processed // before proceeding. - db.runCommand({ whatsmyuri: 1 }); - - checkErr(!allowedActions.hasOwnProperty('killCursor'), function() { - while (cursor.hasNext()) { - var next = cursor.next(); - - // This is a failure in mongos case. Standalone case will fail - // when next() was called. - if (next.code == 16336) { - // could not find cursor in cache for id - throw next.$err; - } - } - }); - }); // TODO: enable test after SERVER-5813 is fixed. - - var isMongos = db.runCommand({ isdbgrid: 1 }).isdbgrid; + db.runCommand({whatsmyuri: 1}); + + checkErr(!allowedActions.hasOwnProperty('killCursor'), + function() { + while (cursor.hasNext()) { + var next = cursor.next(); + + // This is a failure in mongos case. Standalone case will fail + // when next() was called. + if (next.code == 16336) { + // could not find cursor in cache for id + throw next.$err; + } + } + }); + }); // TODO: enable test after SERVER-5813 is fixed. + + var isMongos = db.runCommand({isdbgrid: 1}).isdbgrid; // Note: fsyncUnlock is not supported in mongos. - if (!isMongos){ - checkErr(allowedActions.hasOwnProperty('fsync_unlock'), function() { - var res = db.fsyncUnlock(); - var errorCodeUnauthorized = 13; - - if (res.code == errorCodeUnauthorized) { - throw Error("unauthorized unauthorized fsyncUnlock"); - } - }); + if (!isMongos) { + checkErr(allowedActions.hasOwnProperty('fsync_unlock'), + function() { + var res = db.fsyncUnlock(); + var errorCodeUnauthorized = 13; + + if (res.code == errorCodeUnauthorized) { + throw Error("unauthorized unauthorized fsyncUnlock"); + } + }); } }; @@ -256,217 +244,217 @@ var testOps = function(db, allowedActions) { // object. // } var TESTS = [ -{ - name: 'Test multiple user login separate connection', - test: function(conn) { - var testDB = conn.getDB('test'); - assert.eq(1, testDB.auth('ro', AUTH_INFO.test.ro.pwd)); - - var conn2 = new Mongo(conn.host); - var testDB2 = conn2.getDB('test'); - assert.eq(1, testDB2.auth('uadmin', AUTH_INFO.test.uadmin.pwd)); - - testOps(testDB, READ_PERM); - testOps(testDB2, UADMIN_PERM); - } -}, -{ - name: 'Test user with no role', - test: function(conn) { - var testDB = conn.getDB('test'); - assert.eq(1, testDB.auth('none', AUTH_INFO.test.none.pwd)); - - testOps(testDB, {}); - } -}, -{ - name: 'Test read only user', - test: function(conn) { - var testDB = conn.getDB('test'); - assert.eq(1, testDB.auth('ro', AUTH_INFO.test.ro.pwd)); - - testOps(testDB, READ_PERM); - } -}, -{ - name: 'Test read/write user', - test: function(conn) { - var testDB = conn.getDB('test'); - assert.eq(1, testDB.auth('rw', AUTH_INFO.test.rw.pwd)); - - testOps(testDB, READ_WRITE_PERM); - } -}, -{ - name: 'Test read + dbAdmin user', - test: function(conn) { - var testDB = conn.getDB('test'); - assert.eq(1, testDB.auth('roadmin', AUTH_INFO.test.roadmin.pwd)); - - var combinedPerm = Object.extend({}, READ_PERM); - combinedPerm = Object.extend(combinedPerm, ADMIN_PERM); - testOps(testDB, combinedPerm); - } -}, -{ - name: 'Test dbAdmin user', - test: function(conn) { - var testDB = conn.getDB('test'); - assert.eq(1, testDB.auth('admin', AUTH_INFO.test.admin.pwd)); - - testOps(testDB, ADMIN_PERM); - } -}, -{ - name: 'Test userAdmin user', - test: function(conn) { - var testDB = conn.getDB('test'); - assert.eq(1, testDB.auth('uadmin', AUTH_INFO.test.uadmin.pwd)); - - testOps(testDB, UADMIN_PERM); - } -}, -{ - name: 'Test cluster user', - test: function(conn) { - var adminDB = conn.getDB('admin'); - assert.eq(1, adminDB.auth('cluster', AUTH_INFO.admin.cluster.pwd)); - - testOps(conn.getDB('test'), CLUSTER_PERM); - } -}, -{ - name: 'Test admin user with no role', - test: function(conn) { - var adminDB = conn.getDB('admin'); - assert.eq(1, adminDB.auth('anone', AUTH_INFO.admin.anone.pwd)); - - testOps(adminDB, {}); - testOps(conn.getDB('test'), {}); - } -}, -{ - name: 'Test read only admin user', - test: function(conn) { - var adminDB = conn.getDB('admin'); - assert.eq(1, adminDB.auth('aro', AUTH_INFO.admin.aro.pwd)); - - testOps(adminDB, READ_PERM); - testOps(conn.getDB('test'), {}); - } -}, -{ - name: 'Test read/write admin user', - test: function(conn) { - var adminDB = conn.getDB('admin'); - assert.eq(1, adminDB.auth('arw', AUTH_INFO.admin.arw.pwd)); - - testOps(adminDB, READ_WRITE_PERM); - testOps(conn.getDB('test'), {}); - } -}, -{ - name: 'Test dbAdmin admin user', - test: function(conn) { - var adminDB = conn.getDB('admin'); - assert.eq(1, adminDB.auth('aadmin', AUTH_INFO.admin.aadmin.pwd)); - - testOps(adminDB, ADMIN_PERM); - testOps(conn.getDB('test'), {}); - } -}, -{ - name: 'Test userAdmin admin user', - test: function(conn) { - var adminDB = conn.getDB('admin'); - assert.eq(1, adminDB.auth('auadmin', AUTH_INFO.admin.auadmin.pwd)); - - testOps(adminDB, UADMIN_PERM); - testOps(conn.getDB('test'), {}); - } -}, -{ - name: 'Test read only any db user', - test: function(conn) { - var adminDB = conn.getDB('admin'); - assert.eq(1, adminDB.auth('any_ro', AUTH_INFO.admin.any_ro.pwd)); - - testOps(adminDB, READ_PERM); - testOps(conn.getDB('test'), READ_PERM); - } -}, -{ - name: 'Test read/write any db user', - test: function(conn) { - var adminDB = conn.getDB('admin'); - assert.eq(1, adminDB.auth('any_rw', AUTH_INFO.admin.any_rw.pwd)); - - testOps(adminDB, READ_WRITE_PERM); - testOps(conn.getDB('test'), READ_WRITE_PERM); - } -}, -{ - name: 'Test dbAdmin any db user', - test: function(conn) { - var adminDB = conn.getDB('admin'); - assert.eq(1, adminDB.auth('any_admin', AUTH_INFO.admin.any_admin.pwd)); - - testOps(adminDB, ADMIN_PERM); - testOps(conn.getDB('test'), ADMIN_PERM); - } -}, -{ - name: 'Test userAdmin any db user', - test: function(conn) { - var adminDB = conn.getDB('admin'); - assert.eq(1, adminDB.auth('any_uadmin', AUTH_INFO.admin.any_uadmin.pwd)); - - testOps(adminDB, UADMIN_PERM); - testOps(conn.getDB('test'), UADMIN_PERM); - } -}, - -{ - name: 'Test change role', - test: function(conn) { - var testDB = conn.getDB('test'); - assert.eq(1, testDB.auth('rw', AUTH_INFO.test.rw.pwd)); - - var newConn = new Mongo(conn.host); - assert.eq(1, newConn.getDB('admin').auth('any_uadmin', AUTH_INFO.admin.any_uadmin.pwd)); - newConn.getDB('test').updateUser('rw', {roles: ['read']}); - var origSpec = newConn.getDB("test").getUser("rw"); - - // role change should affect users already authenticated. - testOps(testDB, READ_PERM); - - // role change should affect active connections. - testDB.runCommand({ logout: 1 }); - assert.eq(1, testDB.auth('rw', AUTH_INFO.test.rw.pwd)); - testOps(testDB, READ_PERM); - - // role change should also affect new connections. - var newConn3 = new Mongo(conn.host); - var testDB3 = newConn3.getDB('test'); - assert.eq(1, testDB3.auth('rw', AUTH_INFO.test.rw.pwd)); - testOps(testDB3, READ_PERM); - - newConn.getDB('test').updateUser('rw', {roles: origSpec.roles}); - } -}, + { + name: 'Test multiple user login separate connection', + test: function(conn) { + var testDB = conn.getDB('test'); + assert.eq(1, testDB.auth('ro', AUTH_INFO.test.ro.pwd)); + + var conn2 = new Mongo(conn.host); + var testDB2 = conn2.getDB('test'); + assert.eq(1, testDB2.auth('uadmin', AUTH_INFO.test.uadmin.pwd)); + + testOps(testDB, READ_PERM); + testOps(testDB2, UADMIN_PERM); + } + }, + { + name: 'Test user with no role', + test: function(conn) { + var testDB = conn.getDB('test'); + assert.eq(1, testDB.auth('none', AUTH_INFO.test.none.pwd)); + + testOps(testDB, {}); + } + }, + { + name: 'Test read only user', + test: function(conn) { + var testDB = conn.getDB('test'); + assert.eq(1, testDB.auth('ro', AUTH_INFO.test.ro.pwd)); + + testOps(testDB, READ_PERM); + } + }, + { + name: 'Test read/write user', + test: function(conn) { + var testDB = conn.getDB('test'); + assert.eq(1, testDB.auth('rw', AUTH_INFO.test.rw.pwd)); + + testOps(testDB, READ_WRITE_PERM); + } + }, + { + name: 'Test read + dbAdmin user', + test: function(conn) { + var testDB = conn.getDB('test'); + assert.eq(1, testDB.auth('roadmin', AUTH_INFO.test.roadmin.pwd)); + + var combinedPerm = Object.extend({}, READ_PERM); + combinedPerm = Object.extend(combinedPerm, ADMIN_PERM); + testOps(testDB, combinedPerm); + } + }, + { + name: 'Test dbAdmin user', + test: function(conn) { + var testDB = conn.getDB('test'); + assert.eq(1, testDB.auth('admin', AUTH_INFO.test.admin.pwd)); + + testOps(testDB, ADMIN_PERM); + } + }, + { + name: 'Test userAdmin user', + test: function(conn) { + var testDB = conn.getDB('test'); + assert.eq(1, testDB.auth('uadmin', AUTH_INFO.test.uadmin.pwd)); + + testOps(testDB, UADMIN_PERM); + } + }, + { + name: 'Test cluster user', + test: function(conn) { + var adminDB = conn.getDB('admin'); + assert.eq(1, adminDB.auth('cluster', AUTH_INFO.admin.cluster.pwd)); + + testOps(conn.getDB('test'), CLUSTER_PERM); + } + }, + { + name: 'Test admin user with no role', + test: function(conn) { + var adminDB = conn.getDB('admin'); + assert.eq(1, adminDB.auth('anone', AUTH_INFO.admin.anone.pwd)); + + testOps(adminDB, {}); + testOps(conn.getDB('test'), {}); + } + }, + { + name: 'Test read only admin user', + test: function(conn) { + var adminDB = conn.getDB('admin'); + assert.eq(1, adminDB.auth('aro', AUTH_INFO.admin.aro.pwd)); + + testOps(adminDB, READ_PERM); + testOps(conn.getDB('test'), {}); + } + }, + { + name: 'Test read/write admin user', + test: function(conn) { + var adminDB = conn.getDB('admin'); + assert.eq(1, adminDB.auth('arw', AUTH_INFO.admin.arw.pwd)); + + testOps(adminDB, READ_WRITE_PERM); + testOps(conn.getDB('test'), {}); + } + }, + { + name: 'Test dbAdmin admin user', + test: function(conn) { + var adminDB = conn.getDB('admin'); + assert.eq(1, adminDB.auth('aadmin', AUTH_INFO.admin.aadmin.pwd)); + + testOps(adminDB, ADMIN_PERM); + testOps(conn.getDB('test'), {}); + } + }, + { + name: 'Test userAdmin admin user', + test: function(conn) { + var adminDB = conn.getDB('admin'); + assert.eq(1, adminDB.auth('auadmin', AUTH_INFO.admin.auadmin.pwd)); + + testOps(adminDB, UADMIN_PERM); + testOps(conn.getDB('test'), {}); + } + }, + { + name: 'Test read only any db user', + test: function(conn) { + var adminDB = conn.getDB('admin'); + assert.eq(1, adminDB.auth('any_ro', AUTH_INFO.admin.any_ro.pwd)); + + testOps(adminDB, READ_PERM); + testOps(conn.getDB('test'), READ_PERM); + } + }, + { + name: 'Test read/write any db user', + test: function(conn) { + var adminDB = conn.getDB('admin'); + assert.eq(1, adminDB.auth('any_rw', AUTH_INFO.admin.any_rw.pwd)); + + testOps(adminDB, READ_WRITE_PERM); + testOps(conn.getDB('test'), READ_WRITE_PERM); + } + }, + { + name: 'Test dbAdmin any db user', + test: function(conn) { + var adminDB = conn.getDB('admin'); + assert.eq(1, adminDB.auth('any_admin', AUTH_INFO.admin.any_admin.pwd)); + + testOps(adminDB, ADMIN_PERM); + testOps(conn.getDB('test'), ADMIN_PERM); + } + }, + { + name: 'Test userAdmin any db user', + test: function(conn) { + var adminDB = conn.getDB('admin'); + assert.eq(1, adminDB.auth('any_uadmin', AUTH_INFO.admin.any_uadmin.pwd)); + + testOps(adminDB, UADMIN_PERM); + testOps(conn.getDB('test'), UADMIN_PERM); + } + }, -{ - name: 'Test override user', - test: function(conn) { - var testDB = conn.getDB('test'); - assert.eq(1, testDB.auth('rw', AUTH_INFO.test.rw.pwd)); - assert.eq(1, testDB.auth('ro', AUTH_INFO.test.ro.pwd)); - testOps(testDB, READ_PERM); + { + name: 'Test change role', + test: function(conn) { + var testDB = conn.getDB('test'); + assert.eq(1, testDB.auth('rw', AUTH_INFO.test.rw.pwd)); + + var newConn = new Mongo(conn.host); + assert.eq(1, newConn.getDB('admin').auth('any_uadmin', AUTH_INFO.admin.any_uadmin.pwd)); + newConn.getDB('test').updateUser('rw', {roles: ['read']}); + var origSpec = newConn.getDB("test").getUser("rw"); + + // role change should affect users already authenticated. + testOps(testDB, READ_PERM); + + // role change should affect active connections. + testDB.runCommand({logout: 1}); + assert.eq(1, testDB.auth('rw', AUTH_INFO.test.rw.pwd)); + testOps(testDB, READ_PERM); + + // role change should also affect new connections. + var newConn3 = new Mongo(conn.host); + var testDB3 = newConn3.getDB('test'); + assert.eq(1, testDB3.auth('rw', AUTH_INFO.test.rw.pwd)); + testOps(testDB3, READ_PERM); + + newConn.getDB('test').updateUser('rw', {roles: origSpec.roles}); + } + }, - testDB.runCommand({ logout: 1 }); - testOps(testDB, {}); + { + name: 'Test override user', + test: function(conn) { + var testDB = conn.getDB('test'); + assert.eq(1, testDB.auth('rw', AUTH_INFO.test.rw.pwd)); + assert.eq(1, testDB.auth('ro', AUTH_INFO.test.ro.pwd)); + testOps(testDB, READ_PERM); + + testDB.runCommand({logout: 1}); + testOps(testDB, {}); + } } -} ]; /** @@ -480,13 +468,13 @@ var runTests = function(conn) { var testDB = conn.getDB('test'); var adminDB = conn.getDB('admin'); - adminDB.createUser({ user: 'root', pwd: AUTH_INFO.admin.root.pwd, - roles: AUTH_INFO.admin.root.roles }); + adminDB.createUser( + {user: 'root', pwd: AUTH_INFO.admin.root.pwd, roles: AUTH_INFO.admin.root.roles}); adminDB.auth('root', AUTH_INFO.admin.root.pwd); for (var x = 0; x < 10; x++) { - testDB.kill_cursor.insert({ x: x }); - adminDB.kill_cursor.insert({ x: x }); + testDB.kill_cursor.insert({x: x}); + adminDB.kill_cursor.insert({x: x}); } for (var dbName in AUTH_INFO) { @@ -499,12 +487,11 @@ var runTests = function(conn) { } var info = dbObj[userName]; - conn.getDB(dbName).createUser({ user: userName, - pwd: info.pwd, roles: info.roles }); + conn.getDB(dbName).createUser({user: userName, pwd: info.pwd, roles: info.roles}); } } - adminDB.runCommand({ logout: 1 }); + adminDB.runCommand({logout: 1}); }; var teardown = function() { @@ -533,17 +520,19 @@ var runTests = function(conn) { if (failures.length > 0) { var list = ''; - failures.forEach(function(test) { list += (test + '\n'); }); + failures.forEach(function(test) { + list += (test + '\n'); + }); throw Error('Tests failed:\n' + list); } }; -var conn = MongoRunner.runMongod({ auth: '' }); +var conn = MongoRunner.runMongod({auth: ''}); runTests(conn); MongoRunner.stopMongod(conn.port); jsTest.log('Test sharding'); -var st = new ShardingTest({ shards: 1, keyFile: 'jstests/libs/key1' }); +var st = new ShardingTest({shards: 1, keyFile: 'jstests/libs/key1'}); runTests(st.s); st.stop(); diff --git a/jstests/auth/builtin_roles_system_colls.js b/jstests/auth/builtin_roles_system_colls.js index 0ce2d98664d..a6403311291 100644 --- a/jstests/auth/builtin_roles_system_colls.js +++ b/jstests/auth/builtin_roles_system_colls.js @@ -9,38 +9,42 @@ // the users collection easier if you have a lot of users, etc. function testUserAdminAnyDatabaseSystemCollIndexing(adminDB) { adminDB.auth("root", "pwd"); - adminDB.createUser({ user: "king", pwd: "pwd", roles: ["userAdminAnyDatabase"] }); + adminDB.createUser({user: "king", pwd: "pwd", roles: ["userAdminAnyDatabase"]}); adminDB.logout(); adminDB.auth("king", "pwd"); - assert.commandWorked(adminDB.system.users.createIndex({ db: 1 })); - assert.commandWorked(adminDB.system.roles.createIndex({ db: 1 })); - assert.commandWorked(adminDB.system.users.dropIndex({ db: 1 })); - assert.commandWorked(adminDB.system.roles.dropIndex({ db: 1 })); + assert.commandWorked(adminDB.system.users.createIndex({db: 1})); + assert.commandWorked(adminDB.system.roles.createIndex({db: 1})); + assert.commandWorked(adminDB.system.users.dropIndex({db: 1})); + assert.commandWorked(adminDB.system.roles.dropIndex({db: 1})); adminDB.logout(); } - // SERVER-14701: the backup role should be able to run the // collstats command on all resouces, including system resources. function testBackupSystemCollStats(adminDB) { adminDB.auth("root", "pwd"); - adminDB.createUser({ user: "backup-agent", pwd: "pwd", roles: ["backup"] }); - adminDB.system.js.save({ _id: "testFunction", value: function (x){ return x; }}); + adminDB.createUser({user: "backup-agent", pwd: "pwd", roles: ["backup"]}); + adminDB.system.js.save({ + _id: "testFunction", + value: function(x) { + return x; + } + }); adminDB.logout(); adminDB.auth("backup-agent", "pwd"); - assert.commandWorked(adminDB.runCommand({ collstats: "system.users" })); - assert.commandWorked(adminDB.runCommand({ collstats: "system.roles" })); - assert.commandWorked(adminDB.runCommand({ collstats: "system.js" })); + assert.commandWorked(adminDB.runCommand({collstats: "system.users"})); + assert.commandWorked(adminDB.runCommand({collstats: "system.roles"})); + assert.commandWorked(adminDB.runCommand({collstats: "system.js"})); adminDB.logout(); } // ************************************************************ -var conn = MongoRunner.runMongod({ auth: "" }); +var conn = MongoRunner.runMongod({auth: ""}); var adminDB = conn.getDB("admin"); -adminDB.createUser({ user: "root", pwd: "pwd", roles: ["root"] }); +adminDB.createUser({user: "root", pwd: "pwd", roles: ["root"]}); testUserAdminAnyDatabaseSystemCollIndexing(adminDB); testBackupSystemCollStats(adminDB); diff --git a/jstests/auth/clac_system_colls.js b/jstests/auth/clac_system_colls.js index 3f1782cfbb9..527f6c29e5d 100644 --- a/jstests/auth/clac_system_colls.js +++ b/jstests/auth/clac_system_colls.js @@ -9,53 +9,60 @@ function runTest(admindb) { admindb.createUser({user: "admin", pwd: "pwd", roles: ["userAdminAnyDatabase"]}); assert.eq(1, admindb.auth("admin", "pwd")); - var sysCollections = ["system.indexes", "system.js", "system.namespaces", - "system.profile", "system.roles", "system.users"]; + var sysCollections = [ + "system.indexes", + "system.js", + "system.namespaces", + "system.profile", + "system.roles", + "system.users" + ]; var sysPrivs = new Array(); for (var i in sysCollections) { - sysPrivs.push({resource: {db:admindb.getName(), collection:sysCollections[i]}, - actions:['find']}); + sysPrivs.push( + {resource: {db: admindb.getName(), collection: sysCollections[i]}, actions: ['find']}); } - var findPriv = {resource: {db:admindb.getName(), collection:""}, - actions:['find']}; + var findPriv = { + resource: {db: admindb.getName(), collection: ""}, + actions: ['find'] + }; - admindb.createRole({role:"FindInDB", - roles:[], - privileges:[findPriv]}); - admindb.createRole({role:"FindOnSysRes", - roles:[], - privileges:sysPrivs}); + admindb.createRole({role: "FindInDB", roles: [], privileges: [findPriv]}); + admindb.createRole({role: "FindOnSysRes", roles: [], privileges: sysPrivs}); - - admindb.createUser({user:"sysUser", pwd:"pwd", roles:["FindOnSysRes"]}); - admindb.createUser({user:"user", pwd:"pwd", roles:["FindInDB"]}); + admindb.createUser({user: "sysUser", pwd: "pwd", roles: ["FindOnSysRes"]}); + admindb.createUser({user: "user", pwd: "pwd", roles: ["FindInDB"]}); // Verify the find on all collections exludes system collections - assert.eq(1,admindb.auth("user", "pwd")); + assert.eq(1, admindb.auth("user", "pwd")); - assert.doesNotThrow(function() {admindb.foo.findOne();}); + assert.doesNotThrow(function() { + admindb.foo.findOne(); + }); for (var i in sysCollections) { - assert.commandFailed(admindb.runCommand({count:sysCollections[i]})); + assert.commandFailed(admindb.runCommand({count: sysCollections[i]})); } // Verify that find on system collections gives find permissions - assert.eq(1,admindb.auth("sysUser", "pwd")); + assert.eq(1, admindb.auth("sysUser", "pwd")); - assert.throws(function() {admindb.foo.findOne();}); + assert.throws(function() { + admindb.foo.findOne(); + }); for (var i in sysCollections) { - assert.commandWorked(admindb.runCommand({count:sysCollections[i]})); + assert.commandWorked(admindb.runCommand({count: sysCollections[i]})); } admindb.logout(); } jsTest.log('Test standalone'); -var conn = MongoRunner.runMongod({ auth:'' }); +var conn = MongoRunner.runMongod({auth: ''}); runTest(conn.getDB("admin")); MongoRunner.stopMongod(conn.port); jsTest.log('Test sharding'); -var st = new ShardingTest({ shards:2, config:3, keyFile:'jstests/libs/key1' }); +var st = new ShardingTest({shards: 2, config: 3, keyFile: 'jstests/libs/key1'}); runTest(st.s.getDB("admin")); st.stop(); diff --git a/jstests/auth/commands_builtin_roles.js b/jstests/auth/commands_builtin_roles.js index a089278da6c..1d5f5f59756 100644 --- a/jstests/auth/commands_builtin_roles.js +++ b/jstests/auth/commands_builtin_roles.js @@ -52,30 +52,23 @@ function testProperAuthorization(conn, t, testcase, r) { if (testcase.roles[r.role]) { if (res.ok == 0 && res.code == authErrCode) { - out = "expected authorization success" + - " but received " + tojson(res) + - " on db " + testcase.runOnDb + - " with role " + r.key; - } - else if (res.ok == 0 && !testcase.expectFail && res.code != commandNotSupportedCode) { + out = "expected authorization success" + " but received " + tojson(res) + " on db " + + testcase.runOnDb + " with role " + r.key; + } else if (res.ok == 0 && !testcase.expectFail && res.code != commandNotSupportedCode) { // don't error if the test failed with code commandNotSupported since // some storage engines (e.g wiredTiger) don't support some commands (e.g. touch) - out = "command failed with " + tojson(res) + - " on db " + testcase.runOnDb + - " with role " + r.key; + out = "command failed with " + tojson(res) + " on db " + testcase.runOnDb + + " with role " + r.key; } // test can provide a function that will run if // the command completed successfully else if (testcase.onSuccess) { testcase.onSuccess(res); } - } - else { + } else { if (res.ok == 1 || (res.ok == 0 && res.code != authErrCode)) { - out = "expected authorization failure" + - " but received result " + tojson(res) + - " on db " + testcase.runOnDb + - " with role " + r.key; + out = "expected authorization failure" + " but received result " + tojson(res) + + " on db " + testcase.runOnDb + " with role " + r.key; } } @@ -105,11 +98,7 @@ function runOneTest(conn, t) { function createUsers(conn) { var adminDb = conn.getDB(adminDbName); - adminDb.createUser({ - user: "admin", - pwd: "password", - roles: ["__system"] - }); + adminDb.createUser({user: "admin", pwd: "password", roles: ["__system"]}); assert(adminDb.auth("admin", "password")); for (var i = 0; i < roles.length; i++) { @@ -138,15 +127,16 @@ function checkForNonExistentRoles() { break; } } - assert(roleExists, "Role " + role + " found in test: " + test.testname + - ", but doesn't exist in roles array"); + assert(roleExists, + "Role " + role + " found in test: " + test.testname + + ", but doesn't exist in roles array"); } } } -} +} var opts = { - auth:"", + auth: "", enableExperimentalStorageDetailsCmd: "" }; var impls = { @@ -162,12 +152,7 @@ authCommandsLib.runTests(conn, impls); MongoRunner.stopMongod(conn); // run all tests sharded -conn = new ShardingTest({ - shards: 2, - mongos: 1, - keyFile: "jstests/libs/key1", - other: { shardOptions: opts } -}); +conn = new ShardingTest( + {shards: 2, mongos: 1, keyFile: "jstests/libs/key1", other: {shardOptions: opts}}); authCommandsLib.runTests(conn, impls); conn.stop(); - diff --git a/jstests/auth/commands_user_defined_roles.js b/jstests/auth/commands_user_defined_roles.js index 1d567df7462..8a7402f033d 100644 --- a/jstests/auth/commands_user_defined_roles.js +++ b/jstests/auth/commands_user_defined_roles.js @@ -23,10 +23,8 @@ function testProperAuthorization(conn, t, testcase) { authCommandsLib.setup(conn, t, runOnDb); adminDb.auth("admin", "password"); - assert.commandWorked(adminDb.runCommand({ - updateRole: testRole, - privileges: testcase.privileges - })); + assert.commandWorked( + adminDb.runCommand({updateRole: testRole, privileges: testcase.privileges})); adminDb.logout(); assert(adminDb.auth(testUser, "password")); @@ -36,15 +34,11 @@ function testProperAuthorization(conn, t, testcase) { if (!testcase.expectFail && res.ok != 1 && res.code != commandNotSupportedCode) { // don't error if the test failed with code commandNotSupported since // some storage engines (e.g wiredTiger) don't support some commands (e.g. touch) - out = "command failed with " + tojson(res) + - " on db " + testcase.runOnDb + - " with privileges " + tojson(testcase.privileges); - } - else if (testcase.expectFail && res.code == authErrCode) { - out = "expected authorization success" + - " but received " + tojson(res) + - " on db " + testcase.runOnDb + - " with privileges " + tojson(testcase.privileges); + out = "command failed with " + tojson(res) + " on db " + testcase.runOnDb + + " with privileges " + tojson(testcase.privileges); + } else if (testcase.expectFail && res.code == authErrCode) { + out = "expected authorization success" + " but received " + tojson(res) + " on db " + + testcase.runOnDb + " with privileges " + tojson(testcase.privileges); } firstDb.logout(); @@ -62,10 +56,7 @@ function testInsufficientPrivileges(conn, t, testcase, privileges) { authCommandsLib.setup(conn, t, runOnDb); adminDb.auth("admin", "password"); - assert.commandWorked(adminDb.runCommand({ - updateRole: testRole, - privileges: privileges - })); + assert.commandWorked(adminDb.runCommand({updateRole: testRole, privileges: privileges})); adminDb.logout(); assert(adminDb.auth(testUser, "password")); @@ -73,9 +64,8 @@ function testInsufficientPrivileges(conn, t, testcase, privileges) { var res = runOnDb.runCommand(t.command); if (res.ok == 1 || res.code != authErrCode) { - out = "expected authorization failure " + - " but received " + tojson(res) + - " with privileges " + tojson(privileges); + out = "expected authorization failure " + " but received " + tojson(res) + + " with privileges " + tojson(privileges); } firstDb.logout(); @@ -105,15 +95,17 @@ function runOneTest(conn, t) { continue; } - if ((privileges.length == 1 && privileges[0].actions.length > 1) - || privileges.length > 1) { + if ((privileges.length == 1 && privileges[0].actions.length > 1) || privileges.length > 1) { for (var j = 0; j < privileges.length; j++) { var p = privileges[j]; var resource = p.resource; var actions = p.actions; for (var k = 0; k < actions.length; k++) { - var privDoc = { resource: resource, actions: [actions[k]] }; + var privDoc = { + resource: resource, + actions: [actions[k]] + }; msg = testInsufficientPrivileges(conn, t, testcase, [privDoc]); if (msg) { failures.push(t.testname + ": " + msg); @@ -154,30 +146,19 @@ function runOneTest(conn, t) { function createUsers(conn) { var adminDb = conn.getDB(adminDbName); var firstDb = conn.getDB(firstDbName); - adminDb.createUser({ - user: "admin", - pwd: "password", - roles: ["__system"] - }); + adminDb.createUser({user: "admin", pwd: "password", roles: ["__system"]}); assert(adminDb.auth("admin", "password")); - assert.commandWorked(adminDb.runCommand({ - createRole: testRole, - privileges: [ ], - roles: [ ] - })); - assert.commandWorked(adminDb.runCommand({ - createUser: testUser, - pwd: "password", - roles: [ { role: testRole, db: adminDbName } ] - })); + assert.commandWorked(adminDb.runCommand({createRole: testRole, privileges: [], roles: []})); + assert.commandWorked(adminDb.runCommand( + {createUser: testUser, pwd: "password", roles: [{role: testRole, db: adminDbName}]})); adminDb.logout(); } var opts = { - auth:"", + auth: "", enableExperimentalStorageDetailsCmd: "" }; var impls = { @@ -191,12 +172,7 @@ authCommandsLib.runTests(conn, impls); MongoRunner.stopMongod(conn); // run all tests sharded -conn = new ShardingTest({ - shards: 2, - mongos: 1, - keyFile: "jstests/libs/key1", - other: { shardOptions: opts } -}); +conn = new ShardingTest( + {shards: 2, mongos: 1, keyFile: "jstests/libs/key1", other: {shardOptions: opts}}); authCommandsLib.runTests(conn, impls); conn.stop(); - diff --git a/jstests/auth/copyauth.js b/jstests/auth/copyauth.js index 4fb74101ad5..a8083df400e 100644 --- a/jstests/auth/copyauth.js +++ b/jstests/auth/copyauth.js @@ -1,8 +1,8 @@ // Test copyDatabase command with various combinations of authed/unauthed and single node/replica // set source and dest. -TestData.authMechanism = "SCRAM-SHA-1"; // SERVER-11428 -DB.prototype._defaultAuthenticationMechanism = "SCRAM-SHA-1"; // SERVER-11428 +TestData.authMechanism = "SCRAM-SHA-1"; // SERVER-11428 +DB.prototype._defaultAuthenticationMechanism = "SCRAM-SHA-1"; // SERVER-11428 var baseName = "jstests_clone_copyauth"; @@ -27,13 +27,12 @@ var baseName = "jstests_clone_copyauth"; * stop() - stop and cleanup whatever nodes the helper spawned when it was created. */ function ClusterSpawnHelper(clusterType, startWithAuth) { - if (clusterType === "sharded") { var shardingTestConfig = { - name : baseName + "_source", - mongos : 1, - shards : 1, - config : 1 + name: baseName + "_source", + mongos: 1, + shards: 1, + config: 1 }; if (startWithAuth) { shardingTestConfig.auth = ""; @@ -42,9 +41,12 @@ function ClusterSpawnHelper(clusterType, startWithAuth) { var shardingTest = new ShardingTest(shardingTestConfig); this.conn = shardingTest.s; this.connString = this.conn.host; - } - else if (clusterType === "repl") { - var replSetTestConfig = { name: baseName + "_source", nodes: 3, nodeOptions: {} }; + } else if (clusterType === "repl") { + var replSetTestConfig = { + name: baseName + "_source", + nodes: 3, + nodeOptions: {} + }; if (startWithAuth) { replSetTestConfig.nodeOptions.auth = ""; replSetTestConfig.nodeOptions.keyFile = "jstests/libs/key1"; @@ -55,15 +57,15 @@ function ClusterSpawnHelper(clusterType, startWithAuth) { if (startWithAuth) { authutil.asCluster(replSetTest.nodes, replSetTestConfig.nodeOptions.keyFile, - function() { replSetTest.awaitReplication(); }); - } - else { + function() { + replSetTest.awaitReplication(); + }); + } else { replSetTest.awaitReplication(); } this.conn = replSetTest.getPrimary(); this.connString = replSetTest.getURL(); - } - else { + } else { var singleNodeConfig = {}; if (startWithAuth) { singleNodeConfig.auth = ""; @@ -72,14 +74,12 @@ function ClusterSpawnHelper(clusterType, startWithAuth) { this.connString = this.conn.host; } - this.stop = function () { + this.stop = function() { if (clusterType === "sharded") { shardingTest.stop(); - } - else if (clusterType === "repl") { + } else if (clusterType === "repl") { replSetTest.stopSet(); - } - else { + } else { MongoRunner.stopMongod(this.conn.port); } }; @@ -101,16 +101,9 @@ function ClusterSpawnHelper(clusterType, startWithAuth) { * } */ function copydbBetweenClustersTest(configObj) { - - - // First sanity check the arguments in our configObj - var requiredKeys = [ - 'sourceClusterType', - 'isSourceUsingAuth', - 'targetClusterType', - 'isTargetUsingAuth' - ]; + var requiredKeys = + ['sourceClusterType', 'isSourceUsingAuth', 'targetClusterType', 'isTargetUsingAuth']; var i; for (i = 0; i < requiredKeys.length; i++) { @@ -118,118 +111,111 @@ function copydbBetweenClustersTest(configObj) { "Missing required key: " + requiredKeys[i] + " in config object"); } - - // 1. Get a connection to the source database, insert data and setup auth if applicable source = new ClusterSpawnHelper(configObj.sourceClusterType, configObj.isSourceUsingAuth); if (configObj.isSourceUsingAuth) { // Create a super user so we can create a regular user and not be locked out afterwards - source.conn.getDB("admin").createUser({ user: "sourceSuperUser", pwd: "sourceSuperUser", - roles: [ "root" ] }); + source.conn.getDB("admin") + .createUser({user: "sourceSuperUser", pwd: "sourceSuperUser", roles: ["root"]}); source.conn.getDB("admin").auth("sourceSuperUser", "sourceSuperUser"); - source.conn.getDB(baseName)[baseName].save({i:1}); + source.conn.getDB(baseName)[baseName].save({i: 1}); assert.eq(1, source.conn.getDB(baseName)[baseName].count()); assert.eq(1, source.conn.getDB(baseName)[baseName].findOne().i); // Insert a document and create a regular user that we will use for the target // authenticating with the source - source.conn.getDB(baseName).createUser({ user: "foo", pwd: "bar", - roles: [ "dbOwner" ] }); + source.conn.getDB(baseName).createUser({user: "foo", pwd: "bar", roles: ["dbOwner"]}); source.conn.getDB("admin").logout(); - assert.throws(function() { source.conn.getDB(baseName)[baseName].findOne(); }); + assert.throws(function() { + source.conn.getDB(baseName)[baseName].findOne(); + }); } else { - source.conn.getDB(baseName)[baseName].save({i:1}); + source.conn.getDB(baseName)[baseName].save({i: 1}); assert.eq(1, source.conn.getDB(baseName)[baseName].count()); assert.eq(1, source.conn.getDB(baseName)[baseName].findOne().i); } - - // 2. Get a connection to the target database, and set up auth if necessary target = new ClusterSpawnHelper(configObj.targetClusterType, configObj.isTargetUsingAuth); if (configObj.isTargetUsingAuth) { - target.conn.getDB("admin").createUser({ user: "targetSuperUser", pwd: "targetSuperUser", - roles: [ "root" ] }); - assert.throws(function() { target.conn.getDB(baseName)[baseName].findOne(); }); + target.conn.getDB("admin") + .createUser({user: "targetSuperUser", pwd: "targetSuperUser", roles: ["root"]}); + assert.throws(function() { + target.conn.getDB(baseName)[baseName].findOne(); + }); target.conn.getDB("admin").auth("targetSuperUser", "targetSuperUser"); } - - // 3. Run the copydb command target.conn.getDB(baseName).dropDatabase(); assert.eq(0, target.conn.getDB(baseName)[baseName].count()); if (configObj.isSourceUsingAuth) { // We only need to pass username and password if the target has to send authentication // information to the source cluster - assert.commandWorked(target.conn.getDB(baseName).copyDatabase(baseName, baseName, - source.connString, - "foo", "bar")); - } - else { + assert.commandWorked(target.conn.getDB(baseName).copyDatabase( + baseName, baseName, source.connString, "foo", "bar")); + } else { // We are copying from a cluster with no auth - assert.commandWorked(target.conn.getDB(baseName).copyDatabase(baseName, baseName, - source.connString)); + assert.commandWorked( + target.conn.getDB(baseName).copyDatabase(baseName, baseName, source.connString)); } assert.eq(1, target.conn.getDB(baseName)[baseName].count()); assert.eq(1, target.conn.getDB(baseName)[baseName].findOne().i); - - // 4. Do any necessary cleanup source.stop(); target.stop(); } (function() { -"use strict"; - -var sourceClusterTypeValues = [ "single", "repl", "sharded" ]; -var isSourceUsingAuthValues = [ true, false ]; -var targetClusterTypeValues = [ "single", "repl", "sharded" ]; -var isTargetUsingAuthValues = [ true, false ]; -for (var i = 0; i < sourceClusterTypeValues.length; i++) { - for (var j = 0; j < isSourceUsingAuthValues.length; j++) { - for (var k = 0; k < targetClusterTypeValues.length; k++) { - for (var l = 0; l < isTargetUsingAuthValues.length; l++) { - if (sourceClusterTypeValues[i] === "sharded" && - targetClusterTypeValues[k] === "sharded") { - // SERVER-13112 - continue; - } - if (sourceClusterTypeValues[i] === "repl" && - targetClusterTypeValues[k] === "repl") { - // SERVER-13077 - continue; + "use strict"; + + var sourceClusterTypeValues = ["single", "repl", "sharded"]; + var isSourceUsingAuthValues = [true, false]; + var targetClusterTypeValues = ["single", "repl", "sharded"]; + var isTargetUsingAuthValues = [true, false]; + for (var i = 0; i < sourceClusterTypeValues.length; i++) { + for (var j = 0; j < isSourceUsingAuthValues.length; j++) { + for (var k = 0; k < targetClusterTypeValues.length; k++) { + for (var l = 0; l < isTargetUsingAuthValues.length; l++) { + if (sourceClusterTypeValues[i] === "sharded" && + targetClusterTypeValues[k] === "sharded") { + // SERVER-13112 + continue; + } + if (sourceClusterTypeValues[i] === "repl" && + targetClusterTypeValues[k] === "repl") { + // SERVER-13077 + continue; + } + if (isSourceUsingAuthValues[j] === true && + targetClusterTypeValues[k] === "sharded") { + // SERVER-6427 + continue; + } + if (sourceClusterTypeValues[i] === "repl" && + isSourceUsingAuthValues[j] === false && + targetClusterTypeValues[k] === "sharded" && + isTargetUsingAuthValues[l] == true) { + // SERVER-18103 + continue; + } + var testCase = { + 'sourceClusterType': sourceClusterTypeValues[i], + 'isSourceUsingAuth': isSourceUsingAuthValues[j], + 'targetClusterType': targetClusterTypeValues[k], + 'isTargetUsingAuth': isTargetUsingAuthValues[l] + }; + print("Running copydb with auth test:"); + printjson(testCase); + copydbBetweenClustersTest(testCase); } - if (isSourceUsingAuthValues[j] === true && - targetClusterTypeValues[k] === "sharded") { - // SERVER-6427 - continue; - } - if (sourceClusterTypeValues[i] === "repl" && - isSourceUsingAuthValues[j] === false && - targetClusterTypeValues[k] === "sharded" && - isTargetUsingAuthValues[l] == true) { - // SERVER-18103 - continue; - } - var testCase = { - 'sourceClusterType' : sourceClusterTypeValues[i], - 'isSourceUsingAuth' : isSourceUsingAuthValues[j], - 'targetClusterType' : targetClusterTypeValues[k], - 'isTargetUsingAuth' : isTargetUsingAuthValues[l] - }; - print("Running copydb with auth test:"); - printjson(testCase); - copydbBetweenClustersTest(testCase); } } } -} }()); print(baseName + " success!"); diff --git a/jstests/auth/copyauth2.js b/jstests/auth/copyauth2.js index 852ba40e641..f47bfcba8ad 100644 --- a/jstests/auth/copyauth2.js +++ b/jstests/auth/copyauth2.js @@ -1,26 +1,25 @@ // Basic test that copydb works with auth enabled when copying within the same cluster function runTest(a, b) { - a.createUser({user: "chevy", pwd: "chase", roles: ["read", {role:'readWrite', db: b._name}]}); - a.foo.insert({a:1}); - b.getSiblingDB( "admin").logout(); + a.createUser({user: "chevy", pwd: "chase", roles: ["read", {role: 'readWrite', db: b._name}]}); + a.foo.insert({a: 1}); + b.getSiblingDB("admin").logout(); a.auth("chevy", "chase"); - assert.eq( 1 , a.foo.count() , "A" ); - assert.eq( 0 , b.foo.count() , "B" ); + assert.eq(1, a.foo.count(), "A"); + assert.eq(0, b.foo.count(), "B"); - a.copyDatabase(a._name , b._name); - assert.eq( 1 , a.foo.count() , "C" ); - assert.eq( 1 , b.foo.count() , "D" ); + a.copyDatabase(a._name, b._name); + assert.eq(1, a.foo.count(), "C"); + assert.eq(1, b.foo.count(), "D"); } - // run all tests standalone -var conn = MongoRunner.runMongod({auth:""}); -var a = conn.getDB( "copydb2-test-a" ); -var b = conn.getDB( "copydb2-test-b" ); -var adminDB = conn.getDB( "admin" ); +var conn = MongoRunner.runMongod({auth: ""}); +var a = conn.getDB("copydb2-test-a"); +var b = conn.getDB("copydb2-test-b"); +var adminDB = conn.getDB("admin"); adminDB.createUser({user: "root", pwd: "root", roles: ["root"]}); adminDB.auth("root", "root"); runTest(a, b); diff --git a/jstests/auth/copyauth_between_shards.js b/jstests/auth/copyauth_between_shards.js index cd95c9e1508..219d38c7f0f 100644 --- a/jstests/auth/copyauth_between_shards.js +++ b/jstests/auth/copyauth_between_shards.js @@ -4,9 +4,11 @@ var baseName = "jstests_clone_copyauth_between_shards"; function copydbWithinShardedCluster(useReplSets, passCredentials, useAuth) { - var clusterConfig = {shards : 1, - mongos : 1, - config : 1 }; + var clusterConfig = { + shards: 1, + mongos: 1, + config: 1 + }; if (useAuth) { clusterConfig.auth = ""; @@ -25,7 +27,9 @@ function copydbWithinShardedCluster(useReplSets, passCredentials, useAuth) { if (useAuth) { mongos.getDB("admin").createUser({user: "super", pwd: "super", roles: ["root"]}); - assert.throws(function() { mongos.getDB("test1")["test1"].findOne(); }); + assert.throws(function() { + mongos.getDB("test1")["test1"].findOne(); + }); mongos.getDB("admin").auth("super", "super"); } @@ -36,9 +40,9 @@ function copydbWithinShardedCluster(useReplSets, passCredentials, useAuth) { // The copyDatabase command acts differently depending on whether we pass username and password if (passCredentials) { - var result = mongos.getDB('admin').copyDatabase('test1', 'test2', undefined, "super", "super"); - } - else { + var result = + mongos.getDB('admin').copyDatabase('test1', 'test2', undefined, "super", "super"); + } else { var result = mongos.getDB('admin').copyDatabase('test1', 'test2'); } printjson(result); @@ -49,10 +53,10 @@ function copydbWithinShardedCluster(useReplSets, passCredentials, useAuth) { } // SERVER-13080 -//copydbWithinShardedCluster(true, true, true); -//copydbWithinShardedCluster(false, true, true); -//copydbWithinShardedCluster(true, false, true); -//copydbWithinShardedCluster(false, false, true); +// copydbWithinShardedCluster(true, true, true); +// copydbWithinShardedCluster(false, true, true); +// copydbWithinShardedCluster(true, false, true); +// copydbWithinShardedCluster(false, false, true); copydbWithinShardedCluster(true, false, false); copydbWithinShardedCluster(false, false, false); diff --git a/jstests/auth/db_multiple_login.js b/jstests/auth/db_multiple_login.js index ed48bfb4e98..4a16efdf0f6 100644 --- a/jstests/auth/db_multiple_login.js +++ b/jstests/auth/db_multiple_login.js @@ -3,26 +3,28 @@ // authentication. // // Regression test for SERVER-8144. -var conn = MongoRunner.runMongod({ auth: "", smallfiles: "" }); +var conn = MongoRunner.runMongod({auth: "", smallfiles: ""}); var admin = conn.getDB("admin"); var test = conn.getDB("test"); -admin.createUser({user:'admin', pwd: 'a', roles: jsTest.adminUserRoles}); +admin.createUser({user: 'admin', pwd: 'a', roles: jsTest.adminUserRoles}); assert(admin.auth('admin', 'a')); -test.createUser({user: 'reader', pwd: 'a', roles: [ "read" ]}); -test.createUser({user: 'writer', pwd: 'a', roles: [ "readWrite" ]}); +test.createUser({user: 'reader', pwd: 'a', roles: ["read"]}); +test.createUser({user: 'writer', pwd: 'a', roles: ["readWrite"]}); admin.logout(); // Nothing logged in, can neither read nor write. -assert.writeError(test.docs.insert({ value: 0 })); -assert.throws(function() { test.foo.findOne(); }); +assert.writeError(test.docs.insert({value: 0})); +assert.throws(function() { + test.foo.findOne(); +}); // Writer logged in, can read and write. test.auth('writer', 'a'); -assert.writeOK(test.docs.insert({ value: 1 })); +assert.writeOK(test.docs.insert({value: 1})); test.foo.findOne(); // Reader logged in, replacing writer, can only read. test.auth('reader', 'a'); -assert.writeError(test.docs.insert({ value: 2 })); +assert.writeError(test.docs.insert({value: 2})); test.foo.findOne(); diff --git a/jstests/auth/disable_localhost_bypass.js b/jstests/auth/disable_localhost_bypass.js index 9d29f5ae9fe..a33d582cf15 100644 --- a/jstests/auth/disable_localhost_bypass.js +++ b/jstests/auth/disable_localhost_bypass.js @@ -1,24 +1,26 @@ -var conn1 = MongoRunner.runMongod({ auth: "", - smallfiles: "", - setParameter: "enableLocalhostAuthBypass=true"}); -var conn2 = MongoRunner.runMongod({ auth: "", - smallfiles: "", - setParameter: "enableLocalhostAuthBypass=false"}); +var conn1 = MongoRunner.runMongod( + {auth: "", smallfiles: "", setParameter: "enableLocalhostAuthBypass=true"}); +var conn2 = MongoRunner.runMongod( + {auth: "", smallfiles: "", setParameter: "enableLocalhostAuthBypass=false"}); // Should fail because of localhost exception narrowed (SERVER-12621). -assert.writeError(conn1.getDB("test").foo.insert({a:1})); -assert.throws(function() { conn2.getDB("test").foo.findOne(); }); +assert.writeError(conn1.getDB("test").foo.insert({a: 1})); +assert.throws(function() { + conn2.getDB("test").foo.findOne(); +}); // Should succeed due to localhost exception. conn1.getDB("admin").createUser({user: "root", pwd: "pass", roles: ["root"]}); conn1.getDB("admin").auth("root", "pass"); -conn1.getDB("test").foo.insert({a:1}); +conn1.getDB("test").foo.insert({a: 1}); conn1.getDB("admin").dropAllUsers(); conn1.getDB("admin").logout(); -assert.throws(function() { conn2.getDB("test").foo.findOne(); }); +assert.throws(function() { + conn2.getDB("test").foo.findOne(); +}); // Should fail since localhost exception is disabled assert.throws(function() { diff --git a/jstests/auth/explain_auth.js b/jstests/auth/explain_auth.js index a718ddf8653..70570324260 100644 --- a/jstests/auth/explain_auth.js +++ b/jstests/auth/explain_auth.js @@ -34,8 +34,7 @@ function testExplainAuth(authSpec) { function assertCmdResult(result, expectSuccess) { if (expectSuccess) { assert.commandWorked(result); - } - else { + } else { assert.commandFailedWithCode(result, 13); } } @@ -49,58 +48,36 @@ function testExplainAuth(authSpec) { assertCmdResult(cmdResult, authSpec.count); // .group() - cmdResult = db.runCommand({ - explain: { - group: { - ns: coll.getName(), - key: "a", - $reduce: function() { }, - initial: { } - } - } - }); + cmdResult = db.runCommand( + {explain: {group: {ns: coll.getName(), key: "a", $reduce: function() {}, initial: {}}}}); assertCmdResult(cmdResult, authSpec.group); // .remove() - cmdResult = db.runCommand({ - explain: { - delete: coll.getName(), - deletes: [ {q: {a: 1}, limit: 1} ] - } - }); + cmdResult = + db.runCommand({explain: {delete: coll.getName(), deletes: [{q: {a: 1}, limit: 1}]}}); assertCmdResult(cmdResult, authSpec.remove); // .update() - cmdResult = db.runCommand({ - explain: { - update: coll.getName(), - updates: [ {q: {a: 1}, u: {$set: {b: 1}}} ] - } - }); + cmdResult = db.runCommand( + {explain: {update: coll.getName(), updates: [{q: {a: 1}, u: {$set: {b: 1}}}]}}); assertCmdResult(cmdResult, authSpec.update); } // Create some user-defined roles which we will grant to the users below. db.createRole({ role: "findOnly", - privileges: [ - {resource: {db: db.getName(), collection: coll.getName()}, actions: ["find"]} - ], - roles: [ ] + privileges: [{resource: {db: db.getName(), collection: coll.getName()}, actions: ["find"]}], + roles: [] }); db.createRole({ role: "updateOnly", - privileges: [ - {resource: {db: db.getName(), collection: coll.getName()}, actions: ["update"]} - ], - roles: [ ] + privileges: [{resource: {db: db.getName(), collection: coll.getName()}, actions: ["update"]}], + roles: [] }); db.createRole({ role: "removeOnly", - privileges: [ - {resource: {db: db.getName(), collection: coll.getName()}, actions: ["remove"]} - ], - roles: [ ] + privileges: [{resource: {db: db.getName(), collection: coll.getName()}, actions: ["remove"]}], + roles: [] }); // Create three users: @@ -116,31 +93,13 @@ admin.logout(); // The "find" action allows explain of read operations. db.auth("findOnly", "pwd"); -testExplainAuth({ - find: true, - count: true, - group: true, - remove: false, - update: false -}); +testExplainAuth({find: true, count: true, group: true, remove: false, update: false}); db.logout(); db.auth("updateOnly", "pwd"); -testExplainAuth({ - find: false, - count: false, - group: false, - remove: false, - update: true -}); +testExplainAuth({find: false, count: false, group: false, remove: false, update: true}); db.logout(); db.auth("removeOnly", "pwd"); -testExplainAuth({ - find: false, - count: false, - group: false, - remove: true, - update: false -}); +testExplainAuth({find: false, count: false, group: false, remove: true, update: false}); db.logout(); diff --git a/jstests/auth/indexSystemUsers.js b/jstests/auth/indexSystemUsers.js index 056013f18cf..ef7187dfe46 100644 --- a/jstests/auth/indexSystemUsers.js +++ b/jstests/auth/indexSystemUsers.js @@ -1,34 +1,38 @@ // SERVER-8802: Test that you can't build indexes on system.users and use that to drop users with // dropDups. -var conn = MongoRunner.runMongod({auth : ""}); +var conn = MongoRunner.runMongod({auth: ""}); var adminDB = conn.getDB("admin"); var testDB = conn.getDB("test"); -adminDB.createUser({user:'admin', pwd:'x', roles:['userAdminAnyDatabase']}); -adminDB.auth('admin','x'); -adminDB.createUser({user:'mallory', pwd:'x', roles:['readWriteAnyDatabase']}); -testDB.createUser({user:'user', pwd:'x', roles:['read']}); +adminDB.createUser({user: 'admin', pwd: 'x', roles: ['userAdminAnyDatabase']}); +adminDB.auth('admin', 'x'); +adminDB.createUser({user: 'mallory', pwd: 'x', roles: ['readWriteAnyDatabase']}); +testDB.createUser({user: 'user', pwd: 'x', roles: ['read']}); assert.eq(3, adminDB.system.users.count()); adminDB.logout(); adminDB.auth('mallory', 'x'); -var res = adminDB.system.users.createIndex({ haxx: 1 }, { unique: true, dropDups: true }); +var res = adminDB.system.users.createIndex({haxx: 1}, {unique: true, dropDups: true}); assert(!res.ok); -assert.eq(13, res.code); // unauthorized -assert.writeError(adminDB.exploit.system.indexes.insert({ ns: "admin.system.users", - key: { haxx: 1.0 }, - name: "haxx_1", - unique: true, - dropDups: true })); +assert.eq(13, res.code); // unauthorized +assert.writeError(adminDB.exploit.system.indexes.insert( + {ns: "admin.system.users", key: {haxx: 1.0}, name: "haxx_1", unique: true, dropDups: true})); // Make sure that no indexes were built. -var collectionInfosCursor = adminDB.runCommand("listCollections", { filter: - {$and : [{name : /^admin\.system\.users\.\$/}, - {name : {$ne : "admin.system.users.$_id_"}}, - {name : {$ne : "admin.system.users.$user_1_db_1"}} ]}}); +var collectionInfosCursor = + adminDB.runCommand("listCollections", + { + filter: { + $and: [ + {name: /^admin\.system\.users\.\$/}, + {name: {$ne: "admin.system.users.$_id_"}}, + {name: {$ne: "admin.system.users.$user_1_db_1"}} + ] + } + }); assert.eq([], new DBCommandCursor(adminDB.getMongo(), collectionInfosCursor).toArray()); adminDB.logout(); -adminDB.auth('admin','x'); +adminDB.auth('admin', 'x'); // Make sure that no users were actually dropped assert.eq(3, adminDB.system.users.count()); diff --git a/jstests/auth/iteration_count_control.js b/jstests/auth/iteration_count_control.js index b0a790c43c6..0d710298ff4 100644 --- a/jstests/auth/iteration_count_control.js +++ b/jstests/auth/iteration_count_control.js @@ -3,32 +3,27 @@ load('./jstests/multiVersion/libs/auth_helpers.js'); var conn = MongoRunner.runMongod({auth: ''}); -var testIterationCountControl = function(){ +var testIterationCountControl = function() { var adminDB = conn.getDB('admin'); - adminDB.createUser({user: 'user1', pwd: 'pass', - roles: jsTest.adminUserRoles}); + adminDB.createUser({user: 'user1', pwd: 'pass', roles: jsTest.adminUserRoles}); assert(adminDB.auth({user: 'user1', pwd: 'pass'})); var userDoc = getUserDoc(adminDB, 'user1'); assert.eq(10000, userDoc.credentials['SCRAM-SHA-1'].iterationCount); // Changing iterationCount should not affect existing users. - assert.commandWorked(adminDB.runCommand({setParameter: 1, - scramIterationCount: 5000})); + assert.commandWorked(adminDB.runCommand({setParameter: 1, scramIterationCount: 5000})); userDoc = getUserDoc(adminDB, 'user1'); assert.eq(10000, userDoc.credentials['SCRAM-SHA-1'].iterationCount); // But it should take effect when the user's password is changed. - adminDB.updateUser('user1', {pwd: 'pass', - roles: jsTest.adminUserRoles}); + adminDB.updateUser('user1', {pwd: 'pass', roles: jsTest.adminUserRoles}); userDoc = getUserDoc(adminDB, 'user1'); assert.eq(5000, userDoc.credentials['SCRAM-SHA-1'].iterationCount); // Test invalid values for iterationCount. 5000 is the minimum value. - assert.commandFailed(adminDB.runCommand({setParameter: 1, - scramIterationCount: 4999})); - assert.commandFailed(adminDB.runCommand({setParameter: 1, - scramIterationCount: -5000})); + assert.commandFailed(adminDB.runCommand({setParameter: 1, scramIterationCount: 4999})); + assert.commandFailed(adminDB.runCommand({setParameter: 1, scramIterationCount: -5000})); }; testIterationCountControl(); diff --git a/jstests/auth/js_scope_leak.js b/jstests/auth/js_scope_leak.js index 57e0b112937..f1d5d192876 100644 --- a/jstests/auth/js_scope_leak.js +++ b/jstests/auth/js_scope_leak.js @@ -7,23 +7,24 @@ // // These transitions are tested for dbEval, $where, MapReduce and $group -var conn = MongoRunner.runMongod({ smallfiles: ""}); +var conn = MongoRunner.runMongod({smallfiles: ""}); var test = conn.getDB("test"); // insert a single document and add two test users -test.foo.insert({a:1}); +test.foo.insert({a: 1}); assert.eq(1, test.foo.findOne().a); -test.createUser({user:'a', pwd: 'a', roles: jsTest.basicUserRoles}); -test.createUser({user:'b', pwd: 'b', roles: jsTest.basicUserRoles}); +test.createUser({user: 'a', pwd: 'a', roles: jsTest.basicUserRoles}); +test.createUser({user: 'b', pwd: 'b', roles: jsTest.basicUserRoles}); function missingOrEquals(string) { - return 'function() { ' - + 'var global = function(){return this;}.call();' - // Uncomment the next line when debugging. - // + 'print(global.hasOwnProperty("someGlobal") ? someGlobal : "MISSING" );' - + 'return !global.hasOwnProperty("someGlobal")' - + ' || someGlobal == unescape("' + escape(string) + '");' - +'}()'; + return 'function() { ' + + 'var global = function(){return this;}.call();' + // Uncomment the next line when debugging. + // + 'print(global.hasOwnProperty("someGlobal") ? someGlobal : "MISSING" );' + + + 'return !global.hasOwnProperty("someGlobal")' + + ' || someGlobal == unescape("' + escape(string) + '");' + + '}()'; } function testDbEval() { @@ -50,20 +51,19 @@ testDbEval(); // test $where function testWhere() { // set the global variable 'someGlobal' before authenticating - test.foo.findOne({$where:'someGlobal = "noUsers";'}); + test.foo.findOne({$where: 'someGlobal = "noUsers";'}); // test new user auth causes scope to be cleared test.auth('a', 'a'); - assert.eq(1, - test.foo.count({$where: 'return ' + missingOrEquals('a')}), - "$where: Auth user 'a"); + assert.eq( + 1, test.foo.count({$where: 'return ' + missingOrEquals('a')}), "$where: Auth user 'a"); // test auth as another user causes scope to be cleared - test.foo.findOne({$where:'someGlobal = "a";'}); + test.foo.findOne({$where: 'someGlobal = "a";'}); test.auth('b', 'b'); assert(test.foo.count({$where: 'return ' + missingOrEquals('a&b')}), "$where: Auth user 'b'"); // test user logout causes scope to be cleared - test.foo.findOne({$where:'someGlobal = "a&b";'}); + test.foo.findOne({$where: 'someGlobal = "a&b";'}); test.logout(); assert(test.foo.count({$where: 'return ' + missingOrEquals('noUsers')}), "$where: log out"); } @@ -71,14 +71,18 @@ testWhere(); testWhere(); function testMapReduce() { - var mapSet = function(string) { return Function('someGlobal = "' + string + '"'); }; - var mapGet = function(string) { return Function('assert(' + missingOrEquals(string) +')'); }; - var reduce = function(k, v) { }; + var mapSet = function(string) { + return Function('someGlobal = "' + string + '"'); + }; + var mapGet = function(string) { + return Function('assert(' + missingOrEquals(string) + ')'); + }; + var reduce = function(k, v) {}; var setGlobalInMap = function(string) { - test.foo.mapReduce(mapSet(string), reduce, {out:{inline:1}}); + test.foo.mapReduce(mapSet(string), reduce, {out: {inline: 1}}); }; var getGlobalFromMap = function(string) { - test.foo.mapReduce(mapGet(string), reduce, {out:{inline:1}}); + test.foo.mapReduce(mapGet(string), reduce, {out: {inline: 1}}); }; // set the global variable 'someGlobal' before authenticating @@ -86,33 +90,41 @@ function testMapReduce() { // test new user auth causes scope to be cleared test.auth('a', 'a'); - assert.doesNotThrow(function() { getGlobalFromMap('a'); }, [], "M/R: Auth user 'a'"); + assert.doesNotThrow(function() { + getGlobalFromMap('a'); + }, [], "M/R: Auth user 'a'"); // test auth as another user causes scope to be cleared setGlobalInMap('a'); test.auth('b', 'b'); - assert.doesNotThrow(function() { getGlobalFromMap('a&b'); }, [], "M/R: Auth user 'b'"); + assert.doesNotThrow(function() { + getGlobalFromMap('a&b'); + }, [], "M/R: Auth user 'b'"); // test user logout causes scope to be cleared setGlobalInMap('a&b'); test.logout(); - assert.doesNotThrow(function() { getGlobalFromMap('noUsers'); }, [], "M/R: Log out"); + assert.doesNotThrow(function() { + getGlobalFromMap('noUsers'); + }, [], "M/R: Log out"); } testMapReduce(); testMapReduce(); function testGroup() { var setGlobalInGroup = function(string) { - return test.foo.group({key: 'a', - reduce: Function('doc1', 'agg', - 'someGlobal = "' + string + '"'), - initial:{}}); + return test.foo.group({ + key: 'a', + reduce: Function('doc1', 'agg', 'someGlobal = "' + string + '"'), + initial: {} + }); }; var getGlobalFromGroup = function(string) { - return test.foo.group({key: 'a', - reduce: Function('doc1', 'agg', - 'assert(' + missingOrEquals(string) +')'), - initial:{}}); + return test.foo.group({ + key: 'a', + reduce: Function('doc1', 'agg', 'assert(' + missingOrEquals(string) + ')'), + initial: {} + }); }; // set the global variable 'someGlobal' before authenticating @@ -134,5 +146,3 @@ function testGroup() { } testGroup(); testGroup(); - - diff --git a/jstests/auth/lib/commands_lib.js b/jstests/auth/lib/commands_lib.js index 69339a7655a..bab46779cb6 100644 --- a/jstests/auth/lib/commands_lib.js +++ b/jstests/auth/lib/commands_lib.js @@ -197,2577 +197,2345 @@ var roles_all = { var authCommandsLib = { - - /************* TEST CASES ****************/ tests: [ { - testname: "addShard", - command: {addShard: "x"}, - skipStandalone: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {cluster: true}, actions: ["addShard"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - // Test that clusterManager role has permission to run addTagRange - testname: "addTagRange", - command: { // addTagRange is not a "real command"; it updates config.tags - update: "tags", - updates: [ { - q: {_id: { ns : "test.x" , min : 1 }}, - u: {_id: { ns : "test.x" , min : 1 }, - ns : "test.x"} - } ] }, - skipStandalone: true, - testcases: [ - { - runOnDb: "config", - roles: Object.extend({readWriteAnyDatabase: 1}, roles_clusterManager) - } - ] - }, - { - testname: "applyOps", - command: {applyOps: "x"}, - testcases: [ - { - runOnDb: adminDbName, - roles: {__system: 1}, - privileges: [ - { resource: {anyResource: true}, actions: ["anyAction"] } - ], - expectFail: true - }, - { - runOnDb: firstDbName, - roles: {__system: 1}, - privileges: [ - { resource: {anyResource: true}, actions: ["anyAction"] } - ], - expectFail: true - } - ] - }, - { - testname: "aggregate_readonly", - command: {aggregate: "foo", pipeline: []}, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_read, - privileges: [ - { resource: {db: firstDbName, collection: "foo"}, actions: ["find"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_readAny, - privileges: [ - { resource: {db: secondDbName, collection: "foo"}, actions: ["find"] } - ] - } - ] - }, - { - testname: "aggregate_explain", - command: {aggregate: "foo", explain: true, pipeline: [ {$match: {bar: 1}} ] }, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_read, - privileges: [ - { resource: {db: firstDbName, collection: "foo"}, actions: ["find"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_readAny, - privileges: [ - { resource: {db: secondDbName, collection: "foo"}, actions: ["find"] } - ] - } - ] - }, - { - testname: "aggregate_write", - command: {aggregate: "foo", pipeline: [ {$out: "foo_out"} ] }, - testcases: [ - { - runOnDb: firstDbName, - roles: { readWrite: 1, - readWriteAnyDatabase: 1, - dbOwner: 1, - root: 1, - __system: 1}, - privileges: [ - { resource: {db: firstDbName, collection: "foo"}, actions: ["find"] }, - { resource: {db: firstDbName, collection: "foo_out"}, actions: ["insert"] }, - { resource: {db: firstDbName, collection: "foo_out"}, actions: ["remove"] } - ] - }, - { - runOnDb: secondDbName, - roles: {readWriteAnyDatabase: 1, root: 1, __system: 1}, - privileges: [ - { resource: {db: secondDbName, collection: "foo"}, actions: ["find"] }, - { resource: {db: secondDbName, collection: "foo_out"}, actions: ["insert"] }, - { resource: {db: secondDbName, collection: "foo_out"}, actions: ["remove"] } - ] - } - ] - }, - { - testname: "aggregate_indexStats", - command: {aggregate: "foo", pipeline: [{$indexStats: {}}]}, - setup: function (db) { - db.createCollection("foo"); - }, - teardown: function (db) { - db.foo.drop(); - }, - testcases: [ - { - runOnDb: firstDbName, - roles: { - clusterMonitor: 1, - clusterAdmin: 1, - root: 1, - __system: 1 - }, - privileges: [ - {resource: {anyResource: true}, actions: ["indexStats"]} - ] - } - ] - }, - { - testname: "appendOplogNote", - command: {appendOplogNote: 1, data: {a: 1}}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: { - backup: 1, - clusterManager: 1, - clusterAdmin: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {cluster: true}, actions: ["appendOplogNote"] } - ], - expectFail: true, // because no replication enabled - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "authSchemaUpgrade", - command: {authSchemaUpgrade: 1}, - testcases: [ - { - runOnDb: adminDbName, - roles: { - userAdminAnyDatabase: 1, - root: 1, - __system: 1 + testname: "addShard", + command: {addShard: "x"}, + skipStandalone: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_clusterManager, + privileges: [{resource: {cluster: true}, actions: ["addShard"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + // Test that clusterManager role has permission to run addTagRange + testname: "addTagRange", + command: { + // addTagRange is not a "real command"; it updates config.tags + update: "tags", + updates: [{ + q: {_id: {ns: "test.x", min: 1}}, + u: {_id: {ns: "test.x", min: 1}, ns: "test.x"} + }] + }, + skipStandalone: true, + testcases: [{ + runOnDb: "config", + roles: Object.extend({readWriteAnyDatabase: 1}, roles_clusterManager) + }] + }, + { + testname: "applyOps", + command: {applyOps: "x"}, + testcases: [ + { + runOnDb: adminDbName, + roles: {__system: 1}, + privileges: [{resource: {anyResource: true}, actions: ["anyAction"]}], + expectFail: true + }, + { + runOnDb: firstDbName, + roles: {__system: 1}, + privileges: [{resource: {anyResource: true}, actions: ["anyAction"]}], + expectFail: true + } + ] + }, + { + testname: "aggregate_readonly", + command: {aggregate: "foo", pipeline: []}, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_read, + privileges: [{resource: {db: firstDbName, collection: "foo"}, actions: ["find"]}] + }, + { + runOnDb: secondDbName, + roles: roles_readAny, + privileges: + [{resource: {db: secondDbName, collection: "foo"}, actions: ["find"]}] + } + ] + }, + { + testname: "aggregate_explain", + command: {aggregate: "foo", explain: true, pipeline: [{$match: {bar: 1}}]}, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_read, + privileges: [{resource: {db: firstDbName, collection: "foo"}, actions: ["find"]}] + }, + { + runOnDb: secondDbName, + roles: roles_readAny, + privileges: + [{resource: {db: secondDbName, collection: "foo"}, actions: ["find"]}] + } + ] + }, + { + testname: "aggregate_write", + command: {aggregate: "foo", pipeline: [{$out: "foo_out"}]}, + testcases: [ + { + runOnDb: firstDbName, + roles: {readWrite: 1, readWriteAnyDatabase: 1, dbOwner: 1, root: 1, __system: 1}, + privileges: [ + {resource: {db: firstDbName, collection: "foo"}, actions: ["find"]}, + {resource: {db: firstDbName, collection: "foo_out"}, actions: ["insert"]}, + {resource: {db: firstDbName, collection: "foo_out"}, actions: ["remove"]} + ] + }, + { + runOnDb: secondDbName, + roles: {readWriteAnyDatabase: 1, root: 1, __system: 1}, + privileges: [ + {resource: {db: secondDbName, collection: "foo"}, actions: ["find"]}, + {resource: {db: secondDbName, collection: "foo_out"}, actions: ["insert"]}, + {resource: {db: secondDbName, collection: "foo_out"}, actions: ["remove"]} + ] + } + ] + }, + { + testname: "aggregate_indexStats", + command: {aggregate: "foo", pipeline: [{$indexStats: {}}]}, + setup: function(db) { + db.createCollection("foo"); + }, + teardown: function(db) { + db.foo.drop(); + }, + testcases: [{ + runOnDb: firstDbName, + roles: {clusterMonitor: 1, clusterAdmin: 1, root: 1, __system: 1}, + privileges: [{resource: {anyResource: true}, actions: ["indexStats"]}] + }] + }, + { + testname: "appendOplogNote", + command: {appendOplogNote: 1, data: {a: 1}}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: {backup: 1, clusterManager: 1, clusterAdmin: 1, root: 1, __system: 1}, + privileges: [{resource: {cluster: true}, actions: ["appendOplogNote"]}], + expectFail: true, // because no replication enabled + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "authSchemaUpgrade", + command: {authSchemaUpgrade: 1}, + testcases: [ + { + runOnDb: adminDbName, + roles: {userAdminAnyDatabase: 1, root: 1, __system: 1}, + privileges: [{resource: {cluster: true}, actions: ["authSchemaUpgrade"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "buildInfo", + command: {buildInfo: 1}, + testcases: [ + {runOnDb: firstDbName, roles: roles_all, privileges: []}, + {runOnDb: secondDbName, roles: roles_all, privileges: []} + ] + }, + { + testname: "checkShardingIndex_firstDb", + command: {checkShardingIndex: firstDbName + ".x", keyPattern: {_id: 1}}, + skipSharded: true, + testcases: [{ + runOnDb: firstDbName, + roles: roles_read, + privileges: [{resource: {db: firstDbName, collection: "x"}, actions: ["find"]}] + }] + }, + { + testname: "checkShardingIndex_secondDb", + command: {checkShardingIndex: secondDbName + ".x", keyPattern: {_id: 1}}, + skipSharded: true, + testcases: [{ + runOnDb: secondDbName, + roles: roles_readAny, + privileges: [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] + }] + }, + { + testname: "cleanupOrphaned", + command: {cleanupOrphaned: firstDbName + ".x"}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_clusterManager, + privileges: [{resource: {cluster: true}, actions: ["cleanupOrphaned"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "cloneCollection_1", + command: {cloneCollection: firstDbName + ".x"}, + skipSharded: true, + testcases: [{ + runOnDb: firstDbName, + roles: roles_write, + privileges: [{ + resource: {db: firstDbName, collection: "x"}, + actions: ["insert", "createIndex"] + }], + expectFail: true + }] + }, + { + testname: "cloneCollection_2", + command: {cloneCollection: secondDbName + ".x"}, + skipSharded: true, + testcases: [{ + runOnDb: secondDbName, + roles: {readWriteAnyDatabase: 1, restore: 1, root: 1, __system: 1}, + privileges: [{ + resource: {db: secondDbName, collection: "x"}, + actions: ["insert", "createIndex"] + }], + expectFail: true + }] + }, + { + testname: "cloneCollectionAsCapped", + command: {cloneCollectionAsCapped: "x", toCollection: "y", size: 1000}, + skipSharded: true, + setup: function(db) { + db.x.save({}); + }, + teardown: function(db) { + db.x.drop(); + db.y.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: {readWrite: 1, readWriteAnyDatabase: 1, dbOwner: 1, root: 1, __system: 1}, + privileges: [ + { + resource: {db: firstDbName, collection: "y"}, + actions: ["insert", "createIndex", "convertToCapped"] }, - privileges: [ - { resource: {cluster: true}, actions: ["authSchemaUpgrade"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "buildInfo", - command: {buildInfo: 1}, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_all, - privileges: [ ] - }, - { - runOnDb: secondDbName, - roles: roles_all, - privileges: [ ] - } - ] - }, - { - testname: "checkShardingIndex_firstDb", - command: {checkShardingIndex: firstDbName + ".x", keyPattern: {_id: 1} }, - skipSharded: true, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_read, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["find"] } - ] - } - ] - }, - { - testname: "checkShardingIndex_secondDb", - command: {checkShardingIndex: secondDbName + ".x", keyPattern: {_id: 1} }, - skipSharded: true, - testcases: [ - { - runOnDb: secondDbName, - roles: roles_readAny, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["find"] } - ] - } - ] - }, - { - testname: "cleanupOrphaned", - command: {cleanupOrphaned: firstDbName + ".x"}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {cluster: true}, actions: ["cleanupOrphaned"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "cloneCollection_1", - command: {cloneCollection: firstDbName + ".x"}, - skipSharded: true, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_write, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["insert", "createIndex"] } - ], - expectFail: true - } - ] - }, - { - testname: "cloneCollection_2", - command: {cloneCollection: secondDbName + ".x"}, - skipSharded: true, - testcases: [ - { - runOnDb: secondDbName, - roles: {readWriteAnyDatabase: 1, restore: 1, root: 1, __system: 1}, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["insert", "createIndex"] } - ], - expectFail: true - } - ] - }, - { - testname: "cloneCollectionAsCapped", - command: {cloneCollectionAsCapped: "x", toCollection: "y", size: 1000}, - skipSharded: true, - setup: function (db) { db.x.save( {} ); }, - teardown: function (db) { - db.x.drop(); - db.y.drop(); - }, - testcases: [ - { - runOnDb: firstDbName, - roles: { readWrite: 1, - readWriteAnyDatabase: 1, - dbOwner: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: firstDbName, collection: "y"}, actions: ["insert", "createIndex", "convertToCapped"] }, - { resource: {db: firstDbName, collection: "x"}, actions: ["find"] } - ] - }, - { - runOnDb: secondDbName, - roles: {readWriteAnyDatabase: 1, root: 1, __system: 1}, - privileges: [ - { resource: {db: secondDbName, collection: "y"}, actions: ["insert", "createIndex", "convertToCapped"] }, - { resource: {db: secondDbName, collection: "x"}, actions: ["find"] } - ] - } - ] - }, - { - testname: "collMod", - command: {collMod: "foo", usePowerOf2Sizes: true}, - setup: function (db) { db.foo.save( {} ); }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: Object.extend({restore: 1}, roles_dbAdmin), - privileges: [ - { resource: {db: firstDbName, collection: "foo"}, actions: ["collMod"] } - ] - }, - { - runOnDb: secondDbName, - roles: Object.extend({restore:1}, roles_dbAdminAny), - privileges: [ - { resource: {db: secondDbName, collection: "foo"}, actions: ["collMod"] } - ] - } - ] - }, - { - testname: "collStats", - command: {collStats: "bar", scale: 1}, - setup: function (db) { db.bar.save( {} ); }, - teardown: function (db) { db.dropDatabase(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: { - read: 1, - readAnyDatabase: 1, - readWrite: 1, - readWriteAnyDatabase: 1, - dbAdmin: 1, - dbAdminAnyDatabase: 1, - dbOwner: 1, - clusterMonitor: 1, - clusterAdmin: 1, - backup: 1, - root: 1, - __system: 1 + {resource: {db: firstDbName, collection: "x"}, actions: ["find"]} + ] + }, + { + runOnDb: secondDbName, + roles: {readWriteAnyDatabase: 1, root: 1, __system: 1}, + privileges: [ + { + resource: {db: secondDbName, collection: "y"}, + actions: ["insert", "createIndex", "convertToCapped"] }, - privileges: [ - { resource: {db: firstDbName, collection: "bar"}, actions: ["collStats"] } - ] - }, - { - runOnDb: secondDbName, - roles: { - readAnyDatabase: 1, - readWriteAnyDatabase: 1, - dbAdminAnyDatabase: 1, - clusterMonitor: 1, - clusterAdmin: 1, - backup: 1, - root: 1, - __system: 1 + {resource: {db: secondDbName, collection: "x"}, actions: ["find"]} + ] + } + ] + }, + { + testname: "collMod", + command: {collMod: "foo", usePowerOf2Sizes: true}, + setup: function(db) { + db.foo.save({}); + }, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: Object.extend({restore: 1}, roles_dbAdmin), + privileges: + [{resource: {db: firstDbName, collection: "foo"}, actions: ["collMod"]}] + }, + { + runOnDb: secondDbName, + roles: Object.extend({restore: 1}, roles_dbAdminAny), + privileges: + [{resource: {db: secondDbName, collection: "foo"}, actions: ["collMod"]}] + } + ] + }, + { + testname: "collStats", + command: {collStats: "bar", scale: 1}, + setup: function(db) { + db.bar.save({}); + }, + teardown: function(db) { + db.dropDatabase(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: { + read: 1, + readAnyDatabase: 1, + readWrite: 1, + readWriteAnyDatabase: 1, + dbAdmin: 1, + dbAdminAnyDatabase: 1, + dbOwner: 1, + clusterMonitor: 1, + clusterAdmin: 1, + backup: 1, + root: 1, + __system: 1 + }, + privileges: + [{resource: {db: firstDbName, collection: "bar"}, actions: ["collStats"]}] + }, + { + runOnDb: secondDbName, + roles: { + readAnyDatabase: 1, + readWriteAnyDatabase: 1, + dbAdminAnyDatabase: 1, + clusterMonitor: 1, + clusterAdmin: 1, + backup: 1, + root: 1, + __system: 1 + }, + privileges: + [{resource: {db: secondDbName, collection: "bar"}, actions: ["collStats"]}] + } + ] + }, + { + testname: "compact", + command: {compact: "foo"}, + skipSharded: true, + setup: function(db) { + db.foo.save({}); + }, + teardown: function(db) { + db.dropDatabase(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_dbAdmin, + privileges: + [{resource: {db: firstDbName, collection: "foo"}, actions: ["compact"]}] + }, + { + runOnDb: secondDbName, + roles: roles_dbAdminAny, + privileges: + [{resource: {db: secondDbName, collection: "foo"}, actions: ["compact"]}] + } + ] + }, + { + testname: "connectionStatus", + command: {connectionStatus: 1}, + testcases: [ + {runOnDb: firstDbName, roles: roles_all, privileges: []}, + {runOnDb: secondDbName, roles: roles_all, privileges: []} + ] + }, + { + testname: "connPoolStats", + command: {connPoolStats: 1}, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["connPoolStats"]}] + }, + { + runOnDb: secondDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["connPoolStats"]}] + } + ] + }, + { + testname: "connPoolSync", + command: {connPoolSync: 1}, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_hostManager, + privileges: [{resource: {cluster: true}, actions: ["connPoolSync"]}] + }, + { + runOnDb: secondDbName, + roles: roles_hostManager, + privileges: [{resource: {cluster: true}, actions: ["connPoolSync"]}] + } + ] + }, + { + testname: "convertToCapped", + command: {convertToCapped: "toCapped", size: 1000}, + setup: function(db) { + db.toCapped.save({}); + }, + teardown: function(db) { + db.toCapped.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_writeDbAdmin, + privileges: [{ + resource: {db: firstDbName, collection: "toCapped"}, + actions: ["convertToCapped"] + }] + }, + { + runOnDb: secondDbName, + roles: roles_writeDbAdminAny, + privileges: [{ + resource: {db: secondDbName, collection: "toCapped"}, + actions: ["convertToCapped"] + }] + } + ] + }, + { + testname: "copydb", + command: {copydb: 1, fromdb: firstDbName, todb: secondDbName}, + skipSharded: true, // Does not work sharded due to SERVER-13080 + testcases: [ + { + runOnDb: adminDbName, + roles: {readWriteAnyDatabase: 1, root: 1, __system: 1}, + privileges: [ + {resource: {db: firstDbName, collection: ""}, actions: ["find"]}, + {resource: {db: firstDbName, collection: "system.js"}, actions: ["find"]}, + { + resource: {db: secondDbName, collection: ""}, + actions: ["insert", "createIndex"] }, - privileges: [ - { resource: {db: secondDbName, collection: "bar"}, actions: ["collStats"] } - ] - } - ] - }, - { - testname: "compact", - command: {compact: "foo"}, - skipSharded: true, - setup: function (db) { db.foo.save( {} ); }, - teardown: function (db) { db.dropDatabase(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_dbAdmin, - privileges: [ - { resource: {db: firstDbName, collection: "foo"}, actions: ["compact"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_dbAdminAny, - privileges: [ - { resource: {db: secondDbName, collection: "foo"}, actions: ["compact"] } - ] - } - ] - }, - { - testname: "connectionStatus", - command: {connectionStatus: 1}, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_all, - privileges: [ ] - }, - { - runOnDb: secondDbName, - roles: roles_all, - privileges: [ ] - } - ] - }, - { - testname: "connPoolStats", - command: {connPoolStats: 1}, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["connPoolStats"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["connPoolStats"] } - ] - } - ] - }, - { - testname: "connPoolSync", - command: {connPoolSync: 1}, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_hostManager, - privileges: [ - { resource: {cluster: true}, actions: ["connPoolSync"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_hostManager, - privileges: [ - { resource: {cluster: true}, actions: ["connPoolSync"] } - ] - } - ] - }, - { - testname: "convertToCapped", - command: {convertToCapped: "toCapped", size: 1000}, - setup: function (db) { db.toCapped.save( {} ); }, - teardown: function (db) { db.toCapped.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_writeDbAdmin, - privileges: [ - { resource: {db: firstDbName, collection: "toCapped"}, actions:["convertToCapped"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_writeDbAdminAny, - privileges: [ - { resource: {db: secondDbName, collection: "toCapped"}, actions:["convertToCapped"] } - ] - } - ] - }, - { - testname: "copydb", - command: {copydb: 1, fromdb: firstDbName, todb: secondDbName}, - skipSharded: true, // Does not work sharded due to SERVER-13080 - testcases: [ - { - runOnDb: adminDbName, - roles: {readWriteAnyDatabase: 1, root: 1, __system: 1}, - privileges: [ - { resource: {db: firstDbName, collection: ""}, actions:["find"] }, - { resource: {db: firstDbName, collection: "system.js"}, actions:["find"] }, - { resource: {db: secondDbName, collection: ""}, - actions:["insert", "createIndex"] }, - { resource: {db: secondDbName, collection: "system.js"}, actions:["insert"] }, - ] - }, - ] - }, - { - testname: "count", - command: {count: "x"}, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_read, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["find"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_readAny, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["find"] } - ] - } - ] - }, - { - testname: "create", - command: {create: "x"}, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: Object.extend({restore:1}, roles_writeDbAdmin), - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["createCollection"] } - ] - }, - { - runOnDb: firstDbName, - roles: Object.extend({restore:1}, roles_writeDbAdmin), - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["insert"] } - ] - }, - { - runOnDb: secondDbName, - roles: Object.extend({restore:1}, roles_writeDbAdminAny), - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["createCollection"] } - ] - }, - { - runOnDb: secondDbName, - roles: Object.extend({restore:1}, roles_writeDbAdminAny), - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["insert"] } - ] - } - ] - }, - { - testname: "create_capped", - command: {create: "x", capped: true, size: 1000}, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_writeDbAdmin, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["createCollection", "convertToCapped"] } - ] - }, - { - runOnDb: firstDbName, - roles: roles_writeDbAdmin, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["insert", "convertToCapped"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_writeDbAdminAny, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["createCollection", "convertToCapped"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_writeDbAdminAny, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["insert", "convertToCapped"] } - ] - } - ] - }, - { - testname: "createIndexes", - command: {createIndexes: "x", indexes: [{ns: firstDbName + ".x", key: {a:1}, name: "a_1"}] }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: Object.extend({readWrite: 1, - readWriteAnyDatabase: 1, - dbAdmin: 1, - dbAdminAnyDatabase: 1, - dbOwner: 1, - restore: 1, - root: 1, - __system: 1}), - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["createIndex"] } - ] - } - ] - }, - { - testname: "currentOp", - command: {currentOp: 1, $all: true}, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["inprog"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "currentOpCtx", - command: {currentOpCtx: 1}, - skipSharded: true, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["inprog"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["inprog"] } - ] - } - ] - }, - { - testname: "dataSize_1", - command: {dataSize: firstDbName + ".x"}, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_read, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["find"] } - ] - } - ] - }, - { - testname: "dataSize_2", - command: {dataSize: secondDbName + ".x"}, - testcases: [ - { - runOnDb: secondDbName, - roles: roles_readAny, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["find"] } - ] - } - ] - }, - { - testname: "dbHash", - command: {dbHash: 1}, - skipSharded: true, - testcases: [ - { - runOnDb: firstDbName, - roles: { read: 1, - readAnyDatabase: 1, - readWrite: 1, - readWriteAnyDatabase: 1, - dbOwner: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: firstDbName, collection: ""}, actions: ["dbHash"] } - ] - }, - { - runOnDb: secondDbName, - roles: { readAnyDatabase: 1, - readWriteAnyDatabase: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: secondDbName, collection: ""}, actions: ["dbHash"] } - ] - } - ] - }, - { - testname: "dbStats", - command: {dbStats: 1, scale: 1024}, - testcases: [ - { - runOnDb: firstDbName, - roles: { - read: 1, - readAnyDatabase: 1, - readWrite: 1, - readWriteAnyDatabase: 1, - dbAdmin: 1, - dbAdminAnyDatabase: 1, - dbOwner: 1, - clusterMonitor: 1, - clusterAdmin: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: firstDbName, collection: ""}, actions: ["dbStats"] } - ] - }, - { - runOnDb: secondDbName, - roles: { - readAnyDatabase: 1, - readWriteAnyDatabase: 1, - dbAdminAnyDatabase: 1, - clusterMonitor: 1, - clusterAdmin: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: secondDbName, collection: ""}, actions: ["dbStats"] } - ] - } - ] - }, - { - testname: "diagLogging", - command: {diagLogging: 1}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_hostManager, - privileges: [ - { resource: {cluster: true}, actions: ["diagLogging"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "distinct", - command: {distinct: "coll", key: "a", query: {}}, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_read, - privileges: [ - { resource: {db: firstDbName, collection: "coll"}, actions: ["find"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_readAny, - privileges: [ - { resource: {db: secondDbName, collection: "coll"}, actions: ["find"] } - ] - } - ] - }, - { - testname: "drop", - command: {drop: "x"}, - setup: function (db) { db.x.save({}); }, - testcases: [ - { - runOnDb: firstDbName, - roles: Object.extend({restore: 1}, roles_writeDbAdmin), - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["dropCollection"] } - ] - }, - { - runOnDb: secondDbName, - roles: Object.extend({restore: 1}, roles_writeDbAdminAny), - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["dropCollection"] } - ] - } - ] - }, - { - testname: "dropDatabase", - command: {dropDatabase: 1}, - setup: function (db) { db.x.save({}); }, - teardown: function (db) { db.x.save({}); }, - testcases: [ - { - runOnDb: firstDbName, - roles: { - dbAdmin: 1, - dbAdminAnyDatabase: 1, - dbOwner: 1, - clusterAdmin: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: firstDbName, collection: ""}, actions: ["dropDatabase"] } - ] - }, - { - runOnDb: secondDbName, - roles: { - dbAdminAnyDatabase: 1, - clusterAdmin: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: secondDbName, collection: ""}, actions: ["dropDatabase"] } - ] - } - ] - }, - { - testname: "dropIndexes", - command: {dropIndexes: "x", index: "*"}, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_writeDbAdmin, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["dropIndex"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_writeDbAdminAny, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["dropIndex"] } - ] - } - ] - }, - { - testname: "enableSharding", - command: {enableSharding: "x"}, - skipStandalone: true, - testcases: [ - { - runOnDb: adminDbName, - roles: Object.extend({enableSharding:1}, roles_clusterManager), - privileges: [ - { resource: {db: "x", collection: ""}, actions: ["enableSharding"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "eval", - command: {$eval: function () { print("noop"); } }, - testcases: [ - { - runOnDb: firstDbName, - roles: {__system: 1}, - privileges: [ - { resource: {anyResource: true}, actions: ["anyAction"] } - ] - }, - { - runOnDb: secondDbName, - roles: {__system: 1}, - privileges: [ - { resource: {anyResource: true}, actions: ["anyAction"] } - ] - } - ] - }, - { - testname: "features", - command: {features: 1}, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_all, - privilegesRequired: [ ] - }, - { - runOnDb: secondDbName, - roles: roles_all, - privilegesRequired: [ ] - } - ] - }, - { - testname: "filemd5", - command: {filemd5: 1, root: "fs"}, - setup: function (db) { - db.fs.chunks.drop(); - db.fs.chunks.insert({files_id: 1, n: 0, data: new BinData(0, "test")}); - db.fs.chunks.ensureIndex({files_id: 1, n: 1}); - }, - teardown: function (db) { - db.fs.chunks.drop(); - }, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_read, - privileges: [ - { resource: {db: firstDbName, collection: ""}, actions: ["find"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_readAny, - privileges: [ - { resource: {db: secondDbName, collection: ""}, actions: ["find"] } - ] - } - ] - }, - { - testname: "find", - command: {find: "foo"}, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_read, - privileges: [ - { resource: {db: firstDbName, collection: "foo"}, actions: ["find"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_readAny, - privileges: [ - { resource: {db: secondDbName, collection: "foo"}, actions: ["find"] } - ] - } - ] - }, - { - testname: "findWithTerm", - command: {find: "foo", limit: -1, term: NumberLong(1)}, - testcases: [ - { - runOnDb: firstDbName, - roles: {__system: 1}, - privileges: [ - { resource: {db: firstDbName, collection: "foo"}, actions: ["find"] }, - { resource: {cluster: true}, actions: ["internal"] } - ], - expectFail: true // because of invalid limit - }, - ] - }, - { - testname: "findAndModify", - command: {findAndModify: "x", query: {_id: "abc"}, update: {$inc: {n: 1}}}, - setup: function (db) { - db.x.drop(); - db.x.save( {_id: "abc", n: 0} ); - }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: { readWrite: 1, - readWriteAnyDatabase: 1, - dbOwner: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["find", "update"] } - ] - }, - { - runOnDb: secondDbName, - roles: {readWriteAnyDatabase: 1, root: 1, __system: 1}, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["find", "update"] } - ] - } - ] - }, - { - testname: "flushRouterConfig", - command: {flushRouterConfig: 1}, - skipStandalone: true, - testcases: [ - { - runOnDb: adminDbName, - roles: Object.extend({clusterManager: 1}, roles_hostManager), - privileges: [ - { resource: {cluster: true}, actions: ["flushRouterConfig"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "fsync", - command: {fsync: 1}, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_hostManager, - privileges: [ - { resource: {cluster: true}, actions: ["fsync"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "fsyncUnlock", - command: {fsyncUnlock: 1}, - skipSharded: true, // TODO: remove when fsyncUnlock is implemented in mongos - testcases: [ - { - runOnDb: adminDbName, - roles: roles_hostManager, - privileges: [ - { resource: {cluster: true}, actions: ["unlock"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "geoNear", - command: {geoNear: "x", near: [50, 50], num: 1}, - setup: function (db) { - db.x.drop(); - db.x.save({loc: [50, 50]}); - db.x.ensureIndex({loc: "2d"}); - }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_read, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["find"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_readAny, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["find"] } - ] - } - ] - }, - { - testname: "geoSearch", - command: {geoSearch: "x", near: [50, 50], maxDistance: 6, limit: 1, search: {} }, - skipSharded: true, - setup: function (db) { - db.x.drop(); - db.x.save({loc: {long: 50, lat: 50}}); - db.x.ensureIndex({loc: "geoHaystack", type: 1}, {bucketSize: 1}); - }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_read, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["find"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_readAny, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["find"] } - ] - } - ] - }, - { - testname: "getCmdLineOpts", - command: {getCmdLineOpts: 1}, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["getCmdLineOpts"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "getLastError", - command: {getLastError: 1}, - testcases: [ - { runOnDb: firstDbName, roles: roles_all, privileges: [ ] }, - { runOnDb: secondDbName, roles: roles_all, privileges: [ ] } - ] - }, - { - testname: "getLog", - command: {getLog: "*"}, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["getLog"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "getMore", - command: {getMore: NumberLong("1"), collection: "foo"}, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_read, - privileges: [ - { resource: {db: firstDbName, collection: "foo"}, actions: ["find"] } - ], - expectFail: true - }, - { - runOnDb: secondDbName, - roles: roles_readAny, - privileges: [ - { resource: {db: secondDbName, collection: "foo"}, actions: ["find"] } - ], - expectFail: true - } - ] - }, - { - testname: "getMoreWithTerm", - command: {getMore: NumberLong("1"), collection: "foo", term: NumberLong(1)}, - testcases: [ - { - runOnDb: firstDbName, - roles: {__system: 1}, - privileges: [ - { resource: {db: firstDbName, collection: "foo"}, actions: ["find"] }, - { resource: {cluster: true}, actions: ["internal"] } - ], - expectFail: true - } - ] - }, - { - testname: "getnonce", - command: {getnonce: 1}, - testcases: [ - { runOnDb: firstDbName, roles: roles_all, privileges: [ ] }, - { runOnDb: secondDbName, roles: roles_all, privileges: [ ] } - ] - }, - { - testname: "getParameter", - command: {getParameter: 1, quiet: 1}, - testcases: [ - { - runOnDb: adminDbName, - roles: { backup: 1, - restore: 1, - clusterMonitor: 1, - clusterAdmin: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {cluster: true}, actions: ["getParameter"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "getPrevError", - command: {getPrevError: 1}, - skipSharded: true, - testcases: [ - { runOnDb: firstDbName, roles: roles_all, privileges: [ ] }, - { runOnDb: secondDbName, roles: roles_all, privileges: [ ] } - ] - }, - { - testname: "getShardMap", - command: {getShardMap: "x"}, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["getShardMap"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "getShardVersion", - command: {getShardVersion: "test.foo"}, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_monitoring, - privileges: [ - { resource: {db: "test", collection: 'foo'}, actions: ["getShardVersion"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "group", - command: { - group: { - ns: "x", - key: {groupby: 1}, - initial: {total: 0}, - $reduce: function (curr, result) { - result.total += curr.n; + {resource: {db: secondDbName, collection: "system.js"}, actions: ["insert"]}, + ] + }, + ] + }, + { + testname: "count", + command: {count: "x"}, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_read, + privileges: [{resource: {db: firstDbName, collection: "x"}, actions: ["find"]}] + }, + { + runOnDb: secondDbName, + roles: roles_readAny, + privileges: + [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] + } + ] + }, + { + testname: "create", + command: {create: "x"}, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: Object.extend({restore: 1}, roles_writeDbAdmin), + privileges: [{ + resource: {db: firstDbName, collection: "x"}, + actions: ["createCollection"] + }] + }, + { + runOnDb: firstDbName, + roles: Object.extend({restore: 1}, roles_writeDbAdmin), + privileges: [{resource: {db: firstDbName, collection: "x"}, actions: ["insert"]}] + }, + { + runOnDb: secondDbName, + roles: Object.extend({restore: 1}, roles_writeDbAdminAny), + privileges: [{ + resource: {db: secondDbName, collection: "x"}, + actions: ["createCollection"] + }] + }, + { + runOnDb: secondDbName, + roles: Object.extend({restore: 1}, roles_writeDbAdminAny), + privileges: + [{resource: {db: secondDbName, collection: "x"}, actions: ["insert"]}] + } + ] + }, + { + testname: "create_capped", + command: {create: "x", capped: true, size: 1000}, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_writeDbAdmin, + privileges: [{ + resource: {db: firstDbName, collection: "x"}, + actions: ["createCollection", "convertToCapped"] + }] + }, + { + runOnDb: firstDbName, + roles: roles_writeDbAdmin, + privileges: [{ + resource: {db: firstDbName, collection: "x"}, + actions: ["insert", "convertToCapped"] + }] + }, + { + runOnDb: secondDbName, + roles: roles_writeDbAdminAny, + privileges: [{ + resource: {db: secondDbName, collection: "x"}, + actions: ["createCollection", "convertToCapped"] + }] + }, + { + runOnDb: secondDbName, + roles: roles_writeDbAdminAny, + privileges: [{ + resource: {db: secondDbName, collection: "x"}, + actions: ["insert", "convertToCapped"] + }] + } + ] + }, + { + testname: "createIndexes", + command: + {createIndexes: "x", indexes: [{ns: firstDbName + ".x", key: {a: 1}, name: "a_1"}]}, + teardown: function(db) { + db.x.drop(); + }, + testcases: [{ + runOnDb: firstDbName, + roles: Object.extend({ + readWrite: 1, + readWriteAnyDatabase: 1, + dbAdmin: 1, + dbAdminAnyDatabase: 1, + dbOwner: 1, + restore: 1, + root: 1, + __system: 1 + }), + privileges: + [{resource: {db: firstDbName, collection: "x"}, actions: ["createIndex"]}] + }] + }, + { + testname: "currentOp", + command: {currentOp: 1, $all: true}, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["inprog"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "currentOpCtx", + command: {currentOpCtx: 1}, + skipSharded: true, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["inprog"]}] + }, + { + runOnDb: secondDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["inprog"]}] + } + ] + }, + { + testname: "dataSize_1", + command: {dataSize: firstDbName + ".x"}, + testcases: [{ + runOnDb: firstDbName, + roles: roles_read, + privileges: [{resource: {db: firstDbName, collection: "x"}, actions: ["find"]}] + }] + }, + { + testname: "dataSize_2", + command: {dataSize: secondDbName + ".x"}, + testcases: [{ + runOnDb: secondDbName, + roles: roles_readAny, + privileges: [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] + }] + }, + { + testname: "dbHash", + command: {dbHash: 1}, + skipSharded: true, + testcases: [ + { + runOnDb: firstDbName, + roles: { + read: 1, + readAnyDatabase: 1, + readWrite: 1, + readWriteAnyDatabase: 1, + dbOwner: 1, + root: 1, + __system: 1 + }, + privileges: [{resource: {db: firstDbName, collection: ""}, actions: ["dbHash"]}] + }, + { + runOnDb: secondDbName, + roles: {readAnyDatabase: 1, readWriteAnyDatabase: 1, root: 1, __system: 1}, + privileges: + [{resource: {db: secondDbName, collection: ""}, actions: ["dbHash"]}] + } + ] + }, + { + testname: "dbStats", + command: {dbStats: 1, scale: 1024}, + testcases: [ + { + runOnDb: firstDbName, + roles: { + read: 1, + readAnyDatabase: 1, + readWrite: 1, + readWriteAnyDatabase: 1, + dbAdmin: 1, + dbAdminAnyDatabase: 1, + dbOwner: 1, + clusterMonitor: 1, + clusterAdmin: 1, + root: 1, + __system: 1 + }, + privileges: [{resource: {db: firstDbName, collection: ""}, actions: ["dbStats"]}] + }, + { + runOnDb: secondDbName, + roles: { + readAnyDatabase: 1, + readWriteAnyDatabase: 1, + dbAdminAnyDatabase: 1, + clusterMonitor: 1, + clusterAdmin: 1, + root: 1, + __system: 1 + }, + privileges: + [{resource: {db: secondDbName, collection: ""}, actions: ["dbStats"]}] + } + ] + }, + { + testname: "diagLogging", + command: {diagLogging: 1}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_hostManager, + privileges: [{resource: {cluster: true}, actions: ["diagLogging"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "distinct", + command: {distinct: "coll", key: "a", query: {}}, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_read, + privileges: + [{resource: {db: firstDbName, collection: "coll"}, actions: ["find"]}] + }, + { + runOnDb: secondDbName, + roles: roles_readAny, + privileges: + [{resource: {db: secondDbName, collection: "coll"}, actions: ["find"]}] + } + ] + }, + { + testname: "drop", + command: {drop: "x"}, + setup: function(db) { + db.x.save({}); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: Object.extend({restore: 1}, roles_writeDbAdmin), + privileges: + [{resource: {db: firstDbName, collection: "x"}, actions: ["dropCollection"]}] + }, + { + runOnDb: secondDbName, + roles: Object.extend({restore: 1}, roles_writeDbAdminAny), + privileges: [{ + resource: {db: secondDbName, collection: "x"}, + actions: ["dropCollection"] + }] + } + ] + }, + { + testname: "dropDatabase", + command: {dropDatabase: 1}, + setup: function(db) { + db.x.save({}); + }, + teardown: function(db) { + db.x.save({}); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: { + dbAdmin: 1, + dbAdminAnyDatabase: 1, + dbOwner: 1, + clusterAdmin: 1, + root: 1, + __system: 1 + }, + privileges: + [{resource: {db: firstDbName, collection: ""}, actions: ["dropDatabase"]}] + }, + { + runOnDb: secondDbName, + roles: {dbAdminAnyDatabase: 1, clusterAdmin: 1, root: 1, __system: 1}, + privileges: + [{resource: {db: secondDbName, collection: ""}, actions: ["dropDatabase"]}] + } + ] + }, + { + testname: "dropIndexes", + command: {dropIndexes: "x", index: "*"}, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_writeDbAdmin, + privileges: + [{resource: {db: firstDbName, collection: "x"}, actions: ["dropIndex"]}] + }, + { + runOnDb: secondDbName, + roles: roles_writeDbAdminAny, + privileges: + [{resource: {db: secondDbName, collection: "x"}, actions: ["dropIndex"]}] + } + ] + }, + { + testname: "enableSharding", + command: {enableSharding: "x"}, + skipStandalone: true, + testcases: [ + { + runOnDb: adminDbName, + roles: Object.extend({enableSharding: 1}, roles_clusterManager), + privileges: [{resource: {db: "x", collection: ""}, actions: ["enableSharding"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "eval", + command: { + $eval: function() { + print("noop"); + } + }, + testcases: [ + { + runOnDb: firstDbName, + roles: {__system: 1}, + privileges: [{resource: {anyResource: true}, actions: ["anyAction"]}] + }, + { + runOnDb: secondDbName, + roles: {__system: 1}, + privileges: [{resource: {anyResource: true}, actions: ["anyAction"]}] + } + ] + }, + { + testname: "features", + command: {features: 1}, + testcases: [ + {runOnDb: firstDbName, roles: roles_all, privilegesRequired: []}, + {runOnDb: secondDbName, roles: roles_all, privilegesRequired: []} + ] + }, + { + testname: "filemd5", + command: {filemd5: 1, root: "fs"}, + setup: function(db) { + db.fs.chunks.drop(); + db.fs.chunks.insert({files_id: 1, n: 0, data: new BinData(0, "test")}); + db.fs.chunks.ensureIndex({files_id: 1, n: 1}); + }, + teardown: function(db) { + db.fs.chunks.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_read, + privileges: [{resource: {db: firstDbName, collection: ""}, actions: ["find"]}] + }, + { + runOnDb: secondDbName, + roles: roles_readAny, + privileges: [{resource: {db: secondDbName, collection: ""}, actions: ["find"]}] + } + ] + }, + { + testname: "find", + command: {find: "foo"}, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_read, + privileges: [{resource: {db: firstDbName, collection: "foo"}, actions: ["find"]}] + }, + { + runOnDb: secondDbName, + roles: roles_readAny, + privileges: + [{resource: {db: secondDbName, collection: "foo"}, actions: ["find"]}] + } + ] + }, + { + testname: "findWithTerm", + command: {find: "foo", limit: -1, term: NumberLong(1)}, + testcases: [ + { + runOnDb: firstDbName, + roles: {__system: 1}, + privileges: [ + {resource: {db: firstDbName, collection: "foo"}, actions: ["find"]}, + {resource: {cluster: true}, actions: ["internal"]} + ], + expectFail: true // because of invalid limit + }, + ] + }, + { + testname: "findAndModify", + command: {findAndModify: "x", query: {_id: "abc"}, update: {$inc: {n: 1}}}, + setup: function(db) { + db.x.drop(); + db.x.save({_id: "abc", n: 0}); + }, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: {readWrite: 1, readWriteAnyDatabase: 1, dbOwner: 1, root: 1, __system: 1}, + privileges: + [{resource: {db: firstDbName, collection: "x"}, actions: ["find", "update"]}] + }, + { + runOnDb: secondDbName, + roles: {readWriteAnyDatabase: 1, root: 1, __system: 1}, + privileges: [{ + resource: {db: secondDbName, collection: "x"}, + actions: ["find", "update"] + }] + } + ] + }, + { + testname: "flushRouterConfig", + command: {flushRouterConfig: 1}, + skipStandalone: true, + testcases: [ + { + runOnDb: adminDbName, + roles: Object.extend({clusterManager: 1}, roles_hostManager), + privileges: [{resource: {cluster: true}, actions: ["flushRouterConfig"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "fsync", + command: {fsync: 1}, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_hostManager, + privileges: [{resource: {cluster: true}, actions: ["fsync"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "fsyncUnlock", + command: {fsyncUnlock: 1}, + skipSharded: true, // TODO: remove when fsyncUnlock is implemented in mongos + testcases: [ + { + runOnDb: adminDbName, + roles: roles_hostManager, + privileges: [{resource: {cluster: true}, actions: ["unlock"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "geoNear", + command: {geoNear: "x", near: [50, 50], num: 1}, + setup: function(db) { + db.x.drop(); + db.x.save({loc: [50, 50]}); + db.x.ensureIndex({loc: "2d"}); + }, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_read, + privileges: [{resource: {db: firstDbName, collection: "x"}, actions: ["find"]}] + }, + { + runOnDb: secondDbName, + roles: roles_readAny, + privileges: + [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] + } + ] + }, + { + testname: "geoSearch", + command: {geoSearch: "x", near: [50, 50], maxDistance: 6, limit: 1, search: {}}, + skipSharded: true, + setup: function(db) { + db.x.drop(); + db.x.save({loc: {long: 50, lat: 50}}); + db.x.ensureIndex({loc: "geoHaystack", type: 1}, {bucketSize: 1}); + }, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_read, + privileges: [{resource: {db: firstDbName, collection: "x"}, actions: ["find"]}] + }, + { + runOnDb: secondDbName, + roles: roles_readAny, + privileges: + [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] + } + ] + }, + { + testname: "getCmdLineOpts", + command: {getCmdLineOpts: 1}, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["getCmdLineOpts"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "getLastError", + command: {getLastError: 1}, + testcases: [ + {runOnDb: firstDbName, roles: roles_all, privileges: []}, + {runOnDb: secondDbName, roles: roles_all, privileges: []} + ] + }, + { + testname: "getLog", + command: {getLog: "*"}, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["getLog"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "getMore", + command: {getMore: NumberLong("1"), collection: "foo"}, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_read, + privileges: [{resource: {db: firstDbName, collection: "foo"}, actions: ["find"]}], + expectFail: true + }, + { + runOnDb: secondDbName, + roles: roles_readAny, + privileges: [{resource: {db: secondDbName, collection: "foo"}, actions: ["find"]}], + expectFail: true + } + ] + }, + { + testname: "getMoreWithTerm", + command: {getMore: NumberLong("1"), collection: "foo", term: NumberLong(1)}, + testcases: [{ + runOnDb: firstDbName, + roles: {__system: 1}, + privileges: [ + {resource: {db: firstDbName, collection: "foo"}, actions: ["find"]}, + {resource: {cluster: true}, actions: ["internal"]} + ], + expectFail: true + }] + }, + { + testname: "getnonce", + command: {getnonce: 1}, + testcases: [ + {runOnDb: firstDbName, roles: roles_all, privileges: []}, + {runOnDb: secondDbName, roles: roles_all, privileges: []} + ] + }, + { + testname: "getParameter", + command: {getParameter: 1, quiet: 1}, + testcases: [ + { + runOnDb: adminDbName, + roles: { + backup: 1, + restore: 1, + clusterMonitor: 1, + clusterAdmin: 1, + root: 1, + __system: 1 + }, + privileges: [{resource: {cluster: true}, actions: ["getParameter"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "getPrevError", + command: {getPrevError: 1}, + skipSharded: true, + testcases: [ + {runOnDb: firstDbName, roles: roles_all, privileges: []}, + {runOnDb: secondDbName, roles: roles_all, privileges: []} + ] + }, + { + testname: "getShardMap", + command: {getShardMap: "x"}, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["getShardMap"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "getShardVersion", + command: {getShardVersion: "test.foo"}, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_monitoring, + privileges: + [{resource: {db: "test", collection: 'foo'}, actions: ["getShardVersion"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "group", + command: { + group: { + ns: "x", + key: {groupby: 1}, + initial: {total: 0}, + $reduce: function(curr, result) { + result.total += curr.n; + } + } + }, + setup: function(db) { + db.x.insert({groupby: 1, n: 5}); + db.x.insert({groupby: 1, n: 6}); + }, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_read, + privileges: [{resource: {db: firstDbName, collection: "x"}, actions: ["find"]}] + }, + { + runOnDb: secondDbName, + roles: roles_readAny, + privileges: + [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] + } + ] + }, + { + testname: "hostInfo", + command: {hostInfo: 1}, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["hostInfo"]}] + }, + { + runOnDb: firstDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["hostInfo"]}] + }, + { + runOnDb: secondDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["hostInfo"]}] + } + ] + }, + { + testname: "isMaster", + command: {isMaster: 1}, + testcases: [ + {runOnDb: adminDbName, roles: roles_all, privileges: []}, + {runOnDb: firstDbName, roles: roles_all, privileges: []}, + {runOnDb: secondDbName, roles: roles_all, privileges: []} + ] + }, + { + testname: "killCursors", + command: {killCursors: "foo", cursors: [NumberLong("123")]}, + skipSharded: true, // TODO enable when killCursors command is implemented on mongos + testcases: [ + { + runOnDb: firstDbName, + roles: { + read: 1, + readAnyDatabase: 1, + readWrite: 1, + readWriteAnyDatabase: 1, + dbOwner: 1, + hostManager: 1, + clusterAdmin: 1, + backup: 1, + root: 1, + __system: 1 + }, + privileges: + [{resource: {db: firstDbName, collection: "foo"}, actions: ["killCursors"]}], + expectFail: true + }, + { + runOnDb: secondDbName, + roles: { + readAnyDatabase: 1, + readWriteAnyDatabase: 1, + hostManager: 1, + clusterAdmin: 1, + backup: 1, + root: 1, + __system: 1 + }, + privileges: + [{resource: {db: secondDbName, collection: "foo"}, actions: ["killCursors"]}], + expectFail: true + } + ] + }, + { + testname: "killOp", // standalone version + command: {killOp: 1, op: 123}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_hostManager, + privileges: [{resource: {cluster: true}, actions: ["killop"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "killOp", // sharded version + command: {killOp: 1, op: "shard1:123"}, + skipStandalone: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_hostManager, + privileges: [{resource: {cluster: true}, actions: ["killop"]}], + expectFail: true // we won't be able to find the shardId + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "listCommands", + command: {listCommands: 1}, + testcases: [ + {runOnDb: adminDbName, roles: roles_all, privileges: []}, + {runOnDb: firstDbName, roles: roles_all, privileges: []}, + {runOnDb: secondDbName, roles: roles_all, privileges: []} + ] + }, + { + testname: "listDatabases", + command: {listDatabases: 1}, + testcases: [ + { + runOnDb: adminDbName, + roles: { + readAnyDatabase: 1, + readWriteAnyDatabase: 1, + dbAdminAnyDatabase: 1, + userAdminAnyDatabase: 1, + clusterMonitor: 1, + clusterAdmin: 1, + backup: 1, + root: 1, + __system: 1 + }, + privileges: [{resource: {cluster: true}, actions: ["listDatabases"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "listCollections", + command: {listCollections: 1}, + setup: function(db) { + db.x.insert({_id: 5}); + db.y.insert({_id: 6}); + }, + teardown: function(db) { + db.x.drop(); + db.y.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: { + read: 1, + readAnyDatabase: 1, + readWrite: 1, + readWriteAnyDatabase: 1, + clusterAdmin: 1, + clusterMonitor: 1, + clusterManager: 1, + dbAdmin: 1, + dbAdminAnyDatabase: 1, + dbOwner: 1, + backup: 1, + restore: 1, + root: 1, + __system: 1 + }, + privileges: + [{resource: {db: firstDbName, collection: ""}, actions: ["listCollections"]}] + }, + // Test legacy (pre 3.0) way of authorizing listCollections. + { + runOnDb: firstDbName, + privileges: [{ + resource: {db: firstDbName, collection: "system.namespaces"}, + actions: ["find"] + }] + } + ] + }, + { + testname: "listIndexes", + command: {listIndexes: "x"}, + setup: function(db) { + db.x.insert({_id: 5}); + db.x.insert({_id: 6}); + }, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: { + read: 1, + readAnyDatabase: 1, + readWrite: 1, + readWriteAnyDatabase: 1, + dbAdmin: 1, + dbAdminAnyDatabase: 1, + dbOwner: 1, + backup: 1, + root: 1, + __system: 1 + }, + privileges: + [{resource: {db: firstDbName, collection: ""}, actions: ["listIndexes"]}] + }, + // Test legacy (pre 3.0) way of authorizing listIndexes. + { + runOnDb: firstDbName, + privileges: [{ + resource: {db: firstDbName, collection: "system.indexes"}, + actions: ["find"] + }] + } + ] + }, + { + testname: "listShards", + command: {listShards: 1}, + skipStandalone: true, + testcases: [ + { + runOnDb: adminDbName, + roles: Object.extend({clusterManager: 1}, roles_monitoring), + privileges: [{resource: {cluster: true}, actions: ["listShards"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "logRotate", + command: {logRotate: 1}, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_hostManager, + privileges: [{resource: {cluster: true}, actions: ["logRotate"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "mapReduce_readonly", + command: { + mapreduce: "x", + map: function() { + emit(this.groupby, this.n); + }, + reduce: function(id, emits) { + return Array.sum(emits); + }, + out: {inline: 1} + }, + setup: function(db) { + db.x.insert({groupby: 1, n: 5}); + db.x.insert({groupby: 1, n: 6}); + }, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_read, + privileges: [{resource: {db: firstDbName, collection: "x"}, actions: ["find"]}] + }, + { + runOnDb: secondDbName, + roles: roles_readAny, + privileges: + [{resource: {db: secondDbName, collection: "x"}, actions: ["find"]}] + } + ] + }, + { + testname: "mapReduce_write", + command: { + mapreduce: "x", + map: function() { + emit(this.groupby, this.n); + }, + reduce: function(id, emits) { + return Array.sum(emits); + }, + out: "mr_out" + }, + setup: function(db) { + db.x.insert({groupby: 1, n: 5}); + db.x.insert({groupby: 1, n: 6}); + }, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: {readWrite: 1, readWriteAnyDatabase: 1, dbOwner: 1, root: 1, __system: 1}, + privileges: [ + {resource: {db: firstDbName, collection: "x"}, actions: ["find"]}, + { + resource: {db: firstDbName, collection: "mr_out"}, + actions: ["insert", "remove"] } - } - }, - setup: function (db) { - db.x.insert({groupby: 1, n: 5}); - db.x.insert({groupby: 1, n: 6}); - }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_read, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["find"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_readAny, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["find"] } - ] - } - ] - }, - { - testname: "hostInfo", - command: {hostInfo: 1}, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["hostInfo"] } - ] - }, - { - runOnDb: firstDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["hostInfo"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["hostInfo"] } - ] - } - ] - }, - { - testname: "isMaster", - command: {isMaster: 1}, - testcases: [ - { runOnDb: adminDbName, roles: roles_all, privileges: [ ] }, - { runOnDb: firstDbName, roles: roles_all, privileges: [ ] }, - { runOnDb: secondDbName, roles: roles_all, privileges: [ ] } - ] - }, - { - testname: "killCursors", - command: {killCursors: "foo", cursors: [NumberLong("123")]}, - skipSharded: true, // TODO enable when killCursors command is implemented on mongos - testcases: [ - { - runOnDb: firstDbName, - roles: { - read: 1, - readAnyDatabase: 1, - readWrite: 1, - readWriteAnyDatabase: 1, - dbOwner: 1, - hostManager: 1, - clusterAdmin: 1, - backup: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: firstDbName, collection: "foo"}, actions: ["killCursors"] } - ], - expectFail: true - }, - { - runOnDb: secondDbName, - roles: { - readAnyDatabase: 1, - readWriteAnyDatabase: 1, - hostManager: 1, - clusterAdmin: 1, - backup: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: secondDbName, collection: "foo"}, actions: ["killCursors"] } - ], - expectFail: true - } - ] - }, - { - testname: "killOp", // standalone version - command: {killOp: 1, op: 123}, - skipSharded: true, - testcases : [ - { - runOnDb: adminDbName, - roles: roles_hostManager, - privileges: [ - { resource: {cluster: true}, actions: ["killop"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "killOp", // sharded version - command: {killOp: 1, op: "shard1:123"}, - skipStandalone: true, - testcases : [ - { - runOnDb: adminDbName, - roles: roles_hostManager, - privileges: [ - { resource: {cluster: true}, actions: ["killop"] } - ], - expectFail: true // we won't be able to find the shardId - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "listCommands", - command: {listCommands: 1}, - testcases: [ - { runOnDb: adminDbName, roles: roles_all, privileges: [ ] }, - { runOnDb: firstDbName, roles: roles_all, privileges: [ ] }, - { runOnDb: secondDbName, roles: roles_all, privileges: [ ] } - ] - }, - { - testname: "listDatabases", - command: {listDatabases: 1}, - testcases: [ - { - runOnDb: adminDbName, - roles: { - readAnyDatabase: 1, - readWriteAnyDatabase: 1, - dbAdminAnyDatabase: 1, - userAdminAnyDatabase: 1, - clusterMonitor: 1, - clusterAdmin: 1, - backup: 1, - root: 1, - __system: 1 + ] + }, + { + runOnDb: secondDbName, + roles: {readWriteAnyDatabase: 1, root: 1, __system: 1}, + privileges: [ + {resource: {db: secondDbName, collection: "x"}, actions: ["find"]}, + { + resource: {db: secondDbName, collection: "mr_out"}, + actions: ["insert", "remove"] + } + ] + } + ] + }, + { + testname: "s_mergeChunks", + command: {mergeChunks: "test.x", bounds: [{i: 0}, {i: 5}]}, + skipStandalone: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_clusterManager, + privileges: [{resource: {db: "test", collection: "x"}, actions: ["splitChunk"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "d_mergeChunks", + command: {mergeChunks: "test.x", bounds: [{i: 0}, {i: 5}]}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: {__system: 1}, + privileges: [{resource: {cluster: true}, actions: ["internal"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "s_moveChunk", + command: {moveChunk: "test.x"}, + skipStandalone: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_clusterManager, + privileges: [{resource: {db: "test", collection: "x"}, actions: ["moveChunk"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "d_moveChunk", + command: {moveChunk: "test.x"}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: {__system: 1}, + privileges: [{resource: {cluster: true}, actions: ["internal"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "movePrimary", + command: {movePrimary: "x"}, + skipStandalone: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_clusterManager, + privileges: [{resource: {db: "x", collection: ""}, actions: ["moveChunk"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "netstat", + command: {netstat: "x"}, + skipStandalone: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["netstat"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "planCacheIndexFilter", + command: {planCacheClearFilters: "x"}, + skipSharded: true, + setup: function(db) { + db.x.save({}); + }, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_dbAdmin, + privileges: [{ + resource: {db: firstDbName, collection: "x"}, + actions: ["planCacheIndexFilter"] + }], + }, + { + runOnDb: secondDbName, + roles: roles_dbAdminAny, + privileges: [{ + resource: {db: secondDbName, collection: "x"}, + actions: ["planCacheIndexFilter"] + }], + }, + ] + }, + { + testname: "planCacheRead", + command: {planCacheListQueryShapes: "x"}, + skipSharded: true, + setup: function(db) { + db.x.save({}); + }, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_readDbAdmin, + privileges: + [{resource: {db: firstDbName, collection: "x"}, actions: ["planCacheRead"]}], + }, + { + runOnDb: secondDbName, + roles: roles_readDbAdminAny, + privileges: + [{resource: {db: secondDbName, collection: "x"}, actions: ["planCacheRead"]}], + }, + ] + }, + { + testname: "planCacheWrite", + command: {planCacheClear: "x"}, + skipSharded: true, + setup: function(db) { + db.x.save({}); + }, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_dbAdmin, + privileges: + [{resource: {db: firstDbName, collection: "x"}, actions: ["planCacheWrite"]}], + }, + { + runOnDb: secondDbName, + roles: roles_dbAdminAny, + privileges: + [{resource: {db: secondDbName, collection: "x"}, actions: ["planCacheWrite"]}], + }, + ] + }, + { + testname: "ping", + command: {ping: 1}, + testcases: [ + {runOnDb: adminDbName, roles: roles_all, privileges: []}, + {runOnDb: firstDbName, roles: roles_all, privileges: []}, + {runOnDb: secondDbName, roles: roles_all, privileges: []} + ] + }, + { + testname: "profile", + command: {profile: 0}, + skipSharded: true, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_dbAdmin, + privileges: + [{resource: {db: firstDbName, collection: ""}, actions: ["enableProfiler"]}] + }, + { + runOnDb: secondDbName, + roles: roles_dbAdminAny, + privileges: [{ + resource: {db: secondDbName, collection: ""}, + actions: ["enableProfiler"] + }] + } + ] + }, + { + testname: "profileGetLevel", + command: {profile: -1}, + skipSharded: true, + testcases: [ + { + runOnDb: firstDbName, + roles: { + backup: 1, + dbAdmin: 1, + dbAdminAnyDatabase: 1, + dbOwner: 1, + clusterMonitor: 1, + clusterAdmin: 1, + root: 1, + __system: 1 + }, + privileges: [{ + resource: {db: firstDbName, collection: "system.profile"}, + actions: ["find"] + }] + }, + { + runOnDb: secondDbName, + roles: { + backup: 1, + dbAdminAnyDatabase: 1, + clusterMonitor: 1, + clusterAdmin: 1, + root: 1, + __system: 1 + }, + privileges: [{ + resource: {db: secondDbName, collection: "system.profile"}, + actions: ["find"] + }] + } + ] + }, + { + testname: "renameCollection_sameDb", + command: + {renameCollection: firstDbName + ".x", to: firstDbName + ".y", dropTarget: true}, + setup: function(db) { + db.getSisterDB(firstDbName).x.save({}); + }, + teardown: function(db) { + db.getSisterDB(firstDbName).x.drop(); + db.getSisterDB(firstDbName).y.drop(); + }, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_writeDbAdmin, + privileges: [ + { + resource: {db: firstDbName, collection: ""}, + actions: ["renameCollectionSameDB"] }, - privileges: [ - { resource: {cluster: true}, actions: ["listDatabases"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "listCollections", - command: {listCollections: 1}, - setup: function (db) { - db.x.insert({_id: 5}); - db.y.insert({_id: 6}); - }, - teardown: function (db) { - db.x.drop(); - db.y.drop(); - }, - testcases: [ - { - runOnDb: firstDbName, - roles: { - read: 1, - readAnyDatabase: 1, - readWrite: 1, - readWriteAnyDatabase: 1, - clusterAdmin: 1, - clusterMonitor: 1, - clusterManager: 1, - dbAdmin: 1, - dbAdminAnyDatabase: 1, - dbOwner: 1, - backup: 1, - restore: 1, - root: 1, - __system: 1 + {resource: {db: firstDbName, collection: "y"}, actions: ["dropCollection"]} + ] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + // Make sure that you cannot use renameCollectionSameDB to rename from a collection you + // don't have read access on to one that you do. + testname: "renameCollection_sameDb_failure", + command: {renameCollection: firstDbName + ".x", to: firstDbName + ".y"}, + setup: function(db) { + db.getSisterDB(firstDbName).x.save({}); + }, + teardown: function(db) { + db.getSisterDB(firstDbName).x.drop(); + db.getSisterDB(firstDbName).y.drop(); + }, + testcases: [ + { + runOnDb: adminDbName, + privileges: [ + { + resource: {db: firstDbName, collection: ""}, + actions: ["renameCollectionSameDB"] }, - privileges: [ - { - resource: {db: firstDbName, collection: ""}, - actions: ["listCollections"] - } - ] - }, - // Test legacy (pre 3.0) way of authorizing listCollections. - { - runOnDb: firstDbName, - privileges: [ - { - resource: {db: firstDbName, collection: "system.namespaces"}, - actions: ["find"] - } - ] - } - ] - }, - { - testname: "listIndexes", - command: {listIndexes: "x"}, - setup: function (db) { - db.x.insert({_id: 5}); - db.x.insert({_id: 6}); - }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: { - read: 1, - readAnyDatabase: 1, - readWrite: 1, - readWriteAnyDatabase: 1, - dbAdmin: 1, - dbAdminAnyDatabase: 1, - dbOwner: 1, - backup: 1, - root: 1, - __system: 1 + {resource: {db: firstDbName, collection: "y"}, actions: ["find"]} + ], + expectAuthzFailure: true + }, + ] + }, + { + testname: "renameCollection_twoDbs", + command: {renameCollection: firstDbName + ".x", to: secondDbName + ".y"}, + setup: function(db) { + db.getSisterDB(firstDbName).x.save({}); + db.getSisterDB(adminDbName).runCommand({movePrimary: firstDbName, to: shard0name}); + db.getSisterDB(adminDbName).runCommand({movePrimary: secondDbName, to: shard0name}); + }, + teardown: function(db) { + db.getSisterDB(firstDbName).x.drop(); + db.getSisterDB(secondDbName).y.drop(); + }, + testcases: [ + { + runOnDb: adminDbName, + roles: {readWriteAnyDatabase: 1, root: 1, __system: 1}, + privileges: [ + { + resource: {db: firstDbName, collection: "x"}, + actions: ["find", "dropCollection"] }, - privileges: [ - { - resource: {db: firstDbName, collection: ""}, - actions: ["listIndexes"] - } - ] - }, - // Test legacy (pre 3.0) way of authorizing listIndexes. - { - runOnDb: firstDbName, - privileges: [ - { - resource: {db: firstDbName, collection: "system.indexes"}, - actions: ["find"] - } - ] - } - ] - }, - { - testname: "listShards", - command: {listShards: 1}, - skipStandalone: true, - testcases: [ - { - runOnDb: adminDbName, - roles: Object.extend({clusterManager: 1}, roles_monitoring), - privileges: [ - { resource: {cluster: true}, actions: ["listShards"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "logRotate", - command: {logRotate: 1}, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_hostManager, - privileges: [ - { resource: {cluster: true}, actions: ["logRotate"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "mapReduce_readonly", - command: { - mapreduce: "x", - map: function () { emit(this.groupby, this.n); }, - reduce: function (id,emits) { return Array.sum(emits); }, - out: {inline: 1} - }, - setup: function (db) { - db.x.insert({groupby: 1, n: 5}); - db.x.insert({groupby: 1, n: 6}); - }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_read, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["find"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_readAny, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["find"] } - ] - } - ] - }, - { - testname: "mapReduce_write", - command: { - mapreduce: "x", - map: function () { emit(this.groupby, this.n); }, - reduce: function (id,emits) { return Array.sum(emits); }, - out: "mr_out" - }, - setup: function (db) { - db.x.insert({groupby: 1, n: 5}); - db.x.insert({groupby: 1, n: 6}); - }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: { readWrite: 1, - readWriteAnyDatabase: 1, - dbOwner: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["find"] }, - { resource: {db: firstDbName, collection: "mr_out"}, actions: ["insert", "remove"] } - ] - }, - { - runOnDb: secondDbName, - roles: {readWriteAnyDatabase: 1, root: 1, __system: 1}, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["find"] }, - { resource: {db: secondDbName, collection: "mr_out"}, actions: ["insert", "remove"] } - ] - } - ] - }, - { - testname: "s_mergeChunks", - command: {mergeChunks: "test.x", bounds: [{i : 0}, {i : 5}]}, - skipStandalone: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {db: "test", collection: "x"}, actions: ["splitChunk"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "d_mergeChunks", - command: {mergeChunks: "test.x", bounds: [{i : 0}, {i : 5}]}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: { __system: 1 }, - privileges: [ - { resource: {cluster: true}, actions: ["internal"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "s_moveChunk", - command: {moveChunk: "test.x"}, - skipStandalone: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {db: "test", collection: "x"}, actions: ["moveChunk"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "d_moveChunk", - command: {moveChunk: "test.x"}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: { __system: 1 }, - privileges: [ - { resource: {cluster: true}, actions: ["internal"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "movePrimary", - command: {movePrimary: "x"}, - skipStandalone: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {db: "x", collection: ""}, actions: ["moveChunk"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "netstat", - command: {netstat: "x"}, - skipStandalone: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["netstat"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "planCacheIndexFilter", - command: {planCacheClearFilters: "x"}, - skipSharded: true, - setup: function (db) { db.x.save( {} ); }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_dbAdmin, - privileges: [ + { + resource: {db: secondDbName, collection: "y"}, + actions: ["insert", "createIndex"] + } + ] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "reIndex", + command: {reIndex: "x"}, + setup: function(db) { + db.x.save({}); + }, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_dbAdmin, + privileges: + [{resource: {db: firstDbName, collection: "x"}, actions: ["reIndex"]}] + }, + { + runOnDb: secondDbName, + roles: roles_dbAdminAny, + privileges: + [{resource: {db: secondDbName, collection: "x"}, actions: ["reIndex"]}] + } + ] + }, + { + testname: "removeShard", + command: {removeShard: "x"}, + skipStandalone: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_clusterManager, + privileges: [{resource: {cluster: true}, actions: ["removeShard"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "repairDatabase", + command: {repairDatabase: 1}, + testcases: [ + { + runOnDb: adminDbName, + roles: + {dbAdminAnyDatabase: 1, hostManager: 1, clusterAdmin: 1, root: 1, __system: 1}, + privileges: + [{resource: {db: adminDbName, collection: ""}, actions: ["repairDatabase"]}] + }, + { + runOnDb: firstDbName, + roles: { + dbAdmin: 1, + dbAdminAnyDatabase: 1, + hostManager: 1, + clusterAdmin: 1, + dbOwner: 1, + root: 1, + __system: 1 + }, + privileges: + [{resource: {db: firstDbName, collection: ""}, actions: ["repairDatabase"]}] + }, + { + runOnDb: secondDbName, + roles: + {dbAdminAnyDatabase: 1, hostManager: 1, clusterAdmin: 1, root: 1, __system: 1}, + privileges: [{ + resource: {db: secondDbName, collection: ""}, + actions: ["repairDatabase"] + }] + } + ] + }, + { + testname: "replSetElect", + command: {replSetElect: 1}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: {__system: 1}, + privileges: [{resource: {cluster: true}, actions: ["internal"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "replSetFreeze", + command: {replSetFreeze: "x"}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_clusterManager, + privileges: [{resource: {cluster: true}, actions: ["replSetStateChange"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "replSetFresh", + command: {replSetFresh: "x"}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: {__system: 1}, + privileges: [{resource: {cluster: true}, actions: ["internal"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "replSetGetRBID", + command: {replSetGetRBID: 1}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: {__system: 1}, + privileges: [{resource: {cluster: true}, actions: ["internal"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "replSetGetStatus", + command: {replSetGetStatus: 1}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: + {clusterMonitor: 1, clusterManager: 1, clusterAdmin: 1, root: 1, __system: 1}, + privileges: [{resource: {cluster: true}, actions: ["replSetGetStatus"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "replSetGetConfig", + command: {replSetGetConfig: 1}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: + {clusterMonitor: 1, clusterManager: 1, clusterAdmin: 1, root: 1, __system: 1}, + privileges: [{resource: {cluster: true}, actions: ["replSetGetConfig"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "replSetHeartbeat", + command: {replSetHeartbeat: 1}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: {__system: 1}, + privileges: [{resource: {cluster: true}, actions: ["internal"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "replSetInitiate", + command: {replSetInitiate: "x"}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_clusterManager, + privileges: [{resource: {cluster: true}, actions: ["replSetConfigure"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "replSetMaintenance", + command: {replSetMaintenance: "x"}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_clusterManager, + privileges: [{resource: {cluster: true}, actions: ["replSetStateChange"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "replSetReconfig", + command: {replSetReconfig: "x"}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_clusterManager, + privileges: [{resource: {cluster: true}, actions: ["replSetConfigure"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "replSetStepDown", + command: {replSetStepDown: "x"}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_clusterManager, + privileges: [{resource: {cluster: true}, actions: ["replSetStateChange"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "replSetSyncFrom", + command: {replSetSyncFrom: "x"}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_clusterManager, + privileges: [{resource: {cluster: true}, actions: ["replSetStateChange"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "resetError", + command: {resetError: 1}, + testcases: [ + {runOnDb: adminDbName, roles: roles_all, privileges: []}, + {runOnDb: firstDbName, roles: roles_all, privileges: []}, + {runOnDb: secondDbName, roles: roles_all, privileges: []} + ] + }, + { + testname: "resync", + command: {resync: 1}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: {hostManager: 1, clusterManager: 1, clusterAdmin: 1, root: 1, __system: 1}, + privileges: [{resource: {cluster: true}, actions: ["resync"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "serverStatus", + command: {serverStatus: 1}, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["serverStatus"]}] + }, + { + runOnDb: firstDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["serverStatus"]}] + }, + { + runOnDb: secondDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["serverStatus"]}] + } + ] + }, + { + testname: "setParameter", + command: {setParameter: 1, quiet: 1}, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_hostManager, + privileges: [{resource: {cluster: true}, actions: ["setParameter"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "setShardVersion", + command: {setShardVersion: 1}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: {__system: 1}, + privileges: [{resource: {cluster: true}, actions: ["internal"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "shardCollection", + command: {shardCollection: "test.x"}, + skipStandalone: true, + testcases: [ + { + runOnDb: adminDbName, + roles: Object.extend({enableSharding: 1}, roles_clusterManager), + privileges: + [{resource: {db: "test", collection: "x"}, actions: ["enableSharding"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "shardingState", + command: {shardingState: 1}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["shardingState"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "shutdown", + command: {shutdown: 1}, + testcases: [{runOnDb: firstDbName, roles: {}}, {runOnDb: secondDbName, roles: {}}] + }, + { + testname: "split", + command: {split: "test.x"}, + skipStandalone: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_clusterManager, + privileges: [{resource: {db: "test", collection: "x"}, actions: ["splitChunk"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "splitChunk", + command: {splitChunk: "test.x"}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: {__system: 1}, + privileges: [{resource: {cluster: true}, actions: ["internal"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "splitVector", + command: {splitVector: "test.x"}, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_clusterManager, + privileges: [{resource: {db: "test", collection: "x"}, actions: ["splitVector"]}], + expectFail: true + }, + { + runOnDb: firstDbName, + roles: roles_clusterManager, + privileges: [{resource: {db: "test", collection: "x"}, actions: ["splitVector"]}], + expectFail: true + }, + { + runOnDb: secondDbName, + roles: roles_clusterManager, + privileges: [{resource: {db: "test", collection: "x"}, actions: ["splitVector"]}], + expectFail: true + } + ] + }, + /* temporarily removed see SERVER-13555 + { + testname: "storageDetails", + command: {storageDetails: "x", analyze: "diskStorage"}, + skipSharded: true, + setup: function (db) { db.x.save( {} ); }, + teardown: function (db) { db.x.drop(); }, + testcases: [ { - resource: {db: firstDbName, collection: "x"}, - actions: ["planCacheIndexFilter"] - } - ], - }, - { - runOnDb: secondDbName, - roles: roles_dbAdminAny, - privileges: [ + runOnDb: firstDbName, + roles: roles_dbAdmin, + privileges: [ + { resource: {db: firstDbName, collection: "x"}, actions: + ["storageDetails"] } + ] + }, { - resource: {db: secondDbName, collection: "x"}, - actions: ["planCacheIndexFilter"] + runOnDb: secondDbName, + roles: roles_dbAdminAny, + privileges: [ + { resource: {db: secondDbName, collection: "x"}, actions: + ["storageDetails"] } + ] } - ], - }, - ] - }, - { - testname: "planCacheRead", - command: {planCacheListQueryShapes: "x"}, - skipSharded: true, - setup: function (db) { db.x.save( {} ); }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_readDbAdmin, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["planCacheRead"] } - ], - }, - { - runOnDb: secondDbName, - roles: roles_readDbAdminAny, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["planCacheRead"] } - ], - }, - ] - }, - { - testname: "planCacheWrite", - command: {planCacheClear: "x"}, - skipSharded: true, - setup: function (db) { db.x.save( {} ); }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_dbAdmin, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["planCacheWrite"] } - ], - }, - { - runOnDb: secondDbName, - roles: roles_dbAdminAny, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["planCacheWrite"] } - ], - }, - ] - }, - { - testname: "ping", - command: {ping: 1}, - testcases: [ - { runOnDb: adminDbName, roles: roles_all, privileges: [ ] }, - { runOnDb: firstDbName, roles: roles_all, privileges: [ ] }, - { runOnDb: secondDbName, roles: roles_all, privileges: [ ] } - ] - }, - { - testname: "profile", - command: {profile: 0}, - skipSharded: true, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_dbAdmin, - privileges: [ - { resource: {db: firstDbName, collection: ""}, actions: ["enableProfiler"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_dbAdminAny, - privileges: [ - { resource: {db: secondDbName, collection: ""}, actions: ["enableProfiler"] } - ] - } - ] - }, - { - testname: "profileGetLevel", - command: {profile: -1}, - skipSharded: true, - testcases: [ - { - runOnDb: firstDbName, - roles: { - backup: 1, - dbAdmin: 1, - dbAdminAnyDatabase: 1, - dbOwner: 1, - clusterMonitor: 1, - clusterAdmin: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: firstDbName, collection: "system.profile"}, - actions: ["find"] } - ] - }, - { - runOnDb: secondDbName, - roles: { - backup: 1, - dbAdminAnyDatabase: 1, - clusterMonitor: 1, - clusterAdmin: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: secondDbName, collection: "system.profile"}, - actions: ["find"] } ] - } - ] - }, - { - testname: "renameCollection_sameDb", - command: {renameCollection: firstDbName + ".x", - to: firstDbName + ".y", - dropTarget: true}, - setup: function (db) { db.getSisterDB(firstDbName).x.save( {} ); }, - teardown: function (db) { - db.getSisterDB(firstDbName).x.drop(); - db.getSisterDB(firstDbName).y.drop(); - }, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_writeDbAdmin, - privileges: [ - { resource: {db: firstDbName, collection: ""}, - actions: ["renameCollectionSameDB"] }, - { resource: {db: firstDbName, collection: "y"}, - actions: ["dropCollection"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - // Make sure that you cannot use renameCollectionSameDB to rename from a collection you - // don't have read access on to one that you do. - testname: "renameCollection_sameDb_failure", - command: {renameCollection: firstDbName + ".x", to: firstDbName + ".y"}, - setup: function (db) { db.getSisterDB(firstDbName).x.save( {} ); }, - teardown: function (db) { - db.getSisterDB(firstDbName).x.drop(); - db.getSisterDB(firstDbName).y.drop(); - }, - testcases: [ - { - runOnDb: adminDbName, - privileges: [ - { resource: {db: firstDbName, collection: ""}, - actions: ["renameCollectionSameDB"] }, - { resource: {db: firstDbName, collection: "y"}, actions: ["find"] } - ], - expectAuthzFailure: true - }, - ] - }, - { - testname: "renameCollection_twoDbs", - command: {renameCollection: firstDbName + ".x", to: secondDbName + ".y"}, - setup: function (db) { - db.getSisterDB(firstDbName).x.save( {} ); - db.getSisterDB(adminDbName).runCommand({movePrimary: firstDbName, to: shard0name}); - db.getSisterDB(adminDbName).runCommand({movePrimary: secondDbName, to: shard0name}); - }, - teardown: function (db) { - db.getSisterDB(firstDbName).x.drop(); - db.getSisterDB(secondDbName).y.drop(); - }, - testcases: [ - { - runOnDb: adminDbName, - roles: {readWriteAnyDatabase: 1, root: 1, __system: 1}, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["find", "dropCollection"] }, - { resource: {db: secondDbName, collection: "y"}, actions: ["insert", "createIndex"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "reIndex", - command: {reIndex: "x"}, - setup: function (db) { db.x.save( {} ); }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_dbAdmin, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["reIndex"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_dbAdminAny, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["reIndex"] } - ] - } - ] - }, - { - testname: "removeShard", - command: {removeShard: "x"}, - skipStandalone: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {cluster: true}, actions: ["removeShard"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "repairDatabase", - command: {repairDatabase: 1}, - testcases: [ - { - runOnDb: adminDbName, - roles: { - dbAdminAnyDatabase: 1, - hostManager: 1, - clusterAdmin: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: adminDbName, collection: ""}, actions: ["repairDatabase"] } - ] - }, - { - runOnDb: firstDbName, - roles: { - dbAdmin: 1, - dbAdminAnyDatabase: 1, - hostManager: 1, - clusterAdmin: 1, - dbOwner: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: firstDbName, collection: ""}, actions: ["repairDatabase"] } - ] - }, - { - runOnDb: secondDbName, - roles: { - dbAdminAnyDatabase: 1, - hostManager: 1, - clusterAdmin: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {db: secondDbName, collection: ""}, actions: ["repairDatabase"] } - ] - } - ] - }, - { - testname: "replSetElect", - command: {replSetElect: 1}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: {__system: 1}, - privileges: [ - { resource: {cluster: true}, actions: ["internal"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "replSetFreeze", - command: {replSetFreeze: "x"}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {cluster: true}, actions: ["replSetStateChange"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "replSetFresh", - command: {replSetFresh: "x"}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: {__system: 1}, - privileges: [ - { resource: {cluster: true}, actions: ["internal"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "replSetGetRBID", - command: {replSetGetRBID: 1}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: {__system: 1}, - privileges: [ - { resource: {cluster: true}, actions: ["internal"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "replSetGetStatus", - command: {replSetGetStatus: 1}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: { - clusterMonitor: 1, - clusterManager: 1, - clusterAdmin: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {cluster: true}, actions: ["replSetGetStatus"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "replSetGetConfig", - command: {replSetGetConfig: 1}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: { - clusterMonitor: 1, - clusterManager: 1, - clusterAdmin: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {cluster: true}, actions: ["replSetGetConfig"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "replSetHeartbeat", - command: {replSetHeartbeat: 1}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: {__system: 1}, - privileges: [ - { resource: {cluster: true}, actions: ["internal"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "replSetInitiate", - command: {replSetInitiate: "x"}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {cluster: true}, actions: ["replSetConfigure"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "replSetMaintenance", - command: {replSetMaintenance: "x"}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {cluster: true}, actions: ["replSetStateChange"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "replSetReconfig", - command: {replSetReconfig: "x"}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {cluster: true}, actions: ["replSetConfigure"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "replSetStepDown", - command: {replSetStepDown: "x"}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {cluster: true}, actions: ["replSetStateChange"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "replSetSyncFrom", - command: {replSetSyncFrom: "x"}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {cluster: true}, actions: ["replSetStateChange"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "resetError", - command: {resetError: 1}, - testcases: [ - { runOnDb: adminDbName, roles: roles_all, privileges: [ ] }, - { runOnDb: firstDbName, roles: roles_all, privileges: [ ] }, - { runOnDb: secondDbName, roles: roles_all, privileges: [ ] } - ] - }, - { - testname: "resync", - command: {resync: 1}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: { - hostManager: 1, - clusterManager: 1, - clusterAdmin: 1, - root: 1, - __system: 1 - }, - privileges: [ - { resource: {cluster: true}, actions: ["resync"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "serverStatus", - command: {serverStatus: 1}, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["serverStatus"] } - ] - }, - { - runOnDb: firstDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["serverStatus"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["serverStatus"] } - ] - } - ] - }, - { - testname: "setParameter", - command: {setParameter: 1, quiet: 1}, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_hostManager, - privileges: [ - { resource: {cluster: true}, actions: ["setParameter"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "setShardVersion", - command: {setShardVersion: 1}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: {__system: 1}, - privileges: [ - { resource: {cluster: true}, actions: ["internal"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "shardCollection", - command: {shardCollection: "test.x"}, - skipStandalone: true, - testcases: [ - { - runOnDb: adminDbName, - roles: Object.extend({enableSharding:1}, roles_clusterManager), - privileges: [ - { resource: {db: "test", collection: "x"}, actions: ["enableSharding"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "shardingState", - command: {shardingState: 1}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["shardingState"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "shutdown", - command: {shutdown: 1}, - testcases: [ - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "split", - command: {split: "test.x"}, - skipStandalone: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {db: "test", collection: "x"}, actions: ["splitChunk"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "splitChunk", - command: {splitChunk: "test.x"}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: { __system: 1 }, - privileges: [ - { resource: {cluster: true}, actions: ["internal"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "splitVector", - command: {splitVector: "test.x"}, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {db: "test", collection: "x"}, actions: ["splitVector"] } - ], - expectFail: true - }, - { - runOnDb: firstDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {db: "test", collection: "x"}, actions: ["splitVector"] } - ], - expectFail: true - }, - { - runOnDb: secondDbName, - roles: roles_clusterManager, - privileges: [ - { resource: {db: "test", collection: "x"}, actions: ["splitVector"] } - ], - expectFail: true - } - ] - }, -/* temporarily removed see SERVER-13555 - { - testname: "storageDetails", - command: {storageDetails: "x", analyze: "diskStorage"}, - skipSharded: true, - setup: function (db) { db.x.save( {} ); }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_dbAdmin, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["storageDetails"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_dbAdminAny, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["storageDetails"] } - ] - } - ] - }, */ - { - testname: "top", - command: {top: 1}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_monitoring, - privileges: [ - { resource: {cluster: true}, actions: ["top"] } - ] - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "touch", - command: {touch: "x", data: true, index: false}, - skipSharded: true, - setup: function (db) { db.x.save( {} ); }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: adminDbName, - roles: roles_hostManager, - privileges: [ - { resource: {cluster: true}, actions: ["touch"] } - ] - }, - { - runOnDb: firstDbName, - roles: roles_hostManager, - privileges: [ - { resource: {cluster: true}, actions: ["touch"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_hostManager, - privileges: [ - { resource: {cluster: true}, actions: ["touch"] } - ] - } - ] - }, - { - testname: "unsetSharding", - command: {unsetSharding: "x"}, - skipSharded: true, - testcases: [ - { - runOnDb: adminDbName, - roles: {__system: 1}, - privileges: [ - { resource: {cluster: true}, actions: ["internal"] } - ], - expectFail: true - }, - { runOnDb: firstDbName, roles: {} }, - { runOnDb: secondDbName, roles: {} } - ] - }, - { - testname: "validate", - command: {validate: "x"}, - setup: function (db) { db.x.save( {} ); }, - teardown: function (db) { db.x.drop(); }, - testcases: [ - { - runOnDb: firstDbName, - roles: roles_dbAdmin, - privileges: [ - { resource: {db: firstDbName, collection: "x"}, actions: ["validate"] } - ] - }, - { - runOnDb: secondDbName, - roles: roles_dbAdminAny, - privileges: [ - { resource: {db: secondDbName, collection: "x"}, actions: ["validate"] } - ] - } - ] - }, - { - // Test that the root role has the privilege to validate any system.* collection - testname: "validate_system", - command: {validate: "system.users"}, - testcases: [ - { - runOnDb: adminDbName, - roles: { - root: 1, - __system: 1 - } - } - ] - }, - { - testname: "whatsmyuri", - command: {whatsmyuri: 1}, - testcases: [ - { runOnDb: adminDbName, roles: roles_all, privileges: [ ] }, - { runOnDb: firstDbName, roles: roles_all, privileges: [ ] }, - { runOnDb: secondDbName, roles: roles_all, privileges: [ ] } - ] + }, */ + { + testname: "top", + command: {top: 1}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_monitoring, + privileges: [{resource: {cluster: true}, actions: ["top"]}] + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "touch", + command: {touch: "x", data: true, index: false}, + skipSharded: true, + setup: function(db) { + db.x.save({}); + }, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: adminDbName, + roles: roles_hostManager, + privileges: [{resource: {cluster: true}, actions: ["touch"]}] + }, + { + runOnDb: firstDbName, + roles: roles_hostManager, + privileges: [{resource: {cluster: true}, actions: ["touch"]}] + }, + { + runOnDb: secondDbName, + roles: roles_hostManager, + privileges: [{resource: {cluster: true}, actions: ["touch"]}] + } + ] + }, + { + testname: "unsetSharding", + command: {unsetSharding: "x"}, + skipSharded: true, + testcases: [ + { + runOnDb: adminDbName, + roles: {__system: 1}, + privileges: [{resource: {cluster: true}, actions: ["internal"]}], + expectFail: true + }, + {runOnDb: firstDbName, roles: {}}, + {runOnDb: secondDbName, roles: {}} + ] + }, + { + testname: "validate", + command: {validate: "x"}, + setup: function(db) { + db.x.save({}); + }, + teardown: function(db) { + db.x.drop(); + }, + testcases: [ + { + runOnDb: firstDbName, + roles: roles_dbAdmin, + privileges: + [{resource: {db: firstDbName, collection: "x"}, actions: ["validate"]}] + }, + { + runOnDb: secondDbName, + roles: roles_dbAdminAny, + privileges: + [{resource: {db: secondDbName, collection: "x"}, actions: ["validate"]}] + } + ] + }, + { + // Test that the root role has the privilege to validate any system.* collection + testname: "validate_system", + command: {validate: "system.users"}, + testcases: [{runOnDb: adminDbName, roles: {root: 1, __system: 1}}] + }, + { + testname: "whatsmyuri", + command: {whatsmyuri: 1}, + testcases: [ + {runOnDb: adminDbName, roles: roles_all, privileges: []}, + {runOnDb: firstDbName, roles: roles_all, privileges: []}, + {runOnDb: secondDbName, roles: roles_all, privileges: []} + ] } ], - /************* SHARED TEST LOGIC ****************/ /** @@ -2844,7 +2612,9 @@ var authCommandsLib = { failures = failures.concat(res); } - failures.forEach(function(i) { jsTest.log(i); }); + failures.forEach(function(i) { + jsTest.log(i); + }); assert.eq(0, failures.length); } diff --git a/jstests/auth/localhostAuthBypass.js b/jstests/auth/localhostAuthBypass.js index 1b07456fbe3..fdaf4386794 100644 --- a/jstests/auth/localhostAuthBypass.js +++ b/jstests/auth/localhostAuthBypass.js @@ -1,7 +1,7 @@ -//SERVER-6591: Localhost authentication exception doesn't work right on sharded cluster +// SERVER-6591: Localhost authentication exception doesn't work right on sharded cluster // -//This test is to ensure that localhost authentication works correctly against a standalone -//mongod whether it is hosted with "localhost" or a hostname. +// This test is to ensure that localhost authentication works correctly against a standalone +// mongod whether it is hosted with "localhost" or a hostname. var baseName = "auth_server-6591"; var dbpath = MongoRunner.dataPath + baseName; @@ -12,67 +12,81 @@ load("jstests/libs/host_ipaddr.js"); var createUser = function(mongo) { print("============ adding a user."); - mongo.getDB("admin").createUser( - { user:username, pwd: password, roles: jsTest.adminUserRoles }); + mongo.getDB("admin").createUser({user: username, pwd: password, roles: jsTest.adminUserRoles}); }; var assertCannotRunCommands = function(mongo) { print("============ ensuring that commands cannot be run."); var test = mongo.getDB("test"); - assert.throws( function() { test.system.users.findOne(); }); + assert.throws(function() { + test.system.users.findOne(); + }); - assert.writeError(test.foo.save({ _id: 0 })); + assert.writeError(test.foo.save({_id: 0})); - assert.throws( function() { test.foo.findOne({_id:0}); }); + assert.throws(function() { + test.foo.findOne({_id: 0}); + }); - assert.writeError(test.foo.update({ _id: 0 }, { $set: { x: 20 }})); - assert.writeError(test.foo.remove({ _id: 0 })); + assert.writeError(test.foo.update({_id: 0}, {$set: {x: 20}})); + assert.writeError(test.foo.remove({_id: 0})); - assert.throws(function() { + assert.throws(function() { test.foo.mapReduce( - function() { emit(1, 1); }, - function(id, count) { return Array.sum(count); }, - { out: "other" }); + function() { + emit(1, 1); + }, + function(id, count) { + return Array.sum(count); + }, + {out: "other"}); }); // Additional commands not permitted // Create non-admin user - assert.throws(function() { mongo.getDB("test").createUser( - { user: username, pwd: password, roles: ['readWrite'] }); }); + assert.throws(function() { + mongo.getDB("test").createUser({user: username, pwd: password, roles: ['readWrite']}); + }); // DB operations var authorizeErrorCode = 13; - assert.commandFailedWithCode(mongo.getDB("test").copyDatabase("admin", "admin2"), - authorizeErrorCode, "copyDatabase"); + assert.commandFailedWithCode( + mongo.getDB("test").copyDatabase("admin", "admin2"), authorizeErrorCode, "copyDatabase"); // Create collection - assert.commandFailedWithCode(mongo.getDB("test").createCollection( - "log", { capped: true, size: 5242880, max: 5000 } ), - authorizeErrorCode, "createCollection"); + assert.commandFailedWithCode( + mongo.getDB("test").createCollection("log", {capped: true, size: 5242880, max: 5000}), + authorizeErrorCode, + "createCollection"); // Set/Get system parameters - var params = [{ param: "journalCommitInterval", val: 200 }, - { param: "logLevel", val: 2 }, - { param: "logUserIds", val: 1 }, - { param: "notablescan", val: 1 }, - { param: "quiet", val: 1 }, - { param: "replApplyBatchSize", val: 10 }, - { param: "replIndexPrefetch", val: "none" }, - { param: "syncdelay", val: 30 }, - { param: "traceExceptions", val: true }, - { param: "sslMode", val: "preferSSL" }, - { param: "clusterAuthMode", val: "sendX509" }, - { param: "userCacheInvalidationIntervalSecs", val: 300 } - ]; + var params = [ + {param: "journalCommitInterval", val: 200}, + {param: "logLevel", val: 2}, + {param: "logUserIds", val: 1}, + {param: "notablescan", val: 1}, + {param: "quiet", val: 1}, + {param: "replApplyBatchSize", val: 10}, + {param: "replIndexPrefetch", val: "none"}, + {param: "syncdelay", val: 30}, + {param: "traceExceptions", val: true}, + {param: "sslMode", val: "preferSSL"}, + {param: "clusterAuthMode", val: "sendX509"}, + {param: "userCacheInvalidationIntervalSecs", val: 300} + ]; params.forEach(function(p) { - var cmd = { setParameter: 1 }; + var cmd = { + setParameter: 1 + }; cmd[p.param] = p.val; - assert.commandFailedWithCode(mongo.getDB("admin").runCommand(cmd), - authorizeErrorCode, "setParameter: "+p.param); + assert.commandFailedWithCode( + mongo.getDB("admin").runCommand(cmd), authorizeErrorCode, "setParameter: " + p.param); }); params.forEach(function(p) { - var cmd = { getParameter: 1 }; + var cmd = { + getParameter: 1 + }; cmd[p.param] = 1; - assert.commandFailedWithCode(mongo.getDB("admin").runCommand(cmd), - authorizeErrorCode, "getParameter: "+p.param); + assert.commandFailedWithCode( + mongo.getDB("admin").runCommand(cmd), authorizeErrorCode, "getParameter: " + p.param); }); }; @@ -83,15 +97,18 @@ var assertCanRunCommands = function(mongo) { // will throw on failure test.system.users.findOne(); - assert.writeOK(test.foo.save({ _id: 0 })); - assert.writeOK(test.foo.update({ _id: 0 }, { $set: { x: 20 }})); - assert.writeOK(test.foo.remove({ _id: 0 })); + assert.writeOK(test.foo.save({_id: 0})); + assert.writeOK(test.foo.update({_id: 0}, {$set: {x: 20}})); + assert.writeOK(test.foo.remove({_id: 0})); test.foo.mapReduce( - function() { emit(1, 1); }, - function(id, count) { return Array.sum(count); }, - { out: "other" } - ); + function() { + emit(1, 1); + }, + function(id, count) { + return Array.sum(count); + }, + {out: "other"}); }; var authenticate = function(mongo) { @@ -101,7 +118,7 @@ var authenticate = function(mongo) { var shutdown = function(conn) { print("============ shutting down."); - MongoRunner.stopMongod(conn.port, /*signal*/false, { auth: { user: username, pwd: password}}); + MongoRunner.stopMongod(conn.port, /*signal*/ false, {auth: {user: username, pwd: password}}); }; var runTest = function(useHostName) { @@ -143,10 +160,14 @@ var runNonlocalTest = function(host) { var mongo = new Mongo(host + ":" + conn.port); assertCannotRunCommands(mongo); - assert.throws(function() { mongo.getDB("admin").createUser - ({ user:username, pwd: password, roles: jsTest.adminUserRoles }); }); - assert.throws(function() { mongo.getDB("$external").createUser - ({ user:username, pwd: password, roles: jsTest.adminUserRoles }); }); + assert.throws(function() { + mongo.getDB("admin") + .createUser({user: username, pwd: password, roles: jsTest.adminUserRoles}); + }); + assert.throws(function() { + mongo.getDB("$external") + .createUser({user: username, pwd: password, roles: jsTest.adminUserRoles}); + }); shutdown(conn); }; diff --git a/jstests/auth/log_user_basic.js b/jstests/auth/log_user_basic.js index 82702fc4756..06e74ea3109 100644 --- a/jstests/auth/log_user_basic.js +++ b/jstests/auth/log_user_basic.js @@ -4,258 +4,263 @@ // TODO(schwerin) Re-enable this test after resolving corresponding TODO in mongo/util/log.cpp. if (0) { + /** + * Extracts information from a mongod/mongos log entry. + * + * @param line {string} a single line of log. + * + * @return {Object} format: + * + * { + * id: <string>, // thread id of the log line. + * // list of users logged in. Can be empty. + * users: <Object> // map of db name to user name + * } + */ + var parseLog = function(line) { + var THREAD_ID_PATTERN = / [012]?\d:\d\d:\d\d\.\d\d\d \[(.+)\] /; + var ID_USER_PATTERN = new RegExp(THREAD_ID_PATTERN.source + 'user:([^ ]*) '); + var res = THREAD_ID_PATTERN.exec(line); + + if (res == null) { + return null; + } + + var logInfo = { + id: res[1], + users: {} + }; -/** - * Extracts information from a mongod/mongos log entry. - * - * @param line {string} a single line of log. - * - * @return {Object} format: - * - * { - * id: <string>, // thread id of the log line. - * // list of users logged in. Can be empty. - * users: <Object> // map of db name to user name - * } - */ -var parseLog = function(line) { - var THREAD_ID_PATTERN = / [012]?\d:\d\d:\d\d\.\d\d\d \[(.+)\] /; - var ID_USER_PATTERN = new RegExp(THREAD_ID_PATTERN.source + 'user:([^ ]*) '); - var res = THREAD_ID_PATTERN.exec(line); - - if (res == null) { - return null; - } - - var logInfo = { id: res[1], users: {} }; + var userLog = null; + res = ID_USER_PATTERN.exec(line); - var userLog = null; - res = ID_USER_PATTERN.exec(line); + if (res != null) { + userLog = res[2]; + // should not have trailing commas + assert.neq(',', userLog[userLog.length - 1], 'Bad user log list format: ' + line); - if (res != null) { - userLog = res[2]; - // should not have trailing commas - assert.neq(',', userLog[userLog.length - 1], 'Bad user log list format: ' + line); + userLog.split(',').forEach(function(userData) { + var userAndDB = userData.split('@'); + assert.eq(2, + userAndDB.length, + 'Bad user db pair format: ' + userData + ' from line: ' + line); + logInfo.users[userAndDB[1]] = userAndDB[0]; + }); + } - userLog.split(',').forEach(function(userData) { - var userAndDB = userData.split('@'); - assert.eq(2, userAndDB.length, 'Bad user db pair format: ' + userData + - ' from line: ' + line); - logInfo.users[userAndDB[1]] = userAndDB[0]; - }); - } + return logInfo; + }; - return logInfo; -}; + /** + * Performs a series of test on user id logging. + * + * @param conn1 {Mongo} the connection object to use for logging in users. + * @param conn2 {Mongo} another connection object different from conn1. + */ + var doTest = function(conn1, conn2) { + var connInfo1 = { + id: null, // thread id of this connection + mongo: conn1, // connection object + users: {} // contains authenticated users represented as a map of db to user names. + }; -/** - * Performs a series of test on user id logging. - * - * @param conn1 {Mongo} the connection object to use for logging in users. - * @param conn2 {Mongo} another connection object different from conn1. - */ -var doTest = function(conn1, conn2) { - var connInfo1 = { - id: null, // thread id of this connection - mongo: conn1, // connection object - users: {} // contains authenticated users represented as a map of db to user names. - }; + var connInfo2 = { + id: null, + mongo: conn2, + users: {} + }; - var connInfo2 = { - id: null, mongo: conn2, users: {} - }; + var conn1Auth = + [{user: 'foo', pwd: 'bar', db: 'test'}, {user: 'chun', pwd: 'li', db: 'sf'}]; - var conn1Auth = [ - { user: 'foo', pwd: 'bar', db: 'test' }, - { user: 'chun', pwd: 'li', db: 'sf' } - ]; - - var conn2Auth = [ - { user: 'root', pwd: 'ugat', db: 'admin' }, - { user: 'elbow', pwd: 'freeze', db: 'bboy' } - ]; - - var loginUser = function(connInfo, connAuth) { - var db = connInfo.mongo.getDB(connAuth.db); - db.createUser({user: connAuth.user, pwd: connAuth.pwd, roles: jsTest.adminUserRoles}); - db.auth(connAuth.user, connAuth.pwd); - connInfo.users[connAuth.db] = connAuth.user; - }; + var conn2Auth = + [{user: 'root', pwd: 'ugat', db: 'admin'}, {user: 'elbow', pwd: 'freeze', db: 'bboy'}]; - var logoutUser = function(connInfo, connAuth) { - var db = connInfo.mongo.getDB(connAuth.db); - db.runCommand({ logout: 1 }); - delete connInfo.users[connAuth.db]; - }; + var loginUser = function(connInfo, connAuth) { + var db = connInfo.mongo.getDB(connAuth.db); + db.createUser({user: connAuth.user, pwd: connAuth.pwd, roles: jsTest.adminUserRoles}); + db.auth(connAuth.user, connAuth.pwd); + connInfo.users[connAuth.db] = connAuth.user; + }; - /** - * Performs a couple of test to make sure that the format of the log is correct. - * Also checks that whether the right users show up in the logs. - * - * @param log {Array.<string>} list of log lines to check. - * @param connInfo {Object} - */ - var checkLogs = function(log, connInfo) { - var foundOne = false; + var logoutUser = function(connInfo, connAuth) { + var db = connInfo.mongo.getDB(connAuth.db); + db.runCommand({logout: 1}); + delete connInfo.users[connAuth.db]; + }; /** - * @return true if the logInfo contains the same users as connIfo. + * Performs a couple of test to make sure that the format of the log is correct. + * Also checks that whether the right users show up in the logs. + * + * @param log {Array.<string>} list of log lines to check. + * @param connInfo {Object} */ - var checkUsers = function(logInfo) { - for (var db in logInfo.users) { - if (logInfo.users.hasOwnProperty(db) && - logInfo.users[db] != connInfo.users[db]) { - return false; + var checkLogs = function(log, connInfo) { + var foundOne = false; + + /** + * @return true if the logInfo contains the same users as connIfo. + */ + var checkUsers = function(logInfo) { + for (var db in logInfo.users) { + if (logInfo.users.hasOwnProperty(db) && + logInfo.users[db] != connInfo.users[db]) { + return false; + } } - } - for (db in connInfo.users) { - if (connInfo.users.hasOwnProperty(db) && - logInfo.users[db] != connInfo.users[db]) { - return false; + for (db in connInfo.users) { + if (connInfo.users.hasOwnProperty(db) && + logInfo.users[db] != connInfo.users[db]) { + return false; + } } - } - return true; - }; + return true; + }; - var hasUser = function(logInfo) { - for (var db in logInfo.users) { - if (logInfo.users.hasOwnProperty(db)) { - return true; + var hasUser = function(logInfo) { + for (var db in logInfo.users) { + if (logInfo.users.hasOwnProperty(db)) { + return true; + } } - } - return false; - }; + return false; + }; - log.forEach(function(line) { - var logInfo = parseLog(line); + log.forEach(function(line) { + var logInfo = parseLog(line); - if (logInfo == null) return; - if (connInfo.id == null) { - if (checkUsers(logInfo)) { - connInfo.id = logInfo.id; + if (logInfo == null) + return; + if (connInfo.id == null) { + if (checkUsers(logInfo)) { + connInfo.id = logInfo.id; + foundOne = true; + } + + return; + } + + if (logInfo.id == connInfo.id) { foundOne = true; + assert(checkUsers(logInfo), + 'logged users does not match [' + tojson(connInfo.users) + '], log: ' + + line); + } else if (hasUser(logInfo)) { + assert(!checkUsers(logInfo), 'Unexpected user log on another thread: ' + line); } + }); - return; - } + assert(foundOne, 'User log not found in: ' + tojson(log)); + }; - if (logInfo.id == connInfo.id) { - foundOne = true; - assert(checkUsers(logInfo), 'logged users does not match [' + - tojson(connInfo.users) + '], log: ' + line); + var testDB1 = connInfo1.mongo.getDB('test'); + var testDB2 = connInfo2.mongo.getDB('test'); + + // Note: The succeeding tests should not be re-ordered. + (function() { + jsTest.log('Test single user on 1 connection.'); + loginUser(connInfo1, conn1Auth[0]); + testDB1.runCommand({dbStats: 1}); + var log = testDB1.adminCommand({getLog: 'global'}); + checkLogs(log.log, connInfo1); + })(); + + (function() { + jsTest.log('Test multiple conn with 1 user each'); + loginUser(connInfo2, conn2Auth[0]); + testDB2.runCommand({dbStats: 1}); + var log = testDB1.adminCommand({getLog: 'global'}); + checkLogs(log.log, connInfo2); + })(); + + (function() { + jsTest.log('Test multiple conn with 1 multiple user'); + loginUser(connInfo1, conn1Auth[1]); + var log = testDB1.adminCommand({getLog: 'global'}); + var lastLogLine = log.log.pop(); // Used for trimming out logs before this point. + testDB1.runCommand({dbStats: 1}); + log = testDB1.adminCommand({getLog: 'global'}); + + // Remove old log entries. + while (log.log.shift() != lastLogLine) { } - else if(hasUser(logInfo)) { - - assert(!checkUsers(logInfo), 'Unexpected user log on another thread: ' + line); + assert(log.log.length > 0); + checkLogs(log.log, connInfo1); + })(); + + (function() { + jsTest.log('Test multiple conn with multiple users each'); + loginUser(connInfo2, conn2Auth[1]); + var log = testDB2.adminCommand({getLog: 'global'}); + var lastLogLine = log.log.pop(); // Used for trimming out logs before this point. + testDB1.runCommand({dbStats: 1}); + log = testDB2.adminCommand({getLog: 'global'}); + + // Remove old log entries. + while (log.log.shift() != lastLogLine) { } - }); - - assert(foundOne, 'User log not found in: ' + tojson(log)); + assert(log.log.length > 0); + checkLogs(log.log, connInfo2); + })(); + + (function() { + // Case for logout older user first. + jsTest.log('Test log line will not show foo'); + logoutUser(connInfo1, conn1Auth[0]); + var log = testDB1.adminCommand({getLog: 'global'}); + var lastLogLine = log.log.pop(); // Used for trimming out logs before this point. + testDB1.runCommand({dbStats: 1}); + log = testDB1.adminCommand({getLog: 'global'}); + + // Remove old log entries. + while (log.log.shift() != lastLogLine) { + } + assert(log.log.length > 0); + checkLogs(log.log, connInfo1); + })(); + + (function() { + jsTest.log('Test that log for conn1 will not show \'user:\''); + logoutUser(connInfo1, conn1Auth[1]); + var log = testDB1.adminCommand({getLog: 'global'}); + var lastLogLine = log.log.pop(); // Used for trimming out logs before this point. + testDB1.runCommand({dbStats: 1}); + log = testDB1.adminCommand({getLog: 'global'}); + + // Remove old log entries. + while (log.log.shift() != lastLogLine) { + } + assert(log.log.length > 0); + checkLogs(log.log, connInfo1); + })(); + + (function() { + // Case for logout newer user first. + jsTest.log('Test log line will not show elbow'); + logoutUser(connInfo2, conn2Auth[1]); + var log = testDB2.adminCommand({getLog: 'global'}); + var lastLogLine = log.log.pop(); // Used for trimming out logs before this point. + testDB1.runCommand({dbStats: 1}); + log = testDB2.adminCommand({getLog: 'global'}); + + // Remove old log entries. + while (log.log.shift() != lastLogLine) { + } + assert(log.log.length > 0); + checkLogs(log.log, connInfo2); + })(); }; - var testDB1 = connInfo1.mongo.getDB('test'); - var testDB2 = connInfo2.mongo.getDB('test'); - - // Note: The succeeding tests should not be re-ordered. - (function() { - jsTest.log('Test single user on 1 connection.'); - loginUser(connInfo1, conn1Auth[0]); - testDB1.runCommand({ dbStats: 1 }); - var log = testDB1.adminCommand({ getLog: 'global' }); - checkLogs(log.log, connInfo1); - })(); - - (function() { - jsTest.log('Test multiple conn with 1 user each'); - loginUser(connInfo2, conn2Auth[0]); - testDB2.runCommand({ dbStats: 1 }); - var log = testDB1.adminCommand({ getLog: 'global' }); - checkLogs(log.log, connInfo2); - })(); - - (function(){ - jsTest.log('Test multiple conn with 1 multiple user'); - loginUser(connInfo1, conn1Auth[1]); - var log = testDB1.adminCommand({ getLog: 'global' }); - var lastLogLine = log.log.pop(); // Used for trimming out logs before this point. - testDB1.runCommand({ dbStats: 1 }); - log = testDB1.adminCommand({ getLog: 'global' }); - - // Remove old log entries. - while (log.log.shift() != lastLogLine) { } - assert(log.log.length > 0); - checkLogs(log.log, connInfo1); - })(); - - (function(){ - jsTest.log('Test multiple conn with multiple users each'); - loginUser(connInfo2, conn2Auth[1]); - var log = testDB2.adminCommand({ getLog: 'global' }); - var lastLogLine = log.log.pop(); // Used for trimming out logs before this point. - testDB1.runCommand({ dbStats: 1 }); - log = testDB2.adminCommand({ getLog: 'global' }); - - // Remove old log entries. - while (log.log.shift() != lastLogLine) { } - assert(log.log.length > 0); - checkLogs(log.log, connInfo2); - })(); - - (function(){ - // Case for logout older user first. - jsTest.log('Test log line will not show foo'); - logoutUser(connInfo1, conn1Auth[0]); - var log = testDB1.adminCommand({ getLog: 'global' }); - var lastLogLine = log.log.pop(); // Used for trimming out logs before this point. - testDB1.runCommand({ dbStats: 1 }); - log = testDB1.adminCommand({ getLog: 'global' }); - - // Remove old log entries. - while (log.log.shift() != lastLogLine) { } - assert(log.log.length > 0); - checkLogs(log.log, connInfo1); - })(); - - (function(){ - jsTest.log('Test that log for conn1 will not show \'user:\''); - logoutUser(connInfo1, conn1Auth[1]); - var log = testDB1.adminCommand({ getLog: 'global' }); - var lastLogLine = log.log.pop(); // Used for trimming out logs before this point. - testDB1.runCommand({ dbStats: 1 }); - log = testDB1.adminCommand({ getLog: 'global' }); - - // Remove old log entries. - while (log.log.shift() != lastLogLine) { } - assert(log.log.length > 0); - checkLogs(log.log, connInfo1); - })(); - - (function(){ - // Case for logout newer user first. - jsTest.log('Test log line will not show elbow'); - logoutUser(connInfo2, conn2Auth[1]); - var log = testDB2.adminCommand({ getLog: 'global' }); - var lastLogLine = log.log.pop(); // Used for trimming out logs before this point. - testDB1.runCommand({ dbStats: 1 }); - log = testDB2.adminCommand({ getLog: 'global' }); - - // Remove old log entries. - while (log.log.shift() != lastLogLine) { } - assert(log.log.length > 0); - checkLogs(log.log, connInfo2); - })(); -}; - -var mongo = MongoRunner.runMongod({ verbose: 5, setParameter: 'logUserIds=1' }); -doTest(mongo, new Mongo(mongo.host)); -MongoRunner.stopMongod(mongo.port); - -var st = new ShardingTest({ shards: 1, verbose: 5, - other: { mongosOptions: { setParameter: 'logUserIds=1' }}}); -doTest(st.s, new Mongo(st.s.host)); -st.stop(); + var mongo = MongoRunner.runMongod({verbose: 5, setParameter: 'logUserIds=1'}); + doTest(mongo, new Mongo(mongo.host)); + MongoRunner.stopMongod(mongo.port); + var st = new ShardingTest( + {shards: 1, verbose: 5, other: {mongosOptions: {setParameter: 'logUserIds=1'}}}); + doTest(st.s, new Mongo(st.s.host)); + st.stop(); } diff --git a/jstests/auth/log_userid_off.js b/jstests/auth/log_userid_off.js index abebda28709..62d0af74c02 100644 --- a/jstests/auth/log_userid_off.js +++ b/jstests/auth/log_userid_off.js @@ -3,7 +3,7 @@ * * @param mongo {Mongo} connection object. */ -var doTest = function (mongo, callSetParam) { +var doTest = function(mongo, callSetParam) { var TEST_USER = 'foo'; var TEST_PWD = 'bar'; var testDB = mongo.getDB('test'); @@ -11,30 +11,29 @@ var doTest = function (mongo, callSetParam) { testDB.createUser({user: TEST_USER, pwd: TEST_PWD, roles: jsTest.basicUserRoles}); testDB.auth(TEST_USER, TEST_PWD); - testDB.runCommand({ dbStats: 1 }); + testDB.runCommand({dbStats: 1}); - var log = testDB.adminCommand({ getLog: 'global' }); + var log = testDB.adminCommand({getLog: 'global'}); log.log.forEach(function(line) { assert.eq(-1, line.indexOf('user: foo@'), 'user logged: ' + line); }); // logUserIds should not be settable - var res = testDB.runCommand({ setParameter: 1, logUserIds: 1 }); + var res = testDB.runCommand({setParameter: 1, logUserIds: 1}); assert(!res.ok); - testDB.runCommand({ dbStats: 1 }); + testDB.runCommand({dbStats: 1}); - log = testDB.adminCommand({ getLog: 'global' }); + log = testDB.adminCommand({getLog: 'global'}); log.log.forEach(function(line) { assert.eq(-1, line.indexOf('user: foo@'), 'user logged: ' + line); }); }; -var mongo = MongoRunner.runMongod({ verbose: 5 }); +var mongo = MongoRunner.runMongod({verbose: 5}); doTest(mongo); MongoRunner.stopMongod(mongo.port); -var st = new ShardingTest({ shards: 1, verbose: 5 }); +var st = new ShardingTest({shards: 1, verbose: 5}); doTest(st.s); st.stop(); - diff --git a/jstests/auth/logout_reconnect.js b/jstests/auth/logout_reconnect.js index dc59d408544..fa5d8a8fcdb 100644 --- a/jstests/auth/logout_reconnect.js +++ b/jstests/auth/logout_reconnect.js @@ -4,46 +4,40 @@ * It is a regression test for SERVER-8798. */ -var conn = MongoRunner.runMongod({ - auth : "", - remember : true -}); +var conn = MongoRunner.runMongod({auth: "", remember: true}); // create user with rw permissions and login var testDB = conn.getDB('test'); var adminDB = conn.getDB('admin'); -adminDB.createUser({user:'admin', pwd:'admin', roles:['userAdminAnyDatabase']}); -adminDB.auth('admin','admin'); -testDB.createUser({user:'rwuser', pwd:'rwuser', roles:['readWrite']}); +adminDB.createUser({user: 'admin', pwd: 'admin', roles: ['userAdminAnyDatabase']}); +adminDB.auth('admin', 'admin'); +testDB.createUser({user: 'rwuser', pwd: 'rwuser', roles: ['readWrite']}); adminDB.logout(); testDB.auth('rwuser', 'rwuser'); // verify that the rwuser can read and write -testDB.foo.insert({a:1}); -assert.eq(1, testDB.foo.find({a:1}).count(), "failed to read"); +testDB.foo.insert({a: 1}); +assert.eq(1, testDB.foo.find({a: 1}).count(), "failed to read"); // assert that the user cannot read unauthenticated testDB.logout(); -assert.throws(function(){ testDB.foo.findOne(); }, - [], - "user should not be able to read after logging out"); +assert.throws(function() { + testDB.foo.findOne(); +}, [], "user should not be able to read after logging out"); MongoRunner.stopMongod(conn); -conn = MongoRunner.runMongod({ - restart : conn, - noCleanData : true -}); +conn = MongoRunner.runMongod({restart: conn, noCleanData: true}); // expect to fail on first attempt since the socket is no longer valid -try{ +try { val = testDB.foo.findOne(); +} catch (err) { } -catch(err){} // assert that credentials were not autosubmitted on reconnect -assert.throws(function(){ testDB.foo.findOne(); }, - [], - "user should not be able to read after logging out"); +assert.throws(function() { + testDB.foo.findOne(); +}, [], "user should not be able to read after logging out"); MongoRunner.stopMongod(conn); diff --git a/jstests/auth/mergeAuthCollsCommand.js b/jstests/auth/mergeAuthCollsCommand.js index 612b3e62d32..c89a7ff460d 100644 --- a/jstests/auth/mergeAuthCollsCommand.js +++ b/jstests/auth/mergeAuthCollsCommand.js @@ -3,15 +3,14 @@ */ function assertUsersAndRolesHaveRole(admin, role) { - admin.system.users.find().forEach( function(doc) { - assert.eq(1, doc.roles.length); - assert.eq(role, doc.roles[0].role); - }); - admin.system.roles.find().forEach( function(doc) { - assert.eq(1, doc.roles.length); - assert.eq(role, doc.roles[0].role); - }); - + admin.system.users.find().forEach(function(doc) { + assert.eq(1, doc.roles.length); + assert.eq(role, doc.roles[0].role); + }); + admin.system.roles.find().forEach(function(doc) { + assert.eq(1, doc.roles.length); + assert.eq(role, doc.roles[0].role); + }); } function runTest(conn) { var db = conn.getDB('test'); @@ -25,8 +24,12 @@ function runTest(conn) { // Move the newly created users/roles to the temp collections to be used later by // _mergeAuthzCollections - admin.system.users.find().forEach(function (doc) { admin.tempusers.insert(doc); }); - admin.system.roles.find().forEach(function (doc) { admin.temproles.insert(doc); }); + admin.system.users.find().forEach(function(doc) { + admin.tempusers.insert(doc); + }); + admin.system.roles.find().forEach(function(doc) { + admin.temproles.insert(doc); + }); admin.system.users.remove({}); admin.system.roles.remove({}); @@ -44,11 +47,13 @@ function runTest(conn) { assertUsersAndRolesHaveRole(admin, "readWrite"); jsTestLog("Overriding existing system.users and system.roles collections"); - assert.commandWorked(admin.runCommand({_mergeAuthzCollections: 1, - tempUsersCollection: 'admin.tempusers', - tempRolesCollection: 'admin.temproles', - db: "", - drop: true})); + assert.commandWorked(admin.runCommand({ + _mergeAuthzCollections: 1, + tempUsersCollection: 'admin.tempusers', + tempRolesCollection: 'admin.temproles', + db: "", + drop: true + })); assert.eq(2, admin.system.users.count()); assert.eq(2, admin.system.roles.count()); @@ -68,18 +73,18 @@ function runTest(conn) { assertUsersAndRolesHaveRole(admin, "read"); jsTestLog("Adding users/roles from temp collections to the existing users/roles"); - assert.commandWorked(admin.runCommand({_mergeAuthzCollections: 1, - tempUsersCollection: 'admin.tempusers', - tempRolesCollection: 'admin.temproles', - db: "", - drop: false})); - + assert.commandWorked(admin.runCommand({ + _mergeAuthzCollections: 1, + tempUsersCollection: 'admin.tempusers', + tempRolesCollection: 'admin.temproles', + db: "", + drop: false + })); assert.eq(4, admin.system.users.count()); assert.eq(4, admin.system.roles.count()); assertUsersAndRolesHaveRole(admin, "read"); - jsTestLog("Make sure adding duplicate users/roles fails to change anything if 'drop' is false"); admin.system.users.remove({}); @@ -96,11 +101,13 @@ function runTest(conn) { assertUsersAndRolesHaveRole(admin, "readWrite"); // This should succeed but have no effect as every user/role it tries to restore already exists - assert.commandWorked(admin.runCommand({_mergeAuthzCollections: 1, - tempUsersCollection: 'admin.tempusers', - tempRolesCollection: 'admin.temproles', - db: "", - drop: false})); + assert.commandWorked(admin.runCommand({ + _mergeAuthzCollections: 1, + tempUsersCollection: 'admin.tempusers', + tempRolesCollection: 'admin.temproles', + db: "", + drop: false + })); assert.eq(2, admin.system.users.count()); assert.eq(2, admin.system.roles.count()); @@ -113,6 +120,6 @@ runTest(conn); MongoRunner.stopMongod(conn.port); jsTest.log('Test sharding'); -var st = new ShardingTest({ shards: 2, config: 3 }); +var st = new ShardingTest({shards: 2, config: 3}); runTest(st.s); st.stop(); diff --git a/jstests/auth/mongos_cache_invalidation.js b/jstests/auth/mongos_cache_invalidation.js index 1f8a03bac56..de2fce4ddfb 100644 --- a/jstests/auth/mongos_cache_invalidation.js +++ b/jstests/auth/mongos_cache_invalidation.js @@ -4,17 +4,21 @@ */ var authzErrorCode = 13; -var hasAuthzError = function (result) { +var hasAuthzError = function(result) { assert(result.hasWriteError()); assert.eq(authzErrorCode, result.getWriteError().code); }; -var st = new ShardingTest({ shards: 2, - config: 3, - mongos: [{}, - {setParameter: "userCacheInvalidationIntervalSecs=5"}, - {setParameter: "userCacheInvalidationIntervalSecs=600"}], - keyFile: 'jstests/libs/key1' }); +var st = new ShardingTest({ + shards: 2, + config: 3, + mongos: [ + {}, + {setParameter: "userCacheInvalidationIntervalSecs=5"}, + {setParameter: "userCacheInvalidationIntervalSecs=600"} + ], + keyFile: 'jstests/libs/key1' +}); st.s1.getDB('admin').createUser({user: 'root', pwd: 'pwd', roles: ['root']}); st.s1.getDB('admin').auth('root', 'pwd'); @@ -28,21 +32,22 @@ assert.commandFailed(res, "Setting the invalidation interval to an disallowed va res = st.s1.getDB('admin').runCommand({getParameter: 1, userCacheInvalidationIntervalSecs: 1}); assert.eq(5, res.userCacheInvalidationIntervalSecs); -st.s1.getDB('test').foo.insert({a:1}); // initial data -st.s1.getDB('test').bar.insert({a:1}); // initial data +st.s1.getDB('test').foo.insert({a: 1}); // initial data +st.s1.getDB('test').bar.insert({a: 1}); // initial data st.s1.getDB('admin').createUser({user: 'admin', pwd: 'pwd', roles: ['userAdminAnyDatabase']}); st.s1.getDB('admin').logout(); st.s0.getDB('admin').auth('admin', 'pwd'); -st.s0.getDB('admin').createRole({role: 'myRole', - roles: [], - privileges: [{resource: {cluster: true}, - actions: ['invalidateUserCache', 'setParameter']}]}); -st.s0.getDB('test').createUser({user: 'spencer', - pwd: 'pwd', - roles: ['read', - {role: 'myRole', db: 'admin'}, - {role: 'userAdminAnyDatabase', db: 'admin'}]}); +st.s0.getDB('admin').createRole({ + role: 'myRole', + roles: [], + privileges: [{resource: {cluster: true}, actions: ['invalidateUserCache', 'setParameter']}] +}); +st.s0.getDB('test').createUser({ + user: 'spencer', + pwd: 'pwd', + roles: ['read', {role: 'myRole', db: 'admin'}, {role: 'userAdminAnyDatabase', db: 'admin'}] +}); st.s0.getDB('admin').logout(); var db1 = st.s0.getDB('test'); @@ -61,163 +66,157 @@ db3.auth('spencer', 'pwd'); */ (function testChangingInvalidationInterval() { - jsTestLog("Test that changing the invalidation interval takes effect immediately"); + jsTestLog("Test that changing the invalidation interval takes effect immediately"); - assert.commandFailedWithCode(db3.bar.runCommand("drop"), authzErrorCode); - assert.eq(1, db3.bar.findOne().a); + assert.commandFailedWithCode(db3.bar.runCommand("drop"), authzErrorCode); + assert.eq(1, db3.bar.findOne().a); - db1.getSiblingDB('admin').grantPrivilegesToRole("myRole", - [{resource: {db: 'test', collection: ''}, - actions: ['dropCollection']}]); + db1.getSiblingDB('admin').grantPrivilegesToRole( + "myRole", [{resource: {db: 'test', collection: ''}, actions: ['dropCollection']}]); - // At first db3 should still think we're unauthorized because it hasn't invalidated it's cache. - assert.commandFailedWithCode(db3.bar.runCommand('drop'), authzErrorCode); - // Changing the value of the invalidation interval should make it invalidate its cache quickly. - assert.commandWorked(db3.adminCommand({setParameter: 1, - userCacheInvalidationIntervalSecs: 1})); - sleep(2000); - assert.commandWorked(db3.bar.runCommand('drop')); - assert.eq(0, db3.bar.count()); + // At first db3 should still think we're unauthorized because it hasn't invalidated it's cache. + assert.commandFailedWithCode(db3.bar.runCommand('drop'), authzErrorCode); + // Changing the value of the invalidation interval should make it invalidate its cache quickly. + assert.commandWorked(db3.adminCommand({setParameter: 1, userCacheInvalidationIntervalSecs: 1})); + sleep(2000); + assert.commandWorked(db3.bar.runCommand('drop')); + assert.eq(0, db3.bar.count()); - // Set the invalidation interval back for the rest of the tests - db3.adminCommand({setParameter: 1, userCacheInvalidationIntervalSecs: 600}); - })(); + // Set the invalidation interval back for the rest of the tests + db3.adminCommand({setParameter: 1, userCacheInvalidationIntervalSecs: 600}); +})(); (function testGrantingPrivileges() { - jsTestLog("Testing propagation of granting privileges"); - - hasAuthzError(db1.foo.update({}, { $inc: { a: 1 }})); - hasAuthzError(db2.foo.update({}, { $inc: { a: 1 }})); - hasAuthzError(db3.foo.update({}, { $inc: { a: 1 }})); - - assert.eq(1, db1.foo.findOne().a); - assert.eq(1, db2.foo.findOne().a); - assert.eq(1, db3.foo.findOne().a); - - db1.getSiblingDB('admin').grantPrivilegesToRole("myRole", - [{resource: {db: 'test', collection: ''}, - actions: ['update']}]); - - // s0/db1 should update its cache instantly - assert.writeOK(db1.foo.update({}, { $inc: { a: 1 }})); - assert.eq(2, db1.foo.findOne().a); - - // s1/db2 should update its cache in 10 seconds. - assert.soon(function() { - var res = db2.foo.update({}, { $inc: { a: 1 }}); - if (res.hasWriteError()) { - return false; - } - return db2.foo.findOne().a == 3; - }, - "Mongos did not update its user cache after 10 seconds", - 10 * 1000); - - // We manually invalidate the cache on s2/db3. - db3.adminCommand("invalidateUserCache"); - assert.writeOK(db3.foo.update({}, { $inc: { a: 1 }})); - assert.eq(4, db3.foo.findOne().a); - - })(); + jsTestLog("Testing propagation of granting privileges"); + + hasAuthzError(db1.foo.update({}, {$inc: {a: 1}})); + hasAuthzError(db2.foo.update({}, {$inc: {a: 1}})); + hasAuthzError(db3.foo.update({}, {$inc: {a: 1}})); + + assert.eq(1, db1.foo.findOne().a); + assert.eq(1, db2.foo.findOne().a); + assert.eq(1, db3.foo.findOne().a); + + db1.getSiblingDB('admin').grantPrivilegesToRole( + "myRole", [{resource: {db: 'test', collection: ''}, actions: ['update']}]); + + // s0/db1 should update its cache instantly + assert.writeOK(db1.foo.update({}, {$inc: {a: 1}})); + assert.eq(2, db1.foo.findOne().a); + + // s1/db2 should update its cache in 10 seconds. + assert.soon(function() { + var res = db2.foo.update({}, {$inc: {a: 1}}); + if (res.hasWriteError()) { + return false; + } + return db2.foo.findOne().a == 3; + }, "Mongos did not update its user cache after 10 seconds", 10 * 1000); + + // We manually invalidate the cache on s2/db3. + db3.adminCommand("invalidateUserCache"); + assert.writeOK(db3.foo.update({}, {$inc: {a: 1}})); + assert.eq(4, db3.foo.findOne().a); + +})(); (function testRevokingPrivileges() { - jsTestLog("Testing propagation of revoking privileges"); + jsTestLog("Testing propagation of revoking privileges"); - db1.getSiblingDB('admin').revokePrivilegesFromRole("myRole", - [{resource: {db: 'test', collection: ''}, - actions: ['update']}]); + db1.getSiblingDB('admin').revokePrivilegesFromRole( + "myRole", [{resource: {db: 'test', collection: ''}, actions: ['update']}]); - // s0/db1 should update its cache instantly - hasAuthzError(db1.foo.update({}, { $inc: { a: 1 }})); + // s0/db1 should update its cache instantly + hasAuthzError(db1.foo.update({}, {$inc: {a: 1}})); - jsTest.log("Beginning wait for s1/db2 cache update."); - // s1/db2 should update its cache in 10 seconds. - assert.soon(function() { - var res = db2.foo.update({}, { $inc: { a: 1 }}); - return res.hasWriteError() && res.getWriteError().code == authzErrorCode; - }, - "Mongos did not update its user cache after 10 seconds", - 10 * 1000); + jsTest.log("Beginning wait for s1/db2 cache update."); + // s1/db2 should update its cache in 10 seconds. + assert.soon(function() { + var res = db2.foo.update({}, {$inc: {a: 1}}); + return res.hasWriteError() && res.getWriteError().code == authzErrorCode; + }, "Mongos did not update its user cache after 10 seconds", 10 * 1000); - // We manually invalidate the cache on s1/db3. - db3.adminCommand("invalidateUserCache"); - hasAuthzError(db3.foo.update({}, { $inc: { a: 1 }})); - })(); + // We manually invalidate the cache on s1/db3. + db3.adminCommand("invalidateUserCache"); + hasAuthzError(db3.foo.update({}, {$inc: {a: 1}})); +})(); (function testModifyingUser() { - jsTestLog("Testing propagation modifications to a user, rather than to a role"); + jsTestLog("Testing propagation modifications to a user, rather than to a role"); - hasAuthzError(db1.foo.update({}, { $inc: { a: 1 }})); - hasAuthzError(db2.foo.update({}, { $inc: { a: 1 }})); - hasAuthzError(db3.foo.update({}, { $inc: { a: 1}})); + hasAuthzError(db1.foo.update({}, {$inc: {a: 1}})); + hasAuthzError(db2.foo.update({}, {$inc: {a: 1}})); + hasAuthzError(db3.foo.update({}, {$inc: {a: 1}})); - db1.getSiblingDB('test').grantRolesToUser("spencer", ['readWrite']); + db1.getSiblingDB('test').grantRolesToUser("spencer", ['readWrite']); - // s0/db1 should update its cache instantly - assert.writeOK(db1.foo.update({}, { $inc: { a: 1 }})); + // s0/db1 should update its cache instantly + assert.writeOK(db1.foo.update({}, {$inc: {a: 1}})); - // s1/db2 should update its cache in 5 seconds. - assert.soon(function() { - return !db2.foo.update({}, { $inc: { a: 1 }}).hasWriteError(); - }, - "Mongos did not update its user cache after 5 seconds", - 6 * 1000); // Give an extra 1 second to avoid races + // s1/db2 should update its cache in 5 seconds. + assert.soon( + function() { + return !db2.foo.update({}, {$inc: {a: 1}}).hasWriteError(); + }, + "Mongos did not update its user cache after 5 seconds", + 6 * 1000); // Give an extra 1 second to avoid races - // We manually invalidate the cache on s1/db3. - db3.adminCommand("invalidateUserCache"); - assert.writeOK(db3.foo.update({}, { $inc: { a: 1 }})); - })(); + // We manually invalidate the cache on s1/db3. + db3.adminCommand("invalidateUserCache"); + assert.writeOK(db3.foo.update({}, {$inc: {a: 1}})); +})(); (function testConcurrentUserModification() { - jsTestLog("Testing having 2 mongoses modify the same user at the same time"); // SERVER-13850 + jsTestLog("Testing having 2 mongoses modify the same user at the same time"); // SERVER-13850 - assert.writeOK(db1.foo.update({}, { $inc: { a: 1 }})); - assert.writeOK(db3.foo.update({}, { $inc: { a: 1}})); + assert.writeOK(db1.foo.update({}, {$inc: {a: 1}})); + assert.writeOK(db3.foo.update({}, {$inc: {a: 1}})); - db1.getSiblingDB('test').revokeRolesFromUser("spencer", ['readWrite']); + db1.getSiblingDB('test').revokeRolesFromUser("spencer", ['readWrite']); - // At this point db3 still thinks "spencer" has readWrite. Use it to add a different role - // and make sure it doesn't add back readWrite - hasAuthzError(db1.foo.update({}, { $inc: { a: 1 }})); - assert.writeOK(db3.foo.update({}, { $inc: { a: 1}})); + // At this point db3 still thinks "spencer" has readWrite. Use it to add a different role + // and make sure it doesn't add back readWrite + hasAuthzError(db1.foo.update({}, {$inc: {a: 1}})); + assert.writeOK(db3.foo.update({}, {$inc: {a: 1}})); - db3.getSiblingDB('test').grantRolesToUser("spencer", ['dbAdmin']); + db3.getSiblingDB('test').grantRolesToUser("spencer", ['dbAdmin']); - hasAuthzError(db1.foo.update({}, { $inc: { a: 1 }})); - // modifying "spencer" should force db3 to update its cache entry for "spencer" - hasAuthzError(db3.foo.update({}, { $inc: { a: 1 }})); + hasAuthzError(db1.foo.update({}, {$inc: {a: 1}})); + // modifying "spencer" should force db3 to update its cache entry for "spencer" + hasAuthzError(db3.foo.update({}, {$inc: {a: 1}})); - // Make sure nothing changes from invalidating the cache - db1.adminCommand('invalidateUserCache'); - db3.adminCommand('invalidateUserCache'); - hasAuthzError(db1.foo.update({}, { $inc: { a: 1 }})); - hasAuthzError(db3.foo.update({}, { $inc: { a: 1 }})); - })(); + // Make sure nothing changes from invalidating the cache + db1.adminCommand('invalidateUserCache'); + db3.adminCommand('invalidateUserCache'); + hasAuthzError(db1.foo.update({}, {$inc: {a: 1}})); + hasAuthzError(db3.foo.update({}, {$inc: {a: 1}})); +})(); (function testDroppingUser() { - jsTestLog("Testing propagation of dropping users"); + jsTestLog("Testing propagation of dropping users"); - assert.commandWorked(db1.foo.runCommand("collStats")); - assert.commandWorked(db2.foo.runCommand("collStats")); - assert.commandWorked(db3.foo.runCommand("collStats")); + assert.commandWorked(db1.foo.runCommand("collStats")); + assert.commandWorked(db2.foo.runCommand("collStats")); + assert.commandWorked(db3.foo.runCommand("collStats")); - db1.dropUser('spencer'); + db1.dropUser('spencer'); - // s0/db1 should update its cache instantly - assert.commandFailedWithCode(db1.foo.runCommand("collStats"), authzErrorCode); + // s0/db1 should update its cache instantly + assert.commandFailedWithCode(db1.foo.runCommand("collStats"), authzErrorCode); - // s1/db2 should update its cache in 5 seconds. - assert.soon(function() { - return db2.foo.runCommand("collStats").code == authzErrorCode; - }, - "Mongos did not update its user cache after 5 seconds", - 6 * 1000); // Give an extra 1 second to avoid races + // s1/db2 should update its cache in 5 seconds. + assert.soon( + function() { + return db2.foo.runCommand("collStats").code == authzErrorCode; + }, + "Mongos did not update its user cache after 5 seconds", + 6 * 1000); // Give an extra 1 second to avoid races - // We manually invalidate the cache on s2/db3. - db3.adminCommand("invalidateUserCache"); - assert.commandFailedWithCode(db3.foo.runCommand("collStats"), authzErrorCode); + // We manually invalidate the cache on s2/db3. + db3.adminCommand("invalidateUserCache"); + assert.commandFailedWithCode(db3.foo.runCommand("collStats"), authzErrorCode); - })(); +})(); st.stop(); diff --git a/jstests/auth/mr_auth.js b/jstests/auth/mr_auth.js index 421c5d21bf7..1adc66ea7fa 100644 --- a/jstests/auth/mr_auth.js +++ b/jstests/auth/mr_auth.js @@ -1,4 +1,5 @@ -// MapReduce executed by a read-only user when --auth enabled should only be able to use inline mode. Other modes require writing to an output collection which is not allowed. SERVER-3345 +// MapReduce executed by a read-only user when --auth enabled should only be able to use inline +// mode. Other modes require writing to an output collection which is not allowed. SERVER-3345 // // This test requires users to persist across a restart. // @tags: [requires_persistence] @@ -7,75 +8,98 @@ baseName = "jstests_mr_auth"; dbName = "test"; out = baseName + "_out"; -map = function(){ emit( this.x, this.y );}; -red = function( k, vs ){ var s=0; for (var i=0; i<vs.length; i++) s+=vs[i]; return s;}; -red2 = function( k, vs ){ return 42;}; +map = function() { + emit(this.x, this.y); +}; +red = function(k, vs) { + var s = 0; + for (var i = 0; i < vs.length; i++) + s += vs[i]; + return s; +}; +red2 = function(k, vs) { + return 42; +}; // make sure writing is allowed when started without --auth enabled dbms = MongoRunner.runMongod({bind_ip: "127.0.0.1"}); -var d = dbms.getDB( dbName ); -var t = d[ baseName ]; +var d = dbms.getDB(dbName); +var t = d[baseName]; -for( var i = 0; i < 1000; i++) t.insert( {_id:i, x:i%10, y:i%100} ); -assert.eq( 1000, t.count(), "inserts failed" ); +for (var i = 0; i < 1000; i++) + t.insert({_id: i, x: i % 10, y: i % 100}); +assert.eq(1000, t.count(), "inserts failed"); d.dropAllUsers(); -d.getSisterDB( "admin" ).createUser({user: "admin", pwd: "admin", roles: jsTest.adminUserRoles }); -d.getSisterDB( "admin" ).auth('admin', 'admin'); -d.createUser({user: "write" , pwd: "write", roles: jsTest.basicUserRoles}); -d.createUser({user: "read" , pwd: "read", roles: jsTest.readOnlyUserRoles}); -d.getSisterDB( "admin" ).logout(); +d.getSisterDB("admin").createUser({user: "admin", pwd: "admin", roles: jsTest.adminUserRoles}); +d.getSisterDB("admin").auth('admin', 'admin'); +d.createUser({user: "write", pwd: "write", roles: jsTest.basicUserRoles}); +d.createUser({user: "read", pwd: "read", roles: jsTest.readOnlyUserRoles}); +d.getSisterDB("admin").logout(); -t.mapReduce( map, red, {out: { inline: 1 }} ); +t.mapReduce(map, red, {out: {inline: 1}}); -t.mapReduce( map, red, {out: { replace: out }} ); -t.mapReduce( map, red, {out: { reduce: out }} ); -t.mapReduce( map, red, {out: { merge: out }} ); +t.mapReduce(map, red, {out: {replace: out}}); +t.mapReduce(map, red, {out: {reduce: out}}); +t.mapReduce(map, red, {out: {merge: out}}); -d[ out ].drop(); +d[out].drop(); MongoRunner.stopMongod(dbms); +// In --auth mode, read-only user should not be able to write to existing or temporary collection, +// thus only can execute inline mode -// In --auth mode, read-only user should not be able to write to existing or temporary collection, thus only can execute inline mode +dbms = MongoRunner.runMongod( + {restart: true, cleanData: false, dbpath: dbms.dbpath, auth: "", bind_ip: "127.0.0.1"}); +d = dbms.getDB(dbName); +t = d[baseName]; -dbms = MongoRunner.runMongod({restart: true, cleanData: false, dbpath: dbms.dbpath, auth: "", bind_ip: "127.0.0.1"}); -d = dbms.getDB( dbName ); -t = d[ baseName ]; +assert.throws(function() { + t.findOne(); +}, [], "read without login"); -assert.throws( function() { t.findOne(); }, [], "read without login" ); +assert.throws(function() { + t.mapReduce(map, red, {out: {inline: 1}}); +}, [], "m/r without login"); -assert.throws( function(){ t.mapReduce( map, red, {out: { inline: 1 }} ); }, [], "m/r without login" ); - - -d.auth( "read", "read" ); +d.auth("read", "read"); t.findOne(); -t.mapReduce( map, red, {out: { inline: 1 }} ); +t.mapReduce(map, red, {out: {inline: 1}}); -assert.throws( function(){ t.mapReduce( map, red2, {out: { replace: out }} ); }, [], "read-only user shouldn't be able to output m/r to a collection" ); -assert.throws( function(){ t.mapReduce( map, red2, {out: { reduce: out }} ); }, [], "read-only user shouldn't be able to output m/r to a collection" ); -assert.throws( function(){ t.mapReduce( map, red2, {out: { merge: out }} ); }, [], "read-only user shouldn't be able to output m/r to a collection" ); +assert.throws(function() { + t.mapReduce(map, red2, {out: {replace: out}}); +}, [], "read-only user shouldn't be able to output m/r to a collection"); +assert.throws(function() { + t.mapReduce(map, red2, {out: {reduce: out}}); +}, [], "read-only user shouldn't be able to output m/r to a collection"); +assert.throws(function() { + t.mapReduce(map, red2, {out: {merge: out}}); +}, [], "read-only user shouldn't be able to output m/r to a collection"); -assert.eq (0, d[ out ].count(), "output collection should be empty"); +assert.eq(0, d[out].count(), "output collection should be empty"); d.logout(); -assert.throws( function(){ t.mapReduce( map, red, {out: { replace: out }} ); }, [], "m/r without login" ); - +assert.throws(function() { + t.mapReduce(map, red, {out: {replace: out}}); +}, [], "m/r without login"); -d.auth( "write", "write" ); +d.auth("write", "write"); -t.mapReduce( map, red, {out: { inline: 1 }} ); +t.mapReduce(map, red, {out: {inline: 1}}); -t.mapReduce( map, red, {out: { replace: out }} ); -t.mapReduce( map, red, {out: { reduce: out }} ); -t.mapReduce( map, red, {out: { merge: out }} ); +t.mapReduce(map, red, {out: {replace: out}}); +t.mapReduce(map, red, {out: {reduce: out}}); +t.mapReduce(map, red, {out: {merge: out}}); // make sure it fails if output to a diff db -assert.throws(function() { t.mapReduce( map, red, {out: { replace: out, db: "admin" }} ); }); +assert.throws(function() { + t.mapReduce(map, red, {out: {replace: out, db: "admin"}}); +}); MongoRunner.stopMongod(dbms); diff --git a/jstests/auth/profile.js b/jstests/auth/profile.js index f24a303229f..41a8d86f8a9 100644 --- a/jstests/auth/profile.js +++ b/jstests/auth/profile.js @@ -3,12 +3,11 @@ var conn = MongoRunner.runMongod(); var db1 = conn.getDB("profile-a"); var db2 = db1.getSisterDB("profile-b"); var username = "user"; -db1.createUser({user:username, pwd: "password", roles: jsTest.basicUserRoles}); -db2.createUser({user:username, pwd: "password", roles: jsTest.basicUserRoles}); - +db1.createUser({user: username, pwd: "password", roles: jsTest.basicUserRoles}); +db2.createUser({user: username, pwd: "password", roles: jsTest.basicUserRoles}); function lastOp(db) { - return db.system.profile.find().sort( { $natural:-1 } ).next(); + return db.system.profile.find().sort({$natural: -1}).next(); } function principalName(user, db) { diff --git a/jstests/auth/profile_access.js b/jstests/auth/profile_access.js index 504b89d7931..e7090ef3b0d 100644 --- a/jstests/auth/profile_access.js +++ b/jstests/auth/profile_access.js @@ -1,33 +1,40 @@ -var conn = MongoRunner.runMongod({auth : ""}); +var conn = MongoRunner.runMongod({auth: ""}); var adminDb = conn.getDB("admin"); var testDb = conn.getDB("testdb"); -adminDb.createUser({user:'admin', - pwd:'password', - roles:['userAdminAnyDatabase','dbAdminAnyDatabase', 'readWriteAnyDatabase']}); +adminDb.createUser({ + user: 'admin', + pwd: 'password', + roles: ['userAdminAnyDatabase', 'dbAdminAnyDatabase', 'readWriteAnyDatabase'] +}); -adminDb.auth('admin','password'); -testDb.createUser({user:'readUser',pwd:'password',roles:['read']}); -testDb.createUser({user:'dbAdminUser',pwd:'password',roles:['dbAdmin']}); -testDb.createUser({user:'dbAdminAnyDBUser',pwd:'password',roles:[{role: 'dbAdminAnyDatabase', - db: 'admin'}]}); +adminDb.auth('admin', 'password'); +testDb.createUser({user: 'readUser', pwd: 'password', roles: ['read']}); +testDb.createUser({user: 'dbAdminUser', pwd: 'password', roles: ['dbAdmin']}); +testDb.createUser({ + user: 'dbAdminAnyDBUser', + pwd: 'password', + roles: [{role: 'dbAdminAnyDatabase', db: 'admin'}] +}); testDb.setProfilingLevel(2); testDb.foo.findOne(); adminDb.logout(); -testDb.auth('readUser','password'); -assert.throws(function() { testDb.system.profile.findOne(); }); +testDb.auth('readUser', 'password'); +assert.throws(function() { + testDb.system.profile.findOne(); +}); testDb.logout(); // SERVER-14355 -testDb.auth('dbAdminUser','password'); +testDb.auth('dbAdminUser', 'password'); testDb.setProfilingLevel(0); testDb.system.profile.drop(); assert.commandWorked(testDb.createCollection("system.profile", {capped: true, size: 1024})); testDb.logout(); // SERVER-16944 -testDb.auth('dbAdminAnyDBUser','password'); +testDb.auth('dbAdminAnyDBUser', 'password'); testDb.setProfilingLevel(0); testDb.system.profile.drop(); assert.commandWorked(testDb.createCollection("system.profile", {capped: true, size: 1024}));
\ No newline at end of file diff --git a/jstests/auth/pseudo_commands.js b/jstests/auth/pseudo_commands.js index 629b1fde0d3..510f8c71e53 100644 --- a/jstests/auth/pseudo_commands.js +++ b/jstests/auth/pseudo_commands.js @@ -49,144 +49,156 @@ function runTest(conn) { return (res.ok == 1 && res.isdbgrid == 1); } - (function testInprog() { - jsTestLog("Testing inprog"); - - var roles = {read: false, - readAnyDatabase: false, - readWrite: false, - readWriteAnyDatabase: false, - dbAdmin: false, - dbAdminAnyDatabase: false, - dbOwner: false, - clusterMonitor: true, - clusterManager: false, - hostManager: false, - clusterAdmin: true, - root: true, - __system: true - }; - - var privilege = { resource: {cluster: true}, actions: ['inprog'] }; - - var testFunc = function(shouldPass) { - var passed = true; - try { - var res = db.currentOp(); - passed = res.ok && !res.hasOwnProperty("errmsg"); - } catch (e) { - passed = false; - } - - assert.eq(shouldPass, passed); - if (shouldPass) { - assert.gte(res.inprog.length, 0); - } - }; - - testProperAuthorization(testFunc, roles, privilege); - })(); + jsTestLog("Testing inprog"); + + var roles = { + read: false, + readAnyDatabase: false, + readWrite: false, + readWriteAnyDatabase: false, + dbAdmin: false, + dbAdminAnyDatabase: false, + dbOwner: false, + clusterMonitor: true, + clusterManager: false, + hostManager: false, + clusterAdmin: true, + root: true, + __system: true + }; + + var privilege = { + resource: {cluster: true}, + actions: ['inprog'] + }; + + var testFunc = function(shouldPass) { + var passed = true; + try { + var res = db.currentOp(); + passed = res.ok && !res.hasOwnProperty("errmsg"); + } catch (e) { + passed = false; + } + + assert.eq(shouldPass, passed); + if (shouldPass) { + assert.gte(res.inprog.length, 0); + } + }; + + testProperAuthorization(testFunc, roles, privilege); + })(); (function testKillop() { - jsTestLog("Testing killOp"); - - var roles = {read: false, - readAnyDatabase: false, - readWrite: false, - readWriteAnyDatabase: false, - dbAdmin: false, - dbAdminAnyDatabase: false, - dbOwner: false, - clusterMonitor: false, - clusterManager: false, - hostManager: true, - clusterAdmin: true, - root: true, - __system: true - }; - - var privilege = { resource: {cluster: true}, actions: ['killop'] }; - - var testFunc = function(shouldPass) { - var passed = true; - try { - var opid; - if (isMongos(db)) { // opid format different between mongos and mongod - opid = "shard0000:1234"; - } else { - opid = 1234; - } - var res = db.killOp(opid); - printjson(res); - passed = res.ok && !res.errmsg && !res.err && !res['$err']; - } catch (e) { - passed = false; - } - assert.eq(shouldPass, passed); - }; - - testProperAuthorization(testFunc, roles, privilege); + jsTestLog("Testing killOp"); + + var roles = { + read: false, + readAnyDatabase: false, + readWrite: false, + readWriteAnyDatabase: false, + dbAdmin: false, + dbAdminAnyDatabase: false, + dbOwner: false, + clusterMonitor: false, + clusterManager: false, + hostManager: true, + clusterAdmin: true, + root: true, + __system: true + }; + + var privilege = { + resource: {cluster: true}, + actions: ['killop'] + }; + + var testFunc = function(shouldPass) { + var passed = true; + try { + var opid; + if (isMongos(db)) { // opid format different between mongos and mongod + opid = "shard0000:1234"; + } else { + opid = 1234; + } + var res = db.killOp(opid); + printjson(res); + passed = res.ok && !res.errmsg && !res.err && !res['$err']; + } catch (e) { + passed = false; + } + assert.eq(shouldPass, passed); + }; + + testProperAuthorization(testFunc, roles, privilege); })(); (function testUnlock() { - if (isMongos(db)) { - return; // unlock doesn't work on mongos - } - - jsTestLog("Testing unlock"); - - var roles = {read: false, - readAnyDatabase: false, - readWrite: false, - readWriteAnyDatabase: false, - dbAdmin: false, - dbAdminAnyDatabase: false, - dbOwner: false, - clusterMonitor: false, - clusterManager: false, - hostManager: true, - clusterAdmin: true, - root: true, - __system: true - }; - - var privilege = { resource: {cluster: true}, actions: ['unlock'] }; - - var testFunc = function(shouldPass) { - var passed = true; - try { - var ret = admin.fsyncLock(); // must be locked first - // If the storage engine doesnt support fsync lock, we can't proceed - if (!ret.ok) { + if (isMongos(db)) { + return; // unlock doesn't work on mongos + } + + jsTestLog("Testing unlock"); + + var roles = { + read: false, + readAnyDatabase: false, + readWrite: false, + readWriteAnyDatabase: false, + dbAdmin: false, + dbAdminAnyDatabase: false, + dbOwner: false, + clusterMonitor: false, + clusterManager: false, + hostManager: true, + clusterAdmin: true, + root: true, + __system: true + }; + + var privilege = { + resource: {cluster: true}, + actions: ['unlock'] + }; + + var testFunc = function(shouldPass) { + var passed = true; + try { + var ret = admin.fsyncLock(); // must be locked first + // If the storage engine doesnt support fsync lock, we can't proceed + if (!ret.ok) { assert.commandFailedWithCode(ret, ErrorCodes.CommandNotSupported); - assert(shouldPass); // If we get to the storage engine, we better be authorized. + assert( + shouldPass); // If we get to the storage engine, we better be authorized. return; - } - var res = db.fsyncUnlock(); - printjson(res); - passed = res.ok && !res.errmsg && !res.err && !res['$err']; - passed = passed || false; // convert undefined to false - } catch (e) { - passed = false; - } - if (!passed) { - admin.fsyncUnlock(); - } - - assert.eq(shouldPass, passed); - }; - - testProperAuthorization(testFunc, roles, privilege); - })(); + } + var res = db.fsyncUnlock(); + printjson(res); + passed = res.ok && !res.errmsg && !res.err && !res['$err']; + passed = passed || false; // convert undefined to false + } catch (e) { + passed = false; + } + if (!passed) { + admin.fsyncUnlock(); + } + + assert.eq(shouldPass, passed); + }; + + testProperAuthorization(testFunc, roles, privilege); + })(); } jsTest.log('Test standalone'); -var conn = MongoRunner.runMongod({ auth: '' }); +var conn = MongoRunner.runMongod({auth: ''}); runTest(conn); MongoRunner.stopMongod(conn.port); jsTest.log('Test sharding'); -var st = new ShardingTest({ shards: 2, config: 3, keyFile: 'jstests/libs/key1' }); +var st = new ShardingTest({shards: 2, config: 3, keyFile: 'jstests/libs/key1'}); runTest(st.s); st.stop(); diff --git a/jstests/auth/readIndex.js b/jstests/auth/readIndex.js index 433a2e7eb1d..deda8717a3b 100644 --- a/jstests/auth/readIndex.js +++ b/jstests/auth/readIndex.js @@ -1,21 +1,21 @@ // SERVER-8625: Test that dbAdmins can view index definitions. -var conn = MongoRunner.runMongod({auth : ""}); +var conn = MongoRunner.runMongod({auth: ""}); var adminDB = conn.getDB("admin"); var testDB = conn.getDB("testdb"); var indexName = 'idx_a'; -adminDB.createUser({user:'root', pwd:'password', roles:['root']}); +adminDB.createUser({user: 'root', pwd: 'password', roles: ['root']}); adminDB.auth('root', 'password'); -testDB.foo.insert({a:1}); -testDB.createUser({user:'dbAdmin', pwd:'password', roles:['dbAdmin']}); +testDB.foo.insert({a: 1}); +testDB.createUser({user: 'dbAdmin', pwd: 'password', roles: ['dbAdmin']}); adminDB.logout(); testDB.auth('dbAdmin', 'password'); -testDB.foo.ensureIndex({a:1}, {name:indexName}); -assert.eq(2, testDB.foo.getIndexes().length); // index on 'a' plus default _id index +testDB.foo.ensureIndex({a: 1}, {name: indexName}); +assert.eq(2, testDB.foo.getIndexes().length); // index on 'a' plus default _id index var indexList = testDB.foo.getIndexes().filter(function(idx) { return idx.name === indexName; }); assert.eq(1, indexList.length, tojson(indexList)); -assert.docEq(indexList[0].key, {a:1}, tojson(indexList)); +assert.docEq(indexList[0].key, {a: 1}, tojson(indexList)); diff --git a/jstests/auth/rename.js b/jstests/auth/rename.js index a83d2e75caa..bc1d8a40923 100644 --- a/jstests/auth/rename.js +++ b/jstests/auth/rename.js @@ -4,10 +4,10 @@ var m = MongoRunner.runMongod({auth: ""}); var db1 = m.getDB("foo"); var db2 = m.getDB("bar"); -var admin = m.getDB( 'admin' ); +var admin = m.getDB('admin'); // Setup initial data -admin.createUser({user:'admin', pwd: 'password', roles: jsTest.adminUserRoles}); +admin.createUser({user: 'admin', pwd: 'password', roles: jsTest.adminUserRoles}); admin.auth('admin', 'password'); db1.createUser({user: "foo", pwd: "bar", roles: jsTest.basicUserRoles}); @@ -20,18 +20,22 @@ assert.eq(db1.a.count(), 1); admin.logout(); // can't run same db w/o auth -assert.commandFailed( admin.runCommand({renameCollection:db1.a.getFullName(), to: db1.b.getFullName()}) ); +assert.commandFailed( + admin.runCommand({renameCollection: db1.a.getFullName(), to: db1.b.getFullName()})); // can run same db with auth db1.auth('foo', 'bar'); -assert.commandWorked( admin.runCommand({renameCollection:db1.a.getFullName(), to: db1.b.getFullName()}) ); +assert.commandWorked( + admin.runCommand({renameCollection: db1.a.getFullName(), to: db1.b.getFullName()})); // can't run diff db w/o auth -assert.commandFailed( admin.runCommand({renameCollection:db1.b.getFullName(), to: db2.a.getFullName()}) ); +assert.commandFailed( + admin.runCommand({renameCollection: db1.b.getFullName(), to: db2.a.getFullName()})); // can run diff db with auth db2.auth('bar', 'foo'); -assert.commandWorked( admin.runCommand({renameCollection:db1.b.getFullName(), to: db2.a.getFullName()}) ); +assert.commandWorked( + admin.runCommand({renameCollection: db1.b.getFullName(), to: db2.a.getFullName()})); // test post conditions assert.eq(db1.a.count(), 0); diff --git a/jstests/auth/renameSystemCollections.js b/jstests/auth/renameSystemCollections.js index 7e4c7b821e3..dffee963499 100644 --- a/jstests/auth/renameSystemCollections.js +++ b/jstests/auth/renameSystemCollections.js @@ -1,5 +1,5 @@ // SERVER-8623: Test that renameCollection can't be used to bypass auth checks on system namespaces -var conn = MongoRunner.runMongod({auth : ""}); +var conn = MongoRunner.runMongod({auth: ""}); var adminDB = conn.getDB("admin"); var testDB = conn.getDB("testdb"); @@ -7,38 +7,38 @@ var testDB2 = conn.getDB("testdb2"); var CodeUnauthorized = 13; -var backdoorUserDoc = { user: 'backdoor', db: 'admin', pwd: 'hashed', roles: ['root'] }; +var backdoorUserDoc = { + user: 'backdoor', + db: 'admin', + pwd: 'hashed', + roles: ['root'] +}; -adminDB.createUser({user:'userAdmin', - pwd:'password', - roles:['userAdminAnyDatabase']}); +adminDB.createUser({user: 'userAdmin', pwd: 'password', roles: ['userAdminAnyDatabase']}); adminDB.auth('userAdmin', 'password'); -adminDB.createUser({user:'readWriteAdmin', - pwd:'password', - roles:['readWriteAnyDatabase']}); -adminDB.createUser({user:'readWriteAndUserAdmin', - pwd:'password', - roles:['readWriteAnyDatabase', 'userAdminAnyDatabase']}); +adminDB.createUser({user: 'readWriteAdmin', pwd: 'password', roles: ['readWriteAnyDatabase']}); +adminDB.createUser({ + user: 'readWriteAndUserAdmin', + pwd: 'password', + roles: ['readWriteAnyDatabase', 'userAdminAnyDatabase'] +}); adminDB.createUser({user: 'root', pwd: 'password', roles: ['root']}); adminDB.createUser({user: 'rootier', pwd: 'password', roles: ['__system']}); adminDB.logout(); - jsTestLog("Test that a readWrite user can't rename system.profile to something they can read"); adminDB.auth('readWriteAdmin', 'password'); res = adminDB.system.profile.renameCollection("profile"); assert.eq(0, res.ok); assert.eq(CodeUnauthorized, res.code); - jsTestLog("Test that a readWrite user can't rename system.users to something they can read"); var res = adminDB.system.users.renameCollection("users"); assert.eq(0, res.ok); assert.eq(CodeUnauthorized, res.code); assert.eq(0, adminDB.users.count()); - jsTestLog("Test that a readWrite user can't use renameCollection to override system.users"); adminDB.users.insert(backdoorUserDoc); res = adminDB.users.renameCollection("system.users", true); @@ -70,7 +70,7 @@ assert.eq(0, res.ok); assert.eq(CodeUnauthorized, res.code); assert.eq(null, adminDB.system.users.findOne({user: backdoorUserDoc.user})); -assert.neq(null, adminDB.system.users.findOne({user:'userAdmin'})); +assert.neq(null, adminDB.system.users.findOne({user: 'userAdmin'})); adminDB.auth('rootier', 'password'); diff --git a/jstests/auth/repl.js b/jstests/auth/repl.js index 1ed13ad1400..17ab3c2db20 100644 --- a/jstests/auth/repl.js +++ b/jstests/auth/repl.js @@ -3,7 +3,10 @@ var baseName = "jstests_auth_repl"; var rsName = baseName + "_rs"; var rtName = baseName + "_rt"; -var mongoOptions = {auth: null, keyFile: "jstests/libs/key1"}; +var mongoOptions = { + auth: null, + keyFile: "jstests/libs/key1" +}; var authErrCode = 13; var AuthReplTest = function(spec) { @@ -73,20 +76,15 @@ var AuthReplTest = function(spec) { var updateRole = function() { var res = adminPri.runCommand({ updateRole: testRole, - privileges: [ - { resource: {cluster: true}, actions: ["listDatabases"] } - ], + privileges: [{resource: {cluster: true}, actions: ["listDatabases"]}], writeConcern: {w: 2, wtimeout: 15000} }); assert.commandWorked(res); }; var updateUser = function() { - var res = adminPri.runCommand({ - updateUser: testUser, - roles: [testRole2], - writeConcern: {w: 2, wtimeout: 15000} - }); + var res = adminPri.runCommand( + {updateUser: testUser, roles: [testRole2], writeConcern: {w: 2, wtimeout: 15000}}); assert.commandWorked(res); }; @@ -108,11 +106,10 @@ var AuthReplTest = function(spec) { * Remove test users and roles */ var cleanup = function() { - var res = adminPri.runCommand({dropUser: testUser, - writeConcern: {w: 2, wtimeout: 15000}}); + var res = adminPri.runCommand({dropUser: testUser, writeConcern: {w: 2, wtimeout: 15000}}); assert.commandWorked(res); - res = adminPri.runCommand({dropAllRolesFromDatabase: 1, - writeConcern: {w: 2, wtimeout: 15000}}); + res = adminPri.runCommand( + {dropAllRolesFromDatabase: 1, writeConcern: {w: 2, wtimeout: 15000}}); assert.commandWorked(res); }; @@ -137,10 +134,8 @@ var AuthReplTest = function(spec) { for (var i = 0; i < roles.length; i++) { var res = adminPri.runCommand({ createRole: roles[i], - privileges: [ - { resource: {cluster: true}, actions: [ actions[i] ] } - ], - roles: [ ], + privileges: [{resource: {cluster: true}, actions: [actions[i]]}], + roles: [], writeConcern: {w: numNodes, wtimeout: 15000} }); assert.commandWorked(res); @@ -168,11 +163,11 @@ var AuthReplTest = function(spec) { updateRole(); confirmPrivilegeAfterUpdate(); confirmRolesInfo("listDatabases"); - + updateUser(); confirmPrivilegeAfterUpdate(); confirmUsersInfo(testRole2); - + cleanup(); }; @@ -183,31 +178,33 @@ jsTest.log("1 test replica sets"); var rs = new ReplSetTest({name: rsName, nodes: 2}); var nodes = rs.startSet(mongoOptions); rs.initiate(); -authutil.asCluster(nodes, "jstests/libs/key1", function() { rs.awaitReplication(); }); +authutil.asCluster(nodes, + "jstests/libs/key1", + function() { + rs.awaitReplication(); + }); var primary = rs.getPrimary(); var secondary = rs.getSecondary(); -var authReplTest = AuthReplTest({ - primaryConn: primary, - secondaryConn: secondary -}); +var authReplTest = AuthReplTest({primaryConn: primary, secondaryConn: secondary}); authReplTest.createUserAndRoles(2); authReplTest.testAll(); rs.stopSet(); -jsTest.log("2 test initial sync"); +jsTest.log("2 test initial sync"); rs = new ReplSetTest({name: rsName, nodes: 1, nodeOptions: mongoOptions}); nodes = rs.startSet(); rs.initiate(); -authutil.asCluster(nodes, "jstests/libs/key1", function() { rs.awaitReplication(); }); +authutil.asCluster(nodes, + "jstests/libs/key1", + function() { + rs.awaitReplication(); + }); primary = rs.getPrimary(); -var authReplTest = AuthReplTest({ - primaryConn: primary, - secondaryConn: null -}); +var authReplTest = AuthReplTest({primaryConn: primary, secondaryConn: null}); authReplTest.createUserAndRoles(1); // Add a secondary and wait for initial sync @@ -239,14 +236,10 @@ masterDB.createUser({user: "root", pwd: "pass", roles: ["root"]}); masterDB.auth("root", "pass"); // ensure that master/slave replication is up and running -masterDB.foo.save({}, { writeConcern: { w: 2, wtimeout: 15000 }}); +masterDB.foo.save({}, {writeConcern: {w: 2, wtimeout: 15000}}); masterDB.foo.drop(); -authReplTest = AuthReplTest({ - primaryConn: master, - secondaryConn: slave -}); +authReplTest = AuthReplTest({primaryConn: master, secondaryConn: slave}); authReplTest.createUserAndRoles(2); authReplTest.testAll(); rt.stop(); - diff --git a/jstests/auth/repl_auth.js b/jstests/auth/repl_auth.js index a5bde8167c9..bafaafd8f7b 100644 --- a/jstests/auth/repl_auth.js +++ b/jstests/auth/repl_auth.js @@ -4,8 +4,8 @@ */ var NUM_NODES = 3; -var rsTest = new ReplSetTest({ nodes: NUM_NODES }); -rsTest.startSet({ oplogSize: 10, keyFile: 'jstests/libs/key1' }); +var rsTest = new ReplSetTest({nodes: NUM_NODES}); +rsTest.startSet({oplogSize: 10, keyFile: 'jstests/libs/key1'}); rsTest.initiate(); rsTest.awaitSecondaryNodes(); @@ -13,14 +13,14 @@ var setupConn = rsTest.getPrimary(); var admin = setupConn.getDB('admin'); // Setup initial data -admin.createUser({ user:'admin', pwd: 'password', roles: jsTest.adminUserRoles }); +admin.createUser({user: 'admin', pwd: 'password', roles: jsTest.adminUserRoles}); admin.auth('admin', 'password'); -setupConn.getDB('foo').createUser({ user: 'foo', pwd: 'foopwd', roles: jsTest.basicUserRoles }, - { w: NUM_NODES }); +setupConn.getDB('foo') + .createUser({user: 'foo', pwd: 'foopwd', roles: jsTest.basicUserRoles}, {w: NUM_NODES}); setupConn.getDB('foo').logout(); -setupConn.getDB('bar').createUser({ user: 'bar', pwd: 'barpwd', roles: jsTest.basicUserRoles }, - { w: NUM_NODES }); +setupConn.getDB('bar') + .createUser({user: 'bar', pwd: 'barpwd', roles: jsTest.basicUserRoles}, {w: NUM_NODES}); setupConn.getDB('bar').logout(); var replConn0 = new Mongo(rsTest.getURL()); @@ -33,16 +33,16 @@ var barDB1 = replConn1.getDB('bar'); fooDB0.auth('foo', 'foopwd'); barDB1.auth('bar', 'barpwd'); -assert.writeOK(fooDB0.user.insert({ x: 1 }, { writeConcern: { w: NUM_NODES }})); -assert.writeError(barDB0.user.insert({ x: 1 }, { writeConcern: { w: NUM_NODES }})); +assert.writeOK(fooDB0.user.insert({x: 1}, {writeConcern: {w: NUM_NODES}})); +assert.writeError(barDB0.user.insert({x: 1}, {writeConcern: {w: NUM_NODES}})); -assert.writeError(fooDB1.user.insert({ x: 2 }, { writeConcern: { w: NUM_NODES }})); -assert.writeOK(barDB1.user.insert({ x: 2 }, { writeConcern: { w: NUM_NODES }})); +assert.writeError(fooDB1.user.insert({x: 2}, {writeConcern: {w: NUM_NODES}})); +assert.writeOK(barDB1.user.insert({x: 2}, {writeConcern: {w: NUM_NODES}})); // Make sure replica set connection in the shell is ready. -_awaitRSHostViaRSMonitor(rsTest.getPrimary().name, { ok: true, ismaster: true }, rsTest.name); +_awaitRSHostViaRSMonitor(rsTest.getPrimary().name, {ok: true, ismaster: true}, rsTest.name); rsTest.getSecondaries().forEach(function(sec) { - _awaitRSHostViaRSMonitor(sec.name, { ok: true, secondary: true }, rsTest.name); + _awaitRSHostViaRSMonitor(sec.name, {ok: true, secondary: true}, rsTest.name); }); // Note: secondary nodes are selected randomly and connections will only be returned to the @@ -65,4 +65,3 @@ for (var x = 0; x < 20; x++) { } rsTest.stopSet(); - diff --git a/jstests/auth/resource_pattern_matching.js b/jstests/auth/resource_pattern_matching.js index 7acad4f5f1f..5a4da66871c 100644 --- a/jstests/auth/resource_pattern_matching.js +++ b/jstests/auth/resource_pattern_matching.js @@ -17,17 +17,9 @@ function setup_users(granter) { admindb.auth("admin", "admin"); - printjson(admindb.runCommand({ - createRole: "test_role", - privileges: [], - roles: [] - })); - - printjson(admindb.runCommand({ - createUser: "test_user", - pwd: "password", - roles: [ "test_role" ] - })); + printjson(admindb.runCommand({createRole: "test_role", privileges: [], roles: []})); + + printjson(admindb.runCommand({createUser: "test_user", pwd: "password", roles: ["test_role"]})); } function setup_dbs_and_cols(db) { @@ -54,7 +46,7 @@ function grant_privileges(granter, privileges) { var result = admindb.runCommand({ grantPrivilegesToRole: "test_role", privileges: privileges, - writeConcern: { w: 'majority'} + writeConcern: {w: 'majority'} }); admindb.logout(); @@ -70,7 +62,7 @@ function revoke_privileges(granter, privileges) { var result = admindb.runCommand({ revokePrivilegesFromRole: "test_role", privileges: privileges, - writeConcern: { w: 'majority'} + writeConcern: {w: 'majority'} }); admindb.logout(); @@ -107,118 +99,135 @@ function run_test(name, granter, verifier, privileges, collections) { } function run_test_bad_resource(name, granter, resource) { - print("\n=== testing resource fail " + name + "() ===\n"); - var admindb = granter.getSiblingDB("admin"); - assert.commandFailed( - grant_privileges(granter, [{ resource: resource, actions: [ "find" ] }]) - ); + print("\n=== testing resource fail " + name + "() ===\n"); + var admindb = granter.getSiblingDB("admin"); + assert.commandFailed(grant_privileges(granter, [{resource: resource, actions: ["find"]}])); } function should_insert(testdb, testcol) { - assert.doesNotThrow(function() { testcol.insert({ a : "b" }); }); + assert.doesNotThrow(function() { + testcol.insert({a: "b"}); + }); } function should_fail_insert(testdb, testcol) { - assert.throws(function() { testcol.insert({ a : "b" }); }); + assert.throws(function() { + testcol.insert({a: "b"}); + }); } function should_find(testdb, testcol) { - assert.doesNotThrow(function() { testcol.findOne(); }); + assert.doesNotThrow(function() { + testcol.findOne(); + }); } function should_fail_find(testdb, testcol) { - assert.throws(function() { testcol.findOne(); }); + assert.throws(function() { + testcol.findOne(); + }); } function run_tests(granter, verifier) { setup_users(granter); setup_dbs_and_cols(granter); - run_test("specific", granter, verifier, - [ { resource: { db: "a", collection: "a" }, actions: [ "find" ]} ], - { - "a.a" : should_find, - "a.b" : should_fail_find, - "b.a" : should_fail_find, - "b.b" : should_fail_find - } - ); - - run_test("glob_collection", granter, verifier, - [ { resource: { db: "a", collection: "" }, actions: [ "find" ]} ], - { - "a.a" : should_find, - "a.b" : should_find, - "b.a" : should_fail_find, - "b.b" : should_fail_find - } - ); - - run_test("glob_database", granter, verifier, - [ { resource: { db: "", collection: "a" }, actions: [ "find" ]} ], - { - "a.a" : should_find, - "a.b" : should_fail_find, - "b.a" : should_find, - "b.b" : should_fail_find - } - ); - - run_test("glob_all", granter, verifier, - [ { resource: { db: "", collection: "" }, actions: [ "find" ]} ], - { - "a.a" : should_find, - "a.b" : should_find, - "b.a" : should_find, - "b.b" : should_find - } - ); - - run_test("any_resource", granter, verifier, - [ { resource: { anyResource: true }, actions: [ "find" ]} ], - { - "a.a" : should_find, - "a.b" : should_find, - "b.a" : should_find, - "b.b" : should_find, - "c.a" : should_find - } - ); - - run_test("no_global_access", granter, verifier, - [ { resource: { db: "$", collection: "cmd" }, actions: [ "find" ]} ], - { - "a.a" : function (testdb, testcol) { - var r = testdb.stats(); - - if (r["ok"]) throw ("db.$.cmd shouldn't give a.stats()"); - } - } - ); - - run_test_bad_resource("empty_resource", granter, { }); - run_test_bad_resource("users_collection_any_db", granter, { collection: "users" }); - run_test_bad_resource("bad_key", granter, { myResource: "users" }); - run_test_bad_resource("extra_key", granter, { db: "test", collection: "users", cluster: true }); - run_test_bad_resource("bad_value_type", granter, { cluster: "false" }); - run_test_bad_resource("bad_collection", granter, { db: "test", collection: "$$$$" }); - - run_test("mixed_find_write", granter, verifier, - [ - { resource: { db: "a", collection: "a" }, actions: [ "find" ]}, - { resource: { db: "", collection: "" }, actions: [ "insert" ]} - ], - { - "a.a" : function(testdb, testcol) { should_insert(testdb, testcol); - should_find(testdb, testcol); }, - "a.b" : function(testdb, testcol) { should_insert(testdb, testcol); - should_fail_find(testdb, testcol); }, - "b.a" : function(testdb, testcol) { should_insert(testdb, testcol); - should_fail_find(testdb, testcol); }, - "b.b" : function(testdb, testcol) { should_insert(testdb, testcol); - should_fail_find(testdb, testcol); }, - } - ); + run_test("specific", + granter, + verifier, + [{resource: {db: "a", collection: "a"}, actions: ["find"]}], + { + "a.a": should_find, + "a.b": should_fail_find, + "b.a": should_fail_find, + "b.b": should_fail_find + }); + + run_test("glob_collection", + granter, + verifier, + [{resource: {db: "a", collection: ""}, actions: ["find"]}], + { + "a.a": should_find, + "a.b": should_find, + "b.a": should_fail_find, + "b.b": should_fail_find + }); + + run_test("glob_database", + granter, + verifier, + [{resource: {db: "", collection: "a"}, actions: ["find"]}], + { + "a.a": should_find, + "a.b": should_fail_find, + "b.a": should_find, + "b.b": should_fail_find + }); + + run_test("glob_all", + granter, + verifier, + [{resource: {db: "", collection: ""}, actions: ["find"]}], + {"a.a": should_find, "a.b": should_find, "b.a": should_find, "b.b": should_find}); + + run_test("any_resource", + granter, + verifier, + [{resource: {anyResource: true}, actions: ["find"]}], + { + "a.a": should_find, + "a.b": should_find, + "b.a": should_find, + "b.b": should_find, + "c.a": should_find + }); + + run_test("no_global_access", + granter, + verifier, + [{resource: {db: "$", collection: "cmd"}, actions: ["find"]}], + { + "a.a": function(testdb, testcol) { + var r = testdb.stats(); + + if (r["ok"]) + throw("db.$.cmd shouldn't give a.stats()"); + } + }); + + run_test_bad_resource("empty_resource", granter, {}); + run_test_bad_resource("users_collection_any_db", granter, {collection: "users"}); + run_test_bad_resource("bad_key", granter, {myResource: "users"}); + run_test_bad_resource("extra_key", granter, {db: "test", collection: "users", cluster: true}); + run_test_bad_resource("bad_value_type", granter, {cluster: "false"}); + run_test_bad_resource("bad_collection", granter, {db: "test", collection: "$$$$"}); + + run_test("mixed_find_write", + granter, + verifier, + [ + {resource: {db: "a", collection: "a"}, actions: ["find"]}, + {resource: {db: "", collection: ""}, actions: ["insert"]} + ], + { + "a.a": function(testdb, testcol) { + should_insert(testdb, testcol); + should_find(testdb, testcol); + }, + "a.b": function(testdb, testcol) { + should_insert(testdb, testcol); + should_fail_find(testdb, testcol); + }, + "b.a": function(testdb, testcol) { + should_insert(testdb, testcol); + should_fail_find(testdb, testcol); + }, + "b.b": function(testdb, testcol) { + should_insert(testdb, testcol); + should_fail_find(testdb, testcol); + }, + }); } var keyfile = "jstests/libs/key1"; @@ -231,9 +240,9 @@ print('--- done standalone node test ---'); print('--- replica set test ---'); var rst = new ReplSetTest({ - name: 'testset', - nodes: 2, - nodeOptions: { 'auth': null, 'httpinterface': null, 'keyFile': keyfile } + name: 'testset', + nodes: 2, + nodeOptions: {'auth': null, 'httpinterface': null, 'keyFile': keyfile} }); rst.startSet(); @@ -247,14 +256,14 @@ print('--- done with the rs tests ---'); print('--- sharding test ---'); var st = new ShardingTest({ - mongos: 2, - shard: 1, - keyFile: keyfile, - other: { - mongosOptions: { 'auth': null, 'httpinterface': null }, - configOptions: { 'auth': null, 'httpinterface': null }, - shardOptions: { 'auth': null, 'httpinterface': null } - } + mongos: 2, + shard: 1, + keyFile: keyfile, + other: { + mongosOptions: {'auth': null, 'httpinterface': null}, + configOptions: {'auth': null, 'httpinterface': null}, + shardOptions: {'auth': null, 'httpinterface': null} + } }); run_tests(st.s0.getDB('admin'), st.s1.getDB('admin')); st.stop(); diff --git a/jstests/auth/role_management_commands.js b/jstests/auth/role_management_commands.js index 54b7b91b8c8..9847818e3b1 100644 --- a/jstests/auth/role_management_commands.js +++ b/jstests/auth/role_management_commands.js @@ -15,11 +15,10 @@ function runTest(conn) { var adminUserAdmin = userAdminConn.getDB('admin'); adminUserAdmin.createUser({user: 'userAdmin', pwd: 'pwd', roles: ['userAdminAnyDatabase']}); adminUserAdmin.auth('userAdmin', 'pwd'); - testUserAdmin.createUser({user: 'testUser', pwd: 'pwd', roles:[]}); + testUserAdmin.createUser({user: 'testUser', pwd: 'pwd', roles: []}); var db = conn.getDB('test'); assert(db.auth('testUser', 'pwd')); - // At this point there are 3 databases handles in use. - "testUserAdmin" and "adminUserAdmin" // are handles to the "test" and "admin" dbs respectively. They are on the same connection, // which has been auth'd as a user with the 'userAdminAnyDatabase' role. This will be used @@ -29,248 +28,289 @@ function runTest(conn) { // the roles assigned to "testUser". (function testCreateRole() { - jsTestLog("Testing createRole"); - - testUserAdmin.createRole({role: "testRole1", roles: ['read'], privileges: []}); - testUserAdmin.createRole({role: "testRole2", - roles: [], - privileges: [{resource: {db: 'test', collection: 'foo'}, - actions: ['insert']}]}); - testUserAdmin.createRole({role: "testRole3", - roles: ['testRole1', {role: 'testRole2', db: 'test'}], - privileges: []}); - testUserAdmin.createRole({role: "testRole4", roles: [], privileges: []}); - adminUserAdmin.createRole({role: "adminRole", - roles: [], - privileges: [{resource: {cluster: true}, - actions: ['connPoolSync']}]}); - - testUserAdmin.updateUser('testUser', {roles: [{role: 'adminRole', db: 'admin'}]}); - assert.throws(function() {db.foo.findOne();}); - hasAuthzError(db.foo.insert({ a: 1 })); - hasAuthzError(db.foo.update({}, { $inc: { a: 1 }}, false, true)); - assert.commandWorked(db.adminCommand('connPoolSync')); - - testUserAdmin.updateUser('testUser', {roles: ['testRole1']}); - assert.doesNotThrow(function() {db.foo.findOne();}); - assert.eq(0, db.foo.count()); - hasAuthzError(db.foo.insert({ a: 1 })); - hasAuthzError(db.foo.update({}, { $inc: { a: 1 }}, false, true)); - assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); - - testUserAdmin.updateUser('testUser', {roles: ['testRole2']}); - assert.throws(function() {db.foo.findOne();}); - assert.writeOK(db.foo.insert({ a: 1 })); - hasAuthzError(db.foo.update({}, { $inc: { a: 1 }}, false, true)); - assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); - - testUserAdmin.updateUser('testUser', {roles: ['testRole3']}); - assert.doesNotThrow(function() {db.foo.findOne();}); - assert.eq(1, db.foo.count()); - assert.writeOK(db.foo.insert({ a: 1 })); - assert.eq(2, db.foo.count()); - hasAuthzError(db.foo.update({}, { $inc: { a: 1 }}, false, true)); - assert.eq(1, db.foo.findOne().a); - assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); - - testUserAdmin.updateUser('testUser', {roles: [{role: 'testRole4', db: 'test'}]}); - assert.throws(function() {db.foo.findOne();}); - hasAuthzError(db.foo.insert({ a: 1 })); - hasAuthzError(db.foo.update({}, { $inc: { a: 1 }}, false, true)); - assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); - })(); + jsTestLog("Testing createRole"); + + testUserAdmin.createRole({role: "testRole1", roles: ['read'], privileges: []}); + testUserAdmin.createRole({ + role: "testRole2", + roles: [], + privileges: [{resource: {db: 'test', collection: 'foo'}, actions: ['insert']}] + }); + testUserAdmin.createRole({ + role: "testRole3", + roles: ['testRole1', {role: 'testRole2', db: 'test'}], + privileges: [] + }); + testUserAdmin.createRole({role: "testRole4", roles: [], privileges: []}); + adminUserAdmin.createRole({ + role: "adminRole", + roles: [], + privileges: [{resource: {cluster: true}, actions: ['connPoolSync']}] + }); + + testUserAdmin.updateUser('testUser', {roles: [{role: 'adminRole', db: 'admin'}]}); + assert.throws(function() { + db.foo.findOne(); + }); + hasAuthzError(db.foo.insert({a: 1})); + hasAuthzError(db.foo.update({}, {$inc: {a: 1}}, false, true)); + assert.commandWorked(db.adminCommand('connPoolSync')); + + testUserAdmin.updateUser('testUser', {roles: ['testRole1']}); + assert.doesNotThrow(function() { + db.foo.findOne(); + }); + assert.eq(0, db.foo.count()); + hasAuthzError(db.foo.insert({a: 1})); + hasAuthzError(db.foo.update({}, {$inc: {a: 1}}, false, true)); + assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); + + testUserAdmin.updateUser('testUser', {roles: ['testRole2']}); + assert.throws(function() { + db.foo.findOne(); + }); + assert.writeOK(db.foo.insert({a: 1})); + hasAuthzError(db.foo.update({}, {$inc: {a: 1}}, false, true)); + assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); + + testUserAdmin.updateUser('testUser', {roles: ['testRole3']}); + assert.doesNotThrow(function() { + db.foo.findOne(); + }); + assert.eq(1, db.foo.count()); + assert.writeOK(db.foo.insert({a: 1})); + assert.eq(2, db.foo.count()); + hasAuthzError(db.foo.update({}, {$inc: {a: 1}}, false, true)); + assert.eq(1, db.foo.findOne().a); + assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); + + testUserAdmin.updateUser('testUser', {roles: [{role: 'testRole4', db: 'test'}]}); + assert.throws(function() { + db.foo.findOne(); + }); + hasAuthzError(db.foo.insert({a: 1})); + hasAuthzError(db.foo.update({}, {$inc: {a: 1}}, false, true)); + assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); + })(); (function testUpdateRole() { - jsTestLog("Testing updateRole"); - - testUserAdmin.updateRole('testRole4', - {roles: [{role: 'testRole2', db: 'test'}, "testRole2"]}); - assert.throws(function() {db.foo.findOne();}); - assert.writeOK(db.foo.insert({ a: 1 })); - hasAuthzError(db.foo.update({}, { $inc: { a: 1 }}, false, true)); - assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); - - testUserAdmin.updateRole('testRole4', - {privileges: [{resource: {db: 'test', collection: ''}, - actions: ['find']}]}); - assert.doesNotThrow(function() {db.foo.findOne();}); - assert.eq(3, db.foo.count()); - assert.writeOK(db.foo.insert({ a: 1 })); - assert.eq(4, db.foo.count()); - hasAuthzError(db.foo.update({}, { $inc: { a: 1 }}, false, true)); - assert.eq(1, db.foo.findOne().a); - assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); - - testUserAdmin.updateRole('testRole4', {roles: []}); - assert.doesNotThrow(function() {db.foo.findOne();}); - assert.eq(4, db.foo.count()); - hasAuthzError(db.foo.insert({ a: 1 })); - assert.eq(4, db.foo.count()); - hasAuthzError(db.foo.update({}, { $inc: { a: 1 }}, false, true)); - assert.eq(1, db.foo.findOne().a); - assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); - - testUserAdmin.updateUser('testUser', {roles: [{role: 'adminRole', db: 'admin'}]}); - adminUserAdmin.updateRole('adminRole', {roles: [{role: 'read', db: 'test'}]}); - assert.doesNotThrow(function() {db.foo.findOne();}); - assert.eq(4, db.foo.count()); - hasAuthzError(db.foo.insert({ a: 1 })); - assert.eq(4, db.foo.count()); - hasAuthzError(db.foo.update({}, { $inc: { a: 1 }}, false, true)); - assert.eq(1, db.foo.findOne().a); - assert.commandWorked(db.adminCommand('connPoolSync')); - })(); + jsTestLog("Testing updateRole"); + + testUserAdmin.updateRole('testRole4', + {roles: [{role: 'testRole2', db: 'test'}, "testRole2"]}); + assert.throws(function() { + db.foo.findOne(); + }); + assert.writeOK(db.foo.insert({a: 1})); + hasAuthzError(db.foo.update({}, {$inc: {a: 1}}, false, true)); + assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); + + testUserAdmin.updateRole( + 'testRole4', + {privileges: [{resource: {db: 'test', collection: ''}, actions: ['find']}]}); + assert.doesNotThrow(function() { + db.foo.findOne(); + }); + assert.eq(3, db.foo.count()); + assert.writeOK(db.foo.insert({a: 1})); + assert.eq(4, db.foo.count()); + hasAuthzError(db.foo.update({}, {$inc: {a: 1}}, false, true)); + assert.eq(1, db.foo.findOne().a); + assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); + + testUserAdmin.updateRole('testRole4', {roles: []}); + assert.doesNotThrow(function() { + db.foo.findOne(); + }); + assert.eq(4, db.foo.count()); + hasAuthzError(db.foo.insert({a: 1})); + assert.eq(4, db.foo.count()); + hasAuthzError(db.foo.update({}, {$inc: {a: 1}}, false, true)); + assert.eq(1, db.foo.findOne().a); + assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); + + testUserAdmin.updateUser('testUser', {roles: [{role: 'adminRole', db: 'admin'}]}); + adminUserAdmin.updateRole('adminRole', {roles: [{role: 'read', db: 'test'}]}); + assert.doesNotThrow(function() { + db.foo.findOne(); + }); + assert.eq(4, db.foo.count()); + hasAuthzError(db.foo.insert({a: 1})); + assert.eq(4, db.foo.count()); + hasAuthzError(db.foo.update({}, {$inc: {a: 1}}, false, true)); + assert.eq(1, db.foo.findOne().a); + assert.commandWorked(db.adminCommand('connPoolSync')); + })(); (function testGrantRolesToRole() { - jsTestLog("Testing grantRolesToRole"); - - assert.commandFailedWithCode(db.adminCommand('serverStatus'), authzErrorCode); - - adminUserAdmin.grantRolesToRole("adminRole", - ['clusterMonitor', - {role: 'read', db: 'test'}, - {role: 'testRole2', db: 'test'}]); - assert.doesNotThrow(function() {db.foo.findOne();}); - assert.eq(4, db.foo.count()); - assert.writeOK(db.foo.insert({ a: 1 })); - assert.eq(5, db.foo.count()); - hasAuthzError(db.foo.update({}, {$inc: {a:1}}, false, true)); - assert.eq(1, db.foo.findOne().a); - assert.commandWorked(db.adminCommand('connPoolSync')); - assert.commandWorked(db.adminCommand('serverStatus')); - })(); + jsTestLog("Testing grantRolesToRole"); + + assert.commandFailedWithCode(db.adminCommand('serverStatus'), authzErrorCode); + + adminUserAdmin.grantRolesToRole( + "adminRole", + ['clusterMonitor', {role: 'read', db: 'test'}, {role: 'testRole2', db: 'test'}]); + assert.doesNotThrow(function() { + db.foo.findOne(); + }); + assert.eq(4, db.foo.count()); + assert.writeOK(db.foo.insert({a: 1})); + assert.eq(5, db.foo.count()); + hasAuthzError(db.foo.update({}, {$inc: {a: 1}}, false, true)); + assert.eq(1, db.foo.findOne().a); + assert.commandWorked(db.adminCommand('connPoolSync')); + assert.commandWorked(db.adminCommand('serverStatus')); + })(); (function testRevokeRolesFromRole() { - jsTestLog("Testing revokeRolesFromRole"); - - adminUserAdmin.revokeRolesFromRole("adminRole", - ['clusterMonitor', - {role: 'read', db: 'test'}, - {role: 'testRole2', db: 'test'}]); - assert.throws(function() {db.foo.findOne();}); - hasAuthzError(db.foo.insert({ a: 1 })); - hasAuthzError(db.foo.update({}, { $inc: { a: 1 }}, false, true)); - assert.commandWorked(db.adminCommand('connPoolSync')); - assert.commandFailedWithCode(db.adminCommand('serverStatus'), authzErrorCode); - })(); + jsTestLog("Testing revokeRolesFromRole"); + + adminUserAdmin.revokeRolesFromRole( + "adminRole", + ['clusterMonitor', {role: 'read', db: 'test'}, {role: 'testRole2', db: 'test'}]); + assert.throws(function() { + db.foo.findOne(); + }); + hasAuthzError(db.foo.insert({a: 1})); + hasAuthzError(db.foo.update({}, {$inc: {a: 1}}, false, true)); + assert.commandWorked(db.adminCommand('connPoolSync')); + assert.commandFailedWithCode(db.adminCommand('serverStatus'), authzErrorCode); + })(); (function testGrantPrivilegesToRole() { - jsTestLog("Testing grantPrivilegesToRole"); - - adminUserAdmin.grantPrivilegesToRole('adminRole', - [{resource: {cluster: true}, - actions: ['serverStatus']}, - {resource: {db:"", collection: ""}, - actions: ['find']}]); - assert.doesNotThrow(function() {db.foo.findOne();}); - hasAuthzError(db.foo.insert({ a: 1 })); - assert.eq(5, db.foo.count()); - hasAuthzError(db.foo.update({}, { $inc: { a: 1 }}, false, true)); - assert.eq(1, db.foo.findOne().a); - assert.commandWorked(db.adminCommand('connPoolSync')); - assert.commandWorked(db.adminCommand('serverStatus')); - - testUserAdmin.updateUser('testUser', {roles: ['testRole2']}); - testUserAdmin.grantPrivilegesToRole('testRole2', - [{resource: {db: 'test', collection: ''}, - actions: ['insert', 'update']}, - {resource: {db: 'test', collection: 'foo'}, - actions: ['find']}]); - assert.doesNotThrow(function() {db.foo.findOne();}); - assert.writeOK(db.foo.insert({ a: 1 })); - assert.eq(6, db.foo.count()); - assert.writeOK(db.foo.update({}, { $inc: { a: 1 }}, false, true)); - assert.eq(2, db.foo.findOne().a); - assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); - assert.commandFailedWithCode(db.adminCommand('serverStatus'), authzErrorCode); - })(); + jsTestLog("Testing grantPrivilegesToRole"); + + adminUserAdmin.grantPrivilegesToRole( + 'adminRole', + [ + {resource: {cluster: true}, actions: ['serverStatus']}, + {resource: {db: "", collection: ""}, actions: ['find']} + ]); + assert.doesNotThrow(function() { + db.foo.findOne(); + }); + hasAuthzError(db.foo.insert({a: 1})); + assert.eq(5, db.foo.count()); + hasAuthzError(db.foo.update({}, {$inc: {a: 1}}, false, true)); + assert.eq(1, db.foo.findOne().a); + assert.commandWorked(db.adminCommand('connPoolSync')); + assert.commandWorked(db.adminCommand('serverStatus')); + + testUserAdmin.updateUser('testUser', {roles: ['testRole2']}); + testUserAdmin.grantPrivilegesToRole( + 'testRole2', + [ + {resource: {db: 'test', collection: ''}, actions: ['insert', 'update']}, + {resource: {db: 'test', collection: 'foo'}, actions: ['find']} + ]); + assert.doesNotThrow(function() { + db.foo.findOne(); + }); + assert.writeOK(db.foo.insert({a: 1})); + assert.eq(6, db.foo.count()); + assert.writeOK(db.foo.update({}, {$inc: {a: 1}}, false, true)); + assert.eq(2, db.foo.findOne().a); + assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); + assert.commandFailedWithCode(db.adminCommand('serverStatus'), authzErrorCode); + })(); (function testRevokePrivilegesFromRole() { - jsTestLog("Testing revokePrivilegesFromRole"); - - testUserAdmin.revokePrivilegesFromRole('testRole2', - [{resource: {db: 'test', collection: ''}, - actions: ['insert', 'update', 'find']}]); - assert.doesNotThrow(function() {db.foo.findOne();}); - assert.writeOK(db.foo.insert({ a: 1 })); - assert.eq(7, db.foo.count()); - hasAuthzError(db.foo.update({}, { $inc: { a: 1 }}, false, true)); - assert.eq(2, db.foo.findOne().a); - assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); - assert.commandFailedWithCode(db.adminCommand('serverStatus'), authzErrorCode); - })(); + jsTestLog("Testing revokePrivilegesFromRole"); + + testUserAdmin.revokePrivilegesFromRole( + 'testRole2', + [{resource: {db: 'test', collection: ''}, actions: ['insert', 'update', 'find']}]); + assert.doesNotThrow(function() { + db.foo.findOne(); + }); + assert.writeOK(db.foo.insert({a: 1})); + assert.eq(7, db.foo.count()); + hasAuthzError(db.foo.update({}, {$inc: {a: 1}}, false, true)); + assert.eq(2, db.foo.findOne().a); + assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); + assert.commandFailedWithCode(db.adminCommand('serverStatus'), authzErrorCode); + })(); (function testRolesInfo() { - jsTestLog("Testing rolesInfo"); - - var res = testUserAdmin.runCommand({rolesInfo: 'testRole1'}); - assert.eq(1, res.roles.length); - assert.eq("testRole1", res.roles[0].role); - assert.eq("test", res.roles[0].db); - assert.eq(1, res.roles[0].roles.length); - assert.eq("read", res.roles[0].roles[0].role); - - res = testUserAdmin.runCommand({rolesInfo: {role: 'testRole1', db: 'test'}}); - assert.eq(1, res.roles.length); - assert.eq("testRole1", res.roles[0].role); - assert.eq("test", res.roles[0].db); - assert.eq(1, res.roles[0].roles.length); - assert.eq("read", res.roles[0].roles[0].role); - - res = testUserAdmin.runCommand({rolesInfo: ['testRole1', {role: 'adminRole', db: 'admin'}]}); - assert.eq(2, res.roles.length); - assert.eq("testRole1", res.roles[0].role); - assert.eq("test", res.roles[0].db); - assert.eq(1, res.roles[0].roles.length); - assert.eq("read", res.roles[0].roles[0].role); - assert.eq("adminRole", res.roles[1].role); - assert.eq("admin", res.roles[1].db); - assert.eq(0, res.roles[1].roles.length); - - res = testUserAdmin.runCommand({rolesInfo: 1}); - assert.eq(4, res.roles.length); - - res = testUserAdmin.runCommand({rolesInfo: 1, showBuiltinRoles: 1}); - assert.eq(10, res.roles.length); - })(); + jsTestLog("Testing rolesInfo"); + + var res = testUserAdmin.runCommand({rolesInfo: 'testRole1'}); + assert.eq(1, res.roles.length); + assert.eq("testRole1", res.roles[0].role); + assert.eq("test", res.roles[0].db); + assert.eq(1, res.roles[0].roles.length); + assert.eq("read", res.roles[0].roles[0].role); + + res = testUserAdmin.runCommand({rolesInfo: {role: 'testRole1', db: 'test'}}); + assert.eq(1, res.roles.length); + assert.eq("testRole1", res.roles[0].role); + assert.eq("test", res.roles[0].db); + assert.eq(1, res.roles[0].roles.length); + assert.eq("read", res.roles[0].roles[0].role); + + res = + testUserAdmin.runCommand({rolesInfo: ['testRole1', {role: 'adminRole', db: 'admin'}]}); + assert.eq(2, res.roles.length); + assert.eq("testRole1", res.roles[0].role); + assert.eq("test", res.roles[0].db); + assert.eq(1, res.roles[0].roles.length); + assert.eq("read", res.roles[0].roles[0].role); + assert.eq("adminRole", res.roles[1].role); + assert.eq("admin", res.roles[1].db); + assert.eq(0, res.roles[1].roles.length); + + res = testUserAdmin.runCommand({rolesInfo: 1}); + assert.eq(4, res.roles.length); + + res = testUserAdmin.runCommand({rolesInfo: 1, showBuiltinRoles: 1}); + assert.eq(10, res.roles.length); + })(); (function testDropRole() { - jsTestLog("Testing dropRole"); + jsTestLog("Testing dropRole"); - testUserAdmin.grantRolesToUser('testUser', ['testRole4']); + testUserAdmin.grantRolesToUser('testUser', ['testRole4']); - assert.doesNotThrow(function() {db.foo.findOne();}); - assert.writeOK(db.foo.insert({ a: 1 })); - assert.eq(8, db.foo.count()); + assert.doesNotThrow(function() { + db.foo.findOne(); + }); + assert.writeOK(db.foo.insert({a: 1})); + assert.eq(8, db.foo.count()); - assert.commandWorked(testUserAdmin.runCommand({dropRole: 'testRole2'})); + assert.commandWorked(testUserAdmin.runCommand({dropRole: 'testRole2'})); - assert.doesNotThrow(function() {db.foo.findOne();}); - hasAuthzError(db.foo.insert({ a: 1 })); - assert.eq(8, db.foo.count()); + assert.doesNotThrow(function() { + db.foo.findOne(); + }); + hasAuthzError(db.foo.insert({a: 1})); + assert.eq(8, db.foo.count()); - assert.eq(3, testUserAdmin.getRoles().length); - })(); + assert.eq(3, testUserAdmin.getRoles().length); + })(); (function testDropAllRolesFromDatabase() { - jsTestLog("Testing dropAllRolesFromDatabase"); + jsTestLog("Testing dropAllRolesFromDatabase"); - assert.doesNotThrow(function() {db.foo.findOne();}); - assert.eq(3, testUserAdmin.getRoles().length); + assert.doesNotThrow(function() { + db.foo.findOne(); + }); + assert.eq(3, testUserAdmin.getRoles().length); - assert.commandWorked(testUserAdmin.runCommand({dropAllRolesFromDatabase: 1})); + assert.commandWorked(testUserAdmin.runCommand({dropAllRolesFromDatabase: 1})); - assert.throws(function() {db.foo.findOne();}); - assert.eq(0, testUserAdmin.getRoles().length); - })(); + assert.throws(function() { + db.foo.findOne(); + }); + assert.eq(0, testUserAdmin.getRoles().length); + })(); } jsTest.log('Test standalone'); -var conn = MongoRunner.runMongod({ auth: '', useHostname: false }); +var conn = MongoRunner.runMongod({auth: '', useHostname: false}); runTest(conn); MongoRunner.stopMongod(conn.port); jsTest.log('Test sharding'); -var st = new ShardingTest({ shards: 2, config: 3, keyFile: 'jstests/libs/key1', useHostname: false }); +var st = new ShardingTest({shards: 2, config: 3, keyFile: 'jstests/libs/key1', useHostname: false}); runTest(st.s); st.stop(); diff --git a/jstests/auth/role_management_commands_edge_cases.js b/jstests/auth/role_management_commands_edge_cases.js index 0415c9b20dc..122221ce234 100644 --- a/jstests/auth/role_management_commands_edge_cases.js +++ b/jstests/auth/role_management_commands_edge_cases.js @@ -10,376 +10,381 @@ function runTest(conn) { admin.auth('userAdmin', 'pwd'); (function testCreateRole() { - jsTestLog("Testing createRole"); - - // Role with no privs - db.createRole({role: "role1", roles: [], privileges: []}); - - // Role with duplicate other roles - db.createRole({role: "role2", - roles: ['read', 'read', 'role1', 'role1'], - privileges: []}); - assert.eq(2, db.getRole("role2").roles.length); - - // Role with duplicate privileges - db.createRole({role: "role3", - roles: ['role2'], - privileges: [{resource: {db: 'test', collection: ''}, - actions:['find']}, - {resource: {db: 'test', collection: ''}, - actions:['find']}]}); - assert.eq(1, db.getRole("role3", {showPrivileges: true}).privileges.length); - - // Try to create role that already exists. - assert.throws(function() { - db.createRole({role: 'role2', roles:[], privileges:[]}); - }); - - - // Try to create role with no name - assert.throws(function() { - db.createRole({role: '', roles:[], privileges:[]}); - }); - - // Try to create a role the wrong types for the arguments - assert.throws(function() { - db.createRole({role: 1, roles:[], privileges:[]}); - }); - assert.throws(function() { - db.createRole({role: ["role4", "role5"], - roles:[], - privileges:[]}); - }); - assert.throws(function() { - db.createRole({role: 'role6', roles:1, privileges:[]}); - }); - assert.throws(function() { - db.createRole({role: 'role7', roles:[], privileges:1}); - }); - - // Try to create a role with an invalid privilege - assert.throws(function() { - db.createRole({role: 'role8', - roles:[], - privileges:[{resource: {}, - actions:['find']}]}); - }); - assert.throws(function() { - db.createRole({role: 'role9', - roles:[], - privileges:[{resource: {db:"test", collection:"foo"}, - actions:[]}]}); - }); - assert.throws(function() { - db.createRole({role: 'role10', - roles:[], - privileges:[{resource: {db:"test"}, - actions:['find']}]}); - }); - assert.throws(function() { - db.createRole({role: 'role11', - roles:[], - privileges:[{resource: {collection:"foo"}, - actions:['find']}]}); - }); - assert.throws(function() { - db.createRole({role: 'role12', - roles:[], - privileges:[{resource: {anyResource: false}, - actions:['find']}]}); - }); - assert.throws(function() { - db.createRole({role: 'role13', - roles:[], - privileges:[{resource: {db:"test", - collection:"foo", - cluster:true}, - actions:['find']}]}); - }); - assert.throws(function() { - db.createRole({role: 'role14', - roles:[], - privileges:[{resource: {cluster: false}, - actions:['find']}]}); - }); - assert.throws(function() { - db.createRole({role: 'role15', - roles:[], - privileges:[{resource: {db:"test", collection:"$cmd"}, - actions:['find']}]}); - }); - assert.throws(function() { - db.createRole({role: 'role16', - roles:[], - privileges:[{resource: {db:"test", collection:"foo"}, - actions:['fakeAction']}]}); - }); - - // Try to create role containing itself in its roles array - assert.throws(function() { - db.createRole({role: 'role17', - roles:['role10'], - privileges:[]}); - }); - - - assert.eq(3, db.getRoles().length); - })(); + jsTestLog("Testing createRole"); + + // Role with no privs + db.createRole({role: "role1", roles: [], privileges: []}); + + // Role with duplicate other roles + db.createRole({role: "role2", roles: ['read', 'read', 'role1', 'role1'], privileges: []}); + assert.eq(2, db.getRole("role2").roles.length); + + // Role with duplicate privileges + db.createRole({ + role: "role3", + roles: ['role2'], + privileges: [ + {resource: {db: 'test', collection: ''}, actions: ['find']}, + {resource: {db: 'test', collection: ''}, actions: ['find']} + ] + }); + assert.eq(1, db.getRole("role3", {showPrivileges: true}).privileges.length); + + // Try to create role that already exists. + assert.throws(function() { + db.createRole({role: 'role2', roles: [], privileges: []}); + }); + + // Try to create role with no name + assert.throws(function() { + db.createRole({role: '', roles: [], privileges: []}); + }); + + // Try to create a role the wrong types for the arguments + assert.throws(function() { + db.createRole({role: 1, roles: [], privileges: []}); + }); + assert.throws(function() { + db.createRole({role: ["role4", "role5"], roles: [], privileges: []}); + }); + assert.throws(function() { + db.createRole({role: 'role6', roles: 1, privileges: []}); + }); + assert.throws(function() { + db.createRole({role: 'role7', roles: [], privileges: 1}); + }); + + // Try to create a role with an invalid privilege + assert.throws(function() { + db.createRole( + {role: 'role8', roles: [], privileges: [{resource: {}, actions: ['find']}]}); + }); + assert.throws(function() { + db.createRole({ + role: 'role9', + roles: [], + privileges: [{resource: {db: "test", collection: "foo"}, actions: []}] + }); + }); + assert.throws(function() { + db.createRole({ + role: 'role10', + roles: [], + privileges: [{resource: {db: "test"}, actions: ['find']}] + }); + }); + assert.throws(function() { + db.createRole({ + role: 'role11', + roles: [], + privileges: [{resource: {collection: "foo"}, actions: ['find']}] + }); + }); + assert.throws(function() { + db.createRole({ + role: 'role12', + roles: [], + privileges: [{resource: {anyResource: false}, actions: ['find']}] + }); + }); + assert.throws(function() { + db.createRole({ + role: 'role13', + roles: [], + privileges: [{ + resource: {db: "test", collection: "foo", cluster: true}, + actions: ['find'] + }] + }); + }); + assert.throws(function() { + db.createRole({ + role: 'role14', + roles: [], + privileges: [{resource: {cluster: false}, actions: ['find']}] + }); + }); + assert.throws(function() { + db.createRole({ + role: 'role15', + roles: [], + privileges: [{resource: {db: "test", collection: "$cmd"}, actions: ['find']}] + }); + }); + assert.throws(function() { + db.createRole({ + role: 'role16', + roles: [], + privileges: + [{resource: {db: "test", collection: "foo"}, actions: ['fakeAction']}] + }); + }); + + // Try to create role containing itself in its roles array + assert.throws(function() { + db.createRole({role: 'role17', roles: ['role10'], privileges: []}); + }); + + assert.eq(3, db.getRoles().length); + })(); (function testUpdateRole() { - jsTestLog("Testing updateRole"); - - // Try to update role that doesn't exist - assert.throws(function() { - db.updateRole("fakeRole", {roles: []}); - }); - - // Try to update role to have a role that doesn't exist - assert.throws(function() { - db.updateRole("role1", {roles: ['fakeRole']}); - }); - - // Try to update a built-in role - assert.throws(function() { - db.updateRole("read", {roles: ['readWrite']}); - }); - - // Try to create a cycle in the role graph - assert.throws(function() { - db.updateRole("role1", {roles: ['role1']}); - }); - assert.eq(0, db.getRole('role1').roles.length); - - assert.throws(function() { - db.updateRole("role1", {roles: ['role2']}); - }); - assert.eq(0, db.getRole('role1').roles.length); - - assert.throws(function() { - db.updateRole("role1", {roles: ['role3']}); - }); - assert.eq(0, db.getRole('role1').roles.length); - })(); + jsTestLog("Testing updateRole"); + + // Try to update role that doesn't exist + assert.throws(function() { + db.updateRole("fakeRole", {roles: []}); + }); + + // Try to update role to have a role that doesn't exist + assert.throws(function() { + db.updateRole("role1", {roles: ['fakeRole']}); + }); + + // Try to update a built-in role + assert.throws(function() { + db.updateRole("read", {roles: ['readWrite']}); + }); + + // Try to create a cycle in the role graph + assert.throws(function() { + db.updateRole("role1", {roles: ['role1']}); + }); + assert.eq(0, db.getRole('role1').roles.length); + + assert.throws(function() { + db.updateRole("role1", {roles: ['role2']}); + }); + assert.eq(0, db.getRole('role1').roles.length); + + assert.throws(function() { + db.updateRole("role1", {roles: ['role3']}); + }); + assert.eq(0, db.getRole('role1').roles.length); + })(); (function testGrantRolesToRole() { - jsTestLog("Testing grantRolesToRole"); - - // Grant role1 to role2 even though role2 already has role1 - db.grantRolesToRole("role2", ['role1']); - assert.eq(2, db.getRole('role2').roles.length); - - // Try to grant a role that doesn't exist - assert.throws(function() { - db.grantRolesToRole("role1", ['fakeRole']); - }); - - // Try to grant *to* a role that doesn't exist - assert.throws(function() { - db.grantRolesToRole("fakeRole", ['role1']); - }); - - // Must specify at least 1 role - assert.throws(function() { - db.grantRolesToRole("role1", []); - }); - - // Try to grant to a built-in role - assert.throws(function() { - db.grantRolesToRole("read", ['role1']); - }); - - // Try to create a cycle in the role graph - assert.throws(function() { - db.grantRolesToRole("role1", ['role1']); - }); - assert.eq(0, db.getRole('role1').roles.length); - - assert.throws(function() { - db.grantRolesToRole("role1", ['role2']); - }); - assert.eq(0, db.getRole('role1').roles.length); - - assert.throws(function() { - db.grantRolesToRole("role1", ['role3']); - }); - assert.eq(0, db.getRole('role1').roles.length); - })(); + jsTestLog("Testing grantRolesToRole"); + + // Grant role1 to role2 even though role2 already has role1 + db.grantRolesToRole("role2", ['role1']); + assert.eq(2, db.getRole('role2').roles.length); + + // Try to grant a role that doesn't exist + assert.throws(function() { + db.grantRolesToRole("role1", ['fakeRole']); + }); + + // Try to grant *to* a role that doesn't exist + assert.throws(function() { + db.grantRolesToRole("fakeRole", ['role1']); + }); + + // Must specify at least 1 role + assert.throws(function() { + db.grantRolesToRole("role1", []); + }); + + // Try to grant to a built-in role + assert.throws(function() { + db.grantRolesToRole("read", ['role1']); + }); + + // Try to create a cycle in the role graph + assert.throws(function() { + db.grantRolesToRole("role1", ['role1']); + }); + assert.eq(0, db.getRole('role1').roles.length); + + assert.throws(function() { + db.grantRolesToRole("role1", ['role2']); + }); + assert.eq(0, db.getRole('role1').roles.length); + + assert.throws(function() { + db.grantRolesToRole("role1", ['role3']); + }); + assert.eq(0, db.getRole('role1').roles.length); + })(); (function testRevokeRolesFromRole() { - jsTestLog("Testing revokeRolesFromRole"); + jsTestLog("Testing revokeRolesFromRole"); - // Try to revoke a role that doesn't exist - // Should not error but should do nothing. - assert.doesNotThrow(function() { - db.revokeRolesFromRole("role2", ['fakeRole']); - }); + // Try to revoke a role that doesn't exist + // Should not error but should do nothing. + assert.doesNotThrow(function() { + db.revokeRolesFromRole("role2", ['fakeRole']); + }); - // Try to revoke role3 from role2 even though role2 does not contain role3. - // Should not error but should do nothing. - assert.doesNotThrow(function() { - db.revokeRolesFromRole("role2", ['role3']); - }); - assert.eq(2, db.getRole("role2").roles.length); + // Try to revoke role3 from role2 even though role2 does not contain role3. + // Should not error but should do nothing. + assert.doesNotThrow(function() { + db.revokeRolesFromRole("role2", ['role3']); + }); + assert.eq(2, db.getRole("role2").roles.length); - // Must revoke something - assert.throws(function() { - db.revokeRolesFromRole("role2", []); - }); + // Must revoke something + assert.throws(function() { + db.revokeRolesFromRole("role2", []); + }); - // Try to remove from built-in role - assert.throws(function() { - db.revokeRolesFromRole("readWrite", ['read']); - }); + // Try to remove from built-in role + assert.throws(function() { + db.revokeRolesFromRole("readWrite", ['read']); + }); - })(); + })(); (function testGrantPrivilegesToRole() { - jsTestLog("Testing grantPrivilegesToRole"); - - // Must grant something - assert.throws(function() { - db.grantPrivilegesToRole("role1", []); - }); - - var basicPriv = {resource: {db: 'test', collection:""}, actions: ['find']}; - - // Invalid first argument - assert.throws(function() { - db.grantPrivilegesToRole(["role1", "role2"], [basicPriv]); - }); - - // Try to grant to role that doesn't exist - assert.throws(function() { - db.grantPrivilegesToRole("fakeRole", [basicPriv]); - }); - - // Test with invalid privileges - var badPrivs = []; - badPrivs.push("find"); - badPrivs.push({resource: {db: 'test', collection:""}, actions: ['fakeAction']}); - badPrivs.push({resource: {db: ['test'], collection:""}, actions: ['find']}); - badPrivs.push({resource: {db: 'test', collection:""}}); - badPrivs.push({actions: ['find']}); - badPrivs.push({resource: {db: 'test', collection:""}, actions: []}); - badPrivs.push({resource: {db: 'test'}, actions: ['find']}); - badPrivs.push({resource: {collection: 'test'}, actions: ['find']}); - badPrivs.push({resource: {}, actions: ['find']}); - badPrivs.push({resource: {db: 'test', collection:"", cluster:true }, actions: ['find']}); - - for (var i = 0; i < badPrivs.length; i++) { - assert.throws(function() { - db.grantPrivilegesToRole("role1", [badPrivs[i]]); - }); - } - - assert.eq(0, db.getRole('role1', {showPrivileges: true}).privileges.length); - })(); + jsTestLog("Testing grantPrivilegesToRole"); + + // Must grant something + assert.throws(function() { + db.grantPrivilegesToRole("role1", []); + }); + + var basicPriv = { + resource: {db: 'test', collection: ""}, + actions: ['find'] + }; + + // Invalid first argument + assert.throws(function() { + db.grantPrivilegesToRole(["role1", "role2"], [basicPriv]); + }); + + // Try to grant to role that doesn't exist + assert.throws(function() { + db.grantPrivilegesToRole("fakeRole", [basicPriv]); + }); + + // Test with invalid privileges + var badPrivs = []; + badPrivs.push("find"); + badPrivs.push({resource: {db: 'test', collection: ""}, actions: ['fakeAction']}); + badPrivs.push({resource: {db: ['test'], collection: ""}, actions: ['find']}); + badPrivs.push({resource: {db: 'test', collection: ""}}); + badPrivs.push({actions: ['find']}); + badPrivs.push({resource: {db: 'test', collection: ""}, actions: []}); + badPrivs.push({resource: {db: 'test'}, actions: ['find']}); + badPrivs.push({resource: {collection: 'test'}, actions: ['find']}); + badPrivs.push({resource: {}, actions: ['find']}); + badPrivs.push({resource: {db: 'test', collection: "", cluster: true}, actions: ['find']}); + + for (var i = 0; i < badPrivs.length; i++) { + assert.throws(function() { + db.grantPrivilegesToRole("role1", [badPrivs[i]]); + }); + } + + assert.eq(0, db.getRole('role1', {showPrivileges: true}).privileges.length); + })(); (function testRevokePrivilegesFromRole() { - jsTestLog("Testing revokePrivilegesFromRole"); - - // Try to revoke a privilege the role doesn't have - // Should not error but should do nothing. - assert.doesNotThrow(function() { - db.revokePrivilegesFromRole("role3", - [{resource: {db: "test", - collection: "foobar"}, - actions: ["insert"]}]); - }); - assert.eq(0, db.getRole("role2", {showPrivileges: true}).privileges.length); - - // Must revoke something - assert.throws(function() { - db.revokePrivilegesFromRole("role3", []); - }); - - // Try to remove from built-in role - assert.throws(function() { - db.revokePrivilegesFromRole("readWrite", [{resource: {db: 'test', - collection: ''}, - actions: ['find']}]); - }); - - var basicPriv = {resource: {db: 'test', collection:""}, actions: ['find']}; - - // Invalid first argument - assert.throws(function() { - db.revokePrivilegesFromRole(["role3", "role2"], [basicPriv]); - }); - - // Try to revoke from role that doesn't exist - assert.throws(function() { - db.revokePrivilegesToRole("fakeRole", [basicPriv]); - }); - - // Test with invalid privileges - var badPrivs = []; - badPrivs.push("find"); - badPrivs.push({resource: {db: 'test', collection:""}, actions: ['fakeAction']}); - badPrivs.push({resource: {db: ['test'], collection:""}, actions: ['find']}); - badPrivs.push({resource: {db: 'test', collection:""}}); - badPrivs.push({actions: ['find']}); - badPrivs.push({resource: {db: 'test', collection:""}, actions: []}); - badPrivs.push({resource: {db: 'test'}, actions: ['find']}); - badPrivs.push({resource: {collection: 'test'}, actions: ['find']}); - badPrivs.push({resource: {}, actions: ['find']}); - badPrivs.push({resource: {db: 'test', collection:"", cluster:true }, actions: ['find']}); - - for (var i = 0; i < badPrivs.length; i++) { - assert.throws(function() { - db.revokePrivilegesFromRole("role3", [badPrivs[i]]); - }); - } - - assert.eq(1, db.getRole('role3', {showPrivileges: true}).privileges.length); - })(); + jsTestLog("Testing revokePrivilegesFromRole"); + + // Try to revoke a privilege the role doesn't have + // Should not error but should do nothing. + assert.doesNotThrow(function() { + db.revokePrivilegesFromRole( + "role3", [{resource: {db: "test", collection: "foobar"}, actions: ["insert"]}]); + }); + assert.eq(0, db.getRole("role2", {showPrivileges: true}).privileges.length); + + // Must revoke something + assert.throws(function() { + db.revokePrivilegesFromRole("role3", []); + }); + + // Try to remove from built-in role + assert.throws(function() { + db.revokePrivilegesFromRole( + "readWrite", [{resource: {db: 'test', collection: ''}, actions: ['find']}]); + }); + + var basicPriv = { + resource: {db: 'test', collection: ""}, + actions: ['find'] + }; + + // Invalid first argument + assert.throws(function() { + db.revokePrivilegesFromRole(["role3", "role2"], [basicPriv]); + }); + + // Try to revoke from role that doesn't exist + assert.throws(function() { + db.revokePrivilegesToRole("fakeRole", [basicPriv]); + }); + + // Test with invalid privileges + var badPrivs = []; + badPrivs.push("find"); + badPrivs.push({resource: {db: 'test', collection: ""}, actions: ['fakeAction']}); + badPrivs.push({resource: {db: ['test'], collection: ""}, actions: ['find']}); + badPrivs.push({resource: {db: 'test', collection: ""}}); + badPrivs.push({actions: ['find']}); + badPrivs.push({resource: {db: 'test', collection: ""}, actions: []}); + badPrivs.push({resource: {db: 'test'}, actions: ['find']}); + badPrivs.push({resource: {collection: 'test'}, actions: ['find']}); + badPrivs.push({resource: {}, actions: ['find']}); + badPrivs.push({resource: {db: 'test', collection: "", cluster: true}, actions: ['find']}); + + for (var i = 0; i < badPrivs.length; i++) { + assert.throws(function() { + db.revokePrivilegesFromRole("role3", [badPrivs[i]]); + }); + } + + assert.eq(1, db.getRole('role3', {showPrivileges: true}).privileges.length); + })(); (function testRolesInfo() { - jsTestLog("Testing rolesInfo"); + jsTestLog("Testing rolesInfo"); - // Try to get role that does not exist - assert.eq(null, db.getRole('fakeRole')); + // Try to get role that does not exist + assert.eq(null, db.getRole('fakeRole')); - // Pass wrong type for role name - assert.throws(function() { - db.getRole(5); - }); + // Pass wrong type for role name + assert.throws(function() { + db.getRole(5); + }); - assert.throws(function() { - db.getRole([]); - }); + assert.throws(function() { + db.getRole([]); + }); - assert.throws(function() { - db.getRole(['role1', 'role2']); - }); - })(); + assert.throws(function() { + db.getRole(['role1', 'role2']); + }); + })(); (function testDropRole() { - jsTestLog("Testing dropRole"); + jsTestLog("Testing dropRole"); - // Try to drop a role that doesn't exist - // Should not error but should do nothing - assert.doesNotThrow(function() { - db.dropRole('fakeRole'); - }); + // Try to drop a role that doesn't exist + // Should not error but should do nothing + assert.doesNotThrow(function() { + db.dropRole('fakeRole'); + }); - // Try to drop a built-in role - assert.throws(function() { - db.dropRole('read'); - }); + // Try to drop a built-in role + assert.throws(function() { + db.dropRole('read'); + }); - assert.eq(3, db.getRoles().length); - })(); + assert.eq(3, db.getRoles().length); + })(); // dropAllRolesFromDatabase ignores its arguments, so there's nothing to test for it. } jsTest.log('Test standalone'); -var conn = MongoRunner.runMongod({ auth: '' }); +var conn = MongoRunner.runMongod({auth: ''}); runTest(conn); MongoRunner.stopMongod(conn.port); jsTest.log('Test sharding'); -var st = new ShardingTest({ shards: 2, config: 3, keyFile: 'jstests/libs/key1' }); +var st = new ShardingTest({shards: 2, config: 3, keyFile: 'jstests/libs/key1'}); runTest(st.s); st.stop(); diff --git a/jstests/auth/secondary_invalidation.js b/jstests/auth/secondary_invalidation.js index 4809c3c30fc..3752a3aa678 100644 --- a/jstests/auth/secondary_invalidation.js +++ b/jstests/auth/secondary_invalidation.js @@ -1,11 +1,11 @@ /** - * Test that user modifications on replica set primaries + * Test that user modifications on replica set primaries * will invalidate cached user credentials on secondaries */ var NUM_NODES = 3; -var rsTest = new ReplSetTest({ nodes: NUM_NODES }); -rsTest.startSet({ oplogSize: 10, keyFile: 'jstests/libs/key1' }); +var rsTest = new ReplSetTest({nodes: NUM_NODES}); +rsTest.startSet({oplogSize: 10, keyFile: 'jstests/libs/key1'}); rsTest.initiate(); rsTest.awaitSecondaryNodes(); @@ -14,17 +14,20 @@ var secondary = rsTest.getSecondary(); var admin = primary.getDB('admin'); // Setup initial data -admin.createUser({ user:'admin', pwd: 'password', roles: jsTest.adminUserRoles }); +admin.createUser({user: 'admin', pwd: 'password', roles: jsTest.adminUserRoles}); admin.auth('admin', 'password'); -primary.getDB('foo').createUser({ user: 'foo', pwd: 'foopwd', roles: [] }, - { w: NUM_NODES }); +primary.getDB('foo').createUser({user: 'foo', pwd: 'foopwd', roles: []}, {w: NUM_NODES}); secondaryFoo = secondary.getDB('foo'); secondaryFoo.auth('foo', 'foopwd'); -assert.throws(function (){secondaryFoo.col.findOne();}, [], "Secondary read worked without permissions"); +assert.throws(function() { + secondaryFoo.col.findOne(); +}, [], "Secondary read worked without permissions"); -primary.getDB('foo').updateUser('foo', {roles: jsTest.basicUserRoles}, { w: NUM_NODES }); -assert.doesNotThrow(function (){secondaryFoo.col.findOne();}, [], "Secondary read did not work with permissions"); +primary.getDB('foo').updateUser('foo', {roles: jsTest.basicUserRoles}, {w: NUM_NODES}); +assert.doesNotThrow(function() { + secondaryFoo.col.findOne(); +}, [], "Secondary read did not work with permissions"); rsTest.stopSet(); diff --git a/jstests/auth/server-4892.js b/jstests/auth/server-4892.js index 16e4b8b6f64..ef0c95c868e 100644 --- a/jstests/auth/server-4892.js +++ b/jstests/auth/server-4892.js @@ -26,9 +26,9 @@ function withMongod(extraMongodArgs, operation) { var mongod = MongoRunner.runMongod(Object.merge(mongodCommonArgs, extraMongodArgs)); try { - operation( mongod ); + operation(mongod); } finally { - MongoRunner.stopMongod( mongod.port ); + MongoRunner.stopMongod(mongod.port); } } @@ -37,50 +37,53 @@ function withMongod(extraMongodArgs, operation) { * cursors on the server. */ function expectNumLiveCursors(mongod, expectedNumLiveCursors) { - var conn = new Mongo( mongod.host ); - var db = mongod.getDB( 'admin' ); - db.auth( 'admin', 'admin' ); + var conn = new Mongo(mongod.host); + var db = mongod.getDB('admin'); + db.auth('admin', 'admin'); var actualNumLiveCursors = db.serverStatus().metrics.cursor.open.total; - assert( actualNumLiveCursors == expectedNumLiveCursors, - "actual num live cursors (" + actualNumLiveCursors + ") != exptected (" - + expectedNumLiveCursors + ")"); + assert(actualNumLiveCursors == expectedNumLiveCursors, + "actual num live cursors (" + actualNumLiveCursors + ") != exptected (" + + expectedNumLiveCursors + ")"); } -withMongod({noauth: ""}, function setupTest(mongod) { - var admin, somedb, conn; - conn = new Mongo( mongod.host ); - admin = conn.getDB( 'admin' ); - somedb = conn.getDB( 'somedb' ); - admin.createUser({user: 'admin', pwd: 'admin', roles: jsTest.adminUserRoles}); - admin.auth('admin', 'admin'); - somedb.createUser({user: 'frim', pwd: 'fram', roles: jsTest.basicUserRoles}); - somedb.data.drop(); - for (var i = 0; i < 10; ++i) { - assert.writeOK(somedb.data.insert( { val: i } )); - } - admin.logout(); -} ); - -withMongod({auth: ""}, function runTest(mongod) { - var conn = new Mongo( mongod.host ); - var somedb = conn.getDB( 'somedb' ); - somedb.auth('frim', 'fram'); +withMongod({noauth: ""}, + function setupTest(mongod) { + var admin, somedb, conn; + conn = new Mongo(mongod.host); + admin = conn.getDB('admin'); + somedb = conn.getDB('somedb'); + admin.createUser({user: 'admin', pwd: 'admin', roles: jsTest.adminUserRoles}); + admin.auth('admin', 'admin'); + somedb.createUser({user: 'frim', pwd: 'fram', roles: jsTest.basicUserRoles}); + somedb.data.drop(); + for (var i = 0; i < 10; ++i) { + assert.writeOK(somedb.data.insert({val: i})); + } + admin.logout(); + }); - expectNumLiveCursors( mongod, 0 ); +withMongod({auth: ""}, + function runTest(mongod) { + var conn = new Mongo(mongod.host); + var somedb = conn.getDB('somedb'); + somedb.auth('frim', 'fram'); - var cursor = somedb.data.find({}, {'_id': 1}).batchSize(1); - cursor.next(); - expectNumLiveCursors( mongod, 1 ); + expectNumLiveCursors(mongod, 0); - cursor = null; - // NOTE(schwerin): We assume that after setting cursor = null, there are no remaining references - // to the cursor, and that gc() will deterministically garbage collect it. - gc(); + var cursor = somedb.data.find({}, {'_id': 1}).batchSize(1); + cursor.next(); + expectNumLiveCursors(mongod, 1); - // NOTE(schwerin): dbKillCursors gets piggybacked on subsequent messages on the connection, so we - // have to force a message to the server. - somedb.data.findOne(); + cursor = null; + // NOTE(schwerin): We assume that after setting cursor = null, there are no remaining + // references + // to the cursor, and that gc() will deterministically garbage collect it. + gc(); - expectNumLiveCursors( mongod, 0 ); -}); + // NOTE(schwerin): dbKillCursors gets piggybacked on subsequent messages on the + // connection, so we + // have to force a message to the server. + somedb.data.findOne(); + expectNumLiveCursors(mongod, 0); + }); diff --git a/jstests/auth/show_log_auth.js b/jstests/auth/show_log_auth.js index be7d17cd7bc..b318e0536ad 100644 --- a/jstests/auth/show_log_auth.js +++ b/jstests/auth/show_log_auth.js @@ -3,21 +3,23 @@ var baseName = "jstests_show_log_auth"; var m = MongoRunner.runMongod({auth: "", bind_ip: "127.0.0.1", nojournal: "", smallfiles: ""}); -var db = m.getDB( "admin" ); +var db = m.getDB("admin"); -db.createUser({user: "admin" , pwd: "pass", roles: jsTest.adminUserRoles}); +db.createUser({user: "admin", pwd: "pass", roles: jsTest.adminUserRoles}); function assertStartsWith(s, prefix) { assert.eq(s.substr(0, prefix.length), prefix); } -assertStartsWith( print.captureAllOutput( function () { +assertStartsWith(print.captureAllOutput(function() { shellHelper.show('logs'); -} ).output[0], 'Error while trying to show logs'); +}).output[0], + 'Error while trying to show logs'); -assertStartsWith( print.captureAllOutput( function () { +assertStartsWith(print.captureAllOutput(function() { shellHelper.show('log ' + baseName); -} ).output[0], 'Error while trying to show ' + baseName + ' log'); +}).output[0], + 'Error while trying to show ' + baseName + ' log'); -db.auth( "admin" , "pass" ); +db.auth("admin", "pass"); db.shutdownServer(); diff --git a/jstests/auth/system_user_privileges.js b/jstests/auth/system_user_privileges.js index 1a1c1151be8..2e49a9d5d9a 100644 --- a/jstests/auth/system_user_privileges.js +++ b/jstests/auth/system_user_privileges.js @@ -17,16 +17,17 @@ // Runs the "count" command on a database in a way that returns the result document, for easier // inspection of the errmsg. function runCountCommand(conn, dbName, collectionName) { - return conn.getDB(dbName).runCommand({ count: collectionName }); + return conn.getDB(dbName).runCommand({count: collectionName}); } // Asserts that on the given "conn", "dbName"."collectionName".count() fails as unauthorized. function assertCountUnauthorized(conn, dbName, collectionName) { - assert.eq(runCountCommand(conn, dbName, collectionName).code, 13, + assert.eq(runCountCommand(conn, dbName, collectionName).code, + 13, "On " + dbName + "." + collectionName); } - var conn = MongoRunner.runMongod({ smallfiles: "", auth: "" }); + var conn = MongoRunner.runMongod({smallfiles: "", auth: ""}); var admin = conn.getDB('admin'); var test = conn.getDB('test'); @@ -35,7 +36,7 @@ // // Preliminary set up. // - admin.createUser({user:'admin', pwd: 'a', roles: jsTest.adminUserRoles}); + admin.createUser({user: 'admin', pwd: 'a', roles: jsTest.adminUserRoles}); admin.auth('admin', 'a'); // @@ -57,7 +58,6 @@ test.foo.insert({_id: 2}); local.foo.insert({_id: 3}); - admin.logout(); assertCountUnauthorized(conn, "admin", "foo"); assertCountUnauthorized(conn, "local", "foo"); @@ -99,4 +99,3 @@ assertCountUnauthorized(conn, "test", "foo"); })(); - diff --git a/jstests/auth/user_defined_roles.js b/jstests/auth/user_defined_roles.js index 25eb885366c..0190ad9385e 100644 --- a/jstests/auth/user_defined_roles.js +++ b/jstests/auth/user_defined_roles.js @@ -12,21 +12,19 @@ function runTest(conn) { conn.getDB('admin').createUser({user: 'admin', pwd: 'pwd', roles: ['root']}); conn.getDB('admin').auth('admin', 'pwd'); - conn.getDB('admin').createUser({user: 'userAdmin', - pwd: 'pwd', - roles: ['userAdminAnyDatabase']}); + conn.getDB('admin') + .createUser({user: 'userAdmin', pwd: 'pwd', roles: ['userAdminAnyDatabase']}); conn.getDB('admin').logout(); var userAdminConn = new Mongo(conn.host); var adminUserAdmin = userAdminConn.getDB('admin'); adminUserAdmin.auth('userAdmin', 'pwd'); - adminUserAdmin.createRole({role: 'adminRole', privileges:[], roles:[]}); + adminUserAdmin.createRole({role: 'adminRole', privileges: [], roles: []}); var testUserAdmin = userAdminConn.getDB('test'); - testUserAdmin.createRole({role: 'testRole1', privileges:[], roles:[]}); - testUserAdmin.createRole({role: 'testRole2', privileges:[], roles:['testRole1']}); - testUserAdmin.createUser({user: 'testUser', - pwd: 'pwd', - roles: ['testRole2', {role: 'adminRole', db: 'admin'}]}); + testUserAdmin.createRole({role: 'testRole1', privileges: [], roles: []}); + testUserAdmin.createRole({role: 'testRole2', privileges: [], roles: ['testRole1']}); + testUserAdmin.createUser( + {user: 'testUser', pwd: 'pwd', roles: ['testRole2', {role: 'adminRole', db: 'admin'}]}); var testDB = conn.getDB('test'); assert(testDB.auth('testUser', 'pwd')); @@ -39,66 +37,74 @@ function runTest(conn) { // auth'd as 'testUser@test' - this is the connection that will be used to test how privilege // enforcement works. - // test CRUD - hasAuthzError(testDB.foo.insert({ a: 1 })); - assert.throws(function() { testDB.foo.findOne();}); - - testUserAdmin.grantPrivilegesToRole('testRole1', [{resource: {db: 'test', collection: ''}, - actions:['find']}]); - - hasAuthzError(testDB.foo.insert({ a: 1 })); - assert.doesNotThrow(function() { testDB.foo.findOne();}); + hasAuthzError(testDB.foo.insert({a: 1})); + assert.throws(function() { + testDB.foo.findOne(); + }); + + testUserAdmin.grantPrivilegesToRole( + 'testRole1', [{resource: {db: 'test', collection: ''}, actions: ['find']}]); + + hasAuthzError(testDB.foo.insert({a: 1})); + assert.doesNotThrow(function() { + testDB.foo.findOne(); + }); assert.eq(0, testDB.foo.count()); assert.eq(0, testDB.foo.find().itcount()); - testUserAdmin.grantPrivilegesToRole('testRole1', [{resource: {db: 'test', collection: 'foo'}, - actions:['insert']}]); + testUserAdmin.grantPrivilegesToRole( + 'testRole1', [{resource: {db: 'test', collection: 'foo'}, actions: ['insert']}]); - assert.writeOK(testDB.foo.insert({ a: 1 })); + assert.writeOK(testDB.foo.insert({a: 1})); assert.eq(1, testDB.foo.findOne().a); assert.eq(1, testDB.foo.count()); assert.eq(1, testDB.foo.find().itcount()); - hasAuthzError(testDB.foo.update({ a: 1 }, { $inc: { a: 1 }})); + hasAuthzError(testDB.foo.update({a: 1}, {$inc: {a: 1}})); assert.eq(1, testDB.foo.findOne().a); - hasAuthzError(testDB.bar.insert({ a: 1 })); + hasAuthzError(testDB.bar.insert({a: 1})); assert.eq(0, testDB.bar.count()); - adminUserAdmin.grantPrivilegesToRole('adminRole', [{resource: {db: '', collection: 'foo'}, - actions:['update']}]); - assert.writeOK(testDB.foo.update({ a: 1 }, { $inc: { a: 1 }})); + adminUserAdmin.grantPrivilegesToRole( + 'adminRole', [{resource: {db: '', collection: 'foo'}, actions: ['update']}]); + assert.writeOK(testDB.foo.update({a: 1}, {$inc: {a: 1}})); assert.eq(2, testDB.foo.findOne().a); - assert.writeOK(testDB.foo.update({ b: 1 }, { $inc: { b: 1 }}, true)); // upsert + assert.writeOK(testDB.foo.update({b: 1}, {$inc: {b: 1}}, true)); // upsert assert.eq(2, testDB.foo.count()); assert.eq(2, testDB.foo.findOne({b: {$exists: true}}).b); - hasAuthzError(testDB.foo.remove({ b: 2 })); + hasAuthzError(testDB.foo.remove({b: 2})); assert.eq(2, testDB.foo.count()); - adminUserAdmin.grantPrivilegesToRole('adminRole', [{resource: {db: '', collection: ''}, - actions:['remove']}]); - assert.writeOK(testDB.foo.remove({ b: 2 })); + adminUserAdmin.grantPrivilegesToRole( + 'adminRole', [{resource: {db: '', collection: ''}, actions: ['remove']}]); + assert.writeOK(testDB.foo.remove({b: 2})); assert.eq(1, testDB.foo.count()); - // Test revoking privileges - testUserAdmin.revokePrivilegesFromRole('testRole1', [{resource: {db: 'test', collection: 'foo'}, - actions:['insert']}]); - hasAuthzError(testDB.foo.insert({ a: 1 })); + testUserAdmin.revokePrivilegesFromRole( + 'testRole1', [{resource: {db: 'test', collection: 'foo'}, actions: ['insert']}]); + hasAuthzError(testDB.foo.insert({a: 1})); assert.eq(1, testDB.foo.count()); - assert.writeOK(testDB.foo.update({ a: 2 }, { $inc: { a: 1 }})); + assert.writeOK(testDB.foo.update({a: 2}, {$inc: {a: 1}})); assert.eq(3, testDB.foo.findOne({a: {$exists: true}}).a); - hasAuthzError(testDB.foo.update({ c: 1 }, { $inc: { c: 1 }}, true)); // upsert should fail + hasAuthzError(testDB.foo.update({c: 1}, {$inc: {c: 1}}, true)); // upsert should fail assert.eq(1, testDB.foo.count()); - // Test changeOwnPassword/changeOwnCustomData - assert.throws(function() { testDB.changeUserPassword('testUser', 'password'); }); - assert.throws(function() { testDB.updateUser('testUser', {customData: {zipCode: 10036}});}); + assert.throws(function() { + testDB.changeUserPassword('testUser', 'password'); + }); + assert.throws(function() { + testDB.updateUser('testUser', {customData: {zipCode: 10036}}); + }); assert.eq(null, testDB.getUser('testUser').customData); - testUserAdmin.grantPrivilegesToRole('testRole1', [{resource: {db: 'test', collection: ''}, - actions:['changeOwnPassword', - 'changeOwnCustomData']}]); + testUserAdmin.grantPrivilegesToRole( + 'testRole1', + [{ + resource: {db: 'test', collection: ''}, + actions: ['changeOwnPassword', 'changeOwnCustomData'] + }]); testDB.changeUserPassword('testUser', 'password'); assert(!testDB.auth('testUser', 'pwd')); assert(testDB.auth('testUser', 'password')); @@ -106,36 +112,42 @@ function runTest(conn) { assert.eq(10036, testDB.getUser('testUser').customData.zipCode); testUserAdmin.revokeRolesFromRole('testRole2', ['testRole1']); - assert.throws(function() { testDB.changeUserPassword('testUser', 'pwd'); }); - assert.throws(function() { testDB.foo.findOne();}); - assert.throws(function() { testDB.updateUser('testUser', {customData: {zipCode: 10028}});}); + assert.throws(function() { + testDB.changeUserPassword('testUser', 'pwd'); + }); + assert.throws(function() { + testDB.foo.findOne(); + }); + assert.throws(function() { + testDB.updateUser('testUser', {customData: {zipCode: 10028}}); + }); assert.eq(10036, testDB.getUser('testUser').customData.zipCode); // Test changeAnyPassword/changeAnyCustomData - testUserAdmin.grantPrivilegesToRole('testRole2', [{resource: {db: 'test', collection: ''}, - actions: ['changePassword', - 'changeCustomData']}]); + testUserAdmin.grantPrivilegesToRole('testRole2', + [{ + resource: {db: 'test', collection: ''}, + actions: ['changePassword', 'changeCustomData'] + }]); testDB.changeUserPassword('testUser', 'pwd'); assert(!testDB.auth('testUser', 'password')); assert(testDB.auth('testUser', 'pwd')); testDB.updateUser('testUser', {customData: {zipCode: 10028}}); assert.eq(10028, testDB.getUser('testUser').customData.zipCode); - // Test privileges on the cluster resource - assert.commandFailed(testDB.runCommand({serverStatus:1})); - adminUserAdmin.grantPrivilegesToRole('adminRole', [{resource: {cluster: true}, - actions:['serverStatus']}]); + assert.commandFailed(testDB.runCommand({serverStatus: 1})); + adminUserAdmin.grantPrivilegesToRole( + 'adminRole', [{resource: {cluster: true}, actions: ['serverStatus']}]); assert.commandWorked(testDB.serverStatus()); - } jsTest.log('Test standalone'); -var conn = MongoRunner.runMongod({ auth: '' }); +var conn = MongoRunner.runMongod({auth: ''}); runTest(conn); MongoRunner.stopMongod(conn.port); jsTest.log('Test sharding'); -var st = new ShardingTest({ shards: 2, config: 3, keyFile: 'jstests/libs/key1' }); +var st = new ShardingTest({shards: 2, config: 3, keyFile: 'jstests/libs/key1'}); runTest(st.s); st.stop(); diff --git a/jstests/auth/user_defined_roles_on_secondaries.js b/jstests/auth/user_defined_roles_on_secondaries.js index 4ca2d14f651..959b76a3cae 100644 --- a/jstests/auth/user_defined_roles_on_secondaries.js +++ b/jstests/auth/user_defined_roles_on_secondaries.js @@ -36,193 +36,177 @@ (function() { -var name = 'user_defined_roles_on_secondaries'; -var m0, m1; - -function assertListContainsRole(list, role, msg) { - var i; - for (i = 0; i < list.length; ++i) { - if (list[i].role == role.role && list[i].db == role.db) - return; + var name = 'user_defined_roles_on_secondaries'; + var m0, m1; + + function assertListContainsRole(list, role, msg) { + var i; + for (i = 0; i < list.length; ++i) { + if (list[i].role == role.role && list[i].db == role.db) + return; + } + doassert("Could not find value " + tojson(val) + " in " + + tojson(list)(msg ? ": " + msg : "")); } - doassert("Could not find value " + tojson(val) + " in " + tojson(list) - (msg ? ": " + msg : "")); -} - -// -// Create a 1-node replicaset and add two roles, inheriting the built-in read role on db1. -// -// read -// / \ + + // + // Create a 1-node replicaset and add two roles, inheriting the built-in read role on db1. + // + // read + // / \ // r1 r2 -// -var rstest = new ReplSetTest({ - name: name, - nodes: 1, - nodeOptions: {} -}); - -rstest.startSet(); -rstest.initiate(); - -m0 = rstest.nodes[0]; - -m0.getDB("db1").createRole({ - role: "r1", - roles: [ "read" ], - privileges: [ - { resource: { db: "db1", collection: "system.users" }, actions: [ "find" ] } - ] -}); - -m0.getDB("db1").createRole({ - role: "r2", - roles: [ "read" ], - privileges: [ - { resource: { db: "db1", collection: "log" }, actions: [ "insert" ] } - ] -}); - -// -// Add a second node to the set, and add a third role, dependent on the first two. -// -// read -// / \ + // + var rstest = new ReplSetTest({name: name, nodes: 1, nodeOptions: {}}); + + rstest.startSet(); + rstest.initiate(); + + m0 = rstest.nodes[0]; + + m0.getDB("db1").createRole({ + role: "r1", + roles: ["read"], + privileges: [{resource: {db: "db1", collection: "system.users"}, actions: ["find"]}] + }); + + m0.getDB("db1").createRole({ + role: "r2", + roles: ["read"], + privileges: [{resource: {db: "db1", collection: "log"}, actions: ["insert"]}] + }); + + // + // Add a second node to the set, and add a third role, dependent on the first two. + // + // read + // / \ // r1 r2 -// \ / -// r3 -// -rstest.add(); -rstest.reInitiate(); - -rstest.getPrimary().getDB("db1").createRole({ - role: "r3", - roles: [ "r1", "r2" ], - privileges: [ - { resource: { db: "db1", collection: "log" }, actions: [ "update" ] } - ] -}, { w: 2 }); - -// Verify that both members of the set see the same role graph. -rstest.nodes.forEach(function (node) { - var role = node.getDB("db1").getRole("r3"); - assert.eq(2, role.roles.length, node); - assertListContainsRole(role.roles, {role: "r1", db: "db1"}, node); - assertListContainsRole(role.roles, {role: "r2", db: "db1"}, node); - assert.eq(3, role.inheritedRoles.length, node); - assertListContainsRole(role.inheritedRoles, {role: "r1", db: "db1"}, node); - assertListContainsRole(role.inheritedRoles, {role: "r2", db: "db1"}, node); - assertListContainsRole(role.inheritedRoles, {role: "read", db: "db1"}, node); -}); - -// Verify that updating roles propagates. -rstest.getPrimary().getDB("db1").revokeRolesFromRole("r1", [ "read" ], { w: 2 }); -rstest.getPrimary().getDB("db1").grantRolesToRole("r1", [ "dbAdmin" ], { w: 2 }); -rstest.nodes.forEach(function (node) { - var role = node.getDB("db1").getRole("r1"); - assert.eq(1, role.roles.length, node); - assertListContainsRole(role.roles, { role: "dbAdmin", db: "db1" }); -}); - -// Verify that dropping roles propagates. -rstest.getPrimary().getDB("db1").dropRole("r2", { w: 2}); -rstest.nodes.forEach(function (node) { - assert.eq(null, node.getDB("db1").getRole("r2")); - var role = node.getDB("db1").getRole("r3"); - assert.eq(1, role.roles.length, node); - assertListContainsRole(role.roles, {role: "r1", db: "db1"}, node); - assert.eq(2, role.inheritedRoles.length, node); - assertListContainsRole(role.inheritedRoles, {role: "r1", db: "db1"}, node); - assertListContainsRole(role.inheritedRoles, {role: "dbAdmin", db: "db1"}, node); -}); - -// Verify that dropping the admin database propagates. -assert.commandWorked(rstest.getPrimary().getDB("admin").dropDatabase()); -assert.commandWorked(rstest.getPrimary().getDB("admin").getLastErrorObj(2)); -rstest.nodes.forEach(function (node) { - var roles = node.getDB("db1").getRoles(); - assert.eq(0, roles.length, node); -}); - -// Verify that applyOps commands propagate. -// NOTE: This section of the test depends on the oplog and roles schemas. -assert.commandWorked(rstest.getPrimary().getDB("admin").runCommand({ applyOps: [ - { - op: "c", - ns: "admin.$cmd", - o: { create: "system.roles" } - }, - { - op: "i", - ns: "admin.system.roles", - o: { - _id: "db1.s1", - role: "s1", - db: "db1", - roles: [ { role: "read", db: "db1" } ], - privileges: [ { resource: { db: "db1", collection: "system.users" }, - actions: [ "find" ] } ] } - }, - { - op: "i", - ns: "admin.system.roles", - o: { - _id: "db1.s2", - role: "s2", - db: "db1", - roles: [ { role: "read", db: "db1" } ], - privileges: [ { resource: { db: "db1", collection: "log" }, - actions: [ "insert" ] } ] } - }, - { - op: "c", - ns: "admin.$cmd", - o: { dropDatabase: 1 } - }, - { - op: "c", - ns: "admin.$cmd", - o: { create: "system.roles" } - }, - { - op: "i", - ns: "admin.system.roles", - o: { - _id: "db1.t1", - role: "t1", - db: "db1", - roles: [ { role: "read", db: "db1" } ], - privileges: [ { resource: { db: "db1", collection: "system.users" }, - actions: [ "find" ] } ] } - }, - { - op: "i", - ns: "admin.system.roles", - o: { - _id: "db1.t2", - role: "t2", - db: "db1", - roles: [ ], - privileges: [ { resource: { db: "db1", collection: "log" }, - actions: [ "insert" ] } ] } - }, - { - op: "u", - ns: "admin.system.roles", - o: { $set: { roles: [ { role: "readWrite", db: "db1" } ] } }, - o2: { _id: "db1.t2" } - } -] })); - -assert.commandWorked(rstest.getPrimary().getDB("admin").getLastErrorObj(2)); -rstest.nodes.forEach(function (node) { - var role = node.getDB("db1").getRole("t1"); - assert.eq(1, role.roles.length, node); - assertListContainsRole(role.roles, {role: "read", db: "db1"}, node); - - var role = node.getDB("db1").getRole("t2"); - assert.eq(1, role.roles.length, node); - assertListContainsRole(role.roles, {role: "readWrite", db: "db1"}, node); -}); + // \ / + // r3 + // + rstest.add(); + rstest.reInitiate(); + + rstest.getPrimary().getDB("db1").createRole( + { + role: "r3", + roles: ["r1", "r2"], + privileges: [{resource: {db: "db1", collection: "log"}, actions: ["update"]}] + }, + {w: 2}); + + // Verify that both members of the set see the same role graph. + rstest.nodes.forEach(function(node) { + var role = node.getDB("db1").getRole("r3"); + assert.eq(2, role.roles.length, node); + assertListContainsRole(role.roles, {role: "r1", db: "db1"}, node); + assertListContainsRole(role.roles, {role: "r2", db: "db1"}, node); + assert.eq(3, role.inheritedRoles.length, node); + assertListContainsRole(role.inheritedRoles, {role: "r1", db: "db1"}, node); + assertListContainsRole(role.inheritedRoles, {role: "r2", db: "db1"}, node); + assertListContainsRole(role.inheritedRoles, {role: "read", db: "db1"}, node); + }); + + // Verify that updating roles propagates. + rstest.getPrimary().getDB("db1").revokeRolesFromRole("r1", ["read"], {w: 2}); + rstest.getPrimary().getDB("db1").grantRolesToRole("r1", ["dbAdmin"], {w: 2}); + rstest.nodes.forEach(function(node) { + var role = node.getDB("db1").getRole("r1"); + assert.eq(1, role.roles.length, node); + assertListContainsRole(role.roles, {role: "dbAdmin", db: "db1"}); + }); + + // Verify that dropping roles propagates. + rstest.getPrimary().getDB("db1").dropRole("r2", {w: 2}); + rstest.nodes.forEach(function(node) { + assert.eq(null, node.getDB("db1").getRole("r2")); + var role = node.getDB("db1").getRole("r3"); + assert.eq(1, role.roles.length, node); + assertListContainsRole(role.roles, {role: "r1", db: "db1"}, node); + assert.eq(2, role.inheritedRoles.length, node); + assertListContainsRole(role.inheritedRoles, {role: "r1", db: "db1"}, node); + assertListContainsRole(role.inheritedRoles, {role: "dbAdmin", db: "db1"}, node); + }); + + // Verify that dropping the admin database propagates. + assert.commandWorked(rstest.getPrimary().getDB("admin").dropDatabase()); + assert.commandWorked(rstest.getPrimary().getDB("admin").getLastErrorObj(2)); + rstest.nodes.forEach(function(node) { + var roles = node.getDB("db1").getRoles(); + assert.eq(0, roles.length, node); + }); + + // Verify that applyOps commands propagate. + // NOTE: This section of the test depends on the oplog and roles schemas. + assert.commandWorked(rstest.getPrimary().getDB("admin").runCommand({ + applyOps: [ + {op: "c", ns: "admin.$cmd", o: {create: "system.roles"}}, + { + op: "i", + ns: "admin.system.roles", + o: { + _id: "db1.s1", + role: "s1", + db: "db1", + roles: [{role: "read", db: "db1"}], + privileges: + [{resource: {db: "db1", collection: "system.users"}, actions: ["find"]}] + } + }, + { + op: "i", + ns: "admin.system.roles", + o: { + _id: "db1.s2", + role: "s2", + db: "db1", + roles: [{role: "read", db: "db1"}], + privileges: [{resource: {db: "db1", collection: "log"}, actions: ["insert"]}] + } + }, + {op: "c", ns: "admin.$cmd", o: {dropDatabase: 1}}, + {op: "c", ns: "admin.$cmd", o: {create: "system.roles"}}, + { + op: "i", + ns: "admin.system.roles", + o: { + _id: "db1.t1", + role: "t1", + db: "db1", + roles: [{role: "read", db: "db1"}], + privileges: + [{resource: {db: "db1", collection: "system.users"}, actions: ["find"]}] + } + }, + { + op: "i", + ns: "admin.system.roles", + o: { + _id: "db1.t2", + role: "t2", + db: "db1", + roles: [], + privileges: [{resource: {db: "db1", collection: "log"}, actions: ["insert"]}] + } + }, + { + op: "u", + ns: "admin.system.roles", + o: {$set: {roles: [{role: "readWrite", db: "db1"}]}}, + o2: {_id: "db1.t2"} + } + ] + })); + + assert.commandWorked(rstest.getPrimary().getDB("admin").getLastErrorObj(2)); + rstest.nodes.forEach(function(node) { + var role = node.getDB("db1").getRole("t1"); + assert.eq(1, role.roles.length, node); + assertListContainsRole(role.roles, {role: "read", db: "db1"}, node); + + var role = node.getDB("db1").getRole("t2"); + assert.eq(1, role.roles.length, node); + assertListContainsRole(role.roles, {role: "readWrite", db: "db1"}, node); + }); }()); diff --git a/jstests/auth/user_management_commands.js b/jstests/auth/user_management_commands.js index 1a777a00e6b..e835aa4b348 100644 --- a/jstests/auth/user_management_commands.js +++ b/jstests/auth/user_management_commands.js @@ -12,23 +12,27 @@ function runTest(conn) { conn.getDB('admin').createUser({user: 'admin', pwd: 'pwd', roles: ['root']}); conn.getDB('admin').auth('admin', 'pwd'); - conn.getDB('admin').createUser({user: 'userAdmin', - pwd: 'pwd', - roles: ['userAdminAnyDatabase'], - customData: {userAdmin: true}}); + conn.getDB('admin').createUser({ + user: 'userAdmin', + pwd: 'pwd', + roles: ['userAdminAnyDatabase'], + customData: {userAdmin: true} + }); conn.getDB('admin').logout(); var userAdminConn = new Mongo(conn.host); userAdminConn.getDB('admin').auth('userAdmin', 'pwd'); var testUserAdmin = userAdminConn.getDB('test'); - testUserAdmin.createRole({role: 'testRole', - roles:[], - privileges:[{resource: {db: 'test', collection: ''}, - actions: ['viewRole']}],}); - userAdminConn.getDB('admin').createRole({role: 'adminRole', - roles:[], - privileges:[{resource: {cluster: true}, - actions: ['connPoolSync']}]}); + testUserAdmin.createRole({ + role: 'testRole', + roles: [], + privileges: [{resource: {db: 'test', collection: ''}, actions: ['viewRole']}], + }); + userAdminConn.getDB('admin').createRole({ + role: 'adminRole', + roles: [], + privileges: [{resource: {cluster: true}, actions: ['connPoolSync']}] + }); var db = conn.getDB('test'); @@ -40,182 +44,207 @@ function runTest(conn) { // various users and test that their access control is correct. (function testCreateUser() { - jsTestLog("Testing createUser"); - - testUserAdmin.createUser({user: "spencer", - pwd: "pwd", - customData: {zipCode: 10028}, - roles: ['readWrite', - 'testRole', - {role: 'adminRole', db: 'admin'}]}); - testUserAdmin.createUser({user: "andy", pwd: "pwd", roles: []}); - - var user = testUserAdmin.getUser('spencer'); - assert.eq(10028, user.customData.zipCode); - assert(db.auth('spencer', 'pwd')); - assert.writeOK(db.foo.insert({ a: 1 })); - assert.eq(1, db.foo.findOne().a); - assert.doesNotThrow(function() {db.getRole('testRole');}); - assert.commandWorked(db.adminCommand('connPoolSync')); - - db.logout(); - assert(db.auth('andy', 'pwd')); - hasAuthzError(db.foo.insert({ a: 1 })); - assert.throws(function() { db.foo.findOne();}); - assert.throws(function() {db.getRole('testRole');}); - })(); + jsTestLog("Testing createUser"); + + testUserAdmin.createUser({ + user: "spencer", + pwd: "pwd", + customData: {zipCode: 10028}, + roles: ['readWrite', 'testRole', {role: 'adminRole', db: 'admin'}] + }); + testUserAdmin.createUser({user: "andy", pwd: "pwd", roles: []}); + + var user = testUserAdmin.getUser('spencer'); + assert.eq(10028, user.customData.zipCode); + assert(db.auth('spencer', 'pwd')); + assert.writeOK(db.foo.insert({a: 1})); + assert.eq(1, db.foo.findOne().a); + assert.doesNotThrow(function() { + db.getRole('testRole'); + }); + assert.commandWorked(db.adminCommand('connPoolSync')); + + db.logout(); + assert(db.auth('andy', 'pwd')); + hasAuthzError(db.foo.insert({a: 1})); + assert.throws(function() { + db.foo.findOne(); + }); + assert.throws(function() { + db.getRole('testRole'); + }); + })(); (function testUpdateUser() { - jsTestLog("Testing updateUser"); - - testUserAdmin.updateUser('spencer', {pwd: 'password', customData: {}}); - var user = testUserAdmin.getUser('spencer'); - assert.eq(null, user.customData.zipCode); - assert(!db.auth('spencer', 'pwd')); - assert(db.auth('spencer', 'password')); - - testUserAdmin.updateUser('spencer', {customData: {zipCode: 10036}, - roles: ["read", "testRole"]}); - var user = testUserAdmin.getUser('spencer'); - assert.eq(10036, user.customData.zipCode); - hasAuthzError(db.foo.insert({ a: 1 })); - assert.eq(1, db.foo.findOne().a); - assert.eq(1, db.foo.count()); - assert.doesNotThrow(function() {db.getRole('testRole');}); - assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); - - testUserAdmin.updateUser('spencer', {roles: ["readWrite", - {role: 'adminRole', db:'admin'}]}); - assert.writeOK(db.foo.update({}, { $inc: { a: 1 }})); - assert.eq(2, db.foo.findOne().a); - assert.eq(1, db.foo.count()); - assert.throws(function() {db.getRole('testRole');}); - assert.commandWorked(db.adminCommand('connPoolSync')); - })(); + jsTestLog("Testing updateUser"); + + testUserAdmin.updateUser('spencer', {pwd: 'password', customData: {}}); + var user = testUserAdmin.getUser('spencer'); + assert.eq(null, user.customData.zipCode); + assert(!db.auth('spencer', 'pwd')); + assert(db.auth('spencer', 'password')); + + testUserAdmin.updateUser('spencer', + {customData: {zipCode: 10036}, roles: ["read", "testRole"]}); + var user = testUserAdmin.getUser('spencer'); + assert.eq(10036, user.customData.zipCode); + hasAuthzError(db.foo.insert({a: 1})); + assert.eq(1, db.foo.findOne().a); + assert.eq(1, db.foo.count()); + assert.doesNotThrow(function() { + db.getRole('testRole'); + }); + assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); + + testUserAdmin.updateUser('spencer', + {roles: ["readWrite", {role: 'adminRole', db: 'admin'}]}); + assert.writeOK(db.foo.update({}, {$inc: {a: 1}})); + assert.eq(2, db.foo.findOne().a); + assert.eq(1, db.foo.count()); + assert.throws(function() { + db.getRole('testRole'); + }); + assert.commandWorked(db.adminCommand('connPoolSync')); + })(); (function testGrantRolesToUser() { - jsTestLog("Testing grantRolesToUser"); + jsTestLog("Testing grantRolesToUser"); - assert.commandFailedWithCode(db.runCommand({collMod: 'foo', usePowerOf2Sizes: true}), - authzErrorCode); + assert.commandFailedWithCode(db.runCommand({collMod: 'foo', usePowerOf2Sizes: true}), + authzErrorCode); - testUserAdmin.grantRolesToUser('spencer', - ['readWrite', + testUserAdmin.grantRolesToUser('spencer', + [ + 'readWrite', 'dbAdmin', {role: 'readWrite', db: 'test'}, {role: 'testRole', db: 'test'}, - 'readWrite']); - - assert.commandWorked(db.runCommand({collMod: 'foo', usePowerOf2Sizes: true})); - assert.writeOK(db.foo.update({}, { $inc: { a: 1 }})); - assert.eq(3, db.foo.findOne().a); - assert.eq(1, db.foo.count()); - assert.doesNotThrow(function() {db.getRole('testRole');}); - assert.commandWorked(db.adminCommand('connPoolSync')); - })(); + 'readWrite' + ]); + + assert.commandWorked(db.runCommand({collMod: 'foo', usePowerOf2Sizes: true})); + assert.writeOK(db.foo.update({}, {$inc: {a: 1}})); + assert.eq(3, db.foo.findOne().a); + assert.eq(1, db.foo.count()); + assert.doesNotThrow(function() { + db.getRole('testRole'); + }); + assert.commandWorked(db.adminCommand('connPoolSync')); + })(); (function testRevokeRolesFromUser() { - jsTestLog("Testing revokeRolesFromUser"); - - testUserAdmin.revokeRolesFromUser('spencer', - ['readWrite', - {role: 'dbAdmin', db: 'test2'}, // role user doesnt have - "testRole"]); - - assert.commandWorked(db.runCommand({collMod: 'foo', usePowerOf2Sizes: true})); - hasAuthzError(db.foo.update({}, { $inc: { a: 1 }})); - assert.throws(function() { db.foo.findOne();}); - assert.throws(function() {db.getRole('testRole');}); - assert.commandWorked(db.adminCommand('connPoolSync')); - - - testUserAdmin.revokeRolesFromUser('spencer', [{role: 'adminRole', db: 'admin'}]); - - hasAuthzError(db.foo.update({}, { $inc: { a: 1 }})); - assert.throws(function() { db.foo.findOne();}); - assert.throws(function() {db.getRole('testRole');}); - assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); - - })(); + jsTestLog("Testing revokeRolesFromUser"); + + testUserAdmin.revokeRolesFromUser( + 'spencer', + [ + 'readWrite', + {role: 'dbAdmin', db: 'test2'}, // role user doesnt have + "testRole" + ]); + + assert.commandWorked(db.runCommand({collMod: 'foo', usePowerOf2Sizes: true})); + hasAuthzError(db.foo.update({}, {$inc: {a: 1}})); + assert.throws(function() { + db.foo.findOne(); + }); + assert.throws(function() { + db.getRole('testRole'); + }); + assert.commandWorked(db.adminCommand('connPoolSync')); + + testUserAdmin.revokeRolesFromUser('spencer', [{role: 'adminRole', db: 'admin'}]); + + hasAuthzError(db.foo.update({}, {$inc: {a: 1}})); + assert.throws(function() { + db.foo.findOne(); + }); + assert.throws(function() { + db.getRole('testRole'); + }); + assert.commandFailedWithCode(db.adminCommand('connPoolSync'), authzErrorCode); + + })(); (function testUsersInfo() { - jsTestLog("Testing usersInfo"); - - var res = testUserAdmin.runCommand({usersInfo: 'spencer'}); - printjson(res); - assert.eq(1, res.users.length); - assert.eq(10036, res.users[0].customData.zipCode); - - res = testUserAdmin.runCommand({usersInfo: {user: 'spencer', db: 'test'}}); - assert.eq(1, res.users.length); - assert.eq(10036, res.users[0].customData.zipCode); - - res = testUserAdmin.runCommand({usersInfo: ['spencer', {user: 'userAdmin', db: 'admin'}]}); - printjson(res); - assert.eq(2, res.users.length); - if (res.users[0].user == "spencer") { - assert.eq(10036, res.users[0].customData.zipCode); - assert(res.users[1].customData.userAdmin); - } else if (res.users[0].user == "userAdmin") { - assert.eq(10036, res.users[1].customData.zipCode); - assert(res.users[0].customData.userAdmin); - } else { - doassert("Expected user names returned by usersInfo to be either 'userAdmin' or 'spencer', " - + "but got: " + res.users[0].user); - } - - - res = testUserAdmin.runCommand({usersInfo: 1}); - assert.eq(2, res.users.length); - if (res.users[0].user == "spencer") { - assert.eq("andy", res.users[1].user); - assert.eq(10036, res.users[0].customData.zipCode); - assert(!res.users[1].customData); - } else if (res.users[0].user == "andy") { - assert.eq("spencer", res.users[1].user); - assert(!res.users[0].customData); - assert.eq(10036, res.users[1].customData.zipCode); - } else { - doassert("Expected user names returned by usersInfo to be either 'andy' or 'spencer', " - + "but got: " + res.users[0].user); - } - - })(); + jsTestLog("Testing usersInfo"); + + var res = testUserAdmin.runCommand({usersInfo: 'spencer'}); + printjson(res); + assert.eq(1, res.users.length); + assert.eq(10036, res.users[0].customData.zipCode); + + res = testUserAdmin.runCommand({usersInfo: {user: 'spencer', db: 'test'}}); + assert.eq(1, res.users.length); + assert.eq(10036, res.users[0].customData.zipCode); + + res = testUserAdmin.runCommand({usersInfo: ['spencer', {user: 'userAdmin', db: 'admin'}]}); + printjson(res); + assert.eq(2, res.users.length); + if (res.users[0].user == "spencer") { + assert.eq(10036, res.users[0].customData.zipCode); + assert(res.users[1].customData.userAdmin); + } else if (res.users[0].user == "userAdmin") { + assert.eq(10036, res.users[1].customData.zipCode); + assert(res.users[0].customData.userAdmin); + } else { + doassert( + "Expected user names returned by usersInfo to be either 'userAdmin' or 'spencer', " + + "but got: " + res.users[0].user); + } + + res = testUserAdmin.runCommand({usersInfo: 1}); + assert.eq(2, res.users.length); + if (res.users[0].user == "spencer") { + assert.eq("andy", res.users[1].user); + assert.eq(10036, res.users[0].customData.zipCode); + assert(!res.users[1].customData); + } else if (res.users[0].user == "andy") { + assert.eq("spencer", res.users[1].user); + assert(!res.users[0].customData); + assert.eq(10036, res.users[1].customData.zipCode); + } else { + doassert( + "Expected user names returned by usersInfo to be either 'andy' or 'spencer', " + + "but got: " + res.users[0].user); + } + + })(); (function testDropUser() { - jsTestLog("Testing dropUser"); + jsTestLog("Testing dropUser"); - assert(db.auth('spencer', 'password')); - assert(db.auth('andy', 'pwd')); + assert(db.auth('spencer', 'password')); + assert(db.auth('andy', 'pwd')); - assert.commandWorked(testUserAdmin.runCommand({dropUser: 'spencer'})); + assert.commandWorked(testUserAdmin.runCommand({dropUser: 'spencer'})); - assert(!db.auth('spencer', 'password')); - assert(db.auth('andy', 'pwd')); + assert(!db.auth('spencer', 'password')); + assert(db.auth('andy', 'pwd')); - assert.eq(1, testUserAdmin.getUsers().length); - })(); + assert.eq(1, testUserAdmin.getUsers().length); + })(); (function testDropAllUsersFromDatabase() { - jsTestLog("Testing dropAllUsersFromDatabase"); + jsTestLog("Testing dropAllUsersFromDatabase"); - assert.eq(1, testUserAdmin.getUsers().length); - assert(db.auth('andy', 'pwd')); + assert.eq(1, testUserAdmin.getUsers().length); + assert(db.auth('andy', 'pwd')); - assert.commandWorked(testUserAdmin.runCommand({dropAllUsersFromDatabase: 1})); + assert.commandWorked(testUserAdmin.runCommand({dropAllUsersFromDatabase: 1})); - assert(!db.auth('andy', 'pwd')); - assert.eq(0, testUserAdmin.getUsers().length); - })(); + assert(!db.auth('andy', 'pwd')); + assert.eq(0, testUserAdmin.getUsers().length); + })(); } jsTest.log('Test standalone'); -var conn = MongoRunner.runMongod({ auth: '' }); -conn.getDB('admin').runCommand({setParameter:1, newCollectionsUsePowerOf2Sizes: false}); +var conn = MongoRunner.runMongod({auth: ''}); +conn.getDB('admin').runCommand({setParameter: 1, newCollectionsUsePowerOf2Sizes: false}); runTest(conn); MongoRunner.stopMongod(conn.port); jsTest.log('Test sharding'); -var st = new ShardingTest({ shards: 2, config: 3, keyFile: 'jstests/libs/key1' }); +var st = new ShardingTest({shards: 2, config: 3, keyFile: 'jstests/libs/key1'}); runTest(st.s); st.stop(); diff --git a/jstests/auth/user_management_commands_edge_cases.js b/jstests/auth/user_management_commands_edge_cases.js index b8f11505c58..ab42714fb9a 100644 --- a/jstests/auth/user_management_commands_edge_cases.js +++ b/jstests/auth/user_management_commands_edge_cases.js @@ -4,289 +4,284 @@ */ function runTest(conn) { - var db = conn.getDB('test'); var admin = conn.getDB('admin'); admin.createUser({user: 'userAdmin', pwd: 'pwd', roles: ['userAdminAnyDatabase']}); admin.auth('userAdmin', 'pwd'); (function testCreateUser() { - jsTestLog("Testing createUser"); - - db.createUser({user: 'user1', pwd: 'pwd', roles: []}); - - // Try to create duplicate user - assert.throws(function() { - db.createUser({user: 'user1', pwd: 'pwd', roles: ['read']}); - }); - assert.eq(0, db.getUser('user1').roles.length); - - // Try to create user with role that doesn't exist - assert.throws(function() { - db.createUser({user: 'user2', pwd: 'pwd', roles: ['fakeRole']}); - }); - - // Try to create user with invalid arguments - assert.throws(function() { - db.createUser({user: '', pwd: 'pwd', roles: ['read']}); - }); - assert.throws(function() { - db.createUser({user: ['user2'], pwd: 'pwd', roles: ['read']}); - }); - assert.throws(function() { - db.createUser({user: 'user2', pwd: '', roles: ['read']}); - }); - assert.throws(function() { - db.createUser({user: 'user2', pwd: ['pwd'], roles: ['read']}); - }); - assert.throws(function() { - db.createUser({user: 'user2', pwd: 'pwd', roles: ['']}); - }); - assert.throws(function() { - db.createUser({user: 'user2', pwd: 'pwd', roles: [{}]}); - }); - assert.throws(function() { - db.createUser({user: 'user2', pwd: 'pwd', roles: [1]}); - }); - assert.throws(function() { - db.createUser({user: 'user2', pwd: 'pwd', roles: [{role: 'read'}]}); - }); - assert.throws(function() { - db.createUser({user: 'user2', pwd: 'pwd', roles: [{db: 'test'}]}); - }); - assert.throws(function() { - db.createUser({user: 'user2', pwd: 'pwd', roles: [{role: 'read', - db:''}]}); - }); - assert.throws(function() { - db.createUser({user: 'user2', pwd: 'pwd', roles: [{role: '', - db: 'test'}]}); - }); - assert.throws(function() { - db.createUser({user: 'null\u0000char', pwd: 'pwd', roles: []}); - }); - assert.throws(function() { - db.createUser({user: 'null\0char', pwd: 'pwd', roles: []}); - }); - // Regression test for SERVER-17125 - assert.throws(function() { - db.getSiblingDB('$external').createUser({user: '', roles: []}); - }); - - assert.eq(1, db.getUsers().length); - })(); + jsTestLog("Testing createUser"); + + db.createUser({user: 'user1', pwd: 'pwd', roles: []}); + + // Try to create duplicate user + assert.throws(function() { + db.createUser({user: 'user1', pwd: 'pwd', roles: ['read']}); + }); + assert.eq(0, db.getUser('user1').roles.length); + + // Try to create user with role that doesn't exist + assert.throws(function() { + db.createUser({user: 'user2', pwd: 'pwd', roles: ['fakeRole']}); + }); + + // Try to create user with invalid arguments + assert.throws(function() { + db.createUser({user: '', pwd: 'pwd', roles: ['read']}); + }); + assert.throws(function() { + db.createUser({user: ['user2'], pwd: 'pwd', roles: ['read']}); + }); + assert.throws(function() { + db.createUser({user: 'user2', pwd: '', roles: ['read']}); + }); + assert.throws(function() { + db.createUser({user: 'user2', pwd: ['pwd'], roles: ['read']}); + }); + assert.throws(function() { + db.createUser({user: 'user2', pwd: 'pwd', roles: ['']}); + }); + assert.throws(function() { + db.createUser({user: 'user2', pwd: 'pwd', roles: [{}]}); + }); + assert.throws(function() { + db.createUser({user: 'user2', pwd: 'pwd', roles: [1]}); + }); + assert.throws(function() { + db.createUser({user: 'user2', pwd: 'pwd', roles: [{role: 'read'}]}); + }); + assert.throws(function() { + db.createUser({user: 'user2', pwd: 'pwd', roles: [{db: 'test'}]}); + }); + assert.throws(function() { + db.createUser({user: 'user2', pwd: 'pwd', roles: [{role: 'read', db: ''}]}); + }); + assert.throws(function() { + db.createUser({user: 'user2', pwd: 'pwd', roles: [{role: '', db: 'test'}]}); + }); + assert.throws(function() { + db.createUser({user: 'null\u0000char', pwd: 'pwd', roles: []}); + }); + assert.throws(function() { + db.createUser({user: 'null\0char', pwd: 'pwd', roles: []}); + }); + // Regression test for SERVER-17125 + assert.throws(function() { + db.getSiblingDB('$external').createUser({user: '', roles: []}); + }); + + assert.eq(1, db.getUsers().length); + })(); (function testUpdateUser() { - jsTestLog("Testing updateUser"); - - // Must update something - assert.throws(function() { - db.updateUser('user1', {}); - }); - - // Try to grant role that doesn't exist - assert.throws(function() { - db.updateUser('user1', {roles: ['fakeRole']}); - }); - - // Try to update user that doesn't exist - assert.throws(function() { - db.updateUser('fakeUser', {roles: ['read']}); - }); - - // Try to update user with invalid password - assert.throws(function() { - db.updateUser('user1', {pwd: ''}); - }); - assert.throws(function() { - db.updateUser('user1', {pwd: 5}); - }); - assert.throws(function() { - db.updateUser('user1', {pwd: ['a']}); - }); - - - // Try to update user with invalid customData - assert.throws(function() { - db.updateUser('user1', {customData: 1}); - }); - assert.throws(function() { - db.updateUser('user1', {customData: ""}); - }); - - - // Try to update with invalid "roles" argument - assert.throws(function() { - db.updateUser('user1', {roles: 'read'}); - }); - assert.throws(function() { - db.updateUser('user1', {roles: ['']}); - }); - assert.throws(function() { - db.updateUser('user1', {roles: [{}]}); - }); - assert.throws(function() { - db.updateUser('user1', {roles: [1]}); - }); - assert.throws(function() { - db.updateUser('user1', {roles: [{role: 'read'}]}); - }); - assert.throws(function() { - db.updateUser('user1', {roles: [{db: 'test'}]}); - }); - assert.throws(function() { - db.updateUser('user1', {roles: [{role: '', db:'test'}]}); - }); - assert.throws(function() { - db.updateUser('user1', {roles: [{role: 'read', db: ''}]}); - }); - - assert.eq(0, db.getUser('user1').roles.length); - })(); + jsTestLog("Testing updateUser"); + + // Must update something + assert.throws(function() { + db.updateUser('user1', {}); + }); + + // Try to grant role that doesn't exist + assert.throws(function() { + db.updateUser('user1', {roles: ['fakeRole']}); + }); + + // Try to update user that doesn't exist + assert.throws(function() { + db.updateUser('fakeUser', {roles: ['read']}); + }); + + // Try to update user with invalid password + assert.throws(function() { + db.updateUser('user1', {pwd: ''}); + }); + assert.throws(function() { + db.updateUser('user1', {pwd: 5}); + }); + assert.throws(function() { + db.updateUser('user1', {pwd: ['a']}); + }); + + // Try to update user with invalid customData + assert.throws(function() { + db.updateUser('user1', {customData: 1}); + }); + assert.throws(function() { + db.updateUser('user1', {customData: ""}); + }); + + // Try to update with invalid "roles" argument + assert.throws(function() { + db.updateUser('user1', {roles: 'read'}); + }); + assert.throws(function() { + db.updateUser('user1', {roles: ['']}); + }); + assert.throws(function() { + db.updateUser('user1', {roles: [{}]}); + }); + assert.throws(function() { + db.updateUser('user1', {roles: [1]}); + }); + assert.throws(function() { + db.updateUser('user1', {roles: [{role: 'read'}]}); + }); + assert.throws(function() { + db.updateUser('user1', {roles: [{db: 'test'}]}); + }); + assert.throws(function() { + db.updateUser('user1', {roles: [{role: '', db: 'test'}]}); + }); + assert.throws(function() { + db.updateUser('user1', {roles: [{role: 'read', db: ''}]}); + }); + + assert.eq(0, db.getUser('user1').roles.length); + })(); (function testGrantRolesToUser() { - jsTestLog("Testing grantRolesToUser"); - - // Try to grant role that doesn't exist - assert.throws(function() { - db.grantRolesToUser('user1', {roles: ['fakeRole']}); - }); - - // Try to grant to user that doesn't exist - assert.throws(function() { - db.grantRolesToUser('fakeUser', {roles: ['read']}); - }); - - // Must grant something - assert.throws(function() { - db.grantRolesToUser('user1', []); - }); - - // Try to grant with invalid arguments - assert.throws(function() { - db.grantRolesToUser('user1', 1); - }); - assert.throws(function() { - db.grantRolesToUser('user1', [{}]); - }); - assert.throws(function() { - db.grantRolesToUser('user1', [1]); - }); - assert.throws(function() { - db.grantRolesToUser('user1', 'read'); - }); - assert.throws(function() { - db.grantRolesToUser('user1', [{role: 'read'}]); - }); - assert.throws(function() { - db.grantRolesToUser('user1', [{db: 'test'}]); - }); - assert.throws(function() { - db.grantRolesToUser('user1', [{role: 'read', db: ''}]); - }); - assert.throws(function() { - db.grantRolesToUser('user1', [{role: '', db: 'test'}]); - }); - - assert.eq(0, db.getUser('user1').roles.length); - assert.eq(null, db.getUser('user1').customData); - // Make sure password didn't change - assert(new Mongo(db.getMongo().host).getDB(db.getName()).auth('user1', 'pwd')); - })(); + jsTestLog("Testing grantRolesToUser"); + + // Try to grant role that doesn't exist + assert.throws(function() { + db.grantRolesToUser('user1', {roles: ['fakeRole']}); + }); + + // Try to grant to user that doesn't exist + assert.throws(function() { + db.grantRolesToUser('fakeUser', {roles: ['read']}); + }); + + // Must grant something + assert.throws(function() { + db.grantRolesToUser('user1', []); + }); + + // Try to grant with invalid arguments + assert.throws(function() { + db.grantRolesToUser('user1', 1); + }); + assert.throws(function() { + db.grantRolesToUser('user1', [{}]); + }); + assert.throws(function() { + db.grantRolesToUser('user1', [1]); + }); + assert.throws(function() { + db.grantRolesToUser('user1', 'read'); + }); + assert.throws(function() { + db.grantRolesToUser('user1', [{role: 'read'}]); + }); + assert.throws(function() { + db.grantRolesToUser('user1', [{db: 'test'}]); + }); + assert.throws(function() { + db.grantRolesToUser('user1', [{role: 'read', db: ''}]); + }); + assert.throws(function() { + db.grantRolesToUser('user1', [{role: '', db: 'test'}]); + }); + + assert.eq(0, db.getUser('user1').roles.length); + assert.eq(null, db.getUser('user1').customData); + // Make sure password didn't change + assert(new Mongo(db.getMongo().host).getDB(db.getName()).auth('user1', 'pwd')); + })(); (function testRevokeRolesFromUser() { - jsTestLog("Testing revokeRolesFromUser"); - - // Revoking a role the user doesn't have should succeed but do nothing - db.revokeRolesFromUser('user1', ['read']); - - // Try to revoke role that doesn't exist - assert.throws(function() { - db.revokeRolesFromUser('user1', {roles: ['fakeRole']}); - }); - - // Try to revoke from user that doesn't exist - assert.throws(function() { - db.revokeRolesFromUser('fakeUser', {roles: ['read']}); - }); - - // Must revoke something - assert.throws(function() { - db.revokeRolesFromUser('user1', []); - }); - - // Try to revoke with invalid arguments - assert.throws(function() { - db.revokeRolesFromUser('user1', 1); - }); - assert.throws(function() { - db.revokeRolesFromUser('user1', [{}]); - }); - assert.throws(function() { - db.revokeRolesFromUser('user1', [1]); - }); - assert.throws(function() { - db.revokeRolesFromUser('user1', 'read'); - }); - assert.throws(function() { - db.revokeRolesFromUser('user1', [{role: 'read'}]); - }); - assert.throws(function() { - db.revokeRolesFromUser('user1', [{db: 'test'}]); - }); - assert.throws(function() { - db.revokeRolesFromUser('user1', [{role: 'read', db: ''}]); - }); - assert.throws(function() { - db.revokeRolesFromUser('user1', [{role: '', db: 'test'}]); - }); - - assert.eq(0, db.getUser('user1').roles.length); - })(); + jsTestLog("Testing revokeRolesFromUser"); + + // Revoking a role the user doesn't have should succeed but do nothing + db.revokeRolesFromUser('user1', ['read']); + + // Try to revoke role that doesn't exist + assert.throws(function() { + db.revokeRolesFromUser('user1', {roles: ['fakeRole']}); + }); + + // Try to revoke from user that doesn't exist + assert.throws(function() { + db.revokeRolesFromUser('fakeUser', {roles: ['read']}); + }); + + // Must revoke something + assert.throws(function() { + db.revokeRolesFromUser('user1', []); + }); + + // Try to revoke with invalid arguments + assert.throws(function() { + db.revokeRolesFromUser('user1', 1); + }); + assert.throws(function() { + db.revokeRolesFromUser('user1', [{}]); + }); + assert.throws(function() { + db.revokeRolesFromUser('user1', [1]); + }); + assert.throws(function() { + db.revokeRolesFromUser('user1', 'read'); + }); + assert.throws(function() { + db.revokeRolesFromUser('user1', [{role: 'read'}]); + }); + assert.throws(function() { + db.revokeRolesFromUser('user1', [{db: 'test'}]); + }); + assert.throws(function() { + db.revokeRolesFromUser('user1', [{role: 'read', db: ''}]); + }); + assert.throws(function() { + db.revokeRolesFromUser('user1', [{role: '', db: 'test'}]); + }); + + assert.eq(0, db.getUser('user1').roles.length); + })(); (function testUsersInfo() { - jsTestLog("Testing usersInfo"); + jsTestLog("Testing usersInfo"); - // Try to get user that does not exist - assert.eq(null, db.getUser('fakeUser')); + // Try to get user that does not exist + assert.eq(null, db.getUser('fakeUser')); - // Pass wrong type for user name - assert.throws(function() { - db.getUser(5); - }); + // Pass wrong type for user name + assert.throws(function() { + db.getUser(5); + }); - assert.throws(function() { - db.getUser([]); - }); + assert.throws(function() { + db.getUser([]); + }); - assert.throws(function() { - db.getUser(['user1']); - }); + assert.throws(function() { + db.getUser(['user1']); + }); - })(); + })(); (function testDropUser() { - jsTestLog("Testing dropUser"); + jsTestLog("Testing dropUser"); - // Try to drop a user that doesn't exist - // Should not error but should do nothing - assert.doesNotThrow(function() { - db.dropUser('fakeUser'); - }); + // Try to drop a user that doesn't exist + // Should not error but should do nothing + assert.doesNotThrow(function() { + db.dropUser('fakeUser'); + }); - assert.eq(1, db.getUsers().length); - })(); + assert.eq(1, db.getUsers().length); + })(); // dropAllUsersFromDatabase ignores its arguments, so there's nothing to test for it. } jsTest.log('Test standalone'); -var conn = MongoRunner.runMongod({ auth: '' }); -conn.getDB('admin').runCommand({setParameter:1, newCollectionsUsePowerOf2Sizes: false}); +var conn = MongoRunner.runMongod({auth: ''}); +conn.getDB('admin').runCommand({setParameter: 1, newCollectionsUsePowerOf2Sizes: false}); runTest(conn); MongoRunner.stopMongod(conn.port); jsTest.log('Test sharding'); -var st = new ShardingTest({ shards: 2, config: 3, keyFile: 'jstests/libs/key1' }); +var st = new ShardingTest({shards: 2, config: 3, keyFile: 'jstests/libs/key1'}); runTest(st.s); st.stop(); diff --git a/jstests/auth/user_special_chars.js b/jstests/auth/user_special_chars.js index 72fd06dff53..e28e63dd153 100644 --- a/jstests/auth/user_special_chars.js +++ b/jstests/auth/user_special_chars.js @@ -1,13 +1,12 @@ // Test creating and authenticating a user with special characters. var conn = MongoRunner.runMongod({auth: ''}); -var testUserSpecialCharacters = function(){ +var testUserSpecialCharacters = function() { // Create a user with special characters, make sure it can auth. var adminDB = conn.getDB('admin'); - adminDB.createUser({user: '~`!@#$%^&*()-_+={}[]||;:",.//><', pwd: 'pass', - roles: jsTest.adminUserRoles}); - assert(adminDB.auth({user: '~`!@#$%^&*()-_+={}[]||;:",.//><', - pwd: 'pass'})); + adminDB.createUser( + {user: '~`!@#$%^&*()-_+={}[]||;:",.//><', pwd: 'pass', roles: jsTest.adminUserRoles}); + assert(adminDB.auth({user: '~`!@#$%^&*()-_+={}[]||;:",.//><', pwd: 'pass'})); }; testUserSpecialCharacters(); |