summaryrefslogtreecommitdiff
path: root/jstests/auth/resource_pattern_matching.js
blob: 61aed0e8271dec47a850c2ec7742c2611730e2ea (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
/*
 * Tests that resource pattern matching rules work as expected.
 * @tags: [requires_replication, requires_sharding]
 */

// This test logs in users on the admin database, but doesn't log them out, which can fail with
// implicit sessions and ReplSetTest when the fixture attempts to verify data hashes at shutdown by
// authenticating as the __system user.
TestData.disableImplicitSessions = true;

(function() {
'use strict';

function setup_users(granter) {
    const admin = granter.getSiblingDB("admin");
    assert.commandWorked(admin.runCommand({
        createUser: "admin",
        pwd: "admin",
        roles:
            ["userAdminAnyDatabase",
             "dbAdminAnyDatabase",
             "clusterAdmin",
             "readWriteAnyDatabase"]
    }));

    assert(admin.auth("admin", "admin"));
    printjson(admin.runCommand({createRole: "test_role", privileges: [], roles: []}));
    printjson(admin.runCommand({createUser: "test_user", pwd: "password", roles: ["test_role"]}));
    admin.logout();
}

function setup_dbs_and_cols(db) {
    const admin = db.getSiblingDB('admin');
    const test_db_a = db.getSiblingDB('a');
    const test_db_b = db.getSiblingDB('b');

    assert(admin.auth('admin', 'admin'));
    assert.commandWorked(test_db_a.dropDatabase({w: 'majority'}));
    assert.commandWorked(test_db_b.dropDatabase({w: 'majority'}));

    assert.commandWorked(test_db_a.createCollection("a", {writeConcern: {w: 'majority'}}));
    assert.commandWorked(test_db_a.createCollection("b", {writeConcern: {w: 'majority'}}));

    assert.commandWorked(test_db_b.createCollection("a", {writeConcern: {w: 'majority'}}));
    assert.commandWorked(test_db_b.createCollection("b", {writeConcern: {w: 'majority'}}));
    admin.logout();
}

function grant_privileges(granter, privileges) {
    const admin = granter.getSiblingDB("admin");

    assert(admin.auth("admin", "admin"));
    const result = admin.runCommand({
        grantPrivilegesToRole: "test_role",
        privileges: privileges,
        writeConcern: {w: 'majority'}
    });
    admin.logout();
    return result;
}

function revoke_privileges(granter, privileges) {
    const admin = granter.getSiblingDB("admin");

    assert(admin.auth("admin", "admin"));
    const result = admin.runCommand({
        revokePrivilegesFromRole: "test_role",
        privileges: privileges,
        writeConcern: {w: 'majority'}
    });
    admin.logout();
    return result;
}

function invalidateUserCache(verifier) {
    const admin = verifier.getSiblingDB("admin");
    assert(admin.auth('admin', 'admin'));
    assert.commandWorked(admin.runCommand("invalidateUserCache"));
    admin.logout();
}

function run_test(name, granter, verifier, privileges, collections) {
    print("\n=== testing " + name + "() ===\n");

    grant_privileges(granter, privileges);
    invalidateUserCache(verifier);

    const verifierDB = verifier.getSiblingDB('admin');
    assert(verifierDB.auth("test_user", "password"));

    for (var key in collections) {
        const parts = key.split(".");
        const testdb = verifier.getSiblingDB(parts[0]);
        const col = testdb.getCollection(parts[1]);

        const cb = collections[key];

        cb(testdb, col);
    }
    verifierDB.logout();

    revoke_privileges(granter, privileges);
}

function run_test_bad_resource(name, granter, resource) {
    print("\n=== testing resource fail " + name + "() ===\n");
    assert.commandFailed(grant_privileges(granter, [{resource: resource, actions: ["find"]}]));
}

function should_insert(testdb, testcol) {
    assert.doesNotThrow(function() {
        testcol.insert({a: "b"});
    });
}

function should_fail_insert(testdb, testcol) {
    assert.throws(function() {
        testcol.insert({a: "b"});
    });
}

function should_find(testdb, testcol) {
    assert.doesNotThrow(function() {
        testcol.findOne();
    });
}

function should_fail_find(testdb, testcol) {
    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);
                 },
             });
}

const keyfile = "jstests/libs/key1";

{
    print('--- standalone node test ---');
    const conn = MongoRunner.runMongod({auth: null, keyFile: keyfile});
    run_tests(conn.getDB('test'), conn.getDB('test'));
    MongoRunner.stopMongod(conn);
    print('--- done standalone node test ---');
}

{
    print('--- replica set test ---');
    const rst =
        new ReplSetTest({name: 'testset', nodes: 2, nodeOptions: {'auth': null}, keyFile: keyfile});

    rst.startSet();
    rst.initiate();
    const primary = rst.getPrimary().getDB('admin');
    rst.awaitSecondaryNodes();
    const secondary = rst.getSecondaries()[0].getDB('admin');
    run_tests(primary, secondary);
    rst.stopSet();
    print('--- done with the rs tests ---');
}

{
    print('--- sharding test ---');
    const st = new ShardingTest({
        mongos: 2,
        shard: 1,
        keyFile: keyfile,
        other: {
            mongosOptions: {'auth': null},
            configOptions: {'auth': null},
            shardOptions: {'auth': null}
        }
    });
    run_tests(st.s0.getDB('admin'), st.s1.getDB('admin'));
    st.stop();
    print('--- sharding test done ---');
}
})();