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
|
/**
* 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.
*/
#define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kCommand
#include "mongo/platform/basic.h"
#include "mongo/bson/mutable/algorithm.h"
#include "mongo/bson/mutable/document.h"
#include "mongo/db/auth/action_set.h"
#include "mongo/db/auth/action_type.h"
#include "mongo/db/auth/authorization_session.h"
#include "mongo/db/auth/privilege.h"
#include "mongo/db/commands.h"
#include "mongo/db/commands/copydb.h"
#include "mongo/db/commands/rename_collection.h"
#include "mongo/executor/task_executor_pool.h"
#include "mongo/rpc/get_status_from_command_result.h"
#include "mongo/s/commands/cluster_commands_helpers.h"
#include "mongo/s/commands/cluster_explain.h"
#include "mongo/s/grid.h"
#include "mongo/s/query/store_possible_cursor.h"
#include "mongo/util/log.h"
#include "mongo/util/timer.h"
namespace mongo {
namespace {
bool cursorCommandPassthrough(OperationContext* opCtx,
StringData dbName,
const CachedDatabaseInfo& dbInfo,
const BSONObj& cmdObj,
const NamespaceString& nss,
BSONObjBuilder* out) {
auto response = executeCommandAgainstDatabasePrimary(
opCtx,
dbName,
dbInfo,
CommandHelpers::filterCommandRequestForPassthrough(cmdObj),
ReadPreferenceSetting::get(opCtx),
Shard::RetryPolicy::kIdempotent);
const auto cmdResponse = uassertStatusOK(std::move(response.swResponse));
auto transformedResponse = uassertStatusOK(
storePossibleCursor(opCtx,
dbInfo.primaryId(),
*response.shardHostAndPort,
cmdResponse.data,
nss,
Grid::get(opCtx)->getExecutorPool()->getArbitraryExecutor(),
Grid::get(opCtx)->getCursorManager()));
CommandHelpers::filterCommandReplyForPassthrough(transformedResponse, out);
return true;
}
bool nonShardedCollectionCommandPassthrough(OperationContext* opCtx,
StringData dbName,
const NamespaceString& nss,
const CachedCollectionRoutingInfo& routingInfo,
const BSONObj& cmdObj,
Shard::RetryPolicy retryPolicy,
BSONObjBuilder* out) {
const StringData cmdName(cmdObj.firstElementFieldName());
uassert(ErrorCodes::IllegalOperation,
str::stream() << "Can't do command: " << cmdName << " on a sharded collection",
!routingInfo.cm());
auto responses = scatterGatherVersionedTargetByRoutingTable(opCtx,
dbName,
nss,
routingInfo,
cmdObj,
ReadPreferenceSetting::get(opCtx),
retryPolicy,
{},
{});
invariant(responses.size() == 1);
const auto cmdResponse = uassertStatusOK(std::move(responses.front().swResponse));
const auto status = getStatusFromCommandResult(cmdResponse.data);
uassert(ErrorCodes::IllegalOperation,
str::stream() << "Can't do command: " << cmdName << " on a sharded collection",
!status.isA<ErrorCategory::StaleShardVersionError>());
out->appendElementsUnique(CommandHelpers::filterCommandReplyForPassthrough(cmdResponse.data));
return status.isOK();
}
class NotAllowedOnShardedCollectionCmd : public BasicCommand {
protected:
NotAllowedOnShardedCollectionCmd(const char* n) : BasicCommand(n) {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kAlways;
}
bool run(OperationContext* opCtx,
const std::string& dbName,
const BSONObj& cmdObj,
BSONObjBuilder& result) override {
const NamespaceString nss(parseNs(dbName, cmdObj));
const auto routingInfo =
uassertStatusOK(Grid::get(opCtx)->catalogCache()->getCollectionRoutingInfo(opCtx, nss));
uassert(ErrorCodes::IllegalOperation,
str::stream() << "can't do command: " << getName() << " on sharded collection",
!routingInfo.cm());
const auto primaryShard = routingInfo.db().primary();
// Here, we first filter the command before appending an UNSHARDED shardVersion, because
// "shardVersion" is one of the fields that gets filtered out.
BSONObj filteredCmdObj(CommandHelpers::filterCommandRequestForPassthrough(cmdObj));
BSONObj filteredCmdObjWithVersion(
appendShardVersion(filteredCmdObj, ChunkVersion::UNSHARDED()));
auto commandResponse = uassertStatusOK(primaryShard->runCommandWithFixedRetryAttempts(
opCtx,
ReadPreferenceSetting::get(opCtx),
dbName,
primaryShard->isConfig() ? filteredCmdObj : filteredCmdObjWithVersion,
Shard::RetryPolicy::kIdempotent));
uassert(ErrorCodes::IllegalOperation,
str::stream() << "can't do command: " << getName() << " on a sharded collection",
!ErrorCodes::isStaleShardVersionError(commandResponse.commandStatus.code()));
uassertStatusOK(commandResponse.commandStatus);
if (!commandResponse.writeConcernStatus.isOK()) {
appendWriteConcernErrorToCmdResponse(
primaryShard->getId(), commandResponse.response["writeConcernError"], result);
}
result.appendElementsUnique(
CommandHelpers::filterCommandReplyForPassthrough(std::move(commandResponse.response)));
return true;
}
};
class RenameCollectionCmd : public BasicCommand {
public:
RenameCollectionCmd() : BasicCommand("renameCollection") {}
std::string parseNs(const std::string& dbname, const BSONObj& cmdObj) const override {
return CommandHelpers::parseNsFullyQualified(cmdObj);
}
bool adminOnly() const override {
return true;
}
bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const override {
return rename_collection::checkAuthForRenameCollectionCommand(client, dbname, cmdObj);
}
bool run(OperationContext* opCtx,
const std::string& dbName,
const BSONObj& cmdObj,
BSONObjBuilder& result) override {
const NamespaceString fromNss(parseNs(dbName, cmdObj));
const NamespaceString toNss([&cmdObj] {
const auto fullnsToElt = cmdObj["to"];
uassert(ErrorCodes::InvalidNamespace,
"'to' must be of type String",
fullnsToElt.type() == BSONType::String);
return fullnsToElt.valueStringData();
}());
uassert(ErrorCodes::InvalidNamespace,
str::stream() << "Invalid target namespace: " << toNss.ns(),
toNss.isValid());
const auto fromRoutingInfo = uassertStatusOK(
Grid::get(opCtx)->catalogCache()->getCollectionRoutingInfo(opCtx, fromNss));
uassert(13138, "You can't rename a sharded collection", !fromRoutingInfo.cm());
const auto toRoutingInfo = uassertStatusOK(
Grid::get(opCtx)->catalogCache()->getCollectionRoutingInfo(opCtx, toNss));
uassert(13139, "You can't rename to a sharded collection", !toRoutingInfo.cm());
uassert(13137,
"Source and destination collections must be on same shard",
fromRoutingInfo.db().primaryId() == toRoutingInfo.db().primaryId());
return nonShardedCollectionCommandPassthrough(
opCtx,
NamespaceString::kAdminDb,
fromNss,
fromRoutingInfo,
appendAllowImplicitCreate(CommandHelpers::filterCommandRequestForPassthrough(cmdObj),
true),
Shard::RetryPolicy::kNoRetry,
&result);
}
} renameCollectionCmd;
class CopyDBCmd : public BasicCommand {
public:
CopyDBCmd() : BasicCommand("copydb") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
bool adminOnly() const override {
return true;
}
Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const override {
return copydb::checkAuthForCopydbCommand(client, dbname, cmdObj);
}
bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
bool run(OperationContext* opCtx,
const std::string& dbName,
const BSONObj& cmdObj,
BSONObjBuilder& result) override {
const auto todbElt = cmdObj["todb"];
uassert(ErrorCodes::InvalidNamespace,
"'todb' must be of type String",
todbElt.type() == BSONType::String);
const std::string todb = todbElt.str();
uassert(ErrorCodes::InvalidNamespace,
"Invalid todb argument",
NamespaceString::validDBName(todb, NamespaceString::DollarInDbNameBehavior::Allow));
auto toDbInfo = uassertStatusOK(createShardDatabase(opCtx, todb));
uassert(ErrorCodes::IllegalOperation,
"Cannot copy to a sharded database",
!toDbInfo.shardingEnabled());
const auto copyDbCmdObj = cmdObj["fromhost"] ? cmdObj : [&] {
const auto fromDbElt = cmdObj["fromdb"];
uassert(ErrorCodes::InvalidNamespace,
"'fromdb' must be of type String",
fromDbElt.type() == BSONType::String);
const std::string fromdb = fromDbElt.str();
uassert(ErrorCodes::InvalidNamespace,
"invalid fromdb argument",
NamespaceString::validDBName(fromdb,
NamespaceString::DollarInDbNameBehavior::Allow));
auto fromDbInfo = uassertStatusOK(createShardDatabase(opCtx, fromdb));
uassert(ErrorCodes::IllegalOperation,
"Cannot copy from a sharded database",
!fromDbInfo.shardingEnabled());
// If the source and destination are the same, there is no need to attach the 'fromhost'
// field since the copy is entirely local to the node
if (fromDbInfo.primaryId() == toDbInfo.primaryId()) {
return cmdObj;
}
BSONObjBuilder copyDbCmdObjBuilder;
// Copy everything but the "fromhost" parameter
BSONForEach(e, cmdObj) {
if (strcmp(e.fieldName(), "fromhost")) {
copyDbCmdObjBuilder.append(e);
}
}
// Append "fromhost" as the database's primary
{
const auto shard = uassertStatusOK(
Grid::get(opCtx)->shardRegistry()->getShard(opCtx, fromDbInfo.primaryId()));
copyDbCmdObjBuilder.append("fromhost", shard->getConnString().toString());
}
return copyDbCmdObjBuilder.obj();
}();
// copyDb creates multiple collections and should handle collection creation differently
auto response = executeCommandAgainstDatabasePrimary(
opCtx,
NamespaceString::kAdminDb,
toDbInfo,
appendAllowImplicitCreate(
CommandHelpers::filterCommandRequestForPassthrough(copyDbCmdObj), true),
ReadPreferenceSetting(ReadPreference::PrimaryOnly),
Shard::RetryPolicy::kNoRetry);
const auto cmdResponse = uassertStatusOK(std::move(response.swResponse));
const auto status = getStatusFromCommandResult(cmdResponse.data);
result.appendElementsUnique(
CommandHelpers::filterCommandReplyForPassthrough(cmdResponse.data));
return status.isOK();
}
} clusterCopyDBCmd;
class ConvertToCappedCmd : public BasicCommand {
public:
ConvertToCappedCmd() : BasicCommand("convertToCapped") {}
bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
std::string parseNs(const std::string& dbname, const BSONObj& cmdObj) const override {
return CommandHelpers::parseNsCollectionRequired(dbname, cmdObj).ns();
}
void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) const override {
ActionSet actions;
actions.addAction(ActionType::convertToCapped);
out->push_back(Privilege(parseResourcePattern(dbname, cmdObj), actions));
}
bool run(OperationContext* opCtx,
const std::string& dbName,
const BSONObj& cmdObj,
BSONObjBuilder& result) override {
const NamespaceString nss(parseNs(dbName, cmdObj));
const auto routingInfo =
uassertStatusOK(Grid::get(opCtx)->catalogCache()->getCollectionRoutingInfo(opCtx, nss));
uassert(ErrorCodes::IllegalOperation,
"You can't convertToCapped a sharded collection",
!routingInfo.cm());
// convertToCapped creates a temp collection and renames it at the end. It will require
// special handling for create collection.
return nonShardedCollectionCommandPassthrough(
opCtx,
dbName,
nss,
routingInfo,
appendAllowImplicitCreate(CommandHelpers::filterCommandRequestForPassthrough(cmdObj),
true),
Shard::RetryPolicy::kIdempotent,
&result);
}
} convertToCappedCmd;
class GroupCmd : public NotAllowedOnShardedCollectionCmd {
public:
GroupCmd() : NotAllowedOnShardedCollectionCmd("group") {}
bool supportsWriteConcern(const BSONObj& cmd) const override {
return false;
}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kAlways;
}
std::string parseNs(const std::string& dbname, const BSONObj& cmdObj) const override {
const auto nsElt = cmdObj.firstElement().embeddedObjectUserCheck()["ns"];
uassert(ErrorCodes::InvalidNamespace,
"'ns' must be of type String",
nsElt.type() == BSONType::String);
const NamespaceString nss(dbname, nsElt.valueStringData());
uassert(ErrorCodes::InvalidNamespace,
str::stream() << "Invalid namespace: " << nss.ns(),
nss.isValid());
return nss.ns();
}
void addRequiredPrivileges(const std::string& dbname,
const BSONObj& cmdObj,
std::vector<Privilege>* out) const override {
ActionSet actions;
actions.addAction(ActionType::find);
out->push_back(Privilege(parseResourcePattern(dbname, cmdObj), actions));
}
Status explain(OperationContext* opCtx,
const OpMsgRequest& request,
ExplainOptions::Verbosity verbosity,
BSONObjBuilder* out) const override {
const auto dbName = request.getDatabase();
const auto& cmdObj = request.body;
const NamespaceString nss(parseNs(dbName.toString(), cmdObj));
Timer timer;
const auto explainCommand = ClusterExplain::wrapAsExplain(cmdObj, verbosity);
auto routingInfo =
uassertStatusOK(Grid::get(opCtx)->catalogCache()->getCollectionRoutingInfo(opCtx, nss));
BSONObjBuilder result;
if (!nonShardedCollectionCommandPassthrough(opCtx,
dbName,
nss,
routingInfo,
explainCommand,
Shard::RetryPolicy::kIdempotent,
&result)) {
return getStatusFromCommandResult(result.done());
}
Strategy::CommandResult cmdResult;
cmdResult.shardTargetId = routingInfo.db().primaryId();
cmdResult.result = result.done();
cmdResult.target = routingInfo.db().primary()->getConnString();
return ClusterExplain::buildExplainResult(
opCtx, {cmdResult}, ClusterExplain::kSingleShard, timer.millis(), out);
}
} groupCmd;
class SplitVectorCmd : public NotAllowedOnShardedCollectionCmd {
public:
SplitVectorCmd() : NotAllowedOnShardedCollectionCmd("splitVector") {}
std::string parseNs(const std::string& dbname, const BSONObj& cmdObj) const override {
return CommandHelpers::parseNsFullyQualified(cmdObj);
}
bool supportsWriteConcern(const BSONObj& cmd) const override {
return false;
}
Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const override {
if (!AuthorizationSession::get(client)->isAuthorizedForActionsOnResource(
ResourcePattern::forExactNamespace(NamespaceString(parseNs(dbname, cmdObj))),
ActionType::splitVector)) {
return Status(ErrorCodes::Unauthorized, "Unauthorized");
}
return Status::OK();
}
bool run(OperationContext* opCtx,
const std::string& dbName,
const BSONObj& cmdObj,
BSONObjBuilder& result) override {
const NamespaceString nss(parseNs(dbName, cmdObj));
uassert(ErrorCodes::IllegalOperation,
"Performing splitVector across dbs isn't supported via mongos",
nss.db() == dbName);
return NotAllowedOnShardedCollectionCmd::run(opCtx, dbName, cmdObj, result);
}
} splitVectorCmd;
class CmdListCollections : public BasicCommand {
public:
CmdListCollections() : BasicCommand("listCollections") {}
bool supportsWriteConcern(const BSONObj& cmd) const override {
return false;
}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kAlways;
}
bool adminOnly() const override {
return false;
}
Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const final {
AuthorizationSession* authzSession = AuthorizationSession::get(client);
if (authzSession->isAuthorizedToListCollections(dbname, cmdObj)) {
return Status::OK();
}
return Status(ErrorCodes::Unauthorized,
str::stream() << "Not authorized to list collections on db: " << dbname);
}
BSONObj rewriteCommandForListingOwnCollections(OperationContext* opCtx,
const std::string& dbName,
const BSONObj& cmdObj) {
mutablebson::Document rewrittenCmdObj(cmdObj);
mutablebson::Element ownCollections =
mutablebson::findFirstChildNamed(rewrittenCmdObj.root(), "authorizedCollections");
AuthorizationSession* authzSession = AuthorizationSession::get(opCtx->getClient());
// We must strip $ownCollections from the delegated command.
uassertStatusOK(ownCollections.remove());
BSONObj collectionFilter;
// Extract and retain any previous filter
mutablebson::Element oldFilter =
mutablebson::findFirstChildNamed(rewrittenCmdObj.root(), "filter");
// Make a new filter, containing a $and array.
mutablebson::Element newFilter = rewrittenCmdObj.makeElementObject("filter");
mutablebson::Element newFilterAnd = rewrittenCmdObj.makeElementArray("$and");
uassertStatusOK(newFilter.pushBack(newFilterAnd));
mutablebson::Element newFilterOr = rewrittenCmdObj.makeElementArray("$or");
mutablebson::Element newFilterOrObj = rewrittenCmdObj.makeElementObject("");
uassertStatusOK(newFilterOrObj.pushBack(newFilterOr));
uassertStatusOK(newFilterAnd.pushBack(newFilterOrObj));
// DB resource grants all non-system collections, so filter out system collections.
// This is done inside the $or, since some system collections might be granted specific
// privileges.
if (authzSession->isAuthorizedForAnyActionOnResource(
ResourcePattern::forDatabaseName(dbName))) {
mutablebson::Element systemCollectionsFilter = rewrittenCmdObj.makeElementObject(
"", BSON("name" << BSON("$regex" << BSONRegEx("^(?!system\\.)"))));
uassertStatusOK(newFilterOr.pushBack(systemCollectionsFilter));
}
// Compute the set of collection names which would be permissible to return.
std::set<std::string> collectionNames;
for (UserNameIterator nameIter = authzSession->getAuthenticatedUserNames(); nameIter.more();
nameIter.next()) {
User* authUser = authzSession->lookupUser(*nameIter);
const User::ResourcePrivilegeMap& resourcePrivilegeMap = authUser->getPrivileges();
for (const std::pair<ResourcePattern, Privilege>& resourcePrivilege :
resourcePrivilegeMap) {
const auto& resource = resourcePrivilege.first;
if (resource.isCollectionPattern() ||
(resource.isExactNamespacePattern() && resource.databaseToMatch() == dbName)) {
collectionNames.emplace(resource.collectionToMatch().toString());
}
}
}
// Construct a new filter predicate which returns only collections we were found to
// have privileges for.
BSONObjBuilder predicateBuilder;
BSONObjBuilder nameBuilder(predicateBuilder.subobjStart("name"));
BSONArrayBuilder setBuilder(nameBuilder.subarrayStart("$in"));
// Load the de-duplicated set into a BSON array
for (StringData collectionName : collectionNames) {
setBuilder << collectionName;
}
setBuilder.done();
nameBuilder.done();
collectionFilter = predicateBuilder.obj();
// Filter the results by our collection names.
mutablebson::Element newFilterCollections =
rewrittenCmdObj.makeElementObject("", collectionFilter);
uassertStatusOK(newFilterOr.pushBack(newFilterCollections));
// If there was a pre-existing filter, compose it with our new one.
if (oldFilter.ok()) {
uassertStatusOK(oldFilter.remove());
uassertStatusOK(newFilterAnd.pushBack(oldFilter));
}
// Attach our new composite filter back onto the listCollections command object.
uassertStatusOK(rewrittenCmdObj.root().pushBack(newFilter));
return rewrittenCmdObj.getObject();
}
bool run(OperationContext* opCtx,
const std::string& dbName,
const BSONObj& cmdObj,
BSONObjBuilder& result) override {
const auto nss(NamespaceString::makeListCollectionsNSS(dbName));
BSONObj newCmd = cmdObj;
AuthorizationSession* authzSession = AuthorizationSession::get(opCtx->getClient());
if (authzSession->getAuthorizationManager().isAuthEnabled() &&
newCmd["authorizedCollections"].trueValue()) {
newCmd = rewriteCommandForListingOwnCollections(opCtx, dbName, cmdObj);
}
auto dbInfoStatus = Grid::get(opCtx)->catalogCache()->getDatabase(opCtx, dbName);
if (!dbInfoStatus.isOK()) {
return appendEmptyResultSet(opCtx, result, dbInfoStatus.getStatus(), nss.ns());
}
return cursorCommandPassthrough(
opCtx, dbName, dbInfoStatus.getValue(), newCmd, nss, &result);
}
} cmdListCollections;
class CmdListIndexes : public BasicCommand {
public:
CmdListIndexes() : BasicCommand("listIndexes") {}
std::string parseNs(const std::string& dbname, const BSONObj& cmdObj) const override {
return CommandHelpers::parseNsCollectionRequired(dbname, cmdObj).ns();
}
bool supportsWriteConcern(const BSONObj& cmd) const override {
return false;
}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kAlways;
}
bool adminOnly() const override {
return false;
}
Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const override {
AuthorizationSession* authzSession = AuthorizationSession::get(client);
// Check for the listIndexes ActionType on the database, or find on system.indexes for pre
// 3.0 systems.
const NamespaceString ns(parseNs(dbname, cmdObj));
if (authzSession->isAuthorizedForActionsOnResource(ResourcePattern::forExactNamespace(ns),
ActionType::listIndexes) ||
authzSession->isAuthorizedForActionsOnResource(
ResourcePattern::forExactNamespace(NamespaceString(dbname, "system.indexes")),
ActionType::find)) {
return Status::OK();
}
return Status(ErrorCodes::Unauthorized,
str::stream() << "Not authorized to list indexes on collection: "
<< ns.coll());
}
bool run(OperationContext* opCtx,
const std::string& dbName,
const BSONObj& cmdObj,
BSONObjBuilder& result) override {
const NamespaceString nss(parseNs(dbName, cmdObj));
const auto routingInfo =
uassertStatusOK(Grid::get(opCtx)->catalogCache()->getCollectionRoutingInfo(opCtx, nss));
return cursorCommandPassthrough(opCtx,
nss.db(),
routingInfo.db(),
cmdObj,
NamespaceString::makeListIndexesNSS(nss.db(), nss.coll()),
&result);
}
} cmdListIndexes;
} // namespace
} // namespace mongo
|