summaryrefslogtreecommitdiff
path: root/src/mongo/db/auth/authorization_manager_impl.h
blob: d18b6e7724ad39d62f8639c11fbfe3bcb68f3c84 (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
/**
 *    Copyright (C) 2018-present MongoDB, Inc.
 *
 *    This program is free software: you can redistribute it and/or modify
 *    it under the terms of the Server Side Public License, version 1,
 *    as published by MongoDB, Inc.
 *
 *    This program is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *    Server Side Public License for more details.
 *
 *    You should have received a copy of the Server Side Public License
 *    along with this program. If not, see
 *    <http://www.mongodb.com/licensing/server-side-public-license>.
 *
 *    As a special exception, the copyright holders give permission to link the
 *    code of portions of this program with the OpenSSL library under certain
 *    conditions as described in each individual source file and distribute
 *    linked combinations including the program with the OpenSSL library. You
 *    must comply with the Server Side Public License in all respects for
 *    all of the code used other than as permitted herein. If you modify file(s)
 *    with this exception, you may extend this exception to your version of the
 *    file(s), but you are not obligated to do so. If you do not wish to do so,
 *    delete this exception statement from your version. If you delete this
 *    exception statement from all source files in the program, then also delete
 *    it in the license file.
 */

#pragma once

#include "mongo/db/auth/authorization_manager.h"

#include <functional>
#include <memory>
#include <mutex>
#include <string>

#include "mongo/base/secure_allocator.h"
#include "mongo/base/status.h"
#include "mongo/bson/mutable/element.h"
#include "mongo/bson/oid.h"
#include "mongo/db/auth/action_set.h"
#include "mongo/db/auth/privilege_format.h"
#include "mongo/db/auth/resource_pattern.h"
#include "mongo/db/auth/role_graph.h"
#include "mongo/db/auth/user.h"
#include "mongo/db/auth/user_name.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/server_options.h"
#include "mongo/platform/atomic_word.h"
#include "mongo/stdx/condition_variable.h"
#include "mongo/stdx/mutex.h"
#include "mongo/stdx/unordered_map.h"
#include "mongo/util/invalidating_lru_cache.h"

namespace mongo {
class AuthorizationSession;
class AuthzManagerExternalState;
class OperationContext;
class ServiceContext;
class UserDocumentParser;

/**
 * Contains server/cluster-wide information about Authorization.
 */
class AuthorizationManagerImpl : public AuthorizationManager {
public:
    ~AuthorizationManagerImpl() override;

    AuthorizationManagerImpl();

    struct InstallMockForTestingOrAuthImpl {
        explicit InstallMockForTestingOrAuthImpl() = default;
    };

    AuthorizationManagerImpl(std::unique_ptr<AuthzManagerExternalState> externalState,
                             InstallMockForTestingOrAuthImpl);

    std::unique_ptr<AuthorizationSession> makeAuthorizationSession() override;

    void setShouldValidateAuthSchemaOnStartup(bool validate) override;

    bool shouldValidateAuthSchemaOnStartup() override;

    void setAuthEnabled(bool enabled) override;

    bool isAuthEnabled() const override;

    Status getAuthorizationVersion(OperationContext* opCtx, int* version) override;

    OID getCacheGeneration() override;

    bool hasAnyPrivilegeDocuments(OperationContext* opCtx) override;

    Status getUserDescription(OperationContext* opCtx,
                              const UserName& userName,
                              BSONObj* result) override;

    Status getRoleDescription(OperationContext* opCtx,
                              const RoleName& roleName,
                              PrivilegeFormat privilegeFormat,
                              AuthenticationRestrictionsFormat,
                              BSONObj* result) override;

    Status getRolesDescription(OperationContext* opCtx,
                               const std::vector<RoleName>& roleName,
                               PrivilegeFormat privilegeFormat,
                               AuthenticationRestrictionsFormat,
                               BSONObj* result) override;

    Status getRoleDescriptionsForDB(OperationContext* opCtx,
                                    StringData dbname,
                                    PrivilegeFormat privilegeFormat,
                                    AuthenticationRestrictionsFormat,
                                    bool showBuiltinRoles,
                                    std::vector<BSONObj>* result) override;

    StatusWith<UserHandle> acquireUser(OperationContext* opCtx, const UserName& userName) override;
    StatusWith<UserHandle> acquireUserForSessionRefresh(OperationContext* opCtx,
                                                        const UserName& userName,
                                                        const User::UserId& uid) override;

    /**
     * Invalidate a user, and repin it if necessary.
     */
    void invalidateUserByName(OperationContext* opCtx, const UserName& user) override;

    void invalidateUsersFromDB(OperationContext* opCtx, StringData dbname) override;

    Status initialize(OperationContext* opCtx) override;

    /**
     * Invalidate the user cache, and repin all pinned users.
     */
    void invalidateUserCache(OperationContext* opCtx) override;

    void updatePinnedUsersList(std::vector<UserName> names) override;

    Status _initializeUserFromPrivilegeDocument(User* user, const BSONObj& privDoc) override;

    void logOp(OperationContext* opCtx,
               const char* opstr,
               const NamespaceString& nss,
               const BSONObj& obj,
               const BSONObj* patt) override;

    std::vector<CachedUserInfo> getUserCacheInfo() const override;

private:
    /**
     * Type used to guard accesses and updates to the user cache.
     */
    class CacheGuard;
    friend class AuthorizationManagerImpl::CacheGuard;

    /**
     * Invalidates all User objects in the cache and removes them from the cache.
     * Should only be called when already holding _cacheMutex.
     */
    void _invalidateUserCache_inlock(const CacheGuard&);

    /**
     * Given the objects describing an oplog entry that affects authorization data, invalidates
     * the portion of the user cache that is affected by that operation.  Should only be called
     * with oplog entries that have been pre-verified to actually affect authorization data.
     */
    void _invalidateRelevantCacheData(OperationContext* opCtx,
                                      const char* op,
                                      const NamespaceString& ns,
                                      const BSONObj& o,
                                      const BSONObj* o2);

    /**
     * Updates _cacheGeneration to a new OID
     */
    void _updateCacheGeneration_inlock(const CacheGuard&);

    void _pinnedUsersThreadRoutine() noexcept;

    /**
     * Fetches user information from a v2-schema user document for the named user,
     * and stores a pointer to a new user object into *acquiredUser on success.
     */
    Status _fetchUserV2(OperationContext* opCtx,
                        const UserName& userName,
                        std::unique_ptr<User>* acquiredUser);

    /**
     * True if AuthSchema startup checks should be applied in this AuthorizationManager.
     *
     * Defaults to true.  Changes to its value are not synchronized, so it should only be set
     * at initalization-time.
     */
    bool _startupAuthSchemaValidation;

    /**
     * True if access control enforcement is enabled in this AuthorizationManager.
     *
     * Defaults to false.  Changes to its value are not synchronized, so it should only be set
     * at initalization-time.
     */
    bool _authEnabled;

    /**
     * A cache of whether there are any users set up for the cluster.
     */
    AtomicWord<bool> _privilegeDocsExist;

    std::unique_ptr<AuthzManagerExternalState> _externalState;

    /**
     * Cached value of the authorization schema version.
     *
     * May be set by acquireUser() and getAuthorizationVersion().  Invalidated by
     * invalidateUserCache().
     *
     * Reads and writes guarded by CacheGuard.
     */
    int _version;

    /**
     * Caches User objects with information about user privileges, to avoid the need to
     * go to disk to read user privilege documents whenever possible.  Every User object
     * has a reference count - the AuthorizationManager must not delete a User object in the
     * cache unless its reference count is zero.
     */
    struct UserCacheInvalidator {
        void operator()(User* user);
    };

    InvalidatingLRUCache<UserName, User, UserCacheInvalidator> _userCache;

    stdx::mutex _pinnedUsersMutex;
    stdx::condition_variable _pinnedUsersCond;
    std::once_flag _pinnedThreadTrackerStarted;
    boost::optional<std::vector<UserName>> _usersToPin;

    /**
     * Protects _cacheGeneration, _version and _isFetchPhaseBusy.  Manipulated
     * via CacheGuard.
     */
    stdx::mutex _cacheWriteMutex;

    /**
     * Current generation of cached data.  Updated every time part of the cache gets
     * invalidated.  Protected by CacheGuard.
     */
    OID _fetchGeneration;

    /**
     * True if there is an update to the _userCache in progress, and that update is currently in
     * the "fetch phase", during which it does not hold the _cacheMutex.
     *
     * Manipulated via CacheGuard.
     */
    bool _isFetchPhaseBusy = false;

    /**
     * Condition used to signal that it is OK for another CacheGuard to enter a fetch phase.
     * Manipulated via CacheGuard.
     */
    stdx::condition_variable _fetchPhaseIsReady;
};

extern int authorizationManagerCacheSize;

}  // namespace mongo