summaryrefslogtreecommitdiff
path: root/jstests/sharding/authCommands.js
blob: da8f0d80cabc2bcdbbd74cf097d2ddb6c0f8c03a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
/**
 * This tests using DB commands with authentication enabled when sharded.
 */
(function() {
    'use strict';
    load("jstests/replsets/rslib.js");

    var st = new ShardingTest({
        shards: 2,
        rs: {oplogSize: 10, useHostname: false},
        other:
            {keyFile: 'jstests/libs/key1', useHostname: false, chunkSize: 2, enableAutoSplit: true},
    });

    var mongos = st.s;
    var adminDB = mongos.getDB('admin');
    var configDB = mongos.getDB('config');
    var testDB = mongos.getDB('test');

    jsTestLog('Setting up initial users');
    var rwUser = 'rwUser';
    var roUser = 'roUser';
    var password = 'password';
    var expectedDocs = 1000;

    adminDB.createUser({user: rwUser, pwd: password, roles: jsTest.adminUserRoles});

    assert(adminDB.auth(rwUser, password));

    // Secondaries should be up here, since we awaitReplication in the ShardingTest, but we *don't*
    // wait for the mongos to explicitly detect them.
    awaitRSClientHosts(mongos, st.rs0.getSecondaries(), {ok: true, secondary: true});
    awaitRSClientHosts(mongos, st.rs1.getSecondaries(), {ok: true, secondary: true});

    testDB.createUser({user: rwUser, pwd: password, roles: jsTest.basicUserRoles});
    testDB.createUser({user: roUser, pwd: password, roles: jsTest.readOnlyUserRoles});

    var authenticatedConn = new Mongo(mongos.host);
    authenticatedConn.getDB('admin').auth(rwUser, password);

    // Add user to shards to prevent localhost connections from having automatic full access
    st.rs0.getPrimary().getDB('admin').createUser(
        {user: 'user', pwd: 'password', roles: jsTest.basicUserRoles}, {w: 3, wtimeout: 30000});
    st.rs1.getPrimary().getDB('admin').createUser(
        {user: 'user', pwd: 'password', roles: jsTest.basicUserRoles}, {w: 3, wtimeout: 30000});

    jsTestLog('Creating initial data');

    st.adminCommand({enablesharding: "test"});
    st.ensurePrimaryShard('test', 'test-rs0');
    st.adminCommand({shardcollection: "test.foo", key: {i: 1, j: 1}});

    // Balancer is stopped by default, so no moveChunks will interfere with the splits we're testing

    var str = 'a';
    while (str.length < 8000) {
        str += str;
    }

    var bulk = testDB.foo.initializeUnorderedBulkOp();
    for (var i = 0; i < 100; i++) {
        for (var j = 0; j < 10; j++) {
            bulk.insert({i: i, j: j, str: str});
        }
    }
    assert.writeOK(bulk.execute({w: "majority"}));

    assert.eq(expectedDocs, testDB.foo.count());

    // Wait for the balancer to start back up
    assert.writeOK(
        configDB.settings.update({_id: 'balancer'}, {$set: {_waitForDelete: true}}, true));
    st.startBalancer();

    // Make sure we've done at least some splitting, so the balancer will work
    assert.gt(configDB.chunks.find({ns: 'test.foo'}).count(), 2);

    // Make sure we eventually balance all the chunks we've created
    assert.soon(function() {
        var x = st.chunkDiff("foo", "test");
        print("chunk diff: " + x);
        return x < 2 && configDB.locks.findOne({_id: 'test.foo'}).state == 0;
    }, "no balance happened", 5 * 60 * 1000);

    var map = function() {
        emit(this.i, this.j);
    };

    var reduce = function(key, values) {
        var jCount = 0;
        values.forEach(function(j) {
            jCount += j;
        });
        return jCount;
    };

    var checkCommandSucceeded = function(db, cmdObj) {
        print("Running command that should succeed: ");
        printjson(cmdObj);
        var resultObj = db.runCommand(cmdObj);
        printjson(resultObj);
        assert(resultObj.ok);
        return resultObj;
    };

    var checkCommandFailed = function(db, cmdObj) {
        print("Running command that should fail: ");
        printjson(cmdObj);
        var resultObj = db.runCommand(cmdObj);
        printjson(resultObj);
        assert(!resultObj.ok);
        return resultObj;
    };

    var checkReadOps = function(hasReadAuth) {
        if (hasReadAuth) {
            print("Checking read operations, should work");
            assert.eq(expectedDocs, testDB.foo.find().itcount());
            assert.eq(expectedDocs, testDB.foo.count());
            // NOTE: This is an explicit check that GLE can be run with read prefs, not the result
            // of
            // above.
            assert.eq(null, testDB.runCommand({getlasterror: 1}).err);
            checkCommandSucceeded(testDB, {dbstats: 1});
            checkCommandSucceeded(testDB, {collstats: 'foo'});

            // inline map-reduce works read-only
            var res = checkCommandSucceeded(
                testDB, {mapreduce: 'foo', map: map, reduce: reduce, out: {inline: 1}});
            assert.eq(100, res.results.length);
            assert.eq(45, res.results[0].value);

            res = checkCommandSucceeded(testDB, {
                aggregate: 'foo',
                pipeline: [{$project: {j: 1}}, {$group: {_id: 'j', sum: {$sum: '$j'}}}]
            });
            assert.eq(4500, res.result[0].sum);
        } else {
            print("Checking read operations, should fail");
            assert.throws(function() {
                testDB.foo.find().itcount();
            });
            checkCommandFailed(testDB, {dbstats: 1});
            checkCommandFailed(testDB, {collstats: 'foo'});
            checkCommandFailed(testDB,
                               {mapreduce: 'foo', map: map, reduce: reduce, out: {inline: 1}});
            checkCommandFailed(testDB, {
                aggregate: 'foo',
                pipeline: [{$project: {j: 1}}, {$group: {_id: 'j', sum: {$sum: '$j'}}}]
            });
        }
    };

    var checkWriteOps = function(hasWriteAuth) {
        if (hasWriteAuth) {
            print("Checking write operations, should work");
            testDB.foo.insert({a: 1, i: 1, j: 1});
            var res = checkCommandSucceeded(
                testDB, {findAndModify: "foo", query: {a: 1, i: 1, j: 1}, update: {$set: {b: 1}}});
            assert.eq(1, res.value.a);
            assert.eq(null, res.value.b);
            assert.eq(1, testDB.foo.findOne({a: 1}).b);
            testDB.foo.remove({a: 1});
            assert.eq(null, testDB.runCommand({getlasterror: 1}).err);
            checkCommandSucceeded(testDB, {reIndex: 'foo'});
            checkCommandSucceeded(testDB, {repairDatabase: 1});
            checkCommandSucceeded(testDB,
                                  {mapreduce: 'foo', map: map, reduce: reduce, out: 'mrOutput'});
            assert.eq(100, testDB.mrOutput.count());
            assert.eq(45, testDB.mrOutput.findOne().value);

            checkCommandSucceeded(testDB, {drop: 'foo'});
            assert.eq(0, testDB.foo.count());
            testDB.foo.insert({a: 1});
            assert.eq(1, testDB.foo.count());
            checkCommandSucceeded(testDB, {dropDatabase: 1});
            assert.eq(0, testDB.foo.count());
            checkCommandSucceeded(testDB, {create: 'baz'});
        } else {
            print("Checking write operations, should fail");
            testDB.foo.insert({a: 1, i: 1, j: 1});
            assert.eq(0, authenticatedConn.getDB('test').foo.count({a: 1, i: 1, j: 1}));
            checkCommandFailed(
                testDB, {findAndModify: "foo", query: {a: 1, i: 1, j: 1}, update: {$set: {b: 1}}});
            checkCommandFailed(testDB, {reIndex: 'foo'});
            checkCommandFailed(testDB, {repairDatabase: 1});
            checkCommandFailed(testDB,
                               {mapreduce: 'foo', map: map, reduce: reduce, out: 'mrOutput'});
            checkCommandFailed(testDB, {drop: 'foo'});
            checkCommandFailed(testDB, {dropDatabase: 1});
            var passed = true;
            try {
                // For some reason when create fails it throws an exception instead of just
                // returning ok:0
                var res = testDB.runCommand({create: 'baz'});
                if (!res.ok) {
                    passed = false;
                }
            } catch (e) {
                // expected
                printjson(e);
                passed = false;
            }
            assert(!passed);
        }
    };

    var checkAdminOps = function(hasAuth) {
        if (hasAuth) {
            checkCommandSucceeded(adminDB, {getCmdLineOpts: 1});
            checkCommandSucceeded(adminDB, {serverStatus: 1});
            checkCommandSucceeded(adminDB, {listShards: 1});
            checkCommandSucceeded(adminDB, {whatsmyuri: 1});
            checkCommandSucceeded(adminDB, {isdbgrid: 1});
            checkCommandSucceeded(adminDB, {ismaster: 1});
            checkCommandSucceeded(adminDB, {split: 'test.foo', find: {i: 1, j: 1}});
            var chunk = configDB.chunks.findOne({shard: st.rs0.name});
            checkCommandSucceeded(
                adminDB,
                {moveChunk: 'test.foo', find: chunk.min, to: st.rs1.name, _waitForDelete: true});
        } else {
            checkCommandFailed(adminDB, {getCmdLineOpts: 1});
            checkCommandFailed(adminDB, {serverStatus: 1});
            checkCommandFailed(adminDB, {listShards: 1});
            // whatsmyuri, isdbgrid, and ismaster don't require any auth
            checkCommandSucceeded(adminDB, {whatsmyuri: 1});
            checkCommandSucceeded(adminDB, {isdbgrid: 1});
            checkCommandSucceeded(adminDB, {ismaster: 1});
            checkCommandFailed(adminDB, {split: 'test.foo', find: {i: 1, j: 1}});
            var chunkKey = {i: {$minKey: 1}, j: {$minKey: 1}};
            checkCommandFailed(
                adminDB,
                {moveChunk: 'test.foo', find: chunkKey, to: st.rs1.name, _waitForDelete: true});
        }
    };

    var checkRemoveShard = function(hasWriteAuth) {
        if (hasWriteAuth) {
            // start draining
            checkCommandSucceeded(adminDB, {removeshard: st.rs1.name});
            // Wait for shard to be completely removed
            checkRemoveShard = function() {
                var res = checkCommandSucceeded(adminDB, {removeshard: st.rs1.name});
                return res.msg == 'removeshard completed successfully';
            };
            assert.soon(checkRemoveShard, "failed to remove shard");
        } else {
            checkCommandFailed(adminDB, {removeshard: st.rs1.name});
        }
    };

    var checkAddShard = function(hasWriteAuth) {
        if (hasWriteAuth) {
            checkCommandSucceeded(adminDB, {addshard: st.rs1.getURL()});
        } else {
            checkCommandFailed(adminDB, {addshard: st.rs1.getURL()});
        }
    };

    st.stopBalancer();

    jsTestLog("Checking admin commands with admin auth credentials");
    checkAdminOps(true);
    assert(adminDB.logout().ok);

    jsTestLog("Checking admin commands with no auth credentials");
    checkAdminOps(false);

    jsTestLog("Checking commands with no auth credentials");
    checkReadOps(false);
    checkWriteOps(false);

    // Authenticate as read-only user
    jsTestLog("Checking commands with read-only auth credentials");
    assert(testDB.auth(roUser, password));
    checkReadOps(true);
    checkWriteOps(false);

    // Authenticate as read-write user
    jsTestLog("Checking commands with read-write auth credentials");
    assert(testDB.auth(rwUser, password));
    checkReadOps(true);
    checkWriteOps(true);

    jsTestLog("Check drainging/removing a shard");
    assert(testDB.logout().ok);
    checkRemoveShard(false);
    assert(adminDB.auth(rwUser, password));
    assert(testDB.dropDatabase().ok);
    checkRemoveShard(true);
    st.printShardingStatus();

    jsTestLog("Check adding a shard");
    assert(adminDB.logout().ok);
    checkAddShard(false);
    assert(adminDB.auth(rwUser, password));
    checkAddShard(true);
    st.printShardingStatus();

    st.stop();
})();