forked from heavyai/heavydb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSysCatalog.cpp
2318 lines (2130 loc) · 86.1 KB
/
SysCatalog.cpp
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
/*
* Copyright 2019 MapD Technologies, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file SysCatalog.cpp
* @author Todd Mostak <todd@map-d.com>, Wei Hong <wei@map-d.com>
* @brief Functions for System Catalog
*
* Copyright (c) 2014 MapD Technologies, Inc. All rights reserved.
**/
#include "SysCatalog.h"
#include <algorithm>
#include <cassert>
#include <exception>
#include <list>
#include <memory>
#include <random>
#include <sstream>
#include <string_view>
#include "Catalog.h"
#include "Catalog/AuthMetadata.h"
#include "LockMgr/LockMgr.h"
#include "QueryEngine/ExternalCacheInvalidators.h"
#include <boost/algorithm/string/predicate.hpp>
#include <boost/filesystem.hpp>
#include <boost/range/adaptor/map.hpp>
#include <boost/version.hpp>
#include "../Parser/ParserNode.h"
#include "../Shared/File.h"
#include "../Shared/StringTransform.h"
#include "../Shared/measure.h"
#include "MapDRelease.h"
#include "RWLocks.h"
#include "bcrypt.h"
using std::list;
using std::map;
using std::pair;
using std::runtime_error;
using std::string;
using std::vector;
using namespace std::string_literals;
extern bool g_enable_fsi;
namespace {
std::string hash_with_bcrypt(const std::string& pwd) {
char salt[BCRYPT_HASHSIZE], hash[BCRYPT_HASHSIZE];
CHECK(bcrypt_gensalt(-1, salt) == 0);
CHECK(bcrypt_hashpw(pwd.c_str(), salt, hash) == 0);
return std::string(hash, BCRYPT_HASHSIZE);
}
} // namespace
namespace Catalog_Namespace {
thread_local bool SysCatalog::thread_holds_read_lock = false;
using sys_read_lock = read_lock<SysCatalog>;
using sys_write_lock = write_lock<SysCatalog>;
using sys_sqlite_lock = sqlite_lock<SysCatalog>;
auto CommonFileOperations::assembleCatalogName(std::string const& name) {
return base_path_ + "/mapd_catalogs/" + name;
};
void CommonFileOperations::removeCatalogByFullPath(std::string const& full_path) {
boost::filesystem::remove(full_path);
}
void CommonFileOperations::removeCatalogByName(std::string const& name) {
boost::filesystem::remove(assembleCatalogName(name));
};
auto CommonFileOperations::duplicateAndRenameCatalog(std::string const& current_name,
std::string const& new_name) {
auto full_current_path = assembleCatalogName(current_name);
auto full_new_path = assembleCatalogName(new_name);
try {
boost::filesystem::copy_file(full_current_path, full_new_path);
} catch (std::exception& e) {
std::string err_message{"Could not copy file " + full_current_path + " to " +
full_new_path + " exception was " + e.what()};
LOG(ERROR) << err_message;
throw std::runtime_error(err_message);
}
return std::make_pair(full_current_path, full_new_path);
};
void SysCatalog::init(const std::string& basePath,
std::shared_ptr<Data_Namespace::DataMgr> dataMgr,
const AuthMetadata& authMetadata,
std::shared_ptr<Calcite> calcite,
bool is_new_db,
bool aggregator,
const std::vector<LeafHostInfo>& string_dict_hosts) {
{
sys_write_lock write_lock(this);
sys_sqlite_lock sqlite_lock(this);
basePath_ = basePath;
dataMgr_ = dataMgr;
authMetadata_ = &authMetadata;
ldap_server_.reset(new LdapServer(*authMetadata_));
rest_server_.reset(new RestServer(*authMetadata_));
pki_server_.reset(new PkiServer(*authMetadata_));
calciteMgr_ = calcite;
string_dict_hosts_ = string_dict_hosts;
aggregator_ = aggregator;
bool db_exists =
boost::filesystem::exists(basePath_ + "/mapd_catalogs/" + OMNISCI_SYSTEM_CATALOG);
sqliteConnector_.reset(
new SqliteConnector(OMNISCI_SYSTEM_CATALOG, basePath_ + "/mapd_catalogs/"));
if (is_new_db) {
initDB();
} else {
if (!db_exists) {
importDataFromOldMapdDB();
}
checkAndExecuteMigrations();
}
buildRoleMap();
buildUserRoleMap();
buildObjectDescriptorMap();
}
}
SysCatalog::~SysCatalog() {
sys_write_lock write_lock(this);
for (auto grantee = granteeMap_.begin(); grantee != granteeMap_.end(); ++grantee) {
delete grantee->second;
}
granteeMap_.clear();
for (ObjectRoleDescriptorMap::iterator objectIt = objectDescriptorMap_.begin();
objectIt != objectDescriptorMap_.end();) {
ObjectRoleDescriptorMap::iterator eraseIt = objectIt++;
delete eraseIt->second;
}
objectDescriptorMap_.clear();
}
void SysCatalog::initDB() {
sys_sqlite_lock sqlite_lock(this);
sqliteConnector_->query("BEGIN TRANSACTION");
try {
sqliteConnector_->query(
"CREATE TABLE mapd_users (userid integer primary key, name text unique, "
"passwd_hash text, issuper boolean, default_db integer references "
"mapd_databases, can_login boolean)");
sqliteConnector_->query_with_text_params(
"INSERT INTO mapd_users VALUES (?, ?, ?, 1, NULL, 1)",
std::vector<std::string>{OMNISCI_ROOT_USER_ID_STR,
OMNISCI_ROOT_USER,
hash_with_bcrypt(OMNISCI_ROOT_PASSWD_DEFAULT)});
sqliteConnector_->query(
"CREATE TABLE mapd_databases (dbid integer primary key, name text unique, owner "
"integer references mapd_users)");
sqliteConnector_->query(
"CREATE TABLE mapd_roles(roleName text, userName text, UNIQUE(roleName, "
"userName))");
sqliteConnector_->query(
"CREATE TABLE mapd_object_permissions ("
"roleName text, "
"roleType bool, "
"dbId integer references mapd_databases, "
"objectName text, "
"objectId integer, "
"objectPermissionsType integer, "
"objectPermissions integer, "
"objectOwnerId integer, UNIQUE(roleName, objectPermissionsType, dbId, "
"objectId))");
} catch (const std::exception&) {
sqliteConnector_->query("ROLLBACK TRANSACTION");
throw;
}
sqliteConnector_->query("END TRANSACTION");
createDatabase(OMNISCI_DEFAULT_DB, OMNISCI_ROOT_USER_ID);
}
void SysCatalog::checkAndExecuteMigrations() {
migratePrivileged_old();
createUserRoles();
migratePrivileges();
migrateDBAccessPrivileges();
updateUserSchema(); // must come before updatePasswordsToHashes()
updatePasswordsToHashes();
updateBlankPasswordsToRandom(); // must come after updatePasswordsToHashes()
updateSupportUserDeactivation();
}
void SysCatalog::updateUserSchema() {
sys_sqlite_lock sqlite_lock(this);
// check to see if the new column already exists
sqliteConnector_->query("PRAGMA TABLE_INFO(mapd_users)");
for (size_t i = 0; i < sqliteConnector_->getNumRows(); i++) {
const auto& col_name = sqliteConnector_->getData<std::string>(i, 1);
if (col_name == "default_db") {
return; // new column already exists
}
}
// create the new column
sqliteConnector_->query("BEGIN TRANSACTION");
try {
sqliteConnector_->query(
"ALTER TABLE mapd_users ADD COLUMN default_db INTEGER REFERENCES mapd_databases");
} catch (const std::exception& e) {
sqliteConnector_->query("ROLLBACK TRANSACTION");
throw;
}
sqliteConnector_->query("END TRANSACTION");
}
void SysCatalog::importDataFromOldMapdDB() {
sys_sqlite_lock sqlite_lock(this);
std::string mapd_db_path = basePath_ + "/mapd_catalogs/mapd";
sqliteConnector_->query("ATTACH DATABASE `" + mapd_db_path + "` as old_cat");
sqliteConnector_->query("BEGIN TRANSACTION");
LOG(INFO) << "Moving global metadata into a separate catalog";
try {
auto moveTableIfExists = [conn = sqliteConnector_.get()](const std::string& tableName,
bool deleteOld = true) {
conn->query("SELECT sql FROM old_cat.sqlite_master WHERE type='table' AND name='" +
tableName + "'");
if (conn->getNumRows() != 0) {
conn->query(conn->getData<string>(0, 0));
conn->query("INSERT INTO " + tableName + " SELECT * FROM old_cat." + tableName);
if (deleteOld) {
conn->query("DROP TABLE old_cat." + tableName);
}
}
};
moveTableIfExists("mapd_users");
moveTableIfExists("mapd_databases");
moveTableIfExists("mapd_roles");
moveTableIfExists("mapd_object_permissions");
moveTableIfExists("mapd_privileges");
moveTableIfExists("mapd_version_history", false);
} catch (const std::exception& e) {
LOG(ERROR) << "Failed to move global metadata into a separate catalog: " << e.what();
sqliteConnector_->query("ROLLBACK TRANSACTION");
try {
sqliteConnector_->query("DETACH DATABASE old_cat");
} catch (const std::exception&) {
// nothing to do here
}
throw;
}
sqliteConnector_->query("END TRANSACTION");
const std::string sys_catalog_path =
basePath_ + "/mapd_catalogs/" + OMNISCI_SYSTEM_CATALOG;
LOG(INFO) << "Global metadata has been successfully moved into a separate catalog: "
<< sys_catalog_path
<< ". Using this database with an older version of omnisci_server "
"is now impossible.";
try {
sqliteConnector_->query("DETACH DATABASE old_cat");
} catch (const std::exception&) {
// nothing to do here
}
}
void SysCatalog::createUserRoles() {
sys_sqlite_lock sqlite_lock(this);
sqliteConnector_->query("BEGIN TRANSACTION");
try {
sqliteConnector_->query(
"SELECT name FROM sqlite_master WHERE type='table' AND name='mapd_roles'");
if (sqliteConnector_->getNumRows() != 0) {
// already done
sqliteConnector_->query("END TRANSACTION");
return;
}
sqliteConnector_->query(
"CREATE TABLE mapd_roles(roleName text, userName text, UNIQUE(roleName, "
"userName))");
// need to account for old conversions where we are building and moving
// from pre version 4.0 and 'mapd' was default superuser
sqliteConnector_->query("SELECT name FROM mapd_users WHERE name NOT IN ( \'" +
OMNISCI_ROOT_USER + "\', 'mapd')");
size_t numRows = sqliteConnector_->getNumRows();
vector<string> user_names;
for (size_t i = 0; i < numRows; ++i) {
user_names.push_back(sqliteConnector_->getData<string>(i, 0));
}
for (const auto& user_name : user_names) {
// for each user, create a fake role with the same name
sqliteConnector_->query_with_text_params(
"INSERT INTO mapd_roles(roleName, userName) VALUES (?, ?)",
vector<string>{user_name, user_name});
}
} catch (const std::exception&) {
sqliteConnector_->query("ROLLBACK TRANSACTION");
throw;
}
sqliteConnector_->query("END TRANSACTION");
}
void deleteObjectPrivileges(std::unique_ptr<SqliteConnector>& sqliteConnector,
std::string roleName,
bool userRole,
DBObject& object) {
DBObjectKey key = object.getObjectKey();
sqliteConnector->query_with_text_params(
"DELETE FROM mapd_object_permissions WHERE roleName = ?1 and roleType = ?2 and "
"objectPermissionsType = ?3 and "
"dbId = "
"?4 "
"and objectId = ?5",
std::vector<std::string>{roleName,
std::to_string(userRole),
std::to_string(key.permissionType),
std::to_string(key.dbId),
std::to_string(key.objectId)});
}
void insertOrUpdateObjectPrivileges(std::unique_ptr<SqliteConnector>& sqliteConnector,
std::string roleName,
bool userRole,
DBObject& object) {
DBObjectKey key = object.getObjectKey();
sqliteConnector->query_with_text_params(
"INSERT OR REPLACE INTO mapd_object_permissions("
"roleName, "
"roleType, "
"objectPermissionsType, "
"dbId, "
"objectId, "
"objectPermissions, "
"objectOwnerId,"
"objectName) "
"VALUES (?1, ?2, ?3, "
"?4, ?5, ?6, ?7, ?8)",
std::vector<std::string>{
roleName, // roleName
userRole ? "1" : "0", // roleType
std::to_string(key.permissionType), // permissionType
std::to_string(key.dbId), // dbId
std::to_string(key.objectId), // objectId
std::to_string(object.getPrivileges().privileges), // objectPrivileges
std::to_string(object.getOwner()), // objectOwnerId
object.getName() // name
});
}
void SysCatalog::migratePrivileges() {
sys_sqlite_lock sqlite_lock(this);
sqliteConnector_->query("BEGIN TRANSACTION");
try {
sqliteConnector_->query(
"SELECT name FROM sqlite_master WHERE type='table' AND "
"name='mapd_object_permissions'");
if (sqliteConnector_->getNumRows() != 0) {
// already done
sqliteConnector_->query("END TRANSACTION");
return;
}
sqliteConnector_->query(
"CREATE TABLE IF NOT EXISTS mapd_object_permissions ("
"roleName text, "
"roleType bool, "
"dbId integer references mapd_databases, "
"objectName text, "
"objectId integer, "
"objectPermissionsType integer, "
"objectPermissions integer, "
"objectOwnerId integer, UNIQUE(roleName, objectPermissionsType, dbId, "
"objectId))");
// get the list of databases and their grantees
sqliteConnector_->query(
"SELECT userid, dbid FROM mapd_privileges WHERE select_priv = 1 and insert_priv "
"= 1");
size_t numRows = sqliteConnector_->getNumRows();
vector<pair<int, int>> db_grantees(numRows);
for (size_t i = 0; i < numRows; ++i) {
db_grantees[i].first = sqliteConnector_->getData<int>(i, 0);
db_grantees[i].second = sqliteConnector_->getData<int>(i, 1);
}
// map user names to user ids
sqliteConnector_->query("select userid, name from mapd_users");
numRows = sqliteConnector_->getNumRows();
std::unordered_map<int, string> users_by_id;
std::unordered_map<int, bool> user_has_privs;
for (size_t i = 0; i < numRows; ++i) {
users_by_id[sqliteConnector_->getData<int>(i, 0)] =
sqliteConnector_->getData<string>(i, 1);
user_has_privs[sqliteConnector_->getData<int>(i, 0)] = false;
}
// map db names to db ids
sqliteConnector_->query("select dbid, name from mapd_databases");
numRows = sqliteConnector_->getNumRows();
std::unordered_map<int, string> dbs_by_id;
for (size_t i = 0; i < numRows; ++i) {
dbs_by_id[sqliteConnector_->getData<int>(i, 0)] =
sqliteConnector_->getData<string>(i, 1);
}
// migrate old privileges to new privileges: if user had insert access to database, he
// was a grantee
for (const auto& grantee : db_grantees) {
user_has_privs[grantee.first] = true;
auto dbName = dbs_by_id[grantee.second];
{
// table level permissions
DBObjectKey key;
key.permissionType = DBObjectType::TableDBObjectType;
key.dbId = grantee.second;
DBObject object(key, AccessPrivileges::ALL_TABLE_MIGRATE, OMNISCI_ROOT_USER_ID);
object.setName(dbName);
insertOrUpdateObjectPrivileges(
sqliteConnector_, users_by_id[grantee.first], true, object);
}
{
// dashboard level permissions
DBObjectKey key;
key.permissionType = DBObjectType::DashboardDBObjectType;
key.dbId = grantee.second;
DBObject object(
key, AccessPrivileges::ALL_DASHBOARD_MIGRATE, OMNISCI_ROOT_USER_ID);
object.setName(dbName);
insertOrUpdateObjectPrivileges(
sqliteConnector_, users_by_id[grantee.first], true, object);
}
{
// view level permissions
DBObjectKey key;
key.permissionType = DBObjectType::ViewDBObjectType;
key.dbId = grantee.second;
DBObject object(key, AccessPrivileges::ALL_VIEW_MIGRATE, OMNISCI_ROOT_USER_ID);
object.setName(dbName);
insertOrUpdateObjectPrivileges(
sqliteConnector_, users_by_id[grantee.first], true, object);
}
}
for (auto user : user_has_privs) {
auto dbName = dbs_by_id[0];
if (user.second == false && user.first != OMNISCI_ROOT_USER_ID) {
{
DBObjectKey key;
key.permissionType = DBObjectType::DatabaseDBObjectType;
key.dbId = 0;
DBObject object(key, AccessPrivileges::NONE, OMNISCI_ROOT_USER_ID);
object.setName(dbName);
insertOrUpdateObjectPrivileges(
sqliteConnector_, users_by_id[user.first], true, object);
}
}
}
} catch (const std::exception&) {
sqliteConnector_->query("ROLLBACK TRANSACTION");
throw;
}
sqliteConnector_->query("END TRANSACTION");
}
void SysCatalog::updatePasswordsToHashes() {
sys_sqlite_lock sqlite_lock(this);
sqliteConnector_->query("BEGIN TRANSACTION");
try {
sqliteConnector_->query(
"SELECT name FROM sqlite_master WHERE type='table' AND name='mapd_users'");
if (sqliteConnector_->getNumRows() == 0) {
// Nothing to update
sqliteConnector_->query("END TRANSACTION");
return;
}
sqliteConnector_->query("PRAGMA TABLE_INFO(mapd_users)");
for (size_t i = 0; i < sqliteConnector_->getNumRows(); i++) {
const auto& col_name = sqliteConnector_->getData<std::string>(i, 1);
if (col_name == "passwd_hash") {
sqliteConnector_->query("END TRANSACTION");
return;
}
}
// Alas, SQLite can't drop columns so we have to recreate the table
// (or, optionally, add the new column and reset the old one to a bunch of nulls)
sqliteConnector_->query("SELECT userid, passwd FROM mapd_users");
auto numRows = sqliteConnector_->getNumRows();
vector<std::string> users, passwords;
for (size_t i = 0; i < numRows; i++) {
users.push_back(sqliteConnector_->getData<std::string>(i, 0));
passwords.push_back(sqliteConnector_->getData<std::string>(i, 1));
}
sqliteConnector_->query(
"CREATE TABLE mapd_users_tmp (userid integer primary key, name text unique, "
"passwd_hash text, issuper boolean, default_db integer references "
"mapd_databases)");
sqliteConnector_->query(
"INSERT INTO mapd_users_tmp(userid, name, passwd_hash, issuper, default_db) "
"SELECT userid, name, null, issuper, default_db FROM mapd_users");
for (size_t i = 0; i < users.size(); ++i) {
sqliteConnector_->query_with_text_params(
"UPDATE mapd_users_tmp SET passwd_hash = ? WHERE userid = ?",
std::vector<std::string>{hash_with_bcrypt(passwords[i]), users[i]});
}
sqliteConnector_->query("DROP TABLE mapd_users");
sqliteConnector_->query("ALTER TABLE mapd_users_tmp RENAME TO mapd_users");
} catch (const std::exception& e) {
LOG(ERROR) << "Failed to hash passwords: " << e.what();
sqliteConnector_->query("ROLLBACK TRANSACTION");
throw;
}
sqliteConnector_->query("END TRANSACTION");
sqliteConnector_->query("VACUUM"); // physically delete plain text passwords
LOG(INFO) << "Passwords were successfully hashed";
}
void SysCatalog::updateBlankPasswordsToRandom() {
const std::string UPDATE_BLANK_PASSWORDS_TO_RANDOM = "update_blank_passwords_to_random";
sqliteConnector_->query_with_text_params(
"SELECT migration_history FROM mapd_version_history WHERE migration_history = ?",
std::vector<std::string>{UPDATE_BLANK_PASSWORDS_TO_RANDOM});
if (sqliteConnector_->getNumRows()) {
return;
}
sys_sqlite_lock sqlite_lock(this);
sqliteConnector_->query("BEGIN TRANSACTION");
try {
sqliteConnector_->query(
"SELECT userid, passwd_hash, name FROM mapd_users WHERE name <> 'mapd'");
auto numRows = sqliteConnector_->getNumRows();
vector<std::string> users, passwords, names;
for (size_t i = 0; i < numRows; i++) {
users.push_back(sqliteConnector_->getData<std::string>(i, 0));
passwords.push_back(sqliteConnector_->getData<std::string>(i, 1));
names.push_back(sqliteConnector_->getData<std::string>(i, 2));
}
for (size_t i = 0; i < users.size(); ++i) {
int pwd_check_result = bcrypt_checkpw("", passwords[i].c_str());
// if the check fails there is a good chance that data on disc is broken
CHECK(pwd_check_result >= 0);
if (pwd_check_result != 0) {
continue;
}
LOG(WARNING) << "resetting blank password for user " << names[i] << " (" << users[i]
<< ") to a random password";
sqliteConnector_->query_with_text_params(
"UPDATE mapd_users SET passwd_hash = ? WHERE userid = ?",
std::vector<std::string>{hash_with_bcrypt(generate_random_string(72)),
users[i]});
}
sqliteConnector_->query_with_text_params(
"INSERT INTO mapd_version_history(version, migration_history) values(?,?)",
std::vector<std::string>{std::to_string(MAPD_VERSION),
UPDATE_BLANK_PASSWORDS_TO_RANDOM});
} catch (const std::exception& e) {
LOG(ERROR) << "Failed to fix blank passwords: " << e.what();
sqliteConnector_->query("ROLLBACK TRANSACTION");
throw;
}
sqliteConnector_->query("END TRANSACTION");
}
void SysCatalog::updateSupportUserDeactivation() {
const std::string UPDATE_SUPPORT_USER_DEACTIVATION = "update_support_user_deactivation";
sys_sqlite_lock sqlite_lock(this);
// check to see if the new column already exists
sqliteConnector_->query("PRAGMA TABLE_INFO(mapd_users)");
for (size_t i = 0; i < sqliteConnector_->getNumRows(); i++) {
const auto& col_name = sqliteConnector_->getData<std::string>(i, 1);
if (col_name == "can_login") {
return; // new column already exists
}
}
sqliteConnector_->query("BEGIN TRANSACTION");
try {
sqliteConnector_->query("ALTER TABLE mapd_users ADD COLUMN can_login BOOLEAN");
sqliteConnector_->query("UPDATE mapd_users SET can_login = true");
sqliteConnector_->query_with_text_params(
"INSERT INTO mapd_version_history(version, migration_history) values(?,?)",
std::vector<std::string>{std::to_string(MAPD_VERSION),
UPDATE_SUPPORT_USER_DEACTIVATION});
} catch (const std::exception& e) {
LOG(ERROR) << "Failed to add support for user deactivation: " << e.what();
sqliteConnector_->query("ROLLBACK TRANSACTION");
throw;
}
sqliteConnector_->query("END TRANSACTION");
}
void SysCatalog::migrateDBAccessPrivileges() {
sys_sqlite_lock sqlite_lock(this);
sqliteConnector_->query("BEGIN TRANSACTION");
try {
sqliteConnector_->query(
"select name from sqlite_master WHERE type='table' AND "
"name='mapd_version_history'");
if (sqliteConnector_->getNumRows() == 0) {
sqliteConnector_->query(
"CREATE TABLE mapd_version_history(version integer, migration_history text "
"unique)");
} else {
sqliteConnector_->query(
"select * from mapd_version_history where migration_history = "
"'db_access_privileges'");
if (sqliteConnector_->getNumRows() != 0) {
// both privileges migrated
// no need for further execution
sqliteConnector_->query("END TRANSACTION");
return;
}
}
// Insert check for migration
sqliteConnector_->query_with_text_params(
"INSERT INTO mapd_version_history(version, migration_history) values(?,?)",
std::vector<std::string>{std::to_string(MAPD_VERSION), "db_access_privileges"});
sqliteConnector_->query("select dbid, name from mapd_databases");
std::unordered_map<int, string> databases;
for (size_t i = 0; i < sqliteConnector_->getNumRows(); ++i) {
databases[sqliteConnector_->getData<int>(i, 0)] =
sqliteConnector_->getData<string>(i, 1);
}
sqliteConnector_->query("select userid, name from mapd_users");
std::unordered_map<int, string> users;
for (size_t i = 0; i < sqliteConnector_->getNumRows(); ++i) {
users[sqliteConnector_->getData<int>(i, 0)] =
sqliteConnector_->getData<string>(i, 1);
}
// All existing users by default will be granted DB Access permissions
// and view sql editor privileges
DBMetadata dbmeta;
for (auto db_ : databases) {
CHECK(SysCatalog::instance().getMetadataForDB(db_.second, dbmeta));
for (auto user : users) {
if (user.first != OMNISCI_ROOT_USER_ID) {
{
DBObjectKey key;
key.permissionType = DBObjectType::DatabaseDBObjectType;
key.dbId = dbmeta.dbId;
// access permission;
DBObject object_access(key, AccessPrivileges::ACCESS, dbmeta.dbOwner);
object_access.setObjectType(DBObjectType::DatabaseDBObjectType);
object_access.setName(dbmeta.dbName);
// sql_editor permission
DBObject object_editor(
key, AccessPrivileges::VIEW_SQL_EDITOR, dbmeta.dbOwner);
object_editor.setObjectType(DBObjectType::DatabaseDBObjectType);
object_editor.setName(dbmeta.dbName);
object_editor.updatePrivileges(object_access);
insertOrUpdateObjectPrivileges(
sqliteConnector_, user.second, true, object_editor);
}
}
}
}
} catch (const std::exception& e) {
LOG(ERROR) << "Failed to migrate db access privileges: " << e.what();
sqliteConnector_->query("ROLLBACK TRANSACTION");
throw;
}
sqliteConnector_->query("END TRANSACTION");
LOG(INFO) << "Successfully migrated db access privileges";
}
void SysCatalog::migratePrivileged_old() {
sys_sqlite_lock sqlite_lock(this);
sqliteConnector_->query("BEGIN TRANSACTION");
try {
sqliteConnector_->query(
"CREATE TABLE IF NOT EXISTS mapd_privileges (userid integer references "
"mapd_users, dbid integer references "
"mapd_databases, select_priv boolean, insert_priv boolean, UNIQUE(userid, "
"dbid))");
} catch (const std::exception& e) {
sqliteConnector_->query("ROLLBACK TRANSACTION");
throw;
}
sqliteConnector_->query("END TRANSACTION");
}
std::shared_ptr<Catalog> SysCatalog::login(std::string& dbname,
std::string& username,
const std::string& password,
UserMetadata& user_meta,
bool check_password) {
// NOTE(sy): The dbname isn't const because getMetadataWithDefaultDB()
// can reset it. The username isn't const because SamlServer's
// login()/authenticate_user() can reset it.
sys_write_lock write_lock(this);
if (check_password) {
loginImpl(username, password, user_meta);
} else { // not checking for password so user must exist
if (!getMetadataForUser(username, user_meta)) {
throw std::runtime_error("Invalid credentials.");
}
}
// we should have a user and user_meta by now
if (!user_meta.can_login) {
throw std::runtime_error("Unauthorized Access: User " + username + " is deactivated");
}
Catalog_Namespace::DBMetadata db_meta;
getMetadataWithDefaultDB(dbname, username, db_meta, user_meta);
return Catalog::get(
basePath_, db_meta, dataMgr_, string_dict_hosts_, calciteMgr_, false);
}
// loginImpl() with no EE code and no SAML code
void SysCatalog::loginImpl(std::string& username,
const std::string& password,
UserMetadata& user_meta) {
if (!checkPasswordForUser(password, username, user_meta)) {
throw std::runtime_error("Authentication failure");
}
}
std::shared_ptr<Catalog> SysCatalog::switchDatabase(std::string& dbname,
const std::string& username) {
DBMetadata db_meta;
UserMetadata user_meta;
getMetadataWithDefaultDB(dbname, username, db_meta, user_meta);
// NOTE(max): register database in Catalog that early to allow ldap
// and saml create default user and role privileges on databases
auto cat =
Catalog::get(basePath_, db_meta, dataMgr_, string_dict_hosts_, calciteMgr_, false);
DBObject dbObject(dbname, DatabaseDBObjectType);
dbObject.loadKey();
dbObject.setPrivileges(AccessPrivileges::ACCESS);
if (!checkPrivileges(user_meta, std::vector<DBObject>{dbObject})) {
throw std::runtime_error("Unauthorized Access: user " + username +
" is not allowed to access database " + dbname + ".");
}
return cat;
}
void SysCatalog::check_for_session_encryption(const std::string& pki_cert,
std::string& session) {
if (!pki_server_->inUse()) {
return;
}
pki_server_->encrypt_session(pki_cert, session);
}
void SysCatalog::createUser(const string& name,
const string& passwd,
bool issuper,
const std::string& dbname,
bool can_login) {
sys_write_lock write_lock(this);
sys_sqlite_lock sqlite_lock(this);
UserMetadata user;
if (getMetadataForUser(name, user)) {
throw runtime_error("User " + name + " already exists.");
}
if (getGrantee(name)) {
throw runtime_error(
"User name " + name +
" is same as one of existing grantees. User and role names should be unique.");
}
sqliteConnector_->query("BEGIN TRANSACTION");
try {
std::vector<std::string> vals;
if (!dbname.empty()) {
DBMetadata db;
if (!SysCatalog::instance().getMetadataForDB(dbname, db)) {
throw runtime_error("DEFAULT_DB " + dbname + " not found.");
}
vals = {name,
hash_with_bcrypt(passwd),
std::to_string(issuper),
std::to_string(db.dbId),
std::to_string(can_login)};
sqliteConnector_->query_with_text_params(
"INSERT INTO mapd_users (name, passwd_hash, issuper, default_db, can_login) "
"VALUES (?, ?, ?, ?, ?)",
vals);
} else {
vals = {name,
hash_with_bcrypt(passwd),
std::to_string(issuper),
std::to_string(can_login)};
sqliteConnector_->query_with_text_params(
"INSERT INTO mapd_users (name, passwd_hash, issuper, can_login) "
"VALUES (?, ?, ?, ?)",
vals);
}
createRole_unsafe(name, true);
} catch (const std::exception& e) {
sqliteConnector_->query("ROLLBACK TRANSACTION");
throw;
}
sqliteConnector_->query("END TRANSACTION");
}
void SysCatalog::dropUser(const string& name) {
sys_write_lock write_lock(this);
sys_sqlite_lock sqlite_lock(this);
sqliteConnector_->query("BEGIN TRANSACTION");
try {
UserMetadata user;
if (!getMetadataForUser(name, user)) {
throw runtime_error("User " + name + " does not exist.");
}
dropRole_unsafe(name);
deleteObjectDescriptorMap(name);
const std::string& roleName(name);
sqliteConnector_->query_with_text_param("DELETE FROM mapd_roles WHERE userName = ?",
roleName);
sqliteConnector_->query("DELETE FROM mapd_users WHERE userid = " +
std::to_string(user.userId));
sqliteConnector_->query("DELETE FROM mapd_privileges WHERE userid = " +
std::to_string(user.userId));
} catch (const std::exception& e) {
sqliteConnector_->query("ROLLBACK TRANSACTION");
throw;
}
sqliteConnector_->query("END TRANSACTION");
}
namespace { // anonymous namespace
auto append_with_commas = [](string& s, const string& t) {
if (!s.empty()) {
s += ", ";
}
s += t;
};
} // anonymous namespace
void SysCatalog::alterUser(const int32_t userid,
const string* passwd,
bool* issuper,
const string* dbname,
bool* can_login) {
sys_sqlite_lock sqlite_lock(this);
sqliteConnector_->query("BEGIN TRANSACTION");
try {
string sql;
std::vector<std::string> values;
if (passwd != nullptr) {
append_with_commas(sql, "passwd_hash = ?");
values.push_back(hash_with_bcrypt(*passwd));
}
if (issuper != nullptr) {
append_with_commas(sql, "issuper = ?");
values.push_back(std::to_string(*issuper));
}
if (dbname != nullptr) {
if (!dbname->empty()) {
append_with_commas(sql, "default_db = ?");
DBMetadata db;
if (!SysCatalog::instance().getMetadataForDB(*dbname, db)) {
throw runtime_error(string("DEFAULT_DB ") + *dbname + " not found.");
}
values.push_back(std::to_string(db.dbId));
} else {
append_with_commas(sql, "default_db = NULL");
}
}
if (can_login != nullptr) {
append_with_commas(sql, "can_login = ?");
values.push_back(std::to_string(*can_login));
}
sql = "UPDATE mapd_users SET " + sql + " WHERE userid = ?";
values.push_back(std::to_string(userid));
sqliteConnector_->query_with_text_params(sql, values);
} catch (const std::exception& e) {
sqliteConnector_->query("ROLLBACK TRANSACTION");
throw;
}
sqliteConnector_->query("END TRANSACTION");
}
auto SysCatalog::yieldTransactionStreamer() {
return
[](auto& db_connector, auto on_success, auto on_failure, auto&&... query_requests) {
auto query_runner = [&db_connector](auto&&... query_reqs) {
[[gnu::unused]] int throw_away[] = {
(db_connector->query_with_text_params(
std::forward<decltype(query_reqs)>(query_reqs)),
0)...};
};
db_connector->query("BEGIN TRANSACTION");
try {
query_runner(std::forward<decltype(query_requests)>(query_requests)...);
on_success();
} catch (std::exception&) {
db_connector->query("ROLLBACK TRANSACTION");
on_failure();
throw;
}
db_connector->query("END TRANSACTION");
};
}
void SysCatalog::updateUserRoleName(const std::string& roleName,
const std::string& newName) {
sys_write_lock write_lock(this);
auto it = granteeMap_.find(to_upper(roleName));
if (it != granteeMap_.end()) {
it->second->setName(newName);
std::swap(granteeMap_[to_upper(newName)], it->second);
granteeMap_.erase(it);
}
}
void SysCatalog::renameUser(std::string const& old_name, std::string const& new_name) {
using namespace std::string_literals;
sys_write_lock write_lock(this);
sys_sqlite_lock sqlite_lock(this);
UserMetadata old_user;
if (!getMetadataForUser(old_name, old_user)) {
throw std::runtime_error("User " + old_name + " doesn't exist.");
}
UserMetadata new_user;
if (getMetadataForUser(new_name, new_user)) {
throw std::runtime_error("User " + new_name + " already exists.");
}
if (getGrantee(new_name)) {
throw runtime_error(
"User name " + new_name +
" is same as one of existing grantees. User and role names should be unique.");
}
auto transaction_streamer = yieldTransactionStreamer();
auto failure_handler = [] {};
auto success_handler = [this, &old_name, &new_name] {
updateUserRoleName(old_name, new_name);
};
auto q1 = {"UPDATE mapd_users SET name=?1 where name=?2;"s, new_name, old_name};
auto q2 = {"UPDATE mapd_object_permissions set roleName=?1 WHERE roleName=?2;"s,
new_name,
old_name};
transaction_streamer(sqliteConnector_, success_handler, failure_handler, q1, q2);
}
void SysCatalog::renameDatabase(std::string const& old_name,
std::string const& new_name) {
using namespace std::string_literals;
sys_write_lock write_lock(this);
sys_sqlite_lock sqlite_lock(this);
DBMetadata new_db;
if (getMetadataForDB(new_name, new_db)) {
throw std::runtime_error("Database " + new_name + " already exists.");
}
if (to_upper(new_name) == to_upper(OMNISCI_SYSTEM_CATALOG)) {
throw std::runtime_error("Database name " + new_name + "is reserved.");
}
DBMetadata old_db;
if (!getMetadataForDB(old_name, old_db)) {
throw std::runtime_error("Database " + old_name + " does not exists.");
}
Catalog::remove(old_db.dbName);
std::string old_catalog_path, new_catalog_path;
std::tie(old_catalog_path, new_catalog_path) =
duplicateAndRenameCatalog(old_name, new_name);
auto transaction_streamer = yieldTransactionStreamer();