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
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
|
/**
* 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::kAccessControl
#include "mongo/platform/basic.h"
#include "mongo/db/commands/user_management_commands.h"
#include <string>
#include <vector>
#include "mongo/base/status.h"
#include "mongo/bson/mutable/algorithm.h"
#include "mongo/bson/mutable/document.h"
#include "mongo/bson/mutable/element.h"
#include "mongo/bson/util/bson_extract.h"
#include "mongo/config.h"
#include "mongo/crypto/mechanism_scram.h"
#include "mongo/db/audit.h"
#include "mongo/db/auth/action_set.h"
#include "mongo/db/auth/action_type.h"
#include "mongo/db/auth/address_restriction.h"
#include "mongo/db/auth/authorization_manager.h"
#include "mongo/db/auth/authorization_session.h"
#include "mongo/db/auth/privilege.h"
#include "mongo/db/auth/privilege_parser.h"
#include "mongo/db/auth/resource_pattern.h"
#include "mongo/db/auth/sasl_options.h"
#include "mongo/db/auth/user.h"
#include "mongo/db/auth/user_document_parser.h"
#include "mongo/db/auth/user_management_commands_parser.h"
#include "mongo/db/client.h"
#include "mongo/db/commands.h"
#include "mongo/db/commands/run_aggregate.h"
#include "mongo/db/concurrency/d_concurrency.h"
#include "mongo/db/dbdirectclient.h"
#include "mongo/db/jsobj.h"
#include "mongo/db/operation_context.h"
#include "mongo/db/ops/write_ops.h"
#include "mongo/db/query/cursor_response.h"
#include "mongo/db/service_context.h"
#include "mongo/rpc/get_status_from_command_result.h"
#include "mongo/s/write_ops/batched_command_response.h"
#include "mongo/stdx/functional.h"
#include "mongo/stdx/mutex.h"
#include "mongo/stdx/unordered_set.h"
#include "mongo/util/icu.h"
#include "mongo/util/log.h"
#include "mongo/util/mongoutils/str.h"
#include "mongo/util/net/ssl_manager.h"
#include "mongo/util/password_digest.h"
#include "mongo/util/sequence_util.h"
#include "mongo/util/time_support.h"
namespace mongo {
using std::endl;
using std::string;
using std::stringstream;
using std::vector;
namespace {
Status useDefaultCode(const Status& status, ErrorCodes::Error defaultCode) {
if (status.code() != ErrorCodes::UnknownError)
return status;
return Status(defaultCode, status.reason());
}
BSONArray roleSetToBSONArray(const stdx::unordered_set<RoleName>& roles) {
BSONArrayBuilder rolesArrayBuilder;
for (stdx::unordered_set<RoleName>::const_iterator it = roles.begin(); it != roles.end();
++it) {
const RoleName& role = *it;
rolesArrayBuilder.append(BSON(AuthorizationManager::ROLE_NAME_FIELD_NAME
<< role.getRole()
<< AuthorizationManager::ROLE_DB_FIELD_NAME
<< role.getDB()));
}
return rolesArrayBuilder.arr();
}
BSONArray rolesVectorToBSONArray(const std::vector<RoleName>& roles) {
BSONArrayBuilder rolesArrayBuilder;
for (std::vector<RoleName>::const_iterator it = roles.begin(); it != roles.end(); ++it) {
const RoleName& role = *it;
rolesArrayBuilder.append(BSON(AuthorizationManager::ROLE_NAME_FIELD_NAME
<< role.getRole()
<< AuthorizationManager::ROLE_DB_FIELD_NAME
<< role.getDB()));
}
return rolesArrayBuilder.arr();
}
Status privilegeVectorToBSONArray(const PrivilegeVector& privileges, BSONArray* result) {
BSONArrayBuilder arrBuilder;
for (PrivilegeVector::const_iterator it = privileges.begin(); it != privileges.end(); ++it) {
const Privilege& privilege = *it;
ParsedPrivilege parsedPrivilege;
std::string errmsg;
if (!ParsedPrivilege::privilegeToParsedPrivilege(privilege, &parsedPrivilege, &errmsg)) {
return Status(ErrorCodes::FailedToParse, errmsg);
}
if (!parsedPrivilege.isValid(&errmsg)) {
return Status(ErrorCodes::FailedToParse, errmsg);
}
arrBuilder.append(parsedPrivilege.toBSON());
}
*result = arrBuilder.arr();
return Status::OK();
}
/**
* Used to get all current roles of the user identified by 'userName'.
*/
Status getCurrentUserRoles(OperationContext* opCtx,
AuthorizationManager* authzManager,
const UserName& userName,
stdx::unordered_set<RoleName>* roles) {
auto swUser = authzManager->acquireUser(opCtx, userName);
if (!swUser.isOK()) {
return swUser.getStatus();
}
auto user = std::move(swUser.getValue());
RoleNameIterator rolesIt = user->getRoles();
while (rolesIt.more()) {
roles->insert(rolesIt.next());
}
return Status::OK();
}
/**
* Checks that every role in "rolesToAdd" exists, that adding each of those roles to "role"
* will not result in a cycle to the role graph, and that every role being added comes from the
* same database as the role it is being added to (or that the role being added to is from the
* "admin" database.
*/
Status checkOkayToGrantRolesToRole(OperationContext* opCtx,
const RoleName& role,
const std::vector<RoleName> rolesToAdd,
AuthorizationManager* authzManager) {
for (std::vector<RoleName>::const_iterator it = rolesToAdd.begin(); it != rolesToAdd.end();
++it) {
const RoleName& roleToAdd = *it;
if (roleToAdd == role) {
return Status(ErrorCodes::InvalidRoleModification,
mongoutils::str::stream() << "Cannot grant role " << role.getFullName()
<< " to itself.");
}
if (role.getDB() != "admin" && roleToAdd.getDB() != role.getDB()) {
return Status(
ErrorCodes::InvalidRoleModification,
str::stream() << "Roles on the \'" << role.getDB()
<< "\' database cannot be granted roles from other databases");
}
BSONObj roleToAddDoc;
Status status = authzManager->getRoleDescription(opCtx, roleToAdd, &roleToAddDoc);
if (status == ErrorCodes::RoleNotFound) {
return Status(ErrorCodes::RoleNotFound,
"Cannot grant nonexistent role " + roleToAdd.toString());
}
if (!status.isOK()) {
return status;
}
std::vector<RoleName> indirectRoles;
status = auth::parseRoleNamesFromBSONArray(
BSONArray(roleToAddDoc["inheritedRoles"].Obj()), role.getDB(), &indirectRoles);
if (!status.isOK()) {
return status;
}
if (sequenceContains(indirectRoles, role)) {
return Status(
ErrorCodes::InvalidRoleModification,
mongoutils::str::stream() << "Granting " << roleToAdd.getFullName() << " to "
<< role.getFullName()
<< " would introduce a cycle in the role graph.");
}
}
return Status::OK();
}
/**
* Checks that every privilege being granted targets just the database the role is from, or that
* the role is from the "admin" db.
*/
Status checkOkayToGrantPrivilegesToRole(const RoleName& role, const PrivilegeVector& privileges) {
if (role.getDB() == "admin") {
return Status::OK();
}
for (PrivilegeVector::const_iterator it = privileges.begin(); it != privileges.end(); ++it) {
const ResourcePattern& resource = (*it).getResourcePattern();
if ((resource.isDatabasePattern() || resource.isExactNamespacePattern()) &&
(resource.databaseToMatch() == role.getDB())) {
continue;
}
return Status(ErrorCodes::InvalidRoleModification,
str::stream() << "Roles on the \'" << role.getDB()
<< "\' database cannot be granted privileges that target other "
"databases or the cluster");
}
return Status::OK();
}
/**
* Finds all documents matching "query" in "collectionName". For each document returned,
* calls the function resultProcessor on it.
* Should only be called on collections with authorization documents in them
* (ie admin.system.users and admin.system.roles).
*/
Status queryAuthzDocument(OperationContext* opCtx,
const NamespaceString& collectionName,
const BSONObj& query,
const BSONObj& projection,
const stdx::function<void(const BSONObj&)>& resultProcessor) {
try {
DBDirectClient client(opCtx);
client.query(resultProcessor, collectionName, query, &projection);
return Status::OK();
} catch (const DBException& e) {
return e.toStatus();
}
}
/**
* Inserts "document" into "collectionName".
* If there is a duplicate key error, returns a Status with code DuplicateKey.
*
* Should only be called on collections with authorization documents in them
* (ie admin.system.users and admin.system.roles).
*/
Status insertAuthzDocument(OperationContext* opCtx,
const NamespaceString& collectionName,
const BSONObj& document) {
try {
DBDirectClient client(opCtx);
BSONObj res;
client.runCommand(collectionName.db().toString(),
[&] {
write_ops::Insert insertOp(collectionName);
insertOp.setDocuments({document});
return insertOp.toBSON({});
}(),
res);
BatchedCommandResponse response;
std::string errmsg;
if (!response.parseBSON(res, &errmsg)) {
return Status(ErrorCodes::FailedToParse, errmsg);
}
return response.toStatus();
} catch (const DBException& e) {
return e.toStatus();
}
}
/**
* Updates documents matching "query" according to "updatePattern" in "collectionName".
*
* Should only be called on collections with authorization documents in them
* (ie admin.system.users and admin.system.roles).
*/
Status updateAuthzDocuments(OperationContext* opCtx,
const NamespaceString& collectionName,
const BSONObj& query,
const BSONObj& updatePattern,
bool upsert,
bool multi,
long long* nMatched) {
try {
DBDirectClient client(opCtx);
BSONObj res;
client.runCommand(collectionName.db().toString(),
[&] {
write_ops::Update updateOp(collectionName);
updateOp.setUpdates({[&] {
write_ops::UpdateOpEntry entry;
entry.setQ(query);
entry.setU(updatePattern);
entry.setMulti(multi);
entry.setUpsert(upsert);
return entry;
}()});
return updateOp.toBSON({});
}(),
res);
BatchedCommandResponse response;
std::string errmsg;
if (!response.parseBSON(res, &errmsg)) {
return Status(ErrorCodes::FailedToParse, errmsg);
}
if (response.getOk()) {
*nMatched = response.getN();
}
return response.toStatus();
} catch (const DBException& e) {
return e.toStatus();
}
}
/**
* Update one document matching "query" according to "updatePattern" in "collectionName".
*
* If "upsert" is true and no document matches "query", inserts one using "query" as a
* template.
* If "upsert" is false and no document matches "query", return a Status with the code
* NoMatchingDocument. The Status message in that case is not very descriptive and should
* not be displayed to the end user.
*
* Should only be called on collections with authorization documents in them
* (ie admin.system.users and admin.system.roles).
*/
Status updateOneAuthzDocument(OperationContext* opCtx,
const NamespaceString& collectionName,
const BSONObj& query,
const BSONObj& updatePattern,
bool upsert) {
long long nMatched;
Status status =
updateAuthzDocuments(opCtx, collectionName, query, updatePattern, upsert, false, &nMatched);
if (!status.isOK()) {
return status;
}
dassert(nMatched == 1 || nMatched == 0);
if (nMatched == 0) {
return Status(ErrorCodes::NoMatchingDocument, "No document found");
}
return Status::OK();
}
/**
* Removes all documents matching "query" from "collectionName".
*
* Should only be called on collections with authorization documents in them
* (ie admin.system.users and admin.system.roles).
*/
Status removeAuthzDocuments(OperationContext* opCtx,
const NamespaceString& collectionName,
const BSONObj& query,
long long* numRemoved) {
try {
DBDirectClient client(opCtx);
BSONObj res;
client.runCommand(collectionName.db().toString(),
[&] {
write_ops::Delete deleteOp(collectionName);
deleteOp.setDeletes({[&] {
write_ops::DeleteOpEntry entry;
entry.setQ(query);
entry.setMulti(true);
return entry;
}()});
return deleteOp.toBSON({});
}(),
res);
BatchedCommandResponse response;
std::string errmsg;
if (!response.parseBSON(res, &errmsg)) {
return Status(ErrorCodes::FailedToParse, errmsg);
}
if (response.getOk()) {
*numRemoved = response.getN();
}
return response.toStatus();
} catch (const DBException& e) {
return e.toStatus();
}
}
/**
* Creates the given role object in the given database.
*/
Status insertRoleDocument(OperationContext* opCtx, const BSONObj& roleObj) {
Status status =
insertAuthzDocument(opCtx, AuthorizationManager::rolesCollectionNamespace, roleObj);
if (status.isOK()) {
return status;
}
if (status.code() == ErrorCodes::DuplicateKey) {
std::string name = roleObj[AuthorizationManager::ROLE_NAME_FIELD_NAME].String();
std::string source = roleObj[AuthorizationManager::ROLE_DB_FIELD_NAME].String();
return Status(ErrorCodes::Error(51002),
str::stream() << "Role \"" << name << "@" << source << "\" already exists");
}
if (status.code() == ErrorCodes::UnknownError) {
return Status(ErrorCodes::RoleModificationFailed, status.reason());
}
return status;
}
/**
* Updates the given role object with the given update modifier.
*/
Status updateRoleDocument(OperationContext* opCtx, const RoleName& role, const BSONObj& updateObj) {
Status status = updateOneAuthzDocument(opCtx,
AuthorizationManager::rolesCollectionNamespace,
BSON(AuthorizationManager::ROLE_NAME_FIELD_NAME
<< role.getRole()
<< AuthorizationManager::ROLE_DB_FIELD_NAME
<< role.getDB()),
updateObj,
false);
if (status.isOK()) {
return status;
}
if (status.code() == ErrorCodes::NoMatchingDocument) {
return Status(ErrorCodes::RoleNotFound,
str::stream() << "Role " << role.getFullName() << " not found");
}
if (status.code() == ErrorCodes::UnknownError) {
return Status(ErrorCodes::RoleModificationFailed, status.reason());
}
return status;
}
/**
* Removes roles matching the given query.
* Writes into *numRemoved the number of role documents that were modified.
*/
Status removeRoleDocuments(OperationContext* opCtx, const BSONObj& query, long long* numRemoved) {
Status status = removeAuthzDocuments(
opCtx, AuthorizationManager::rolesCollectionNamespace, query, numRemoved);
if (status.code() == ErrorCodes::UnknownError) {
return Status(ErrorCodes::RoleModificationFailed, status.reason());
}
return status;
}
/**
* Creates the given user object in the given database.
*/
Status insertPrivilegeDocument(OperationContext* opCtx, const BSONObj& userObj) {
Status status =
insertAuthzDocument(opCtx, AuthorizationManager::usersCollectionNamespace, userObj);
if (status.isOK()) {
return status;
}
if (status.code() == ErrorCodes::DuplicateKey) {
std::string name = userObj[AuthorizationManager::USER_NAME_FIELD_NAME].String();
std::string source = userObj[AuthorizationManager::USER_DB_FIELD_NAME].String();
return Status(ErrorCodes::Error(51003),
str::stream() << "User \"" << name << "@" << source << "\" already exists");
}
if (status.code() == ErrorCodes::UnknownError) {
return Status(ErrorCodes::UserModificationFailed, status.reason());
}
return status;
}
/**
* Updates the given user object with the given update modifier.
*/
Status updatePrivilegeDocument(OperationContext* opCtx,
const UserName& user,
const BSONObj& queryObj,
const BSONObj& updateObj) {
// Minimum fields required for an update.
dassert(queryObj.hasField(AuthorizationManager::USER_NAME_FIELD_NAME));
dassert(queryObj.hasField(AuthorizationManager::USER_DB_FIELD_NAME));
const auto status = updateOneAuthzDocument(
opCtx, AuthorizationManager::usersCollectionNamespace, queryObj, updateObj, false);
if (status.code() == ErrorCodes::UnknownError) {
return {ErrorCodes::UserModificationFailed, status.reason()};
}
if (status.code() == ErrorCodes::NoMatchingDocument) {
return {ErrorCodes::UserNotFound,
str::stream() << "User " << user.getFullName() << " not found"};
}
return status;
}
/**
* Convenience wrapper for above using only the UserName to match the original document.
* Clarifies NoMatchingDocument result to reflect the user not existing.
*/
Status updatePrivilegeDocument(OperationContext* opCtx,
const UserName& user,
const BSONObj& updateObj) {
const auto status = updatePrivilegeDocument(opCtx,
user,
BSON(AuthorizationManager::USER_NAME_FIELD_NAME
<< user.getUser()
<< AuthorizationManager::USER_DB_FIELD_NAME
<< user.getDB()),
updateObj);
return status;
}
/**
* Removes users for the given database matching the given query.
* Writes into *numRemoved the number of user documents that were modified.
*/
Status removePrivilegeDocuments(OperationContext* opCtx,
const BSONObj& query,
long long* numRemoved) {
Status status = removeAuthzDocuments(
opCtx, AuthorizationManager::usersCollectionNamespace, query, numRemoved);
if (status.code() == ErrorCodes::UnknownError) {
return Status(ErrorCodes::UserModificationFailed, status.reason());
}
return status;
}
/**
* Updates the auth schema version document to reflect the current state of the system.
* 'foundSchemaVersion' is the authSchemaVersion to update with.
*/
Status writeAuthSchemaVersionIfNeeded(OperationContext* opCtx,
AuthorizationManager* authzManager,
int foundSchemaVersion) {
Status status = updateOneAuthzDocument(
opCtx,
AuthorizationManager::versionCollectionNamespace,
AuthorizationManager::versionDocumentQuery,
BSON("$set" << BSON(AuthorizationManager::schemaVersionFieldName << foundSchemaVersion)),
true); // upsert
if (status == ErrorCodes::NoMatchingDocument) { // SERVER-11492
status = Status::OK();
}
return status;
}
class AuthzLockGuard {
AuthzLockGuard(AuthzLockGuard&) = delete;
AuthzLockGuard& operator=(AuthzLockGuard&) = delete;
public:
AuthzLockGuard(OperationContext* opCtx, LockMode mode)
: _opCtx(opCtx),
_lock(_opCtx,
AuthorizationManager::usersCollectionNamespace.db(),
mode,
_opCtx->getDeadline()) {
auto authzMgr = AuthorizationManager::get(_opCtx->getServiceContext());
authzMgr->setInUserManagementCommand(_opCtx, true);
}
~AuthzLockGuard() {
auto authzMgr = AuthorizationManager::get(_opCtx->getServiceContext());
authzMgr->setInUserManagementCommand(_opCtx, false);
}
AuthzLockGuard(AuthzLockGuard&&) = default;
private:
OperationContext* _opCtx;
Lock::DBLock _lock;
};
/**
* Returns Status::OK() if the current Auth schema version is at least the auth schema version
* for the MongoDB 3.0 SCRAM auth mode.
* Returns an error otherwise.
*/
StatusWith<AuthzLockGuard> requireWritableAuthSchema28SCRAM(OperationContext* opCtx,
AuthorizationManager* authzManager) {
int foundSchemaVersion;
// We take a MODE_X lock during writes because we want to be sure that we can read any pinned
// user documents back out of the database after writing them during the user management
// commands, and to ensure only one user management command is running at a time.
AuthzLockGuard lk(opCtx, MODE_X);
Status status = authzManager->getAuthorizationVersion(opCtx, &foundSchemaVersion);
if (!status.isOK()) {
return status;
}
if (foundSchemaVersion < AuthorizationManager::schemaVersion28SCRAM) {
return Status(ErrorCodes::AuthSchemaIncompatible,
str::stream()
<< "User and role management commands require auth data to have "
<< "at least schema version "
<< AuthorizationManager::schemaVersion28SCRAM
<< " but found "
<< foundSchemaVersion);
}
status = writeAuthSchemaVersionIfNeeded(opCtx, authzManager, foundSchemaVersion);
if (!status.isOK()) {
return status;
}
return std::move(lk);
}
/**
* Returns Status::OK() if the current Auth schema version is at least the auth schema version
* for MongoDB 2.6 during the upgrade process.
* Returns an error otherwise.
*
* This method should only be called by READ-ONLY commands (usersInfo & rolesInfo)
* because getAuthorizationVersion() will return the current max version without
* reifying the authSchema setting in the admin database.
*
* If records are added thinking we're at one schema level, then the default is changed,
* then the auth database would wind up in an inconsistent state.
*/
StatusWith<AuthzLockGuard> requireReadableAuthSchema26Upgrade(OperationContext* opCtx,
AuthorizationManager* authzManager) {
int foundSchemaVersion;
AuthzLockGuard lk(opCtx, MODE_IS);
Status status = authzManager->getAuthorizationVersion(opCtx, &foundSchemaVersion);
if (!status.isOK()) {
return status;
}
if (foundSchemaVersion < AuthorizationManager::schemaVersion26Upgrade) {
return Status(ErrorCodes::AuthSchemaIncompatible,
str::stream() << "The usersInfo and rolesInfo commands require auth data to "
<< "have at least schema version "
<< AuthorizationManager::schemaVersion26Upgrade
<< " but found "
<< foundSchemaVersion);
}
return std::move(lk);
}
Status buildCredentials(BSONObjBuilder* builder, const auth::CreateOrUpdateUserArgs& args) {
if (!args.hasPassword) {
// Must be external user.
builder->append("external", true);
return Status::OK();
}
bool buildSCRAMSHA1 = false, buildSCRAMSHA256 = false;
if (args.mechanisms.empty()) {
buildSCRAMSHA1 = sequenceContains(saslGlobalParams.authenticationMechanisms, "SCRAM-SHA-1");
buildSCRAMSHA256 =
sequenceContains(saslGlobalParams.authenticationMechanisms, "SCRAM-SHA-256");
} else {
for (const auto& mech : args.mechanisms) {
if (mech == "SCRAM-SHA-1") {
buildSCRAMSHA1 = true;
} else if (mech == "SCRAM-SHA-256") {
buildSCRAMSHA256 = true;
} else {
return {ErrorCodes::BadValue,
str::stream() << "Unknown auth mechanism '" << mech << "'"};
}
if (!sequenceContains(saslGlobalParams.authenticationMechanisms, mech)) {
return {ErrorCodes::BadValue,
str::stream() << mech << " not supported in authMechanisms"};
}
}
}
if (buildSCRAMSHA1) {
// Add SCRAM-SHA-1 credentials.
std::string hashedPwd;
if (args.digestPassword) {
hashedPwd = createPasswordDigest(args.userName.getUser(), args.password);
} else {
hashedPwd = args.password;
}
auto sha1Cred = scram::Secrets<SHA1Block>::generateCredentials(
hashedPwd, saslGlobalParams.scramSHA1IterationCount.load());
builder->append("SCRAM-SHA-1", sha1Cred);
}
if (buildSCRAMSHA256) {
if (!args.digestPassword) {
return {ErrorCodes::BadValue, "Use of SCRAM-SHA-256 requires undigested passwords"};
}
const auto swPwd = icuSaslPrep(args.password);
if (!swPwd.isOK()) {
return swPwd.getStatus();
}
auto sha256Cred = scram::Secrets<SHA256Block>::generateCredentials(
swPwd.getValue(), saslGlobalParams.scramSHA256IterationCount.load());
builder->append("SCRAM-SHA-256", sha256Cred);
}
return Status::OK();
}
Status trimCredentials(OperationContext* opCtx,
BSONObjBuilder* queryBuilder,
BSONObjBuilder* unsetBuilder,
const auth::CreateOrUpdateUserArgs& args) {
auto* authzManager = AuthorizationManager::get(opCtx->getServiceContext());
BSONObj userObj;
const auto status = authzManager->getUserDescription(opCtx, args.userName, &userObj);
if (!status.isOK()) {
return status;
}
const auto& credsElem = userObj["credentials"];
if (credsElem.eoo() || (credsElem.type() != Object)) {
return {ErrorCodes::UnsupportedFormat,
"Unable to trim credentials from a user document with no credentials"};
}
const auto& creds = credsElem.Obj();
queryBuilder->append("credentials", creds);
bool keepSCRAMSHA1 = false, keepSCRAMSHA256 = false;
for (const auto& mech : args.mechanisms) {
if (!creds.hasField(mech)) {
return {ErrorCodes::BadValue,
"mechanisms field must be a subset of previously set mechanisms"};
}
if (mech == "SCRAM-SHA-1") {
keepSCRAMSHA1 = true;
} else if (mech == "SCRAM-SHA-256") {
keepSCRAMSHA256 = true;
}
}
if (!(keepSCRAMSHA1 || keepSCRAMSHA256)) {
return {ErrorCodes::BadValue,
"mechanisms field must contain at least one previously set known mechanism"};
}
if (!keepSCRAMSHA1) {
unsetBuilder->append("credentials.SCRAM-SHA-1", "");
}
if (!keepSCRAMSHA256) {
unsetBuilder->append("credentials.SCRAM-SHA-256", "");
}
return Status::OK();
}
} // namespace
class CmdCreateUser : public BasicCommand {
public:
CmdCreateUser() : BasicCommand("createUser") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
std::string help() const override {
return "Adds a user to the system";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForCreateUserCommand(client, dbname, cmdObj);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
auth::CreateOrUpdateUserArgs args;
Status status = auth::parseCreateOrUpdateUserCommands(cmdObj, "createUser", dbname, &args);
uassertStatusOK(status);
if (args.userName.getDB() == "local") {
uasserted(ErrorCodes::BadValue, "Cannot create users in the local database");
}
if (!args.hasPassword && args.userName.getDB() != "$external") {
uasserted(ErrorCodes::BadValue,
"Must provide a 'pwd' field for all user documents, except those"
" with '$external' as the user's source db");
}
if ((args.hasPassword) && args.userName.getDB() == "$external") {
uasserted(ErrorCodes::BadValue,
"Cannot set the password for users defined on the '$external' "
"database");
}
if (!args.hasRoles) {
uasserted(ErrorCodes::BadValue, "\"createUser\" command requires a \"roles\" array");
}
#ifdef MONGO_CONFIG_SSL
if (args.userName.getDB() == "$external" && getSSLManager() &&
getSSLManager()->getSSLConfiguration().isClusterMember(args.userName.getUser())) {
uasserted(ErrorCodes::BadValue,
"Cannot create an x.509 user with a subjectname "
"that would be recognized as an internal "
"cluster member.");
}
#endif
BSONObjBuilder userObjBuilder;
userObjBuilder.append(
"_id", str::stream() << args.userName.getDB() << "." << args.userName.getUser());
userObjBuilder.append(AuthorizationManager::USER_NAME_FIELD_NAME, args.userName.getUser());
userObjBuilder.append(AuthorizationManager::USER_DB_FIELD_NAME, args.userName.getDB());
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
auto lk = uassertStatusOK(requireWritableAuthSchema28SCRAM(opCtx, authzManager));
int authzVersion;
status = authzManager->getAuthorizationVersion(opCtx, &authzVersion);
uassertStatusOK(status);
BSONObjBuilder credentialsBuilder(userObjBuilder.subobjStart("credentials"));
status = buildCredentials(&credentialsBuilder, args);
uassertStatusOK(status);
credentialsBuilder.done();
if (args.authenticationRestrictions && !args.authenticationRestrictions->isEmpty()) {
credentialsBuilder.append("authenticationRestrictions",
*args.authenticationRestrictions);
}
if (args.hasCustomData) {
userObjBuilder.append("customData", args.customData);
}
userObjBuilder.append("roles", rolesVectorToBSONArray(args.roles));
BSONObj userObj = userObjBuilder.obj();
V2UserDocumentParser parser;
status = parser.checkValidUserDocument(userObj);
uassertStatusOK(status);
// Role existence has to be checked after acquiring the update lock
for (size_t i = 0; i < args.roles.size(); ++i) {
BSONObj ignored;
status = authzManager->getRoleDescription(opCtx, args.roles[i], &ignored);
uassertStatusOK(status);
}
audit::logCreateUser(Client::getCurrent(),
args.userName,
args.hasPassword,
args.hasCustomData ? &args.customData : NULL,
args.roles,
args.authenticationRestrictions);
status = insertPrivilegeDocument(opCtx, userObj);
authzManager->invalidateUserByName(opCtx, args.userName);
uassertStatusOK(status);
return true;
}
StringData sensitiveFieldName() const final {
return "pwd"_sd;
}
} cmdCreateUser;
class CmdUpdateUser : public BasicCommand {
public:
CmdUpdateUser() : BasicCommand("updateUser") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
std::string help() const override {
return "Used to update a user, for example to change its password";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForUpdateUserCommand(client, dbname, cmdObj);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
auth::CreateOrUpdateUserArgs args;
Status status = auth::parseCreateOrUpdateUserCommands(cmdObj, "updateUser", dbname, &args);
uassertStatusOK(status);
if (!args.hasPassword && !args.hasCustomData && !args.hasRoles &&
!args.authenticationRestrictions && args.mechanisms.empty()) {
uasserted(ErrorCodes::BadValue,
"Must specify at least one field to update in updateUser");
}
if (args.hasPassword && args.userName.getDB() == "$external") {
uasserted(ErrorCodes::BadValue,
"Cannot set the password for users defined on the '$external' "
"database");
}
BSONObjBuilder queryBuilder;
queryBuilder.append(AuthorizationManager::USER_NAME_FIELD_NAME, args.userName.getUser());
queryBuilder.append(AuthorizationManager::USER_DB_FIELD_NAME, args.userName.getDB());
BSONObjBuilder updateSetBuilder;
BSONObjBuilder updateUnsetBuilder;
if (args.hasPassword) {
BSONObjBuilder credentialsBuilder(updateSetBuilder.subobjStart("credentials"));
status = buildCredentials(&credentialsBuilder, args);
uassertStatusOK(status);
credentialsBuilder.done();
} else if (!args.mechanisms.empty()) {
status = trimCredentials(opCtx, &queryBuilder, &updateUnsetBuilder, args);
uassertStatusOK(status);
}
if (args.hasCustomData) {
updateSetBuilder.append("customData", args.customData);
}
if (args.authenticationRestrictions) {
if (args.authenticationRestrictions->isEmpty()) {
updateUnsetBuilder.append("authenticationRestrictions", "");
} else {
auto swParsedRestrictions =
parseAuthenticationRestriction(*args.authenticationRestrictions);
uassertStatusOK(swParsedRestrictions.getStatus());
updateSetBuilder.append("authenticationRestrictions",
*args.authenticationRestrictions);
}
}
if (args.hasRoles) {
updateSetBuilder.append("roles", rolesVectorToBSONArray(args.roles));
}
BSONObj updateSet = updateSetBuilder.done();
BSONObj updateUnset = updateUnsetBuilder.done();
BSONObjBuilder updateDocumentBuilder;
if (!updateSet.isEmpty()) {
updateDocumentBuilder << "$set" << updateSet;
}
if (!updateUnset.isEmpty()) {
updateDocumentBuilder << "$unset" << updateUnset;
}
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
auto lk = uassertStatusOK(requireWritableAuthSchema28SCRAM(opCtx, authzManager));
// Role existence has to be checked after acquiring the update lock
if (args.hasRoles) {
for (size_t i = 0; i < args.roles.size(); ++i) {
BSONObj ignored;
status = authzManager->getRoleDescription(opCtx, args.roles[i], &ignored);
uassertStatusOK(status);
}
}
audit::logUpdateUser(Client::getCurrent(),
args.userName,
args.hasPassword,
args.hasCustomData ? &args.customData : NULL,
args.hasRoles ? &args.roles : NULL,
args.authenticationRestrictions);
status = updatePrivilegeDocument(
opCtx, args.userName, queryBuilder.done(), updateDocumentBuilder.done());
// Must invalidate even on bad status - what if the write succeeded but the GLE failed?
authzManager->invalidateUserByName(opCtx, args.userName);
uassertStatusOK(status);
return true;
}
StringData sensitiveFieldName() const final {
return "pwd"_sd;
}
} cmdUpdateUser;
class CmdDropUser : public BasicCommand {
public:
CmdDropUser() : BasicCommand("dropUser") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
std::string help() const override {
return "Drops a single user.";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForDropUserCommand(client, dbname, cmdObj);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
UserName userName;
Status status = auth::parseAndValidateDropUserCommand(cmdObj, dbname, &userName);
uassertStatusOK(status);
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
auto lk = uassertStatusOK(requireWritableAuthSchema28SCRAM(opCtx, authzManager));
audit::logDropUser(Client::getCurrent(), userName);
long long nMatched;
status = removePrivilegeDocuments(opCtx,
BSON(AuthorizationManager::USER_NAME_FIELD_NAME
<< userName.getUser()
<< AuthorizationManager::USER_DB_FIELD_NAME
<< userName.getDB()),
&nMatched);
// Must invalidate even on bad status - what if the write succeeded but the GLE failed?
authzManager->invalidateUserByName(opCtx, userName);
uassertStatusOK(status);
if (nMatched == 0) {
uasserted(ErrorCodes::UserNotFound,
str::stream() << "User '" << userName.getFullName() << "' not found");
}
return true;
}
} cmdDropUser;
class CmdDropAllUsersFromDatabase : public BasicCommand {
public:
CmdDropAllUsersFromDatabase() : BasicCommand("dropAllUsersFromDatabase") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
std::string help() const override {
return "Drops all users for a single database.";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForDropAllUsersFromDatabaseCommand(client, dbname);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
Status status = auth::parseAndValidateDropAllUsersFromDatabaseCommand(cmdObj, dbname);
uassertStatusOK(status);
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
auto lk = uassertStatusOK(requireWritableAuthSchema28SCRAM(opCtx, authzManager));
audit::logDropAllUsersFromDatabase(Client::getCurrent(), dbname);
long long numRemoved;
status = removePrivilegeDocuments(
opCtx, BSON(AuthorizationManager::USER_DB_FIELD_NAME << dbname), &numRemoved);
// Must invalidate even on bad status - what if the write succeeded but the GLE failed?
authzManager->invalidateUsersFromDB(opCtx, dbname);
uassertStatusOK(status);
result.append("n", numRemoved);
return true;
}
} cmdDropAllUsersFromDatabase;
class CmdGrantRolesToUser : public BasicCommand {
public:
CmdGrantRolesToUser() : BasicCommand("grantRolesToUser") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
std::string help() const override {
return "Grants roles to a user.";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForGrantRolesToUserCommand(client, dbname, cmdObj);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
std::string userNameString;
std::vector<RoleName> roles;
Status status = auth::parseRolePossessionManipulationCommands(
cmdObj, "grantRolesToUser", dbname, &userNameString, &roles);
uassertStatusOK(status);
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
auto lk = uassertStatusOK(requireWritableAuthSchema28SCRAM(opCtx, authzManager));
UserName userName(userNameString, dbname);
stdx::unordered_set<RoleName> userRoles;
status = getCurrentUserRoles(opCtx, authzManager, userName, &userRoles);
uassertStatusOK(status);
for (vector<RoleName>::iterator it = roles.begin(); it != roles.end(); ++it) {
RoleName& roleName = *it;
BSONObj roleDoc;
status = authzManager->getRoleDescription(opCtx, roleName, &roleDoc);
uassertStatusOK(status);
userRoles.insert(roleName);
}
audit::logGrantRolesToUser(Client::getCurrent(), userName, roles);
BSONArray newRolesBSONArray = roleSetToBSONArray(userRoles);
status = updatePrivilegeDocument(
opCtx, userName, BSON("$set" << BSON("roles" << newRolesBSONArray)));
// Must invalidate even on bad status - what if the write succeeded but the GLE failed?
authzManager->invalidateUserByName(opCtx, userName);
uassertStatusOK(status);
return true;
}
} cmdGrantRolesToUser;
class CmdRevokeRolesFromUser : public BasicCommand {
public:
CmdRevokeRolesFromUser() : BasicCommand("revokeRolesFromUser") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
std::string help() const override {
return "Revokes roles from a user.";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForRevokeRolesFromUserCommand(client, dbname, cmdObj);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
std::string userNameString;
std::vector<RoleName> roles;
Status status = auth::parseRolePossessionManipulationCommands(
cmdObj, "revokeRolesFromUser", dbname, &userNameString, &roles);
uassertStatusOK(status);
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
auto lk = uassertStatusOK(requireWritableAuthSchema28SCRAM(opCtx, authzManager));
UserName userName(userNameString, dbname);
stdx::unordered_set<RoleName> userRoles;
status = getCurrentUserRoles(opCtx, authzManager, userName, &userRoles);
uassertStatusOK(status);
for (vector<RoleName>::iterator it = roles.begin(); it != roles.end(); ++it) {
RoleName& roleName = *it;
BSONObj roleDoc;
status = authzManager->getRoleDescription(opCtx, roleName, &roleDoc);
uassertStatusOK(status);
userRoles.erase(roleName);
}
audit::logRevokeRolesFromUser(Client::getCurrent(), userName, roles);
BSONArray newRolesBSONArray = roleSetToBSONArray(userRoles);
status = updatePrivilegeDocument(
opCtx, userName, BSON("$set" << BSON("roles" << newRolesBSONArray)));
// Must invalidate even on bad status - what if the write succeeded but the GLE failed?
authzManager->invalidateUserByName(opCtx, userName);
uassertStatusOK(status);
return true;
}
} cmdRevokeRolesFromUser;
class CmdUsersInfo : public BasicCommand {
public:
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kOptIn;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return false;
}
CmdUsersInfo() : BasicCommand("usersInfo") {}
std::string help() const override {
return "Returns information about users.";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForUsersInfoCommand(client, dbname, cmdObj);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
auth::UsersInfoArgs args;
Status status = auth::parseUsersInfoCommand(cmdObj, dbname, &args);
uassertStatusOK(status);
AuthorizationManager* authzManager = AuthorizationManager::get(opCtx->getServiceContext());
auto lk = uassertStatusOK(requireReadableAuthSchema26Upgrade(opCtx, authzManager));
if ((args.target != auth::UsersInfoArgs::Target::kExplicitUsers || args.filter) &&
(args.showPrivileges ||
args.authenticationRestrictionsFormat == AuthenticationRestrictionsFormat::kShow)) {
uasserted(ErrorCodes::IllegalOperation,
"Privilege or restriction details require exact-match usersInfo "
"queries.");
}
BSONArrayBuilder usersArrayBuilder;
if (args.target == auth::UsersInfoArgs::Target::kExplicitUsers &&
(args.showPrivileges ||
args.authenticationRestrictionsFormat == AuthenticationRestrictionsFormat::kShow)) {
// If you want privileges or restrictions you need to call getUserDescription on each
// user.
for (size_t i = 0; i < args.userNames.size(); ++i) {
BSONObj userDetails;
status = authzManager->getUserDescription(opCtx, args.userNames[i], &userDetails);
if (status.code() == ErrorCodes::UserNotFound) {
continue;
}
uassertStatusOK(status);
// getUserDescription always includes credentials and restrictions, which may need
// to be stripped out
BSONObjBuilder strippedUser(usersArrayBuilder.subobjStart());
for (const BSONElement& e : userDetails) {
if (e.fieldNameStringData() == "credentials") {
BSONArrayBuilder mechanismNamesBuilder;
BSONObj mechanismsObj = e.Obj();
for (const BSONElement& mechanismElement : mechanismsObj) {
mechanismNamesBuilder.append(mechanismElement.fieldNameStringData());
}
strippedUser.append("mechanisms", mechanismNamesBuilder.arr());
if (!args.showCredentials) {
continue;
}
}
if (e.fieldNameStringData() == "authenticationRestrictions" &&
args.authenticationRestrictionsFormat ==
AuthenticationRestrictionsFormat::kOmit) {
continue;
}
strippedUser.append(e);
}
strippedUser.doneFast();
}
} else {
// If you don't need privileges, or authenticationRestrictions, you can just do a
// regular query on system.users
std::vector<BSONObj> pipeline;
if (args.target == auth::UsersInfoArgs::Target::kGlobal) {
// Leave the pipeline unconstrained, we want to return every user.
} else if (args.target == auth::UsersInfoArgs::Target::kDB) {
pipeline.push_back(
BSON("$match" << BSON(AuthorizationManager::USER_DB_FIELD_NAME << dbname)));
} else {
BSONArrayBuilder usersMatchArray;
for (size_t i = 0; i < args.userNames.size(); ++i) {
usersMatchArray.append(BSON(AuthorizationManager::USER_NAME_FIELD_NAME
<< args.userNames[i].getUser()
<< AuthorizationManager::USER_DB_FIELD_NAME
<< args.userNames[i].getDB()));
}
pipeline.push_back(BSON("$match" << BSON("$or" << usersMatchArray.arr())));
}
// Order results by user field then db field, matching how UserNames are ordered
pipeline.push_back(BSON("$sort" << BSON("user" << 1 << "db" << 1)));
// Authentication restrictions are only rendered in the single user case.
pipeline.push_back(BSON("$project" << BSON("authenticationRestrictions" << false)));
// Rewrite the credentials object into an array of its fieldnames.
pipeline.push_back(
BSON("$addFields" << BSON("mechanisms"
<< BSON("$map" << BSON("input" << BSON("$objectToArray"
<< "$credentials")
<< "as"
<< "cred"
<< "in"
<< "$$cred.k")))));
// Remove credentials, they're not required in the output
if (!args.showCredentials) {
pipeline.push_back(BSON("$project" << BSON("credentials" << false)));
}
// Handle a user specified filter.
if (args.filter) {
pipeline.push_back(BSON("$match" << *args.filter));
}
DBDirectClient client(opCtx);
rpc::OpMsgReplyBuilder replyBuilder;
AggregationRequest aggRequest(AuthorizationManager::usersCollectionNamespace,
std::move(pipeline));
uassertStatusOK(runAggregate(opCtx,
AuthorizationManager::usersCollectionNamespace,
aggRequest,
aggRequest.serializeToCommandObj().toBson(),
&replyBuilder));
auto bodyBuilder = replyBuilder.getBodyBuilder();
CommandHelpers::appendSimpleCommandStatus(bodyBuilder, true);
bodyBuilder.doneFast();
auto response = CursorResponse::parseFromBSONThrowing(replyBuilder.releaseBody());
DBClientCursor cursor(
&client, response.getNSS(), response.getCursorId(), 0, 0, response.releaseBatch());
while (cursor.more()) {
usersArrayBuilder.append(cursor.next());
}
}
result.append("users", usersArrayBuilder.arr());
return true;
}
} cmdUsersInfo;
class CmdCreateRole : public BasicCommand {
public:
CmdCreateRole() : BasicCommand("createRole") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
std::string help() const override {
return "Adds a role to the system";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForCreateRoleCommand(client, dbname, cmdObj);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
auth::CreateOrUpdateRoleArgs args;
Status status = auth::parseCreateOrUpdateRoleCommands(cmdObj, "createRole", dbname, &args);
uassertStatusOK(status);
if (args.roleName.getRole().empty()) {
uasserted(ErrorCodes::BadValue, "Role name must be non-empty");
}
if (args.roleName.getDB() == "local") {
uasserted(ErrorCodes::BadValue, "Cannot create roles in the local database");
}
if (args.roleName.getDB() == "$external") {
uasserted(ErrorCodes::BadValue, "Cannot create roles in the $external database");
}
if (RoleGraph::isBuiltinRole(args.roleName)) {
uasserted(ErrorCodes::BadValue,
"Cannot create roles with the same name as a built-in role");
}
if (!args.hasRoles) {
uasserted(ErrorCodes::BadValue, "\"createRole\" command requires a \"roles\" array");
}
if (!args.hasPrivileges) {
uasserted(ErrorCodes::BadValue,
"\"createRole\" command requires a \"privileges\" array");
}
BSONObjBuilder roleObjBuilder;
roleObjBuilder.append(
"_id", str::stream() << args.roleName.getDB() << "." << args.roleName.getRole());
roleObjBuilder.append(AuthorizationManager::ROLE_NAME_FIELD_NAME, args.roleName.getRole());
roleObjBuilder.append(AuthorizationManager::ROLE_DB_FIELD_NAME, args.roleName.getDB());
BSONArray privileges;
status = privilegeVectorToBSONArray(args.privileges, &privileges);
uassertStatusOK(status);
roleObjBuilder.append("privileges", privileges);
roleObjBuilder.append("roles", rolesVectorToBSONArray(args.roles));
if (args.authenticationRestrictions && !args.authenticationRestrictions->isEmpty()) {
roleObjBuilder.append("authenticationRestrictions",
args.authenticationRestrictions.get());
}
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
auto lk = uassertStatusOK(requireWritableAuthSchema28SCRAM(opCtx, authzManager));
// Role existence has to be checked after acquiring the update lock
status = checkOkayToGrantRolesToRole(opCtx, args.roleName, args.roles, authzManager);
uassertStatusOK(status);
status = checkOkayToGrantPrivilegesToRole(args.roleName, args.privileges);
uassertStatusOK(status);
audit::logCreateRole(Client::getCurrent(),
args.roleName,
args.roles,
args.privileges,
args.authenticationRestrictions);
status = insertRoleDocument(opCtx, roleObjBuilder.done());
uassertStatusOK(status);
return true;
}
} cmdCreateRole;
class CmdUpdateRole : public BasicCommand {
public:
CmdUpdateRole() : BasicCommand("updateRole") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
std::string help() const override {
return "Used to update a role";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForUpdateRoleCommand(client, dbname, cmdObj);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
auth::CreateOrUpdateRoleArgs args;
Status status = auth::parseCreateOrUpdateRoleCommands(cmdObj, "updateRole", dbname, &args);
uassertStatusOK(status);
if (!args.hasPrivileges && !args.hasRoles && !args.authenticationRestrictions) {
uasserted(ErrorCodes::BadValue,
"Must specify at least one field to update in updateRole");
}
BSONObjBuilder updateSetBuilder;
BSONObjBuilder updateUnsetBuilder;
if (args.hasPrivileges) {
BSONArray privileges;
status = privilegeVectorToBSONArray(args.privileges, &privileges);
uassertStatusOK(status);
updateSetBuilder.append("privileges", privileges);
}
if (args.hasRoles) {
updateSetBuilder.append("roles", rolesVectorToBSONArray(args.roles));
}
if (args.authenticationRestrictions) {
if (args.authenticationRestrictions->isEmpty()) {
updateUnsetBuilder.append("authenticationRestrictions", "");
} else {
updateSetBuilder.append("authenticationRestrictions",
args.authenticationRestrictions.get());
}
}
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
auto lk = uassertStatusOK(requireWritableAuthSchema28SCRAM(opCtx, authzManager));
// Role existence has to be checked after acquiring the update lock
BSONObj ignored;
status = authzManager->getRoleDescription(opCtx, args.roleName, &ignored);
uassertStatusOK(status);
if (args.hasRoles) {
status = checkOkayToGrantRolesToRole(opCtx, args.roleName, args.roles, authzManager);
uassertStatusOK(status);
}
if (args.hasPrivileges) {
status = checkOkayToGrantPrivilegesToRole(args.roleName, args.privileges);
uassertStatusOK(status);
}
audit::logUpdateRole(Client::getCurrent(),
args.roleName,
args.hasRoles ? &args.roles : nullptr,
args.hasPrivileges ? &args.privileges : nullptr,
args.authenticationRestrictions);
const auto updateSet = updateSetBuilder.obj();
const auto updateUnset = updateUnsetBuilder.obj();
BSONObjBuilder updateDocumentBuilder;
if (!updateSet.isEmpty()) {
updateDocumentBuilder.append("$set", updateSet);
}
if (!updateUnset.isEmpty()) {
updateDocumentBuilder.append("$unset", updateUnset);
}
status = updateRoleDocument(opCtx, args.roleName, updateDocumentBuilder.obj());
// Must invalidate even on bad status - what if the write succeeded but the GLE failed?
authzManager->invalidateUserCache(opCtx);
uassertStatusOK(status);
return true;
}
} cmdUpdateRole;
class CmdGrantPrivilegesToRole : public BasicCommand {
public:
CmdGrantPrivilegesToRole() : BasicCommand("grantPrivilegesToRole") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
std::string help() const override {
return "Grants privileges to a role";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForGrantPrivilegesToRoleCommand(client, dbname, cmdObj);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
RoleName roleName;
PrivilegeVector privilegesToAdd;
Status status = auth::parseAndValidateRolePrivilegeManipulationCommands(
cmdObj, "grantPrivilegesToRole", dbname, &roleName, &privilegesToAdd);
uassertStatusOK(status);
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
auto lk = uassertStatusOK(requireWritableAuthSchema28SCRAM(opCtx, authzManager));
if (RoleGraph::isBuiltinRole(roleName)) {
uasserted(ErrorCodes::InvalidRoleModification,
str::stream() << roleName.getFullName()
<< " is a built-in role and cannot be modified.");
}
status = checkOkayToGrantPrivilegesToRole(roleName, privilegesToAdd);
uassertStatusOK(status);
BSONObj roleDoc;
status = authzManager->getRoleDescription(opCtx,
roleName,
PrivilegeFormat::kShowSeparate,
AuthenticationRestrictionsFormat::kOmit,
&roleDoc);
uassertStatusOK(status);
PrivilegeVector privileges;
status = auth::parseAndValidatePrivilegeArray(BSONArray(roleDoc["privileges"].Obj()),
&privileges);
uassertStatusOK(status);
for (PrivilegeVector::iterator it = privilegesToAdd.begin(); it != privilegesToAdd.end();
++it) {
Privilege::addPrivilegeToPrivilegeVector(&privileges, *it);
}
// Build up update modifier object to $set privileges.
mutablebson::Document updateObj;
mutablebson::Element setElement = updateObj.makeElementObject("$set");
status = updateObj.root().pushBack(setElement);
uassertStatusOK(status);
mutablebson::Element privilegesElement = updateObj.makeElementArray("privileges");
status = setElement.pushBack(privilegesElement);
uassertStatusOK(status);
status = Privilege::getBSONForPrivileges(privileges, privilegesElement);
uassertStatusOK(status);
BSONObjBuilder updateBSONBuilder;
updateObj.writeTo(&updateBSONBuilder);
audit::logGrantPrivilegesToRole(Client::getCurrent(), roleName, privilegesToAdd);
status = updateRoleDocument(opCtx, roleName, updateBSONBuilder.done());
// Must invalidate even on bad status - what if the write succeeded but the GLE failed?
authzManager->invalidateUserCache(opCtx);
uassertStatusOK(status);
return true;
}
} cmdGrantPrivilegesToRole;
class CmdRevokePrivilegesFromRole : public BasicCommand {
public:
CmdRevokePrivilegesFromRole() : BasicCommand("revokePrivilegesFromRole") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
std::string help() const override {
return "Revokes privileges from a role";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForRevokePrivilegesFromRoleCommand(client, dbname, cmdObj);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
RoleName roleName;
PrivilegeVector privilegesToRemove;
Status status = auth::parseAndValidateRolePrivilegeManipulationCommands(
cmdObj, "revokePrivilegesFromRole", dbname, &roleName, &privilegesToRemove);
uassertStatusOK(status);
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
auto lk = uassertStatusOK(requireWritableAuthSchema28SCRAM(opCtx, authzManager));
if (RoleGraph::isBuiltinRole(roleName)) {
uasserted(ErrorCodes::InvalidRoleModification,
str::stream() << roleName.getFullName()
<< " is a built-in role and cannot be modified.");
}
BSONObj roleDoc;
status = authzManager->getRoleDescription(opCtx,
roleName,
PrivilegeFormat::kShowSeparate,
AuthenticationRestrictionsFormat::kOmit,
&roleDoc);
uassertStatusOK(status);
PrivilegeVector privileges;
status = auth::parseAndValidatePrivilegeArray(BSONArray(roleDoc["privileges"].Obj()),
&privileges);
uassertStatusOK(status);
for (PrivilegeVector::iterator itToRm = privilegesToRemove.begin();
itToRm != privilegesToRemove.end();
++itToRm) {
for (PrivilegeVector::iterator curIt = privileges.begin(); curIt != privileges.end();
++curIt) {
if (curIt->getResourcePattern() == itToRm->getResourcePattern()) {
curIt->removeActions(itToRm->getActions());
if (curIt->getActions().empty()) {
privileges.erase(curIt);
}
break;
}
}
}
// Build up update modifier object to $set privileges.
mutablebson::Document updateObj;
mutablebson::Element setElement = updateObj.makeElementObject("$set");
status = updateObj.root().pushBack(setElement);
uassertStatusOK(status);
mutablebson::Element privilegesElement = updateObj.makeElementArray("privileges");
status = setElement.pushBack(privilegesElement);
uassertStatusOK(status);
status = Privilege::getBSONForPrivileges(privileges, privilegesElement);
uassertStatusOK(status);
audit::logRevokePrivilegesFromRole(Client::getCurrent(), roleName, privilegesToRemove);
BSONObjBuilder updateBSONBuilder;
updateObj.writeTo(&updateBSONBuilder);
status = updateRoleDocument(opCtx, roleName, updateBSONBuilder.done());
// Must invalidate even on bad status - what if the write succeeded but the GLE failed?
authzManager->invalidateUserCache(opCtx);
uassertStatusOK(status);
return true;
}
} cmdRevokePrivilegesFromRole;
class CmdGrantRolesToRole : public BasicCommand {
public:
CmdGrantRolesToRole() : BasicCommand("grantRolesToRole") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
std::string help() const override {
return "Grants roles to another role.";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForGrantRolesToRoleCommand(client, dbname, cmdObj);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
std::string roleNameString;
std::vector<RoleName> rolesToAdd;
Status status = auth::parseRolePossessionManipulationCommands(
cmdObj, "grantRolesToRole", dbname, &roleNameString, &rolesToAdd);
uassertStatusOK(status);
RoleName roleName(roleNameString, dbname);
if (RoleGraph::isBuiltinRole(roleName)) {
uasserted(ErrorCodes::InvalidRoleModification,
str::stream() << roleName.getFullName()
<< " is a built-in role and cannot be modified.");
}
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
auto lk = uassertStatusOK(requireWritableAuthSchema28SCRAM(opCtx, authzManager));
// Role existence has to be checked after acquiring the update lock
BSONObj roleDoc;
status = authzManager->getRoleDescription(opCtx, roleName, &roleDoc);
uassertStatusOK(status);
// Check for cycles
status = checkOkayToGrantRolesToRole(opCtx, roleName, rolesToAdd, authzManager);
uassertStatusOK(status);
// Add new roles to existing roles
std::vector<RoleName> directRoles;
status = auth::parseRoleNamesFromBSONArray(
BSONArray(roleDoc["roles"].Obj()), roleName.getDB(), &directRoles);
uassertStatusOK(status);
for (vector<RoleName>::iterator it = rolesToAdd.begin(); it != rolesToAdd.end(); ++it) {
const RoleName& roleToAdd = *it;
if (!sequenceContains(directRoles, roleToAdd)) // Don't double-add role
directRoles.push_back(*it);
}
audit::logGrantRolesToRole(Client::getCurrent(), roleName, rolesToAdd);
status = updateRoleDocument(
opCtx, roleName, BSON("$set" << BSON("roles" << rolesVectorToBSONArray(directRoles))));
// Must invalidate even on bad status - what if the write succeeded but the GLE failed?
authzManager->invalidateUserCache(opCtx);
uassertStatusOK(status);
return true;
}
} cmdGrantRolesToRole;
class CmdRevokeRolesFromRole : public BasicCommand {
public:
CmdRevokeRolesFromRole() : BasicCommand("revokeRolesFromRole") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
std::string help() const override {
return "Revokes roles from another role.";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForRevokeRolesFromRoleCommand(client, dbname, cmdObj);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
std::string roleNameString;
std::vector<RoleName> rolesToRemove;
Status status = auth::parseRolePossessionManipulationCommands(
cmdObj, "revokeRolesFromRole", dbname, &roleNameString, &rolesToRemove);
uassertStatusOK(status);
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
auto lk = uassertStatusOK(requireWritableAuthSchema28SCRAM(opCtx, authzManager));
RoleName roleName(roleNameString, dbname);
if (RoleGraph::isBuiltinRole(roleName)) {
uasserted(ErrorCodes::InvalidRoleModification,
str::stream() << roleName.getFullName()
<< " is a built-in role and cannot be modified.");
}
BSONObj roleDoc;
status = authzManager->getRoleDescription(opCtx, roleName, &roleDoc);
uassertStatusOK(status);
std::vector<RoleName> roles;
status = auth::parseRoleNamesFromBSONArray(
BSONArray(roleDoc["roles"].Obj()), roleName.getDB(), &roles);
uassertStatusOK(status);
for (vector<RoleName>::const_iterator it = rolesToRemove.begin(); it != rolesToRemove.end();
++it) {
vector<RoleName>::iterator itToRm = std::find(roles.begin(), roles.end(), *it);
if (itToRm != roles.end()) {
roles.erase(itToRm);
}
}
audit::logRevokeRolesFromRole(Client::getCurrent(), roleName, rolesToRemove);
status = updateRoleDocument(
opCtx, roleName, BSON("$set" << BSON("roles" << rolesVectorToBSONArray(roles))));
// Must invalidate even on bad status - what if the write succeeded but the GLE failed?
authzManager->invalidateUserCache(opCtx);
uassertStatusOK(status);
return true;
}
} cmdRevokeRolesFromRole;
class CmdDropRole : public BasicCommand {
public:
CmdDropRole() : BasicCommand("dropRole") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
std::string help() const override {
return "Drops a single role. Before deleting the role completely it must remove it "
"from any users or roles that reference it. If any errors occur in the middle "
"of that process it's possible to be left in a state where the role has been "
"removed from some user/roles but otherwise still exists.";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForDropRoleCommand(client, dbname, cmdObj);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
RoleName roleName;
Status status = auth::parseDropRoleCommand(cmdObj, dbname, &roleName);
uassertStatusOK(status);
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
auto lk = uassertStatusOK(requireWritableAuthSchema28SCRAM(opCtx, authzManager));
if (RoleGraph::isBuiltinRole(roleName)) {
uasserted(ErrorCodes::InvalidRoleModification,
str::stream() << roleName.getFullName()
<< " is a built-in role and cannot be modified.");
}
BSONObj roleDoc;
status = authzManager->getRoleDescription(opCtx, roleName, &roleDoc);
uassertStatusOK(status);
// From here on, we always want to invalidate the user cache before returning.
auto invalidateGuard = makeGuard([&] {
try {
authzManager->invalidateUserCache(opCtx);
} catch (const DBException& e) {
// Since this may be called after a uassert, we want to catch any uasserts
// that come out of invalidating the user cache and explicitly append it to
// the command response.
CommandHelpers::appendCommandStatusNoThrow(result, e.toStatus());
}
});
// Remove this role from all users
long long nMatched;
status = updateAuthzDocuments(
opCtx,
AuthorizationManager::usersCollectionNamespace,
BSON("roles" << BSON("$elemMatch" << BSON(AuthorizationManager::ROLE_NAME_FIELD_NAME
<< roleName.getRole()
<< AuthorizationManager::ROLE_DB_FIELD_NAME
<< roleName.getDB()))),
BSON("$pull" << BSON("roles" << BSON(AuthorizationManager::ROLE_NAME_FIELD_NAME
<< roleName.getRole()
<< AuthorizationManager::ROLE_DB_FIELD_NAME
<< roleName.getDB()))),
false,
true,
&nMatched);
if (!status.isOK()) {
uassertStatusOK(useDefaultCode(status, ErrorCodes::UserModificationFailed)
.withContext(str::stream() << "Failed to remove role "
<< roleName.getFullName()
<< " from all users"));
}
// Remove this role from all other roles
status = updateAuthzDocuments(
opCtx,
AuthorizationManager::rolesCollectionNamespace,
BSON("roles" << BSON("$elemMatch" << BSON(AuthorizationManager::ROLE_NAME_FIELD_NAME
<< roleName.getRole()
<< AuthorizationManager::ROLE_DB_FIELD_NAME
<< roleName.getDB()))),
BSON("$pull" << BSON("roles" << BSON(AuthorizationManager::ROLE_NAME_FIELD_NAME
<< roleName.getRole()
<< AuthorizationManager::ROLE_DB_FIELD_NAME
<< roleName.getDB()))),
false,
true,
&nMatched);
if (!status.isOK()) {
uassertStatusOK(
useDefaultCode(status, ErrorCodes::RoleModificationFailed)
.withContext(
str::stream() << "Removed role " << roleName.getFullName()
<< " from all users but failed to remove from all roles"));
}
audit::logDropRole(Client::getCurrent(), roleName);
// Finally, remove the actual role document
status = removeRoleDocuments(opCtx,
BSON(AuthorizationManager::ROLE_NAME_FIELD_NAME
<< roleName.getRole()
<< AuthorizationManager::ROLE_DB_FIELD_NAME
<< roleName.getDB()),
&nMatched);
if (!status.isOK()) {
uassertStatusOK(status.withContext(
str::stream() << "Removed role " << roleName.getFullName()
<< " from all users and roles but failed to actually delete"
" the role itself"));
}
dassert(nMatched == 0 || nMatched == 1);
if (nMatched == 0) {
uasserted(ErrorCodes::RoleNotFound,
str::stream() << "Role '" << roleName.getFullName() << "' not found");
}
return true;
}
} cmdDropRole;
class CmdDropAllRolesFromDatabase : public BasicCommand {
public:
CmdDropAllRolesFromDatabase() : BasicCommand("dropAllRolesFromDatabase") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
std::string help() const override {
return "Drops all roles from the given database. Before deleting the roles completely "
"it must remove them from any users or other roles that reference them. If any "
"errors occur in the middle of that process it's possible to be left in a state "
"where the roles have been removed from some user/roles but otherwise still "
"exist.";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForDropAllRolesFromDatabaseCommand(client, dbname);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
Status status = auth::parseDropAllRolesFromDatabaseCommand(cmdObj, dbname);
uassertStatusOK(status);
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
auto lk = uassertStatusOK(requireWritableAuthSchema28SCRAM(opCtx, authzManager));
// From here on, we always want to invalidate the user cache before returning.
auto invalidateGuard = makeGuard([&] {
try {
authzManager->invalidateUserCache(opCtx);
} catch (const DBException& e) {
// Since this may be called after a uassert, we want to catch any uasserts
// that come out of invalidating the user cache and explicitly append it to
// the command response.
CommandHelpers::appendCommandStatusNoThrow(result, e.toStatus());
}
});
// Remove these roles from all users
long long nMatched;
status = updateAuthzDocuments(
opCtx,
AuthorizationManager::usersCollectionNamespace,
BSON("roles" << BSON(AuthorizationManager::ROLE_DB_FIELD_NAME << dbname)),
BSON("$pull" << BSON("roles"
<< BSON(AuthorizationManager::ROLE_DB_FIELD_NAME << dbname))),
false,
true,
&nMatched);
if (!status.isOK()) {
uassertStatusOK(useDefaultCode(status, ErrorCodes::UserModificationFailed)
.withContext(str::stream() << "Failed to remove roles from \""
<< dbname
<< "\" db from all users"));
}
// Remove these roles from all other roles
std::string sourceFieldName = str::stream() << "roles."
<< AuthorizationManager::ROLE_DB_FIELD_NAME;
status = updateAuthzDocuments(
opCtx,
AuthorizationManager::rolesCollectionNamespace,
BSON(sourceFieldName << dbname),
BSON("$pull" << BSON("roles"
<< BSON(AuthorizationManager::ROLE_DB_FIELD_NAME << dbname))),
false,
true,
&nMatched);
if (!status.isOK()) {
uassertStatusOK(useDefaultCode(status, ErrorCodes::RoleModificationFailed)
.withContext(str::stream() << "Failed to remove roles from \""
<< dbname
<< "\" db from all roles"));
}
audit::logDropAllRolesFromDatabase(Client::getCurrent(), dbname);
// Finally, remove the actual role documents
status = removeRoleDocuments(
opCtx, BSON(AuthorizationManager::ROLE_DB_FIELD_NAME << dbname), &nMatched);
if (!status.isOK()) {
uassertStatusOK(status.withContext(
str::stream() << "Removed roles from \"" << dbname
<< "\" db "
" from all users and roles but failed to actually delete"
" those roles themselves"));
}
result.append("n", nMatched);
return true;
}
} cmdDropAllRolesFromDatabase;
/**
* Provides information about one or more roles, the indirect roles they are members of, and
* optionally the privileges they provide.
*
* This command accepts the following arguments:
* rolesInfo:
* (String) Returns information about a single role on the current database.
* {role: (String), db: (String)} Returns information about a specified role, on a specific db
* (BooleanTrue) Returns information about all roles in this database
* [ //Zero or more of
* {role: (String), db: (String) ] Returns information about all specified roles
*
* showBuiltinRoles:
* (Boolean) If true, and rolesInfo == (BooleanTrue), include built-in roles from the database
*
* showPrivileges:
* (BooleanFalse) Do not show information about privileges
* (BooleanTrue) Attach all privileges inherited from roles to role descriptions
* "asUserFragment" Render results as a partial user document as-if a user existed which possessed
* these roles. This format may change over time with changes to the auth
* schema.
*/
class CmdRolesInfo : public BasicCommand {
public:
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kOptIn;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return false;
}
CmdRolesInfo() : BasicCommand("rolesInfo") {}
std::string help() const override {
return "Returns information about roles.";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForRolesInfoCommand(client, dbname, cmdObj);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
auth::RolesInfoArgs args;
Status status = auth::parseRolesInfoCommand(cmdObj, dbname, &args);
uassertStatusOK(status);
AuthorizationManager* authzManager = AuthorizationManager::get(opCtx->getServiceContext());
auto lk = uassertStatusOK(requireReadableAuthSchema26Upgrade(opCtx, authzManager));
if (args.allForDB) {
std::vector<BSONObj> rolesDocs;
status = authzManager->getRoleDescriptionsForDB(opCtx,
dbname,
args.privilegeFormat,
args.authenticationRestrictionsFormat,
args.showBuiltinRoles,
&rolesDocs);
uassertStatusOK(status);
if (args.privilegeFormat == PrivilegeFormat::kShowAsUserFragment) {
uasserted(ErrorCodes::IllegalOperation,
"Cannot get user fragment for all roles in a database");
}
BSONArrayBuilder rolesArrayBuilder;
for (size_t i = 0; i < rolesDocs.size(); ++i) {
rolesArrayBuilder.append(rolesDocs[i]);
}
result.append("roles", rolesArrayBuilder.arr());
} else {
BSONObj roleDetails;
status = authzManager->getRolesDescription(opCtx,
args.roleNames,
args.privilegeFormat,
args.authenticationRestrictionsFormat,
&roleDetails);
uassertStatusOK(status);
if (args.privilegeFormat == PrivilegeFormat::kShowAsUserFragment) {
result.append("userFragment", roleDetails);
} else {
result.append("roles", BSONArray(roleDetails));
}
}
return true;
}
} cmdRolesInfo;
class CmdInvalidateUserCache : public BasicCommand {
public:
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kAlways;
}
virtual bool adminOnly() const {
return true;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return false;
}
CmdInvalidateUserCache() : BasicCommand("invalidateUserCache") {}
std::string help() const override {
return "Invalidates the in-memory cache of user information";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForInvalidateUserCacheCommand(client);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
AuthorizationManager* authzManager = AuthorizationManager::get(opCtx->getServiceContext());
auto lk = requireReadableAuthSchema26Upgrade(opCtx, authzManager);
authzManager->invalidateUserCache(opCtx);
return true;
}
} cmdInvalidateUserCache;
class CmdGetCacheGeneration : public BasicCommand {
public:
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kAlways;
}
virtual bool adminOnly() const {
return true;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return false;
}
CmdGetCacheGeneration() : BasicCommand("_getUserCacheGeneration") {}
std::string help() const override {
return "internal";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForGetUserCacheGenerationCommand(client);
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
AuthorizationManager* authzManager = AuthorizationManager::get(opCtx->getServiceContext());
result.append("cacheGeneration", authzManager->getCacheGeneration());
return true;
}
} CmdGetCacheGeneration;
/**
* This command is used only by mongorestore to handle restoring users/roles. We do this so
* that mongorestore doesn't do direct inserts into the admin.system.users and
* admin.system.roles, which would bypass the authzUpdateLock and allow multiple concurrent
* modifications to users/roles. What mongorestore now does instead is it inserts all user/role
* definitions it wants to restore into temporary collections, then this command moves those
* user/role definitions into their proper place in admin.system.users and admin.system.roles.
* It either adds the users/roles to the existing ones or replaces the existing ones, depending
* on whether the "drop" argument is true or false.
*/
class CmdMergeAuthzCollections : public BasicCommand {
public:
CmdMergeAuthzCollections() : BasicCommand("_mergeAuthzCollections") {}
AllowedOnSecondary secondaryAllowed(ServiceContext*) const override {
return AllowedOnSecondary::kNever;
}
virtual bool supportsWriteConcern(const BSONObj& cmd) const override {
return true;
}
virtual bool adminOnly() const {
return true;
}
std::string help() const override {
return "Internal command used by mongorestore for updating user/role data";
}
virtual Status checkAuthForCommand(Client* client,
const std::string& dbname,
const BSONObj& cmdObj) const {
return auth::checkAuthForMergeAuthzCollectionsCommand(client, cmdObj);
}
static UserName extractUserNameFromBSON(const BSONObj& userObj) {
std::string name;
std::string db;
Status status =
bsonExtractStringField(userObj, AuthorizationManager::USER_NAME_FIELD_NAME, &name);
uassertStatusOK(status);
status = bsonExtractStringField(userObj, AuthorizationManager::USER_DB_FIELD_NAME, &db);
uassertStatusOK(status);
return UserName(name, db);
}
static RoleName extractRoleNameFromBSON(const BSONObj& roleObj) {
std::string name;
std::string db;
Status status =
bsonExtractStringField(roleObj, AuthorizationManager::ROLE_NAME_FIELD_NAME, &name);
uassertStatusOK(status);
status = bsonExtractStringField(roleObj, AuthorizationManager::ROLE_DB_FIELD_NAME, &db);
uassertStatusOK(status);
return RoleName(name, db);
}
/**
* Audits the fact that we are creating or updating the user described by userObj.
*/
static void auditCreateOrUpdateUser(const BSONObj& userObj, bool create) {
UserName userName = extractUserNameFromBSON(userObj);
std::vector<RoleName> roles;
uassertStatusOK(auth::parseRoleNamesFromBSONArray(
BSONArray(userObj["roles"].Obj()), userName.getDB(), &roles));
BSONObj customData;
if (userObj.hasField("customData")) {
customData = userObj["customData"].Obj();
}
boost::optional<BSONArray> authenticationRestrictions;
if (userObj.hasField("authenticationRestrictions")) {
auto r = getRawAuthenticationRestrictions(
BSONArray(userObj["authenticationRestrictions"].Obj()));
uassertStatusOK(r);
authenticationRestrictions = r.getValue();
}
const bool hasPwd = userObj["credentials"].Obj().hasField("SCRAM-SHA-1") ||
userObj["credentials"].Obj().hasField("SCRAM-SHA-256");
if (create) {
audit::logCreateUser(Client::getCurrent(),
userName,
hasPwd,
userObj.hasField("customData") ? &customData : NULL,
roles,
authenticationRestrictions);
} else {
audit::logUpdateUser(Client::getCurrent(),
userName,
hasPwd,
userObj.hasField("customData") ? &customData : NULL,
&roles,
authenticationRestrictions);
}
}
/**
* Audits the fact that we are creating or updating the role described by roleObj.
*/
static void auditCreateOrUpdateRole(const BSONObj& roleObj, bool create) {
RoleName roleName = extractRoleNameFromBSON(roleObj);
std::vector<RoleName> roles;
std::vector<Privilege> privileges;
uassertStatusOK(auth::parseRoleNamesFromBSONArray(
BSONArray(roleObj["roles"].Obj()), roleName.getDB(), &roles));
uassertStatusOK(auth::parseAndValidatePrivilegeArray(BSONArray(roleObj["privileges"].Obj()),
&privileges));
boost::optional<BSONArray> authenticationRestrictions;
if (roleObj.hasField("authenticationRestrictions")) {
auto r = getRawAuthenticationRestrictions(
BSONArray(roleObj["authenticationRestrictions"].Obj()));
uassertStatusOK(r);
authenticationRestrictions = r.getValue();
}
if (create) {
audit::logCreateRole(
Client::getCurrent(), roleName, roles, privileges, authenticationRestrictions);
} else {
audit::logUpdateRole(
Client::getCurrent(), roleName, &roles, &privileges, authenticationRestrictions);
}
}
/**
* Designed to be used as a callback to be called on every user object in the result
* set of a query over the tempUsersCollection provided to the command. For each user
* in the temp collection that is defined on the given db, adds that user to the actual
* admin.system.users collection.
* Also removes any users it encounters from the usersToDrop set.
*/
static void addUser(OperationContext* opCtx,
AuthorizationManager* authzManager,
StringData db,
bool update,
stdx::unordered_set<UserName>* usersToDrop,
const BSONObj& userObj) {
UserName userName = extractUserNameFromBSON(userObj);
if (!db.empty() && userName.getDB() != db) {
return;
}
if (update && usersToDrop->count(userName)) {
auditCreateOrUpdateUser(userObj, false);
Status status = updatePrivilegeDocument(opCtx, userName, userObj);
if (!status.isOK()) {
// Match the behavior of mongorestore to continue on failure
warning() << "Could not update user " << userName
<< " in _mergeAuthzCollections command: " << redact(status);
}
} else {
auditCreateOrUpdateUser(userObj, true);
Status status = insertPrivilegeDocument(opCtx, userObj);
if (!status.isOK()) {
// Match the behavior of mongorestore to continue on failure
warning() << "Could not insert user " << userName
<< " in _mergeAuthzCollections command: " << redact(status);
}
}
usersToDrop->erase(userName);
}
/**
* Designed to be used as a callback to be called on every role object in the result
* set of a query over the tempRolesCollection provided to the command. For each role
* in the temp collection that is defined on the given db, adds that role to the actual
* admin.system.roles collection.
* Also removes any roles it encounters from the rolesToDrop set.
*/
static void addRole(OperationContext* opCtx,
AuthorizationManager* authzManager,
StringData db,
bool update,
stdx::unordered_set<RoleName>* rolesToDrop,
const BSONObj roleObj) {
RoleName roleName = extractRoleNameFromBSON(roleObj);
if (!db.empty() && roleName.getDB() != db) {
return;
}
if (update && rolesToDrop->count(roleName)) {
auditCreateOrUpdateRole(roleObj, false);
Status status = updateRoleDocument(opCtx, roleName, roleObj);
if (!status.isOK()) {
// Match the behavior of mongorestore to continue on failure
warning() << "Could not update role " << roleName
<< " in _mergeAuthzCollections command: " << redact(status);
}
} else {
auditCreateOrUpdateRole(roleObj, true);
Status status = insertRoleDocument(opCtx, roleObj);
if (!status.isOK()) {
// Match the behavior of mongorestore to continue on failure
warning() << "Could not insert role " << roleName
<< " in _mergeAuthzCollections command: " << redact(status);
}
}
rolesToDrop->erase(roleName);
}
/**
* Moves all user objects from usersCollName into admin.system.users. If drop is true,
* removes any users that were in admin.system.users but not in usersCollName.
*/
Status processUsers(OperationContext* opCtx,
AuthorizationManager* authzManager,
StringData usersCollName,
StringData db,
bool drop) {
// When the "drop" argument has been provided, we use this set to store the users
// that are currently in the system, and remove from it as we encounter
// same-named users in the collection we are restoring from. Once we've fully
// moved over the temp users collection into its final location, we drop
// any users that previously existed there but weren't in the temp collection.
// This is so that we can completely replace the system.users
// collection with the users from the temp collection, without removing all
// users at the beginning and thus potentially locking ourselves out by having
// no users in the whole system for a time.
stdx::unordered_set<UserName> usersToDrop;
if (drop) {
// Create map of the users currently in the DB
BSONObj query =
db.empty() ? BSONObj() : BSON(AuthorizationManager::USER_DB_FIELD_NAME << db);
BSONObj fields = BSON(AuthorizationManager::USER_NAME_FIELD_NAME
<< 1
<< AuthorizationManager::USER_DB_FIELD_NAME
<< 1);
Status status =
queryAuthzDocument(opCtx,
AuthorizationManager::usersCollectionNamespace,
query,
fields,
[&](const BSONObj& userObj) {
usersToDrop.insert(extractUserNameFromBSON(userObj));
});
if (!status.isOK()) {
return status;
}
}
Status status = queryAuthzDocument(
opCtx,
NamespaceString(usersCollName),
db.empty() ? BSONObj() : BSON(AuthorizationManager::USER_DB_FIELD_NAME << db),
BSONObj(),
[&](const BSONObj& userObj) {
return addUser(opCtx, authzManager, db, drop, &usersToDrop, userObj);
});
if (!status.isOK()) {
return status;
}
if (drop) {
long long numRemoved;
for (const UserName& userName : usersToDrop) {
audit::logDropUser(Client::getCurrent(), userName);
status = removePrivilegeDocuments(opCtx,
BSON(AuthorizationManager::USER_NAME_FIELD_NAME
<< userName.getUser().toString()
<< AuthorizationManager::USER_DB_FIELD_NAME
<< userName.getDB().toString()),
&numRemoved);
if (!status.isOK()) {
return status;
}
dassert(numRemoved == 1);
}
}
return Status::OK();
}
/**
* Moves all user objects from usersCollName into admin.system.users. If drop is true,
* removes any users that were in admin.system.users but not in usersCollName.
*/
Status processRoles(OperationContext* opCtx,
AuthorizationManager* authzManager,
StringData rolesCollName,
StringData db,
bool drop) {
// When the "drop" argument has been provided, we use this set to store the roles
// that are currently in the system, and remove from it as we encounter
// same-named roles in the collection we are restoring from. Once we've fully
// moved over the temp roles collection into its final location, we drop
// any roles that previously existed there but weren't in the temp collection.
// This is so that we can completely replace the system.roles
// collection with the roles from the temp collection, without removing all
// roles at the beginning and thus potentially locking ourselves out.
stdx::unordered_set<RoleName> rolesToDrop;
if (drop) {
// Create map of the roles currently in the DB
BSONObj query =
db.empty() ? BSONObj() : BSON(AuthorizationManager::ROLE_DB_FIELD_NAME << db);
BSONObj fields = BSON(AuthorizationManager::ROLE_NAME_FIELD_NAME
<< 1
<< AuthorizationManager::ROLE_DB_FIELD_NAME
<< 1);
Status status =
queryAuthzDocument(opCtx,
AuthorizationManager::rolesCollectionNamespace,
query,
fields,
[&](const BSONObj& roleObj) {
return rolesToDrop.insert(extractRoleNameFromBSON(roleObj));
});
if (!status.isOK()) {
return status;
}
}
Status status = queryAuthzDocument(
opCtx,
NamespaceString(rolesCollName),
db.empty() ? BSONObj() : BSON(AuthorizationManager::ROLE_DB_FIELD_NAME << db),
BSONObj(),
[&](const BSONObj& roleObj) {
return addRole(opCtx, authzManager, db, drop, &rolesToDrop, roleObj);
});
if (!status.isOK()) {
return status;
}
if (drop) {
long long numRemoved;
for (stdx::unordered_set<RoleName>::iterator it = rolesToDrop.begin();
it != rolesToDrop.end();
++it) {
const RoleName& roleName = *it;
audit::logDropRole(Client::getCurrent(), roleName);
status = removeRoleDocuments(opCtx,
BSON(AuthorizationManager::ROLE_NAME_FIELD_NAME
<< roleName.getRole().toString()
<< AuthorizationManager::ROLE_DB_FIELD_NAME
<< roleName.getDB().toString()),
&numRemoved);
if (!status.isOK()) {
return status;
}
dassert(numRemoved == 1);
}
}
return Status::OK();
}
bool run(OperationContext* opCtx,
const string& dbname,
const BSONObj& cmdObj,
BSONObjBuilder& result) {
auth::MergeAuthzCollectionsArgs args;
Status status = auth::parseMergeAuthzCollectionsCommand(cmdObj, &args);
uassertStatusOK(status);
if (args.usersCollName.empty() && args.rolesCollName.empty()) {
uasserted(ErrorCodes::BadValue,
"Must provide at least one of \"tempUsersCollection\" and "
"\"tempRolescollection\"");
}
ServiceContext* serviceContext = opCtx->getClient()->getServiceContext();
AuthorizationManager* authzManager = AuthorizationManager::get(serviceContext);
auto lk = uassertStatusOK(requireWritableAuthSchema28SCRAM(opCtx, authzManager));
// From here on, we always want to invalidate the user cache before returning.
auto invalidateGuard = makeGuard([&] {
try {
authzManager->invalidateUserCache(opCtx);
} catch (const DBException& e) {
// Since this may be called after a uassert, we want to catch any uasserts
// that come out of invalidating the user cache and explicitly append it to
// the command response.
CommandHelpers::appendCommandStatusNoThrow(result, e.toStatus());
}
});
if (!args.usersCollName.empty()) {
Status status =
processUsers(opCtx, authzManager, args.usersCollName, args.db, args.drop);
uassertStatusOK(status);
}
if (!args.rolesCollName.empty()) {
Status status =
processRoles(opCtx, authzManager, args.rolesCollName, args.db, args.drop);
uassertStatusOK(status);
}
return true;
}
} cmdMergeAuthzCollections;
} // namespace mongo
|