summaryrefslogtreecommitdiff
path: root/src/mongo/db/auth/umc_info_command_arg.h
blob: e97bade41ed3d23ee8caa8787ede7c70e33134fd (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
/**
 *    Copyright (C) 2020-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 <string>

#include "mongo/base/string_data.h"
#include "mongo/bson/bsonelement.h"
#include "mongo/bson/bsonobjbuilder.h"
#include "mongo/db/auth/role_name.h"
#include "mongo/db/auth/user_name.h"
#include "mongo/stdx/variant.h"

namespace mongo {
namespace auth {

/**
 * Wraps the usersInfo and rolesInfo command args.
 *
 * These commands accept the following formats:
 *  {....sInfo: 1} // All users on the current DB.
 *  {usersInfo: {forAllDBs: 1}} // All users on all DBs. (usersInfo only)
 *
 *  {....sInfo: 'alice'} // Specific user on current DB.
 *  {....sInfo: {db: 'test', user: 'alice'} // Specific user on specific DB.
 *  {....sInfo: [stringOrDoc]} // Set of users (using above two formats)
 *
 * Use isAllOnCurrentDB(), isAllForAllDBs(), and isExact() to determine format.
 * Then use getElements(dbname) for isExact() form to get list of T names.
 */
template <typename T, bool enableForAllDBs>
class UMCInfoCommandArg {
public:
    UMCInfoCommandArg() : UMCInfoCommandArg(AllOnCurrentDB{}) {}
    static_assert(std::is_same<UserName, T>::value || std::is_same<RoleName, T>::value,
                  "UMCInfoCommandArg only valid with T = UserName | RoleName");

    static UMCInfoCommandArg parseFromBSON(const BSONElement& elem) {
        if (elem.numberInt() == 1) {
            return UMCInfoCommandArg(AllOnCurrentDB{});
        }
        if (enableForAllDBs && (elem.type() == Object) && (elem.Obj()[kForAllDBs].trueValue())) {
            return UMCInfoCommandArg(AllForAllDBs{});
        }

        if (elem.type() == Array) {
            Multiple values;
            for (const auto& v : elem.Obj()) {
                values.push_back(parseNamedElement(v));
            }
            return UMCInfoCommandArg(std::move(values));
        }

        return UMCInfoCommandArg(parseNamedElement(elem));
    }

    void serializeToBSON(StringData fieldName, BSONObjBuilder* bob) const {
        if (stdx::holds_alternative<AllOnCurrentDB>(_value)) {
            bob->append(fieldName, 1);
        } else if (stdx::holds_alternative<AllForAllDBs>(_value)) {
            bob->append(fieldName, BSON(kForAllDBs << 1));
        } else if (stdx::holds_alternative<Single>(_value)) {
            serializeSingle(fieldName, bob, stdx::get<Single>(_value));
        } else {
            invariant(stdx::holds_alternative<Multiple>(_value));
            const auto& elems = stdx::get<Multiple>(_value);
            BSONArrayBuilder setBuilder(bob->subarrayStart(fieldName));
            for (const auto& elem : elems) {
                serializeSingle(&setBuilder, elem);
            }
            setBuilder.doneFast();
        }
    }

    void serializeToBSON(BSONArrayBuilder* bob) const {
        // Minimize code duplication by using object serialization path.
        // In practice, we don't use this API, it only exists for IDL completeness.
        BSONObjBuilder tmp;
        serializeToBSON("", &tmp);
        auto elem = tmp.obj();
        bob->append(elem.firstElement());
    }

    /**
     * {usersInfo: 1}
     */
    bool isAllOnCurrentDB() const {
        return stdx::holds_alternative<AllOnCurrentDB>(_value);
    }

    /**
     * {usersInfo: {forrAllDBs: 1}}
     */
    bool isAllForAllDBs() const {
        return stdx::holds_alternative<AllForAllDBs>(_value);
    }

    /**
     * {usersInfo: 'string' | {db,user|role} | [...] }
     */
    bool isExact() const {
        return stdx::holds_alternative<Single>(_value) || stdx::holds_alternative<Multiple>(_value);
    }

    /**
     * For isExact() commands, returns a set of T with unspecified DB names resolved with $dbname.
     */
    std::vector<T> getElements(StringData dbname) const {
        if (!isExact()) {
            dassert(false);
            uasserted(ErrorCodes::InternalError, "Unable to get exact match for wildcard query");
        }

        if (stdx::holds_alternative<Single>(_value)) {
            return {getElement(stdx::get<Single>(_value), dbname)};
        } else {
            invariant(stdx::holds_alternative<Multiple>(_value));
            const auto& values = stdx::get<Multiple>(_value);
            std::vector<T> ret;
            std::transform(values.cbegin(),
                           values.cend(),
                           std::back_inserter(ret),
                           [dbname](const auto& value) { return getElement(value, dbname); });
            return ret;
        }
    }

private:
    static constexpr StringData kForAllDBs = "forAllDBs"_sd;

    struct AllOnCurrentDB {};
    struct AllForAllDBs {};
    using Single = stdx::variant<T, std::string>;
    using Multiple = std::vector<Single>;

    explicit UMCInfoCommandArg(AllOnCurrentDB opt) : _value(std::move(opt)) {}
    explicit UMCInfoCommandArg(AllForAllDBs opt) : _value(std::move(opt)) {}
    explicit UMCInfoCommandArg(Single value) : _value(std::move(value)) {}
    explicit UMCInfoCommandArg(Multiple values) : _value(std::move(values)) {}

    static Single parseNamedElement(const BSONElement& elem) {
        if (elem.type() == String) {
            return elem.String();
        }
        return T::parseFromBSON(elem);
    }

    static void serializeSingle(StringData fieldName, BSONObjBuilder* builder, Single elem) {
        if (stdx::holds_alternative<T>(elem)) {
            builder->append(fieldName, stdx::get<T>(elem).toBSON());
        } else {
            invariant(stdx::holds_alternative<std::string>(elem));
            builder->append(fieldName, stdx::get<std::string>(elem));
        }
    }

    static void serializeSingle(BSONArrayBuilder* builder, Single elem) {
        if (stdx::holds_alternative<T>(elem)) {
            builder->append(stdx::get<T>(elem).toBSON());
        } else {
            invariant(stdx::holds_alternative<std::string>(elem));
            builder->append(stdx::get<std::string>(elem));
        }
    }

    static T getElement(Single elem, StringData dbname) {
        if (stdx::holds_alternative<T>(elem)) {
            return stdx::get<T>(elem);
        } else {
            invariant(stdx::holds_alternative<std::string>(elem));
            return T(stdx::get<std::string>(elem), dbname);
        }
    }

    // Single is stored as a distinct type from Multiple
    // to ensure that reserialization maintains the same level of nesting.
    stdx::variant<AllOnCurrentDB, AllForAllDBs, Single, Multiple> _value;
};

using UsersInfoCommandArg = UMCInfoCommandArg<UserName, true>;
using RolesInfoCommandArg = UMCInfoCommandArg<RoleName, false>;

}  // namespace auth
}  // namespace mongo