summaryrefslogtreecommitdiff
path: root/src/mongo/db/auth/authorization_session_impl.cpp
blob: b18cc3790898d14ddcd780b5bad1a05c8f294980 (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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
/**
 *    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.
 */


#include "mongo/platform/basic.h"

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

#include <array>
#include <string>
#include <vector>

#include "mongo/base/shim.h"
#include "mongo/base/status.h"
#include "mongo/db/audit.h"
#include "mongo/db/auth/action_set.h"
#include "mongo/db/auth/action_type.h"
#include "mongo/db/auth/authz_session_external_state.h"
#include "mongo/db/auth/privilege.h"
#include "mongo/db/auth/security_token.h"
#include "mongo/db/bson/dotted_path_support.h"
#include "mongo/db/client.h"
#include "mongo/db/namespace_string.h"
#include "mongo/db/operation_context.h"
#include "mongo/logv2/log.h"
#include "mongo/util/assert_util.h"
#include "mongo/util/fail_point.h"
#include "mongo/util/str.h"
#include "mongo/util/testing_proctor.h"

#define MONGO_LOGV2_DEFAULT_COMPONENT ::mongo::logv2::LogComponent::kAccessControl


namespace mongo {

namespace dps = ::mongo::dotted_path_support;
using std::vector;
namespace {

std::unique_ptr<AuthorizationSession> authorizationSessionCreateImpl(
    AuthorizationManager* authzManager) {
    return std::make_unique<AuthorizationSessionImpl>(
        AuthzSessionExternalState::create(authzManager),
        AuthorizationSessionImpl::InstallMockForTestingOrAuthImpl{});
}

auto authorizationSessionCreateRegistration =
    MONGO_WEAK_FUNCTION_REGISTRATION(AuthorizationSession::create, authorizationSessionCreateImpl);

constexpr StringData ADMIN_DBNAME = "admin"_sd;
constexpr StringData SYSTEM_BUCKETS_PREFIX = "system.buckets."_sd;

bool checkContracts() {
    // Only check contracts in testing modes, invalid contracts should not break customers.
    if (!TestingProctor::instance().isEnabled()) {
        return false;
    }

    return true;
}

using ServerlessPermissionMap = stdx::unordered_map<MatchTypeEnum, ActionSet>;
ServerlessPermissionMap kServerlessPrivilegesPermitted;

/**
 * Load extra data from action_types.idl into runtime structure.
 * For any given resource match type, we allow only the ActionTypes named
 * to be granted to security token based users.
 */
MONGO_INITIALIZER(ServerlessPrivilegePermittedMap)(InitializerContext*) try {
    ServerlessPermissionMap ret;

    for (std::size_t i = 0; i < kNumMatchTypeEnum; ++i) {
        auto matchType = static_cast<MatchTypeEnum>(i);
        auto matchTypeName = MatchType_serializer(matchType);
        auto dataObj = MatchType_get_extra_data(matchType);
        auto data = MatchTypeExtraData::parse({matchTypeName}, dataObj);
        auto actionTypes = data.getServerlessActionTypes();

        std::vector<std::string> actionsToParse;
        std::transform(actionTypes.cbegin(),
                       actionTypes.cend(),
                       std::back_inserter(actionsToParse),
                       [](const auto& at) { return at.toString(); });

        ActionSet actions;
        std::vector<std::string> unknownActions;
        auto status =
            ActionSet::parseActionSetFromStringVector(actionsToParse, &actions, &unknownActions);
        if (!status.isOK()) {
            StringBuilder sb;
            sb << "Unknown actions listed for match type '" << matchTypeName << "':";
            for (const auto& unknownAction : unknownActions) {
                sb << " '" << unknownAction << "'";
            }
            uassertStatusOK(status.withContext(sb.str()));
        }

        ret[matchType] = std::move(actions);
    }

    kServerlessPrivilegesPermitted = std::move(ret);
} catch (const DBException& ex) {
    uassertStatusOK(ex.toStatus().withContext("Failed parsing extraData for MatchType enum"));
}

void validateSecurityTokenUserPrivileges(const User::ResourcePrivilegeMap& privs) {
    for (const auto& priv : privs) {
        auto matchType = priv.first.matchType();
        const auto& actions = priv.second.getActions();
        auto it = kServerlessPrivilegesPermitted.find(matchType);
        // This actually can't happen since the initializer above populated the map with all match
        // types.
        uassert(6161701,
                str::stream() << "Unknown matchType: " << MatchType_serializer(matchType),
                it != kServerlessPrivilegesPermitted.end());
        if (MONGO_unlikely(!it->second.isSupersetOf(actions))) {
            auto unauthorized = actions;
            unauthorized.removeAllActionsFromSet(it->second);
            uasserted(6161702,
                      str::stream()
                          << "Security Token user has one or more actions not approved for "
                             "resource matchType '"
                          << MatchType_serializer(matchType) << "': " << unauthorized.toString());
        }
    }
}

MONGO_FAIL_POINT_DEFINE(allowMultipleUsersWithApiStrict);

const Privilege kBypassWriteBlockingModeOnClusterPrivilege(ResourcePattern::forClusterResource(),
                                                           ActionType::bypassWriteBlockingMode);
}  // namespace

AuthorizationSessionImpl::AuthorizationSessionImpl(
    std::unique_ptr<AuthzSessionExternalState> externalState, InstallMockForTestingOrAuthImpl)
    : _externalState(std::move(externalState)),
      _impersonationFlag(false),
      _mayBypassWriteBlockingMode(false) {}

AuthorizationSessionImpl::~AuthorizationSessionImpl() {
    invariant(_authenticatedUsers.count() == 0,
              "All authenticated users should be logged out by the Client destruction hook");
}

AuthorizationManager& AuthorizationSessionImpl::getAuthorizationManager() {
    return _externalState->getAuthorizationManager();
}

void AuthorizationSessionImpl::startRequest(OperationContext* opCtx) {
    _externalState->startRequest(opCtx);
    _refreshUserInfoAsNeeded(opCtx);
    if (_authenticationMode == AuthenticationMode::kSecurityToken) {
        // Previously authenticated using SecurityToken,
        // clear that user and reset to unauthenticated state.
        invariant(_authenticatedUsers.count() <= 1);
        if (auto users = std::exchange(_authenticatedUsers, {}); users.count()) {
            LOGV2_DEBUG(6161507,
                        3,
                        "security token based user still authenticated at start of request, "
                        "clearing from authentication state",
                        "user"_attr = users.getNames().get().toBSON(true /* encode tenant */));
            _updateInternalAuthorizationState();
        }
        _authenticationMode = AuthenticationMode::kNone;
    }
}

void AuthorizationSessionImpl::startContractTracking() {
    if (!checkContracts()) {
        return;
    }

    _contract.clear();
}

Status AuthorizationSessionImpl::addAndAuthorizeUser(OperationContext* opCtx,
                                                     const UserName& userName) try {
    auto checkForMultipleUsers = [&]() {
        const auto userCount = _authenticatedUsers.count();
        if (userCount == 0) {
            // This is the first authentication.
            return;
        }
        invariant(userCount == 1);

        auto previousUser = _authenticatedUsers.begin()->get()->getName();
        if (previousUser == userName) {
            // Allow reauthenticating as the same user, but warn.
            LOGV2_WARNING(5626700,
                          "Client has attempted to reauthenticate as a single user",
                          "user"_attr = userName);

            // Strict API requires no reauth, even as same user, unless FP is enabled.
            const bool hasStrictAPI = APIParameters::get(opCtx).getAPIStrict().value_or(false);
            uassert(5626703,
                    "Each client connection may only be authenticated once",
                    !hasStrictAPI || allowMultipleUsersWithApiStrict.shouldFail());
        } else {
            uassert(5626701,
                    str::stream() << "Each client connection may only be authenticated once. "
                                  << "Previously authenticated as: " << previousUser,
                    previousUser.getDB() == userName.getDB());
            uasserted(5626702,
                      str::stream() << "Client has attempted to authenticate on multiple databases."
                                    << "Already authenticated as: " << previousUser);
        }
    };

    // Check before we start to reveal as little as possible. Note that we do not need the lock
    // because only the Client thread can mutate _authenticatedUsers.
    checkForMultipleUsers();

    AuthorizationManager* authzManager = AuthorizationManager::get(opCtx->getServiceContext());
    auto swUser = authzManager->acquireUser(opCtx, userName);
    if (!swUser.isOK()) {
        return swUser.getStatus();
    }

    auto user = std::move(swUser.getValue());

    auto restrictionStatus = user->validateRestrictions(opCtx);
    if (!restrictionStatus.isOK()) {
        LOGV2(20240,
              "Failed to acquire user because of unmet authentication restrictions",
              "user"_attr = userName,
              "reason"_attr = restrictionStatus.reason());
        return AuthorizationManager::authenticationFailedStatus;
    }

    stdx::lock_guard<Client> lk(*opCtx->getClient());

    if (auto token = auth::getSecurityToken(opCtx)) {
        uassert(
            6161501,
            "Attempt to authorize via security token on connection with established authentication",
            _authenticationMode != AuthenticationMode::kConnection);
        uassert(6161502,
                "Attempt to authorize a user other than that present in the security token",
                token->getAuthenticatedUser() == userName);
        validateSecurityTokenUserPrivileges(user->getPrivileges());
        _authenticationMode = AuthenticationMode::kSecurityToken;
    } else {
        _authenticationMode = AuthenticationMode::kConnection;
    }
    _authenticatedUsers.add(std::move(user));

    // If there are any users and roles in the impersonation data, clear it out.
    clearImpersonatedUserData();

    _updateInternalAuthorizationState();
    return Status::OK();

} catch (const DBException& ex) {
    return ex.toStatus();
}

User* AuthorizationSessionImpl::lookupUser(const UserName& name) {
    _contract.addAccessCheck(AccessCheckEnum::kLookupUser);

    auto user = _authenticatedUsers.lookup(name);
    return user ? user.get() : nullptr;
}

User* AuthorizationSessionImpl::getSingleUser() {
    UserName userName;

    _contract.addAccessCheck(AccessCheckEnum::kGetSingleUser);

    auto userNameItr = getAuthenticatedUserNames();
    if (userNameItr.more()) {
        userName = userNameItr.next();
        if (userNameItr.more()) {
            uasserted(
                ErrorCodes::Unauthorized,
                "logical sessions can't have multiple authenticated users (for more details see: "
                "https://docs.mongodb.com/manual/core/authentication/#authentication-methods)");
        }
    } else {
        uasserted(ErrorCodes::Unauthorized, "there are no users authenticated");
    }

    return lookupUser(userName);
}

void AuthorizationSessionImpl::logoutSecurityTokenUser(Client* client) {
    stdx::lock_guard<Client> lk(*client);

    uassert(6161503,
            "Attempted to deauth a security token user while using standard login",
            _authenticationMode != AuthenticationMode::kConnection);

    auto users = std::exchange(_authenticatedUsers, {});
    invariant(users.count() <= 1);
    if (users.count() == 1) {
        LOGV2_DEBUG(6161506,
                    5,
                    "security token based user explicitly logged out",
                    "user"_attr = users.getNames().get().toBSON(true /* encode tenant */));
    }

    // Explicitly skip auditing the logout event,
    // security tokens don't represent a permanent login.
    clearImpersonatedUserData();
    _updateInternalAuthorizationState();
}

void AuthorizationSessionImpl::logoutAllDatabases(Client* client, StringData reason) {
    stdx::lock_guard<Client> lk(*client);

    uassert(6161504,
            "May not log out while using a security token based authentication",
            _authenticationMode != AuthenticationMode::kSecurityToken);

    auto users = std::exchange(_authenticatedUsers, {});
    if (users.count() == 0) {
        return;
    }

    audit::logLogout(client, reason, users.toBSON(), BSONArray());

    clearImpersonatedUserData();
    _updateInternalAuthorizationState();
}


void AuthorizationSessionImpl::logoutDatabase(Client* client,
                                              StringData dbname,
                                              StringData reason) {
    stdx::lock_guard<Client> lk(*client);

    uassert(6161505,
            "May not log out while using a security token based authentication",
            _authenticationMode != AuthenticationMode::kSecurityToken);

    // Emit logout audit event and then remove all users logged into dbname.
    UserSet updatedUsers(_authenticatedUsers);
    updatedUsers.removeByDBName(dbname);
    if (updatedUsers.count() != _authenticatedUsers.count()) {
        audit::logLogout(client, reason, _authenticatedUsers.toBSON(), updatedUsers.toBSON());
    }
    std::swap(_authenticatedUsers, updatedUsers);

    clearImpersonatedUserData();
    _updateInternalAuthorizationState();
}

UserNameIterator AuthorizationSessionImpl::getAuthenticatedUserNames() {
    _contract.addAccessCheck(AccessCheckEnum::kGetAuthenticatedUserNames);

    return _authenticatedUsers.getNames();
}

RoleNameIterator AuthorizationSessionImpl::getAuthenticatedRoleNames() {
    _contract.addAccessCheck(AccessCheckEnum::kGetAuthenticatedRoleNames);

    return makeRoleNameIterator(_authenticatedRoleNames.begin(), _authenticatedRoleNames.end());
}

void AuthorizationSessionImpl::grantInternalAuthorization(Client* client) {
    stdx::lock_guard<Client> lk(*client);
    if (MONGO_unlikely(_authenticatedUsers.count() > 0)) {
        invariant(_authenticatedUsers.count() == 1);
        auto previousUser = _authenticatedUsers.begin()->get()->getName();
        uassert(ErrorCodes::Unauthorized,
                str::stream() << "Unable to grant internal authorization, previously authorized as "
                              << previousUser.getUnambiguousName(),
                previousUser == internalSecurity.getUser()->get()->getName());
        return;
    }

    _authenticatedUsers.add(*internalSecurity.getUser());
    _updateInternalAuthorizationState();
}

/**
 * Overloaded function - takes in the opCtx of the current AuthSession
 * and calls the function above.
 */
void AuthorizationSessionImpl::grantInternalAuthorization(OperationContext* opCtx) {
    grantInternalAuthorization(opCtx->getClient());
}

PrivilegeVector AuthorizationSessionImpl::_getDefaultPrivileges() {
    PrivilegeVector defaultPrivileges;

    // If localhost exception is active (and no users exist),
    // return a vector of the minimum privileges required to bootstrap
    // a system and add the first user.
    if (_externalState->shouldAllowLocalhost()) {
        ResourcePattern adminDBResource = ResourcePattern::forDatabaseName(ADMIN_DBNAME);
        ActionSet setupAdminUserActionSet;
        setupAdminUserActionSet.addAction(ActionType::createUser);
        setupAdminUserActionSet.addAction(ActionType::grantRole);
        Privilege setupAdminUserPrivilege = Privilege(adminDBResource, setupAdminUserActionSet);

        ResourcePattern externalDBResource = ResourcePattern::forDatabaseName("$external");
        Privilege setupExternalUserPrivilege =
            Privilege(externalDBResource, ActionType::createUser);

        ActionSet setupServerConfigActionSet;

        // If this server is an arbiter, add specific privileges meant to circumvent
        // the behavior of an arbiter in an authenticated replset. See SERVER-5479.
        if (_externalState->serverIsArbiter()) {
            setupServerConfigActionSet.addAction(ActionType::getCmdLineOpts);
            setupServerConfigActionSet.addAction(ActionType::getParameter);
            setupServerConfigActionSet.addAction(ActionType::serverStatus);
            setupServerConfigActionSet.addAction(ActionType::shutdown);
        }

        setupServerConfigActionSet.addAction(ActionType::addShard);
        setupServerConfigActionSet.addAction(ActionType::replSetConfigure);
        setupServerConfigActionSet.addAction(ActionType::replSetGetStatus);
        Privilege setupServerConfigPrivilege =
            Privilege(ResourcePattern::forClusterResource(), setupServerConfigActionSet);

        Privilege::addPrivilegeToPrivilegeVector(&defaultPrivileges, setupAdminUserPrivilege);
        Privilege::addPrivilegeToPrivilegeVector(&defaultPrivileges, setupExternalUserPrivilege);
        Privilege::addPrivilegeToPrivilegeVector(&defaultPrivileges, setupServerConfigPrivilege);
        return defaultPrivileges;
    }

    return defaultPrivileges;
}

bool AuthorizationSessionImpl::isAuthorizedToParseNamespaceElement(const BSONElement& element) {
    const bool isUUID = element.type() == BinData && element.binDataType() == BinDataType::newUUID;
    _contract.addAccessCheck(AccessCheckEnum::kIsAuthorizedToParseNamespaceElement);

    uassert(ErrorCodes::InvalidNamespace,
            "Failed to parse namespace element",
            element.type() == String || isUUID);

    if (isUUID) {
        return isAuthorizedForActionsOnResource(ResourcePattern::forClusterResource(),
                                                ActionType::useUUID);
    }

    return true;
}

bool AuthorizationSessionImpl::isAuthorizedToParseNamespaceElement(
    const NamespaceStringOrUUID& nss) {
    _contract.addAccessCheck(AccessCheckEnum::kIsAuthorizedToParseNamespaceElement);

    if (nss.uuid()) {
        return isAuthorizedForActionsOnResource(ResourcePattern::forClusterResource(),
                                                ActionType::useUUID);
    }
    return true;
}

bool AuthorizationSessionImpl::isAuthorizedToCreateRole(const RoleName& roleName) {
    _contract.addAccessCheck(AccessCheckEnum::kIsAuthorizedToCreateRole);

    // A user is allowed to create a role under either of two conditions.

    // The user may create a role if the authorization system says they are allowed to.
    if (isAuthorizedForActionsOnResource(ResourcePattern::forDatabaseName(roleName.getDB()),
                                         ActionType::createRole)) {
        return true;
    }

    // The user may create a role if the localhost exception is enabled, and they already own the
    // role. This implies they have obtained the role through an external authorization mechanism.
    if (_externalState->shouldAllowLocalhost()) {
        for (const auto& user : _authenticatedUsers) {
            if (user->hasRole(roleName)) {
                return true;
            }
        }
        LOGV2(20241,
              "Not authorized to create the first role in the system using the "
              "localhost exception. The user needs to acquire the role through "
              "external authentication first.",
              "role"_attr = roleName);
    }

    return false;
}

bool AuthorizationSessionImpl::isAuthorizedForPrivilege(const Privilege& privilege) {
    if (_externalState->shouldIgnoreAuthChecks())
        return true;

    return _isAuthorizedForPrivilege(privilege);
}

bool AuthorizationSessionImpl::isAuthorizedForPrivileges(const vector<Privilege>& privileges) {
    if (_externalState->shouldIgnoreAuthChecks())
        return true;

    for (size_t i = 0; i < privileges.size(); ++i) {
        if (!_isAuthorizedForPrivilege(privileges[i]))
            return false;
    }

    return true;
}

bool AuthorizationSessionImpl::isAuthorizedForActionsOnResource(const ResourcePattern& resource,
                                                                ActionType action) {
    return isAuthorizedForPrivilege(Privilege(resource, action));
}

bool AuthorizationSessionImpl::isAuthorizedForActionsOnResource(const ResourcePattern& resource,
                                                                const ActionSet& actions) {
    return isAuthorizedForPrivilege(Privilege(resource, actions));
}

bool AuthorizationSessionImpl::isAuthorizedForActionsOnNamespace(const NamespaceString& ns,
                                                                 ActionType action) {
    return isAuthorizedForPrivilege(Privilege(ResourcePattern::forExactNamespace(ns), action));
}

bool AuthorizationSessionImpl::isAuthorizedForActionsOnNamespace(const NamespaceString& ns,
                                                                 const ActionSet& actions) {
    return isAuthorizedForPrivilege(Privilege(ResourcePattern::forExactNamespace(ns), actions));
}

constexpr int resourceSearchListCapacity = 7;
/**
 * Builds from "target" an exhaustive list of all ResourcePatterns that match "target".
 *
 * Some resources are considered to be "normal resources", and are matched by the
 * forAnyNormalResource pattern. Collections which are not prefixed with "system.",
 * and which do not belong inside of the "local" or "config" databases are "normal".
 * Database other than "local" and "config" are normal.
 *
 * Most collections are matched by their database's resource. Collections prefixed with "system."
 * are not. Neither are collections on the "local" database, whose name are prefixed with "replset."
 *
 *
 * Stores the resulting list into resourceSearchList, and returns the length.
 *
 * The seach lists are as follows, depending on the type of "target":
 *
 * target is ResourcePattern::forAnyResource():
 *   searchList = { ResourcePattern::forAnyResource(), ResourcePattern::forAnyResource() }
 * target is the ResourcePattern::forClusterResource():
 *   searchList = { ResourcePattern::forAnyResource(), ResourcePattern::forClusterResource() }
 * target is a database, db:
 *   searchList = { ResourcePattern::forAnyResource(),
 *                  ResourcePattern::forAnyNormalResource(),
 *                  db }
 * target is a non-system collection, db.coll:
 *   searchList = { ResourcePattern::forAnyResource(),
 *                  ResourcePattern::forAnyNormalResource(),
 *                  db,
 *                  coll,
 *                  db.coll }
 * target is a system buckets collection, db.system.buckets.coll:
 *   searchList = { ResourcePattern::forAnyResource(),
 *                  ResourcePattern::forAnySystemBuckets(),
 *                  ResourcePattern::forAnySystemBucketsInDatabase("db"),
 *                  ResourcePattern::forAnySystemBucketsInAnyDatabase("coll"),
 *                  ResourcePattern::forExactSystemBucketsCollection("db", "coll"),
 *                  system.buckets.coll,
 *                  db.system.buckets.coll }
 * target is a system collection, db.system.coll:
 *   searchList = { ResourcePattern::forAnyResource(),
 *                  system.coll,
 *                  db.system.coll }
 */
static int buildResourceSearchList(const ResourcePattern& target,
                                   ResourcePattern resourceSearchList[resourceSearchListCapacity]) {
    int size = 0;
    resourceSearchList[size++] = ResourcePattern::forAnyResource();
    if (target.isExactNamespacePattern()) {
        // Normal collections can be matched by anyNormalResource, or their database's resource.
        if (target.ns().isNormalCollection()) {
            // But even normal collections in non-normal databases should not be matchable with
            // ResourcePattern::forAnyNormalResource. 'local' and 'config' are
            // used to store special system collections, which user level
            // administrators should not be able to manipulate.
            if (target.ns().db() != "local" && target.ns().db() != "config") {
                resourceSearchList[size++] = ResourcePattern::forAnyNormalResource();
            }
            resourceSearchList[size++] = ResourcePattern::forDatabaseName(target.ns().db());
        } else if (target.ns().coll().startsWith(SYSTEM_BUCKETS_PREFIX) &&
                   target.ns().coll().size() > SYSTEM_BUCKETS_PREFIX.size()) {
            auto bucketColl = target.ns().coll().substr(SYSTEM_BUCKETS_PREFIX.size());
            resourceSearchList[size++] =
                ResourcePattern::forExactSystemBucketsCollection(target.ns().db(), bucketColl);
            resourceSearchList[size++] = ResourcePattern::forAnySystemBuckets();
            resourceSearchList[size++] =
                ResourcePattern::forAnySystemBucketsInDatabase(target.ns().db());
            resourceSearchList[size++] =
                ResourcePattern::forAnySystemBucketsInAnyDatabase(bucketColl);
        }

        // All collections can be matched by a collection resource for their name
        resourceSearchList[size++] = ResourcePattern::forCollectionName(target.ns().coll());
    } else if (target.isDatabasePattern()) {
        if (target.ns().db() != "local" && target.ns().db() != "config") {
            resourceSearchList[size++] = ResourcePattern::forAnyNormalResource();
        }
    }
    resourceSearchList[size++] = target;
    dassert(size <= resourceSearchListCapacity);
    return size;
}

bool AuthorizationSessionImpl::isAuthorizedToChangeAsUser(const UserName& userName,
                                                          ActionType actionType) {
    _contract.addAccessCheck(AccessCheckEnum::kIsAuthorizedToChangeAsUser);

    User* user = lookupUser(userName);
    if (!user) {
        return false;
    }
    ResourcePattern resourceSearchList[resourceSearchListCapacity];
    const int resourceSearchListLength = buildResourceSearchList(
        ResourcePattern::forDatabaseName(userName.getDB()), resourceSearchList);

    ActionSet actions;
    for (int i = 0; i < resourceSearchListLength; ++i) {
        actions.addAllActionsFromSet(user->getActionsForResource(resourceSearchList[i]));
    }
    return actions.contains(actionType);
}

StatusWith<PrivilegeVector> AuthorizationSessionImpl::checkAuthorizedToListCollections(
    StringData dbname, const BSONObj& cmdObj) {
    _contract.addAccessCheck(AccessCheckEnum::kCheckAuthorizedToListCollections);

    if (cmdObj["authorizedCollections"].trueValue() && cmdObj["nameOnly"].trueValue() &&
        AuthorizationSessionImpl::isAuthorizedForAnyActionOnAnyResourceInDB(dbname)) {
        return PrivilegeVector();
    }

    // Check for the listCollections ActionType on the database.
    PrivilegeVector privileges = {
        Privilege(ResourcePattern::forDatabaseName(dbname), ActionType::listCollections)};
    if (AuthorizationSessionImpl::isAuthorizedForPrivileges(privileges)) {
        return privileges;
    }

    return Status(ErrorCodes::Unauthorized,
                  str::stream() << "Not authorized to list collections on db: " << dbname);
}

bool AuthorizationSessionImpl::isAuthenticatedAsUserWithRole(const RoleName& roleName) {
    _contract.addAccessCheck(AccessCheckEnum::kIsAuthenticatedAsUserWithRole);

    for (UserSet::iterator it = _authenticatedUsers.begin(); it != _authenticatedUsers.end();
         ++it) {
        if ((*it)->hasRole(roleName)) {
            return true;
        }
    }
    return false;
}

bool AuthorizationSessionImpl::shouldIgnoreAuthChecks() {
    _contract.addAccessCheck(AccessCheckEnum::kShouldIgnoreAuthChecks);

    return _externalState->shouldIgnoreAuthChecks();
}

bool AuthorizationSessionImpl::isAuthenticated() {
    _contract.addAccessCheck(AccessCheckEnum::kIsAuthenticated);

    return _authenticatedUsers.begin() != _authenticatedUsers.end();
}

void AuthorizationSessionImpl::_refreshUserInfoAsNeeded(OperationContext* opCtx) {
    AuthorizationManager& authMan = getAuthorizationManager();
    UserSet::iterator it = _authenticatedUsers.begin();
    auto removeUser = [&](const auto& it) {
        // Take out a lock on the client here to ensure that no one reads while
        // _authenticatedUsers is being modified.
        stdx::lock_guard<Client> lk(*opCtx->getClient());

        // The user is invalid, so make sure that we erase it from _authenticateUsers.
        _authenticatedUsers.removeAt(it);
    };

    auto replaceUser = [&](const auto& it, UserHandle updatedUser) {
        // Take out a lock on the client here to ensure that no one reads while
        // _authenticatedUsers is being modified.
        stdx::lock_guard<Client> lk(*opCtx->getClient());
        _authenticatedUsers.replaceAt(it, std::move(updatedUser));
    };

    while (it != _authenticatedUsers.end()) {
        // Anchor the UserHandle on the stack so we can refer to it throughout this iteration.
        const auto currentUser = *it;
        const auto& name = currentUser->getName();
        auto swUser = authMan.reacquireUser(opCtx, currentUser);
        if (!swUser.isOK()) {
            auto& status = swUser.getStatus();
            // If an external user is no longer in the cache and cannot be acquired from the cache's
            // backing external service, it should be removed from _authenticatedUsers. This
            // guarantees that no operations can be performed until the external authorization
            // provider comes back up.
            if (name.getDB() == "$external"_sd) {
                removeUser(it++);
                LOGV2(5914804,
                      "Removed external user from session cache of user information because of "
                      "error status",
                      "user"_attr = name,
                      "status"_attr = status);
                continue;  // No need to advance "it" in this case.
            }

            switch (status.code()) {
                case ErrorCodes::UserNotFound: {
                    // User does not exist anymore; remove it from _authenticatedUsers.
                    removeUser(it++);
                    LOGV2(20245,
                          "Removed deleted user from session cache of user information",
                          "user"_attr = name);
                    continue;  // No need to advance "it" in this case.
                }
                case ErrorCodes::UnsupportedFormat: {
                    // An auth subsystem has explicitly indicated a failure.
                    removeUser(it++);
                    LOGV2(20246,
                          "Removed user from session cache of user information because of "
                          "refresh failure",
                          "user"_attr = name,
                          "error"_attr = status);
                    continue;  // No need to advance "it" in this case.
                }
                default:
                    // Unrecognized error; assume that it's transient, and continue working with the
                    // out-of-date privilege data.
                    LOGV2_WARNING(20247,
                                  "Could not fetch updated user privilege information for {user}; "
                                  "continuing to use old information. Reason is {error}",
                                  "Could not fetch updated user privilege information, continuing "
                                  "to use old information",
                                  "user"_attr = name,
                                  "error"_attr = redact(status));
                    break;
            }
        } else if (!currentUser.isValid() || currentUser->isInvalidated()) {
            // Our user handle has changed, update the our list of users.
            auto updatedUser = std::move(swUser.getValue());
            try {
                uassertStatusOK(updatedUser->validateRestrictions(opCtx));
            } catch (const DBException& ex) {
                removeUser(it++);

                LOGV2(20242,
                      "Removed user with unmet authentication restrictions from "
                      "session cache of user information. Restriction failed",
                      "user"_attr = name,
                      "reason"_attr = ex.reason());
                continue;  // No need to advance "it" in this case.
            } catch (...) {
                removeUser(it++);

                LOGV2(20243,
                      "Evaluating authentication restrictions for user resulted in an "
                      "unknown exception. Removing user from the session cache",
                      "user"_attr = name);
                continue;  // No need to advance "it" in this case.
            }

            replaceUser(it, std::move(updatedUser));

            LOGV2_DEBUG(
                20244, 1, "Updated session cache of user information for user", "user"_attr = name);
        }

        ++it;
    }
    _updateInternalAuthorizationState();
}

bool AuthorizationSessionImpl::isAuthorizedForAnyActionOnAnyResourceInDB(StringData db) {
    _contract.addAccessCheck(AccessCheckEnum::kIsAuthorizedForAnyActionOnAnyResourceInDB);

    if (_externalState->shouldIgnoreAuthChecks()) {
        return true;
    }

    for (const auto& user : _authenticatedUsers) {
        // First lookup any Privileges on this database specifying Database resources
        if (user->hasActionsForResource(ResourcePattern::forDatabaseName(db))) {
            return true;
        }

        // Any resource will match any collection in the database
        if (user->hasActionsForResource(ResourcePattern::forAnyResource())) {
            return true;
        }

        // Any resource will match any system_buckets collection in the database
        if (user->hasActionsForResource(ResourcePattern::forAnySystemBuckets()) ||
            user->hasActionsForResource(ResourcePattern::forAnySystemBucketsInDatabase(db))) {
            return true;
        }

        // If the user is authorized for anyNormalResource, then they implicitly have access
        // to most databases.
        if (db != "local" && db != "config" &&
            user->hasActionsForResource(ResourcePattern::forAnyNormalResource())) {
            return true;
        }

        // We've checked all the resource types that can be directly expressed. Now we must
        // iterate all privileges, until we see something that could reside in the target database.
        User::ResourcePrivilegeMap map = user->getPrivileges();
        for (const auto& privilege : map) {
            // If the user has a Collection privilege, then they're authorized for this resource
            // on all databases.
            if (privilege.first.isCollectionPattern()) {
                return true;
            }

            // User can see system_buckets in any database so we consider them to have permission in
            // this database
            if (privilege.first.isAnySystemBucketsCollectionInAnyDB()) {
                return true;
            }

            // If the user has an exact namespace privilege on a collection in this database, they
            // have access to a resource in this database.
            if (privilege.first.isExactNamespacePattern() &&
                privilege.first.databaseToMatch() == db) {
                return true;
            }

            // If the user has an exact namespace privilege on a system.buckets collection in this
            // database, they have access to a resource in this database.
            if (privilege.first.isExactSystemBucketsCollection() &&
                privilege.first.databaseToMatch() == db) {
                return true;
            }
        }
    }

    return false;
}

bool AuthorizationSessionImpl::isAuthorizedForAnyActionOnResource(const ResourcePattern& resource) {
    _contract.addAccessCheck(AccessCheckEnum::kIsAuthorizedForAnyActionOnResource);

    if (_externalState->shouldIgnoreAuthChecks()) {
        return true;
    }

    std::array<ResourcePattern, resourceSearchListCapacity> resourceSearchList;
    const int resourceSearchListLength =
        buildResourceSearchList(resource, resourceSearchList.data());

    for (int i = 0; i < resourceSearchListLength; ++i) {
        for (const auto& user : _authenticatedUsers) {
            if (user->hasActionsForResource(resourceSearchList[i])) {
                return true;
            }
        }
    }

    return false;
}


bool AuthorizationSessionImpl::_isAuthorizedForPrivilege(const Privilege& privilege) {
    _contract.addPrivilege(privilege);

    const ResourcePattern& target(privilege.getResourcePattern());

    ResourcePattern resourceSearchList[resourceSearchListCapacity];
    const int resourceSearchListLength = buildResourceSearchList(target, resourceSearchList);

    ActionSet unmetRequirements = privilege.getActions();

    PrivilegeVector defaultPrivileges = _getDefaultPrivileges();
    for (PrivilegeVector::iterator it = defaultPrivileges.begin(); it != defaultPrivileges.end();
         ++it) {
        for (int i = 0; i < resourceSearchListLength; ++i) {
            if (!(it->getResourcePattern() == resourceSearchList[i]))
                continue;

            ActionSet userActions = it->getActions();
            unmetRequirements.removeAllActionsFromSet(userActions);

            if (unmetRequirements.empty())
                return true;
        }
    }

    for (const auto& user : _authenticatedUsers) {
        for (int i = 0; i < resourceSearchListLength; ++i) {
            ActionSet userActions = user->getActionsForResource(resourceSearchList[i]);
            unmetRequirements.removeAllActionsFromSet(userActions);

            if (unmetRequirements.empty()) {
                return true;
            }
        }
    }

    return false;
}

void AuthorizationSessionImpl::setImpersonatedUserData(const std::vector<UserName>& usernames,
                                                       const std::vector<RoleName>& roles) {
    _impersonatedUserNames = usernames;
    _impersonatedRoleNames = roles;
    _impersonationFlag = true;
}

bool AuthorizationSessionImpl::isCoauthorizedWithClient(Client* opClient, WithLock opClientLock) {
    _contract.addAccessCheck(AccessCheckEnum::kIsCoauthorizedWithClient);
    auto getUserNames = [](AuthorizationSession* authSession) {
        if (authSession->isImpersonating()) {
            return authSession->getImpersonatedUserNames();
        } else {
            return authSession->getAuthenticatedUserNames();
        }
    };

    UserNameIterator it = getUserNames(this);
    while (it.more()) {
        UserNameIterator opIt = getUserNames(AuthorizationSession::get(opClient));
        while (opIt.more()) {
            if (it.get() == opIt.get()) {
                return true;
            }
            opIt.next();
        }
        it.next();
    }

    return false;
}

bool AuthorizationSessionImpl::isCoauthorizedWith(UserNameIterator userNameIter) {
    _contract.addAccessCheck(AccessCheckEnum::kIsCoauthorizedWith);
    if (!getAuthorizationManager().isAuthEnabled()) {
        return true;
    }

    if (!userNameIter.more() && !isAuthenticated()) {
        return true;
    }

    for (; userNameIter.more(); userNameIter.next()) {
        for (UserNameIterator thisUserNameIter = getAuthenticatedUserNames();
             thisUserNameIter.more();
             thisUserNameIter.next()) {
            if (*userNameIter == *thisUserNameIter) {
                return true;
            }
        }
    }

    return false;
}

UserNameIterator AuthorizationSessionImpl::getImpersonatedUserNames() {
    _contract.addAccessCheck(AccessCheckEnum::kGetImpersonatedUserNames);

    return makeUserNameIterator(_impersonatedUserNames.begin(), _impersonatedUserNames.end());
}

RoleNameIterator AuthorizationSessionImpl::getImpersonatedRoleNames() {
    _contract.addAccessCheck(AccessCheckEnum::kGetImpersonatedRoleNames);

    return makeRoleNameIterator(_impersonatedRoleNames.begin(), _impersonatedRoleNames.end());
}

bool AuthorizationSessionImpl::isUsingLocalhostBypass() {
    _contract.addAccessCheck(AccessCheckEnum::kIsUsingLocalhostBypass);

    return getAuthorizationManager().isAuthEnabled() && _externalState->shouldAllowLocalhost();
}

// Clear the vectors of impersonated usernames and roles.
void AuthorizationSessionImpl::clearImpersonatedUserData() {
    _impersonatedUserNames.clear();
    _impersonatedRoleNames.clear();
    _impersonationFlag = false;
}


bool AuthorizationSessionImpl::isImpersonating() const {
    return _impersonationFlag;
}

auto AuthorizationSessionImpl::checkCursorSessionPrivilege(
    OperationContext* const opCtx, const boost::optional<LogicalSessionId> cursorSessionId)
    -> Status {
    _contract.addAccessCheck(AccessCheckEnum::kCheckCursorSessionPrivilege);

    auto nobodyIsLoggedIn = [authSession = this] { return !authSession->isAuthenticated(); };

    auto authHasImpersonatePrivilege = [authSession = this] {
        return authSession->isAuthorizedForPrivilege(
            Privilege(ResourcePattern::forClusterResource(), ActionType::impersonate));
    };

    auto authIsOn = [authSession = this] {
        return authSession->getAuthorizationManager().isAuthEnabled();
    };

    auto sessionIdToStringOrNone =
        [](const boost::optional<LogicalSessionId>& sessionId) -> std::string {
        if (sessionId) {
            return str::stream() << *sessionId;
        }
        return "none";
    };

    // If the cursor has a session then one of the following must be true:
    // 1: context session id must match cursor session id.
    // 2: user must be magic special (__system, or background task, etc).

    // We do not check the user's ID against the cursor's notion of a user ID, since higher level
    // auth checks will check that for us anyhow.
    if (authIsOn() &&  // If the authorization is not on, then we permit anybody to do anything.
        cursorSessionId != opCtx->getLogicalSessionId() &&  // If the cursor's session doesn't match
                                                            // the Operation Context's session, then
                                                            // we should forbid the operation even
                                                            // when the cursor has no session.
        !nobodyIsLoggedIn() &&          // Unless, for some reason a user isn't actually using this
                                        // Operation Context (which implies a background job
        !authHasImpersonatePrivilege()  // Or if the user has an impersonation privilege, in which
                                        // case, the user gets to sidestep certain checks.
    ) {
        return Status{ErrorCodes::Unauthorized,
                      str::stream()
                          << "Cursor session id (" << sessionIdToStringOrNone(cursorSessionId)
                          << ") is not the same as the operation context's session id ("
                          << sessionIdToStringOrNone(opCtx->getLogicalSessionId()) << ")"};
    }

    return Status::OK();
}

void AuthorizationSessionImpl::verifyContract(const AuthorizationContract* contract) const {
    if (contract == nullptr) {
        return;
    }

    if (!checkContracts()) {
        return;
    }

    // Make a mutable copy so that the common auth checks can be added.
    auto tempContract = *contract;

    // Certain access checks are done by code common to all commands.
    //
    // The first two checks are done by initializeOperationSessionInfo
    tempContract.addAccessCheck(AccessCheckEnum::kIsUsingLocalhostBypass);
    tempContract.addAccessCheck(AccessCheckEnum::kIsAuthenticated);

    // These checks are done by auditing
    tempContract.addAccessCheck(AccessCheckEnum::kGetAuthenticatedRoleNames);
    tempContract.addAccessCheck(AccessCheckEnum::kGetAuthenticatedUserNames);
    tempContract.addAccessCheck(AccessCheckEnum::kGetImpersonatedUserNames);
    tempContract.addAccessCheck(AccessCheckEnum::kGetImpersonatedRoleNames);

    // Since internal sessions are started by the server, the generated authorization contract is
    // missing the following user access checks, so we add them here to allow commands that spawn
    // internal sessions to pass this authorization check.
    tempContract.addAccessCheck(AccessCheckEnum::kGetSingleUser);
    tempContract.addAccessCheck(AccessCheckEnum::kLookupUser);

    // "internal" comes from readRequestMetadata and sharded clusters
    // "advanceClusterTime" is an implicit check in clusters in metadata handling
    tempContract.addPrivilege(Privilege(ResourcePattern::forClusterResource(),
                                        {ActionType::advanceClusterTime, ActionType::internal}));

    // Implicitly checked often to keep mayBypassWriteBlockingMode() fast
    tempContract.addPrivilege(kBypassWriteBlockingModeOnClusterPrivilege);

    uassert(5452401,
            "Authorization Session contains more authorization checks then permitted by contract.",
            tempContract.contains(_contract));
}

void AuthorizationSessionImpl::_updateInternalAuthorizationState() {
    // Update the authenticated role names vector to reflect current state.
    _authenticatedRoleNames.clear();
    for (const auto& userHandle : _authenticatedUsers) {
        RoleNameIterator roles = userHandle->getIndirectRoles();
        while (roles.more()) {
            RoleName roleName = roles.next();
            _authenticatedRoleNames.push_back(RoleName(roleName.getRole(), roleName.getDB()));
        }
    }

    if (_authenticatedUsers.count() == 0) {
        _authenticationMode = AuthenticationMode::kNone;
    }

    // Update cached _mayBypassWriteBlockingMode to reflect current state.
    _mayBypassWriteBlockingMode =
        _isAuthorizedForPrivilege(kBypassWriteBlockingModeOnClusterPrivilege);
}

bool AuthorizationSessionImpl::mayBypassWriteBlockingMode() const {
    return MONGO_unlikely(_mayBypassWriteBlockingMode);
}

}  // namespace mongo