summaryrefslogtreecommitdiff
path: root/jstests/concurrency/fsm_workloads/auth_privilege_consistency.js
blob: 4997d47ad2eebcc27e440b489230c5a8b38a7b91 (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
'use strict';

/**
 * auth_privilege_consistency.js
 *
 * Validate user cache invalidation upon subordinate role removal.
 *
 * @tags: [incompatible_with_concurrency_simultaneous]
 */
load('jstests/concurrency/fsm_workload_helpers/drop_utils.js');  // for dropRoles

// UMC commands are not supported in transactions.
TestData.runInsideTransaction = false;

var $config = (function() {
    const kTestUserPassword = 'secret';
    const kMaxCmdTimeMs = 60000;
    const kMaxTxnLockReqTimeMs = 100;
    const kDefaultTxnLockReqTimeMs = 5;

    function doRetry(cb) {
        const kNumRetries = 5;
        const kRetryInterval = 5 * 1000;

        assert.retry(function() {
            try {
                cb();
                return true;
            } catch (e) {
                jsTest.log("Caught exception performing: " + tojson(cb) +
                           ", exception was: " + tojson(e));
                return false;
            }
        }, "Failed performing: " + tojson(cb), kNumRetries, kRetryInterval);
    }

    const states = (function() {
        let roleWithDB = {};
        let privilege = {actions: ['insert', 'update', 'remove', 'find']};
        let RSnodes = [];

        function getTestUser(node, userName) {
            const users =
                assert
                    .commandWorked(node.getDB(userName.db)
                                       .runCommand({usersInfo: userName.user, showPrivileges: 1}))
                    .users;
            assert.eq(users.length, 1, tojson(users));
            return users[0];
        }

        return {
            init: function(db, collName) {},

            mutateInit: function(db, collName) {
                privilege.resource = {db: db.getName(), collection: ''};
                const roleName = this.getRoleName(this.tid);
                roleWithDB = {role: roleName, db: db.getName()};
                doRetry(() => db.createRole({role: roleName, privileges: [privilege], roles: []}));
            },

            mutate: function(db, collName) {
                // Revoke privs from intermediate role,
                // then give that, now empty, role to the user.
                const roleName = this.getRoleName(this.tid);

                doRetry(() => assert.commandWorked(db.runCommand({
                    revokePrivilegesFromRole: roleName,
                    privileges: [privilege],
                    maxTimeMS: kMaxCmdTimeMs
                })));

                doRetry(() => assert.commandWorked(db.runCommand({
                    grantRolesToUser: this.getUserName(),
                    roles: [roleWithDB],
                    maxTimeMS: kMaxCmdTimeMs
                })));

                // Take the role away from the user, and give it privs.

                doRetry(() => assert.commandWorked(db.runCommand({
                    revokeRolesFromUser: this.getUserName(),
                    roles: [roleWithDB],
                    maxTimeMS: kMaxCmdTimeMs
                })));

                doRetry(() => assert.commandWorked(db.runCommand({
                    grantPrivilegesToRole: roleName,
                    privileges: [privilege],
                    maxTimeMS: kMaxCmdTimeMs
                })));
            },

            observeInit: function(db, collName) {
                // Drop privileges to normal user.
                // The workload runner disallows `db.logout()` for reasons we're okay with.
                assert.commandWorked(db.runCommand({logout: 1}));
                assert(db.auth(this.getUserName(), kTestUserPassword));

                // Setup a connection to every member host if this is a replica set
                // so that we can confirm secondary state during observe().
                const hello = assert.commandWorked(db.runCommand({hello: 1}));
                jsTest.log('hello: ' + tojson(hello));
                if (hello.hosts) {
                    const allHosts = hello.hosts.concat(hello.passives);
                    allHosts.forEach(function(node) {
                        if (node === hello.me) {
                            // Reuse existing connection for db's connection.
                            const conn = db.getMongo();
                            RSnodes.push(conn);
                            return;
                        }

                        // Create a new connection to any node which isn't "me".
                        const conn = new Mongo(node);
                        assert(conn);
                        conn.setSecondaryOk();
                        RSnodes.push(conn);
                    });

                    // Wait for user to replicate to all nodes.
                    const userName = {user: this.getUserName(), db: db.getName()};
                    RSnodes.forEach(function(node) {
                        assert.soon(function() {
                            try {
                                getTestUser(node, userName);
                                return true;
                            } catch (e) {
                                return false;
                            }
                        });
                    });
                }
            },

            observe: function(db, collName) {
                // Make sure we never appear to have any privileges,
                // but that we remain authenticated.
                const info =
                    assert.commandWorked(db.runCommand({connectionStatus: 1, showPrivileges: true}))
                        .authInfo;
                assert.eq(info.authenticatedUsers.length, 1, tojson(info));
                assert.eq(info.authenticatedUsers[0].user, this.getUserName(), tojson(info));
                assert.eq(info.authenticatedUserPrivileges.length, 0, tojson(info));

                // If this is a ReplSet, iterate nodes and check usersInfo.
                const userName = {user: this.getUserName(), db: db.getName()};
                RSnodes.forEach(function(node) {
                    const user = getTestUser(node, userName);
                    jsTest.log(node + ' userInfo: ' + tojson(user));
                    assert.eq(user.user, user.user, tojson(user));
                    assert.eq(user.inheritedPrivileges.length, 0, tojson(user));
                });
            },
        };
    })();

    const transitions = {
        init: {mutateInit: 0.8, observeInit: 0.2},
        mutateInit: {mutate: 1},
        mutate: {mutate: 1},
        observeInit: {observe: 1},
        observe: {observe: 1},
    };

    function setup(db, collName, cluster) {
        cluster.executeOnMongodNodes(function(db) {
            db.adminCommand(
                {setParameter: 1, maxTransactionLockRequestTimeoutMillis: kMaxTxnLockReqTimeMs});
        });

        cluster.executeOnMongosNodes(function(db) {
            db.adminCommand(
                {setParameter: 1, maxTransactionLockRequestTimeoutMillis: kMaxTxnLockReqTimeMs});
        });

        db.createUser({user: this.getUserName(), pwd: kTestUserPassword, roles: []});
    }

    function teardown(db, collName, cluster) {
        // Calling getRoleName() with an empty string allows us to just get the prefix
        // and match any thread id by pattern.
        const pattern = new RegExp('^' + this.getRoleName('') + '\\d+$');
        dropRoles(db, pattern);
        db.dropUser(this.getUserName());

        cluster.executeOnMongodNodes(function(db) {
            db.adminCommand({
                setParameter: 1,
                maxTransactionLockRequestTimeoutMillis: kDefaultTxnLockReqTimeMs
            });
        });

        cluster.executeOnMongosNodes(function(db) {
            db.adminCommand({
                setParameter: 1,
                maxTransactionLockRequestTimeoutMillis: kDefaultTxnLockReqTimeMs
            });
        });
    }

    return {
        threadCount: 10,
        iterations: 50,
        states: states,
        transitions: transitions,
        setup: setup,
        teardown: teardown,
        data: {
            // Tests which extend this must provide their own unique name.
            // So that 'simultaneous' runs will not step over each other.
            test_name: 'auth_privilege_consistency',

            getUserName: function() {
                return this.test_name + '_user';
            },

            getRoleName: function(id) {
                return this.test_name + '_role_' + id;
            },
        },
    };
})();