OmniSciDB  0bd2ec9cf4
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
SysCatalog.cpp
Go to the documentation of this file.
1 /*
2  * Copyright 2019 MapD Technologies, Inc.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
25 #include "SysCatalog.h"
26 #include <algorithm>
27 #include <cassert>
28 #include <exception>
29 #include <list>
30 #include <memory>
31 #include <random>
32 #include <sstream>
33 #include "Catalog.h"
34 
35 #include "Catalog/AuthMetadata.h"
36 #include "LockMgr/LockMgr.h"
38 
39 #include <boost/algorithm/string/predicate.hpp>
40 #include <boost/filesystem.hpp>
41 #include <boost/range/adaptor/map.hpp>
42 #include <boost/version.hpp>
43 
44 #include "../Parser/ParserNode.h"
45 #include "../Shared/File.h"
46 #include "../Shared/StringTransform.h"
47 #include "../Shared/measure.h"
48 #include "MapDRelease.h"
49 #include "RWLocks.h"
50 #include "bcrypt.h"
51 
52 using std::list;
53 using std::map;
54 using std::pair;
55 using std::runtime_error;
56 using std::string;
57 using std::vector;
58 
59 namespace {
60 
61 std::string hash_with_bcrypt(const std::string& pwd) {
62  char salt[BCRYPT_HASHSIZE], hash[BCRYPT_HASHSIZE];
63  CHECK(bcrypt_gensalt(-1, salt) == 0);
64  CHECK(bcrypt_hashpw(pwd.c_str(), salt, hash) == 0);
65  return std::string(hash, BCRYPT_HASHSIZE);
66 }
67 
68 } // namespace
69 
70 namespace Catalog_Namespace {
71 
72 thread_local bool SysCatalog::thread_holds_read_lock = false;
73 
77 
78 auto CommonFileOperations::assembleCatalogName(std::string const& name) {
79  return base_path_ + "/mapd_catalogs/" + name;
80 };
81 
82 void CommonFileOperations::removeCatalogByFullPath(std::string const& full_path) {
83  boost::filesystem::remove(full_path);
84 }
85 
86 void CommonFileOperations::removeCatalogByName(std::string const& name) {
87  boost::filesystem::remove(assembleCatalogName(name));
88 };
89 
90 auto CommonFileOperations::duplicateAndRenameCatalog(std::string const& current_name,
91  std::string const& new_name) {
92  auto full_current_path = assembleCatalogName(current_name);
93  auto full_new_path = assembleCatalogName(new_name);
94 
95  try {
96  boost::filesystem::copy_file(full_current_path, full_new_path);
97  } catch (std::exception& e) {
98  std::string err_message{"Could not copy file " + full_current_path + " to " +
99  full_new_path + " exception was " + e.what()};
100  LOG(ERROR) << err_message;
101  throw std::runtime_error(err_message);
102  }
103 
104  return std::make_pair(full_current_path, full_new_path);
105 };
106 
107 void SysCatalog::init(const std::string& basePath,
108  std::shared_ptr<Data_Namespace::DataMgr> dataMgr,
109  const AuthMetadata& authMetadata,
110  std::shared_ptr<Calcite> calcite,
111  bool is_new_db,
112  bool aggregator,
113  const std::vector<LeafHostInfo>& string_dict_hosts) {
114  {
117 
118  basePath_ = basePath;
119  dataMgr_ = dataMgr;
120  authMetadata_ = &authMetadata;
123  pki_server_.reset(new PkiServer(*authMetadata_));
124  calciteMgr_ = calcite;
125  string_dict_hosts_ = string_dict_hosts;
126  aggregator_ = aggregator;
127  bool db_exists =
128  boost::filesystem::exists(basePath_ + "/mapd_catalogs/" + OMNISCI_SYSTEM_CATALOG);
129  sqliteConnector_.reset(
130  new SqliteConnector(OMNISCI_SYSTEM_CATALOG, basePath_ + "/mapd_catalogs/"));
131  if (is_new_db) {
132  initDB();
133  } else {
134  if (!db_exists) {
136  }
138  }
139  buildRoleMap();
142  }
143 }
144 
147  for (auto grantee = granteeMap_.begin(); grantee != granteeMap_.end(); ++grantee) {
148  delete grantee->second;
149  }
150  granteeMap_.clear();
151  for (ObjectRoleDescriptorMap::iterator objectIt = objectDescriptorMap_.begin();
152  objectIt != objectDescriptorMap_.end();) {
153  ObjectRoleDescriptorMap::iterator eraseIt = objectIt++;
154  delete eraseIt->second;
155  }
156  objectDescriptorMap_.clear();
157 }
158 
161  sqliteConnector_->query("BEGIN TRANSACTION");
162  try {
163  sqliteConnector_->query(
164  "CREATE TABLE mapd_users (userid integer primary key, name text unique, "
165  "passwd_hash text, issuper boolean, default_db integer references "
166  "mapd_databases, can_login boolean)");
167  sqliteConnector_->query_with_text_params(
168  "INSERT INTO mapd_users VALUES (?, ?, ?, 1, NULL, 1)",
169  std::vector<std::string>{OMNISCI_ROOT_USER_ID_STR,
172  sqliteConnector_->query(
173  "CREATE TABLE mapd_databases (dbid integer primary key, name text unique, owner "
174  "integer references mapd_users)");
175  sqliteConnector_->query(
176  "CREATE TABLE mapd_roles(roleName text, userName text, UNIQUE(roleName, "
177  "userName))");
178  sqliteConnector_->query(
179  "CREATE TABLE mapd_object_permissions ("
180  "roleName text, "
181  "roleType bool, "
182  "dbId integer references mapd_databases, "
183  "objectName text, "
184  "objectId integer, "
185  "objectPermissionsType integer, "
186  "objectPermissions integer, "
187  "objectOwnerId integer, UNIQUE(roleName, objectPermissionsType, dbId, "
188  "objectId))");
189  } catch (const std::exception&) {
190  sqliteConnector_->query("ROLLBACK TRANSACTION");
191  throw;
192  }
193  sqliteConnector_->query("END TRANSACTION");
195 }
196 
199  createUserRoles();
202  updateUserSchema(); // must come before updatePasswordsToHashes()
204  updateBlankPasswordsToRandom(); // must come after updatePasswordsToHashes()
206 }
207 
210 
211  // check to see if the new column already exists
212  sqliteConnector_->query("PRAGMA TABLE_INFO(mapd_users)");
213  for (size_t i = 0; i < sqliteConnector_->getNumRows(); i++) {
214  const auto& col_name = sqliteConnector_->getData<std::string>(i, 1);
215  if (col_name == "default_db") {
216  return; // new column already exists
217  }
218  }
219 
220  // create the new column
221  sqliteConnector_->query("BEGIN TRANSACTION");
222  try {
223  sqliteConnector_->query(
224  "ALTER TABLE mapd_users ADD COLUMN default_db INTEGER REFERENCES mapd_databases");
225  } catch (const std::exception& e) {
226  sqliteConnector_->query("ROLLBACK TRANSACTION");
227  throw;
228  }
229  sqliteConnector_->query("END TRANSACTION");
230 }
231 
234  std::string mapd_db_path = basePath_ + "/mapd_catalogs/mapd";
235  sqliteConnector_->query("ATTACH DATABASE `" + mapd_db_path + "` as old_cat");
236  sqliteConnector_->query("BEGIN TRANSACTION");
237  LOG(INFO) << "Moving global metadata into a separate catalog";
238  try {
239  auto moveTableIfExists = [conn = sqliteConnector_.get()](const std::string& tableName,
240  bool deleteOld = true) {
241  conn->query("SELECT sql FROM old_cat.sqlite_master WHERE type='table' AND name='" +
242  tableName + "'");
243  if (conn->getNumRows() != 0) {
244  conn->query(conn->getData<string>(0, 0));
245  conn->query("INSERT INTO " + tableName + " SELECT * FROM old_cat." + tableName);
246  if (deleteOld) {
247  conn->query("DROP TABLE old_cat." + tableName);
248  }
249  }
250  };
251  moveTableIfExists("mapd_users");
252  moveTableIfExists("mapd_databases");
253  moveTableIfExists("mapd_roles");
254  moveTableIfExists("mapd_object_permissions");
255  moveTableIfExists("mapd_privileges");
256  moveTableIfExists("mapd_version_history", false);
257  } catch (const std::exception& e) {
258  LOG(ERROR) << "Failed to move global metadata into a separate catalog: " << e.what();
259  sqliteConnector_->query("ROLLBACK TRANSACTION");
260  try {
261  sqliteConnector_->query("DETACH DATABASE old_cat");
262  } catch (const std::exception&) {
263  // nothing to do here
264  }
265  throw;
266  }
267  sqliteConnector_->query("END TRANSACTION");
268  const std::string sys_catalog_path =
269  basePath_ + "/mapd_catalogs/" + OMNISCI_SYSTEM_CATALOG;
270  LOG(INFO) << "Global metadata has been successfully moved into a separate catalog: "
271  << sys_catalog_path
272  << ". Using this database with an older version of omnisci_server "
273  "is now impossible.";
274  try {
275  sqliteConnector_->query("DETACH DATABASE old_cat");
276  } catch (const std::exception&) {
277  // nothing to do here
278  }
279 }
280 
283  sqliteConnector_->query("BEGIN TRANSACTION");
284  try {
285  sqliteConnector_->query(
286  "SELECT name FROM sqlite_master WHERE type='table' AND name='mapd_roles'");
287  if (sqliteConnector_->getNumRows() != 0) {
288  // already done
289  sqliteConnector_->query("END TRANSACTION");
290  return;
291  }
292  sqliteConnector_->query(
293  "CREATE TABLE mapd_roles(roleName text, userName text, UNIQUE(roleName, "
294  "userName))");
295  // need to account for old conversions where we are building and moving
296  // from pre version 4.0 and 'mapd' was default superuser
297  sqliteConnector_->query("SELECT name FROM mapd_users WHERE name NOT IN ( \'" +
298  OMNISCI_ROOT_USER + "\', 'mapd')");
299  size_t numRows = sqliteConnector_->getNumRows();
300  vector<string> user_names;
301  for (size_t i = 0; i < numRows; ++i) {
302  user_names.push_back(sqliteConnector_->getData<string>(i, 0));
303  }
304  for (const auto& user_name : user_names) {
305  // for each user, create a fake role with the same name
306  sqliteConnector_->query_with_text_params(
307  "INSERT INTO mapd_roles(roleName, userName) VALUES (?, ?)",
308  vector<string>{user_name, user_name});
309  }
310  } catch (const std::exception&) {
311  sqliteConnector_->query("ROLLBACK TRANSACTION");
312  throw;
313  }
314  sqliteConnector_->query("END TRANSACTION");
315 }
316 
317 void deleteObjectPrivileges(std::unique_ptr<SqliteConnector>& sqliteConnector,
318  std::string roleName,
319  bool userRole,
320  DBObject& object) {
321  DBObjectKey key = object.getObjectKey();
322 
323  sqliteConnector->query_with_text_params(
324  "DELETE FROM mapd_object_permissions WHERE roleName = ?1 and roleType = ?2 and "
325  "objectPermissionsType = ?3 and "
326  "dbId = "
327  "?4 "
328  "and objectId = ?5",
329  std::vector<std::string>{roleName,
330  std::to_string(userRole),
332  std::to_string(key.dbId),
333  std::to_string(key.objectId)});
334 }
335 
336 void insertOrUpdateObjectPrivileges(std::unique_ptr<SqliteConnector>& sqliteConnector,
337  std::string roleName,
338  bool userRole,
339  DBObject& object) {
340  DBObjectKey key = object.getObjectKey();
341 
342  sqliteConnector->query_with_text_params(
343  "INSERT OR REPLACE INTO mapd_object_permissions("
344  "roleName, "
345  "roleType, "
346  "objectPermissionsType, "
347  "dbId, "
348  "objectId, "
349  "objectPermissions, "
350  "objectOwnerId,"
351  "objectName) "
352  "VALUES (?1, ?2, ?3, "
353  "?4, ?5, ?6, ?7, ?8)",
354  std::vector<std::string>{
355  roleName, // roleName
356  userRole ? "1" : "0", // roleType
357  std::to_string(key.permissionType), // permissionType
358  std::to_string(key.dbId), // dbId
359  std::to_string(key.objectId), // objectId
360  std::to_string(object.getPrivileges().privileges), // objectPrivileges
361  std::to_string(object.getOwner()), // objectOwnerId
362  object.getName() // name
363  });
364 }
365 
368  sqliteConnector_->query("BEGIN TRANSACTION");
369  try {
370  sqliteConnector_->query(
371  "SELECT name FROM sqlite_master WHERE type='table' AND "
372  "name='mapd_object_permissions'");
373  if (sqliteConnector_->getNumRows() != 0) {
374  // already done
375  sqliteConnector_->query("END TRANSACTION");
376  return;
377  }
378 
379  sqliteConnector_->query(
380  "CREATE TABLE IF NOT EXISTS mapd_object_permissions ("
381  "roleName text, "
382  "roleType bool, "
383  "dbId integer references mapd_databases, "
384  "objectName text, "
385  "objectId integer, "
386  "objectPermissionsType integer, "
387  "objectPermissions integer, "
388  "objectOwnerId integer, UNIQUE(roleName, objectPermissionsType, dbId, "
389  "objectId))");
390 
391  // get the list of databases and their grantees
392  sqliteConnector_->query(
393  "SELECT userid, dbid FROM mapd_privileges WHERE select_priv = 1 and insert_priv "
394  "= 1");
395  size_t numRows = sqliteConnector_->getNumRows();
396  vector<pair<int, int>> db_grantees(numRows);
397  for (size_t i = 0; i < numRows; ++i) {
398  db_grantees[i].first = sqliteConnector_->getData<int>(i, 0);
399  db_grantees[i].second = sqliteConnector_->getData<int>(i, 1);
400  }
401  // map user names to user ids
402  sqliteConnector_->query("select userid, name from mapd_users");
403  numRows = sqliteConnector_->getNumRows();
404  std::unordered_map<int, string> users_by_id;
405  std::unordered_map<int, bool> user_has_privs;
406  for (size_t i = 0; i < numRows; ++i) {
407  users_by_id[sqliteConnector_->getData<int>(i, 0)] =
408  sqliteConnector_->getData<string>(i, 1);
409  user_has_privs[sqliteConnector_->getData<int>(i, 0)] = false;
410  }
411  // map db names to db ids
412  sqliteConnector_->query("select dbid, name from mapd_databases");
413  numRows = sqliteConnector_->getNumRows();
414  std::unordered_map<int, string> dbs_by_id;
415  for (size_t i = 0; i < numRows; ++i) {
416  dbs_by_id[sqliteConnector_->getData<int>(i, 0)] =
417  sqliteConnector_->getData<string>(i, 1);
418  }
419  // migrate old privileges to new privileges: if user had insert access to database, he
420  // was a grantee
421  for (const auto& grantee : db_grantees) {
422  user_has_privs[grantee.first] = true;
423  auto dbName = dbs_by_id[grantee.second];
424  {
425  // table level permissions
426  DBObjectKey key;
428  key.dbId = grantee.second;
430  object.setName(dbName);
432  sqliteConnector_, users_by_id[grantee.first], true, object);
433  }
434 
435  {
436  // dashboard level permissions
437  DBObjectKey key;
439  key.dbId = grantee.second;
440  DBObject object(
442  object.setName(dbName);
444  sqliteConnector_, users_by_id[grantee.first], true, object);
445  }
446 
447  {
448  // view level permissions
449  DBObjectKey key;
451  key.dbId = grantee.second;
453  object.setName(dbName);
455  sqliteConnector_, users_by_id[grantee.first], true, object);
456  }
457  }
458  for (auto user : user_has_privs) {
459  auto dbName = dbs_by_id[0];
460  if (user.second == false && user.first != OMNISCI_ROOT_USER_ID) {
461  {
462  DBObjectKey key;
464  key.dbId = 0;
466  object.setName(dbName);
468  sqliteConnector_, users_by_id[user.first], true, object);
469  }
470  }
471  }
472  } catch (const std::exception&) {
473  sqliteConnector_->query("ROLLBACK TRANSACTION");
474  throw;
475  }
476  sqliteConnector_->query("END TRANSACTION");
477 }
478 
481  sqliteConnector_->query("BEGIN TRANSACTION");
482  try {
483  sqliteConnector_->query(
484  "SELECT name FROM sqlite_master WHERE type='table' AND name='mapd_users'");
485  if (sqliteConnector_->getNumRows() == 0) {
486  // Nothing to update
487  sqliteConnector_->query("END TRANSACTION");
488  return;
489  }
490  sqliteConnector_->query("PRAGMA TABLE_INFO(mapd_users)");
491  for (size_t i = 0; i < sqliteConnector_->getNumRows(); i++) {
492  const auto& col_name = sqliteConnector_->getData<std::string>(i, 1);
493  if (col_name == "passwd_hash") {
494  sqliteConnector_->query("END TRANSACTION");
495  return;
496  }
497  }
498  // Alas, SQLite can't drop columns so we have to recreate the table
499  // (or, optionally, add the new column and reset the old one to a bunch of nulls)
500  sqliteConnector_->query("SELECT userid, passwd FROM mapd_users");
501  auto numRows = sqliteConnector_->getNumRows();
502  vector<std::string> users, passwords;
503  for (size_t i = 0; i < numRows; i++) {
504  users.push_back(sqliteConnector_->getData<std::string>(i, 0));
505  passwords.push_back(sqliteConnector_->getData<std::string>(i, 1));
506  }
507  sqliteConnector_->query(
508  "CREATE TABLE mapd_users_tmp (userid integer primary key, name text unique, "
509  "passwd_hash text, issuper boolean, default_db integer references "
510  "mapd_databases)");
511  sqliteConnector_->query(
512  "INSERT INTO mapd_users_tmp(userid, name, passwd_hash, issuper, default_db) "
513  "SELECT userid, name, null, issuper, default_db FROM mapd_users");
514  for (size_t i = 0; i < users.size(); ++i) {
515  sqliteConnector_->query_with_text_params(
516  "UPDATE mapd_users_tmp SET passwd_hash = ? WHERE userid = ?",
517  std::vector<std::string>{hash_with_bcrypt(passwords[i]), users[i]});
518  }
519  sqliteConnector_->query("DROP TABLE mapd_users");
520  sqliteConnector_->query("ALTER TABLE mapd_users_tmp RENAME TO mapd_users");
521  } catch (const std::exception& e) {
522  LOG(ERROR) << "Failed to hash passwords: " << e.what();
523  sqliteConnector_->query("ROLLBACK TRANSACTION");
524  throw;
525  }
526  sqliteConnector_->query("END TRANSACTION");
527  sqliteConnector_->query("VACUUM"); // physically delete plain text passwords
528  LOG(INFO) << "Passwords were successfully hashed";
529 }
530 
532  const std::string UPDATE_BLANK_PASSWORDS_TO_RANDOM = "update_blank_passwords_to_random";
533  sqliteConnector_->query_with_text_params(
534  "SELECT migration_history FROM mapd_version_history WHERE migration_history = ?",
535  std::vector<std::string>{UPDATE_BLANK_PASSWORDS_TO_RANDOM});
536  if (sqliteConnector_->getNumRows()) {
537  return;
538  }
539 
541  sqliteConnector_->query("BEGIN TRANSACTION");
542  try {
543  sqliteConnector_->query(
544  "SELECT userid, passwd_hash, name FROM mapd_users WHERE name <> 'mapd'");
545  auto numRows = sqliteConnector_->getNumRows();
546  vector<std::string> users, passwords, names;
547  for (size_t i = 0; i < numRows; i++) {
548  users.push_back(sqliteConnector_->getData<std::string>(i, 0));
549  passwords.push_back(sqliteConnector_->getData<std::string>(i, 1));
550  names.push_back(sqliteConnector_->getData<std::string>(i, 2));
551  }
552  for (size_t i = 0; i < users.size(); ++i) {
553  int pwd_check_result = bcrypt_checkpw("", passwords[i].c_str());
554  // if the check fails there is a good chance that data on disc is broken
555  CHECK(pwd_check_result >= 0);
556  if (pwd_check_result != 0) {
557  continue;
558  }
559  LOG(WARNING) << "resetting blank password for user " << names[i] << " (" << users[i]
560  << ") to a random password";
561  sqliteConnector_->query_with_text_params(
562  "UPDATE mapd_users SET passwd_hash = ? WHERE userid = ?",
563  std::vector<std::string>{hash_with_bcrypt(generate_random_string(72)),
564  users[i]});
565  }
566  sqliteConnector_->query_with_text_params(
567  "INSERT INTO mapd_version_history(version, migration_history) values(?,?)",
568  std::vector<std::string>{std::to_string(MAPD_VERSION),
569  UPDATE_BLANK_PASSWORDS_TO_RANDOM});
570  } catch (const std::exception& e) {
571  LOG(ERROR) << "Failed to fix blank passwords: " << e.what();
572  sqliteConnector_->query("ROLLBACK TRANSACTION");
573  throw;
574  }
575  sqliteConnector_->query("END TRANSACTION");
576 }
577 
579  const std::string UPDATE_SUPPORT_USER_DEACTIVATION = "update_support_user_deactivation";
581  // check to see if the new column already exists
582  sqliteConnector_->query("PRAGMA TABLE_INFO(mapd_users)");
583  for (size_t i = 0; i < sqliteConnector_->getNumRows(); i++) {
584  const auto& col_name = sqliteConnector_->getData<std::string>(i, 1);
585  if (col_name == "can_login") {
586  return; // new column already exists
587  }
588  }
589  sqliteConnector_->query("BEGIN TRANSACTION");
590  try {
591  sqliteConnector_->query("ALTER TABLE mapd_users ADD COLUMN can_login BOOLEAN");
592  sqliteConnector_->query("UPDATE mapd_users SET can_login = true");
593  sqliteConnector_->query_with_text_params(
594  "INSERT INTO mapd_version_history(version, migration_history) values(?,?)",
595  std::vector<std::string>{std::to_string(MAPD_VERSION),
596  UPDATE_SUPPORT_USER_DEACTIVATION});
597  } catch (const std::exception& e) {
598  LOG(ERROR) << "Failed to add support for user deactivation: " << e.what();
599  sqliteConnector_->query("ROLLBACK TRANSACTION");
600  throw;
601  }
602  sqliteConnector_->query("END TRANSACTION");
603 }
604 
607  sqliteConnector_->query("BEGIN TRANSACTION");
608  try {
609  sqliteConnector_->query(
610  "select name from sqlite_master WHERE type='table' AND "
611  "name='mapd_version_history'");
612  if (sqliteConnector_->getNumRows() == 0) {
613  sqliteConnector_->query(
614  "CREATE TABLE mapd_version_history(version integer, migration_history text "
615  "unique)");
616  } else {
617  sqliteConnector_->query(
618  "select * from mapd_version_history where migration_history = "
619  "'db_access_privileges'");
620  if (sqliteConnector_->getNumRows() != 0) {
621  // both privileges migrated
622  // no need for further execution
623  sqliteConnector_->query("END TRANSACTION");
624  return;
625  }
626  }
627  // Insert check for migration
628  sqliteConnector_->query_with_text_params(
629  "INSERT INTO mapd_version_history(version, migration_history) values(?,?)",
630  std::vector<std::string>{std::to_string(MAPD_VERSION), "db_access_privileges"});
631 
632  sqliteConnector_->query("select dbid, name from mapd_databases");
633  std::unordered_map<int, string> databases;
634  for (size_t i = 0; i < sqliteConnector_->getNumRows(); ++i) {
635  databases[sqliteConnector_->getData<int>(i, 0)] =
636  sqliteConnector_->getData<string>(i, 1);
637  }
638 
639  sqliteConnector_->query("select userid, name from mapd_users");
640  std::unordered_map<int, string> users;
641  for (size_t i = 0; i < sqliteConnector_->getNumRows(); ++i) {
642  users[sqliteConnector_->getData<int>(i, 0)] =
643  sqliteConnector_->getData<string>(i, 1);
644  }
645 
646  // All existing users by default will be granted DB Access permissions
647  // and view sql editor privileges
648  DBMetadata dbmeta;
649  for (auto db_ : databases) {
650  CHECK(SysCatalog::instance().getMetadataForDB(db_.second, dbmeta));
651  for (auto user : users) {
652  if (user.first != OMNISCI_ROOT_USER_ID) {
653  {
654  DBObjectKey key;
656  key.dbId = dbmeta.dbId;
657 
658  // access permission;
659  DBObject object_access(key, AccessPrivileges::ACCESS, dbmeta.dbOwner);
661  object_access.setName(dbmeta.dbName);
662  // sql_editor permission
663  DBObject object_editor(
666  object_editor.setName(dbmeta.dbName);
667  object_editor.updatePrivileges(object_access);
669  sqliteConnector_, user.second, true, object_editor);
670  }
671  }
672  }
673  }
674  } catch (const std::exception& e) {
675  LOG(ERROR) << "Failed to migrate db access privileges: " << e.what();
676  sqliteConnector_->query("ROLLBACK TRANSACTION");
677  throw;
678  }
679  sqliteConnector_->query("END TRANSACTION");
680  LOG(INFO) << "Successfully migrated db access privileges";
681 }
682 
685 
686  sqliteConnector_->query("BEGIN TRANSACTION");
687  try {
688  sqliteConnector_->query(
689  "CREATE TABLE IF NOT EXISTS mapd_privileges (userid integer references "
690  "mapd_users, dbid integer references "
691  "mapd_databases, select_priv boolean, insert_priv boolean, UNIQUE(userid, "
692  "dbid))");
693  } catch (const std::exception& e) {
694  sqliteConnector_->query("ROLLBACK TRANSACTION");
695  throw;
696  }
697  sqliteConnector_->query("END TRANSACTION");
698 }
699 
700 std::shared_ptr<Catalog> SysCatalog::login(std::string& dbname,
701  std::string& username,
702  const std::string& password,
703  UserMetadata& user_meta,
704  bool check_password) {
705  // NOTE: The dbname isn't const because getMetadataWithDefaultDB() can
706  // reset it. The username isn't const because SamlServer's
707  // login()/authenticate_user() can reset it.
708 
710  if (check_password) {
711  loginImpl(username, password, user_meta);
712  } else { // not checking for password so user must exist
713  if (!getMetadataForUser(username, user_meta)) {
714  throw std::runtime_error("Invalid credentials.");
715  }
716  }
717  // we should have a user and user_meta by now
718  if (!user_meta.can_login) {
719  throw std::runtime_error("Unauthorized Access: User " + username + " is deactivated");
720  }
722  getMetadataWithDefaultDB(dbname, username, db_meta, user_meta);
723  return Catalog::get(
724  basePath_, db_meta, dataMgr_, string_dict_hosts_, calciteMgr_, false);
725 }
726 
727 // loginImpl() with no EE code and no SAML code
728 void SysCatalog::loginImpl(std::string& username,
729  const std::string& password,
730  UserMetadata& user_meta) {
731  if (!checkPasswordForUser(password, username, user_meta)) {
732  throw std::runtime_error("Invalid credentials.");
733  }
734 }
735 
736 std::shared_ptr<Catalog> SysCatalog::switchDatabase(std::string& dbname,
737  const std::string& username) {
738  DBMetadata db_meta;
739  UserMetadata user_meta;
740 
741  getMetadataWithDefaultDB(dbname, username, db_meta, user_meta);
742 
743  // NOTE(max): register database in Catalog that early to allow ldap
744  // and saml create default user and role privileges on databases
745  auto cat =
747 
748  DBObject dbObject(dbname, DatabaseDBObjectType);
749  dbObject.loadKey();
751  if (!checkPrivileges(user_meta, std::vector<DBObject>{dbObject})) {
752  throw std::runtime_error("Invalid credentials.");
753  }
754 
755  return cat;
756 }
757 
758 void SysCatalog::check_for_session_encryption(const std::string& pki_cert,
759  std::string& session) {
760  if (!pki_server_->inUse()) {
761  return;
762  }
763  pki_server_->encrypt_session(pki_cert, session);
764 }
765 
766 void SysCatalog::createUser(const string& name,
767  const string& passwd,
768  bool issuper,
769  const std::string& dbname,
770  bool can_login) {
773 
774  UserMetadata user;
775  if (getMetadataForUser(name, user)) {
776  throw runtime_error("User " + name + " already exists.");
777  }
778  if (getGrantee(name)) {
779  throw runtime_error(
780  "User name " + name +
781  " is same as one of existing grantees. User and role names should be unique.");
782  }
783  sqliteConnector_->query("BEGIN TRANSACTION");
784  try {
785  std::vector<std::string> vals;
786  if (!dbname.empty()) {
787  DBMetadata db;
788  if (!SysCatalog::instance().getMetadataForDB(dbname, db)) {
789  throw runtime_error("DEFAULT_DB " + dbname + " not found.");
790  }
791  vals = {name,
792  hash_with_bcrypt(passwd),
793  std::to_string(issuper),
794  std::to_string(db.dbId),
795  std::to_string(can_login)};
796  sqliteConnector_->query_with_text_params(
797  "INSERT INTO mapd_users (name, passwd_hash, issuper, default_db, can_login) "
798  "VALUES (?, ?, ?, ?, ?)",
799  vals);
800  } else {
801  vals = {name,
802  hash_with_bcrypt(passwd),
803  std::to_string(issuper),
804  std::to_string(can_login)};
805  sqliteConnector_->query_with_text_params(
806  "INSERT INTO mapd_users (name, passwd_hash, issuper, can_login) "
807  "VALUES (?, ?, ?, ?)",
808  vals);
809  }
810  createRole_unsafe(name, true);
811  } catch (const std::exception& e) {
812  sqliteConnector_->query("ROLLBACK TRANSACTION");
813  throw;
814  }
815  sqliteConnector_->query("END TRANSACTION");
816 }
817 
818 void SysCatalog::dropUser(const string& name) {
821 
822  sqliteConnector_->query("BEGIN TRANSACTION");
823  try {
824  UserMetadata user;
825  if (!getMetadataForUser(name, user)) {
826  throw runtime_error("User " + name + " does not exist.");
827  }
828  dropRole_unsafe(name);
830  const std::string& roleName(name);
831  sqliteConnector_->query_with_text_param("DELETE FROM mapd_roles WHERE userName = ?",
832  roleName);
833  sqliteConnector_->query("DELETE FROM mapd_users WHERE userid = " +
834  std::to_string(user.userId));
835  sqliteConnector_->query("DELETE FROM mapd_privileges WHERE userid = " +
836  std::to_string(user.userId));
837  } catch (const std::exception& e) {
838  sqliteConnector_->query("ROLLBACK TRANSACTION");
839  throw;
840  }
841  sqliteConnector_->query("END TRANSACTION");
842 }
843 
844 namespace { // anonymous namespace
845 
846 auto append_with_commas = [](string& s, const string& t) {
847  if (!s.empty()) {
848  s += ", ";
849  }
850  s += t;
851 };
852 
853 } // anonymous namespace
854 
855 void SysCatalog::alterUser(const int32_t userid,
856  const string* passwd,
857  bool* issuper,
858  const string* dbname,
859  bool* can_login) {
861  sqliteConnector_->query("BEGIN TRANSACTION");
862  try {
863  string sql;
864  std::vector<std::string> values;
865  if (passwd != nullptr) {
866  append_with_commas(sql, "passwd_hash = ?");
867  values.push_back(hash_with_bcrypt(*passwd));
868  }
869  if (issuper != nullptr) {
870  append_with_commas(sql, "issuper = ?");
871  values.push_back(std::to_string(*issuper));
872  }
873  if (dbname != nullptr) {
874  if (!dbname->empty()) {
875  append_with_commas(sql, "default_db = ?");
876  DBMetadata db;
877  if (!SysCatalog::instance().getMetadataForDB(*dbname, db)) {
878  throw runtime_error(string("DEFAULT_DB ") + *dbname + " not found.");
879  }
880  values.push_back(std::to_string(db.dbId));
881  } else {
882  append_with_commas(sql, "default_db = NULL");
883  }
884  }
885  if (can_login != nullptr) {
886  append_with_commas(sql, "can_login = ?");
887  values.push_back(std::to_string(*can_login));
888  }
889 
890  sql = "UPDATE mapd_users SET " + sql + " WHERE userid = ?";
891  values.push_back(std::to_string(userid));
892 
893  sqliteConnector_->query_with_text_params(sql, values);
894  } catch (const std::exception& e) {
895  sqliteConnector_->query("ROLLBACK TRANSACTION");
896  throw;
897  }
898  sqliteConnector_->query("END TRANSACTION");
899 }
900 
902  return
903  [](auto& db_connector, auto on_success, auto on_failure, auto&&... query_requests) {
904  auto query_runner = [&db_connector](auto&&... query_reqs) {
905  [[gnu::unused]] int throw_away[] = {
906  (db_connector->query_with_text_params(
907  std::forward<decltype(query_reqs)>(query_reqs)),
908  0)...};
909  };
910 
911  db_connector->query("BEGIN TRANSACTION");
912  try {
913  query_runner(std::forward<decltype(query_requests)>(query_requests)...);
914  on_success();
915  } catch (std::exception&) {
916  db_connector->query("ROLLBACK TRANSACTION");
917  on_failure();
918  throw;
919  }
920  db_connector->query("END TRANSACTION");
921  };
922 }
923 
924 void SysCatalog::updateUserRoleName(const std::string& roleName,
925  const std::string& newName) {
927 
928  auto it = granteeMap_.find(to_upper(roleName));
929  if (it != granteeMap_.end()) {
930  it->second->setName(newName);
931  std::swap(granteeMap_[to_upper(newName)], it->second);
932  granteeMap_.erase(it);
933  }
934 }
935 
936 void SysCatalog::renameUser(std::string const& old_name, std::string const& new_name) {
937  using namespace std::string_literals;
940 
941  UserMetadata old_user;
942  if (!getMetadataForUser(old_name, old_user)) {
943  throw std::runtime_error("User " + old_name + " doesn't exist.");
944  }
945 
946  UserMetadata new_user;
947  if (getMetadataForUser(new_name, new_user)) {
948  throw std::runtime_error("User " + new_name + " already exists.");
949  }
950 
951  if (getGrantee(new_name)) {
952  throw runtime_error(
953  "User name " + new_name +
954  " is same as one of existing grantees. User and role names should be unique.");
955  }
956 
957  auto transaction_streamer = yieldTransactionStreamer();
958  auto failure_handler = [] {};
959  auto success_handler = [this, &old_name, &new_name] {
960  updateUserRoleName(old_name, new_name);
961  };
962  auto q1 = {"UPDATE mapd_users SET name=?1 where name=?2;"s, new_name, old_name};
963  auto q2 = {"UPDATE mapd_object_permissions set roleName=?1 WHERE roleName=?2;"s,
964  new_name,
965  old_name};
966  transaction_streamer(sqliteConnector_, success_handler, failure_handler, q1, q2);
967 }
968 
969 void SysCatalog::renameDatabase(std::string const& old_name,
970  std::string const& new_name) {
971  using namespace std::string_literals;
974 
975  DBMetadata new_db;
976  if (getMetadataForDB(new_name, new_db)) {
977  throw std::runtime_error("Database " + new_name + " already exists.");
978  }
979  if (to_upper(new_name) == to_upper(OMNISCI_SYSTEM_CATALOG)) {
980  throw std::runtime_error("Database name " + new_name + "is reserved.");
981  }
982 
983  DBMetadata old_db;
984  if (!getMetadataForDB(old_name, old_db)) {
985  throw std::runtime_error("Database " + old_name + " does not exists.");
986  }
987 
988  Catalog::remove(old_db.dbName);
989 
990  std::string old_catalog_path, new_catalog_path;
991  std::tie(old_catalog_path, new_catalog_path) =
992  duplicateAndRenameCatalog(old_name, new_name);
993 
994  auto transaction_streamer = yieldTransactionStreamer();
995  auto failure_handler = [this, new_catalog_path] {
996  removeCatalogByFullPath(new_catalog_path);
997  };
998  auto success_handler = [this, old_catalog_path] {
999  removeCatalogByFullPath(old_catalog_path);
1000  };
1001 
1002  auto q1 = {"UPDATE mapd_databases SET name=?1 WHERE name=?2;"s, new_name, old_name};
1003  auto q2 = {
1004  "UPDATE mapd_object_permissions SET objectName=?1 WHERE objectNAME=?2 and (objectPermissionsType=?3 or objectId = -1) and dbId=?4;"s,
1005  new_name,
1006  old_name,
1008  std::to_string(old_db.dbId)};
1009 
1010  transaction_streamer(sqliteConnector_, success_handler, failure_handler, q1, q2);
1011 }
1012 
1013 void SysCatalog::createDatabase(const string& name, int owner) {
1014  sys_write_lock write_lock(this);
1016 
1017  DBMetadata db;
1018  if (getMetadataForDB(name, db)) {
1019  throw runtime_error("Database " + name + " already exists.");
1020  }
1021  if (to_upper(name) == to_upper(OMNISCI_SYSTEM_CATALOG)) {
1022  throw runtime_error("Database name " + name + " is reserved.");
1023  }
1024 
1025  std::unique_ptr<SqliteConnector> dbConn(
1026  new SqliteConnector(name, basePath_ + "/mapd_catalogs/"));
1027  // NOTE(max): it's okay to run this in a separate transaction. If we fail later
1028  // we delete the database anyways.
1029  // If we run it in the same transaction as SysCatalog functions, then Catalog
1030  // constructor won't find the tables we have just created.
1031  dbConn->query("BEGIN TRANSACTION");
1032  try {
1033  dbConn->query(
1034  "CREATE TABLE mapd_tables (tableid integer primary key, name text unique, userid "
1035  "integer, ncolumns integer, "
1036  "isview boolean, "
1037  "fragments text, frag_type integer, max_frag_rows integer, max_chunk_size "
1038  "bigint, "
1039  "frag_page_size integer, "
1040  "max_rows bigint, partitions text, shard_column_id integer, shard integer, "
1041  "sort_column_id integer default 0, "
1042  "num_shards integer, key_metainfo TEXT, version_num "
1043  "BIGINT DEFAULT 1) ");
1044  dbConn->query(
1045  "CREATE TABLE mapd_columns (tableid integer references mapd_tables, columnid "
1046  "integer, name text, coltype "
1047  "integer, colsubtype integer, coldim integer, colscale integer, is_notnull "
1048  "boolean, compression integer, "
1049  "comp_param integer, size integer, chunks text, is_systemcol boolean, "
1050  "is_virtualcol boolean, virtual_expr "
1051  "text, is_deletedcol boolean, version_num BIGINT, "
1052  "primary key(tableid, columnid), unique(tableid, name))");
1053  dbConn->query(
1054  "CREATE TABLE mapd_views (tableid integer references mapd_tables, sql text)");
1055  dbConn->query(
1056  "CREATE TABLE mapd_dashboards (id integer primary key autoincrement, name text , "
1057  "userid integer references mapd_users, state text, image_hash text, update_time "
1058  "timestamp, "
1059  "metadata text, UNIQUE(userid, name) )");
1060  dbConn->query(
1061  "CREATE TABLE mapd_links (linkid integer primary key, userid integer references "
1062  "mapd_users, "
1063  "link text unique, view_state text, update_time timestamp, view_metadata text)");
1064  dbConn->query(
1065  "CREATE TABLE mapd_dictionaries (dictid integer primary key, name text unique, "
1066  "nbits int, is_shared boolean, "
1067  "refcount int, version_num BIGINT DEFAULT 1)");
1068  dbConn->query(
1069  "CREATE TABLE mapd_logical_to_physical(logical_table_id integer, "
1070  "physical_table_id "
1071  "integer)");
1072  dbConn->query("CREATE TABLE mapd_record_ownership_marker (dummy integer)");
1073  dbConn->query_with_text_params(
1074  "INSERT INTO mapd_record_ownership_marker (dummy) VALUES (?1)",
1075  std::vector<std::string>{std::to_string(owner)});
1076  } catch (const std::exception&) {
1077  dbConn->query("ROLLBACK TRANSACTION");
1078  boost::filesystem::remove(basePath_ + "/mapd_catalogs/" + name);
1079  throw;
1080  }
1081  dbConn->query("END TRANSACTION");
1082 
1083  // Now update SysCatalog with privileges and the new database
1084  sqliteConnector_->query("BEGIN TRANSACTION");
1085  try {
1086  sqliteConnector_->query_with_text_param(
1087  "INSERT INTO mapd_databases (name, owner) VALUES (?, " + std::to_string(owner) +
1088  ")",
1089  name);
1090  CHECK(getMetadataForDB(name, db));
1091  auto cat =
1093  if (owner != OMNISCI_ROOT_USER_ID) {
1095  object.loadKey(*cat);
1096  UserMetadata user;
1097  CHECK(getMetadataForUserById(owner, user));
1098  grantAllOnDatabase_unsafe(user.userName, object, *cat);
1099  }
1100  } catch (const std::exception&) {
1101  sqliteConnector_->query("ROLLBACK TRANSACTION");
1102  boost::filesystem::remove(basePath_ + "/mapd_catalogs/" + name);
1103  throw;
1104  }
1105  sqliteConnector_->query("END TRANSACTION");
1106 }
1107 
1109  sys_write_lock write_lock(this);
1111  auto cat =
1113  sqliteConnector_->query("BEGIN TRANSACTION");
1114  try {
1115  // remove this database ID from any users that have it set as their default database
1116  sqliteConnector_->query_with_text_param(
1117  "UPDATE mapd_users SET default_db = NULL WHERE default_db = ?",
1118  std::to_string(db.dbId));
1119  /* revoke object privileges to all tables of the database being dropped */
1120  const auto tables = cat->getAllTableMetadata();
1121  for (const auto table : tables) {
1122  if (table->shard >= 0) {
1123  // skip shards, they're not standalone tables
1124  continue;
1125  }
1127  DBObject(table->tableName, TableDBObjectType), cat.get());
1128  }
1129  const auto dashboards = cat->getAllDashboardsMetadata();
1130  for (const auto dashboard : dashboards) {
1132  DBObject(dashboard->dashboardId, DashboardDBObjectType), cat.get());
1133  }
1134  /* revoke object privileges to the database being dropped */
1135  for (const auto& grantee : granteeMap_) {
1136  if (grantee.second->hasAnyPrivilegesOnDb(db.dbId, true)) {
1137  revokeAllOnDatabase_unsafe(grantee.second->getName(), db.dbId, grantee.second);
1138  }
1139  }
1140  sqliteConnector_->query_with_text_param("DELETE FROM mapd_databases WHERE dbid = ?",
1141  std::to_string(db.dbId));
1142  cat->eraseDBData();
1143  Catalog::remove(db.dbName);
1144  } catch (const std::exception&) {
1145  sqliteConnector_->query("ROLLBACK TRANSACTION");
1146  throw;
1147  }
1148  sqliteConnector_->query("END TRANSACTION");
1149 }
1150 
1151 // checkPasswordForUser() with no EE code
1152 bool SysCatalog::checkPasswordForUser(const std::string& passwd,
1153  std::string& name,
1154  UserMetadata& user) {
1155  return checkPasswordForUserImpl(passwd, name, user);
1156 }
1157 
1158 bool SysCatalog::checkPasswordForUserImpl(const std::string& passwd,
1159  std::string& name,
1160  UserMetadata& user) {
1161  if (!getMetadataForUser(name, user)) {
1162  // Check password against some fake hash just to waste time so that response times
1163  // for invalid password and invalid user are similar and a caller can't say the
1164  // difference
1165  char fake_hash[BCRYPT_HASHSIZE];
1166  CHECK(bcrypt_gensalt(-1, fake_hash) == 0);
1167  bcrypt_checkpw(passwd.c_str(), fake_hash);
1168  LOG(WARNING) << "Local login failed";
1169  return false;
1170  }
1171  int pwd_check_result = bcrypt_checkpw(passwd.c_str(), user.passwd_hash.c_str());
1172  // if the check fails there is a good chance that data on disc is broken
1173  CHECK(pwd_check_result >= 0);
1174  if (pwd_check_result != 0) {
1175  LOG(WARNING) << "Local login failed";
1176  return false;
1177  }
1178  return true;
1179 }
1180 
1181 static bool parseUserMetadataFromSQLite(const std::unique_ptr<SqliteConnector>& conn,
1182  UserMetadata& user) {
1183  int numRows = conn->getNumRows();
1184  if (numRows == 0) {
1185  return false;
1186  }
1187  user.userId = conn->getData<int>(0, 0);
1188  user.userName = conn->getData<string>(0, 1);
1189  user.passwd_hash = conn->getData<string>(0, 2);
1190  user.isSuper = conn->getData<bool>(0, 3);
1191  user.defaultDbId = conn->isNull(0, 4) ? -1 : conn->getData<int>(0, 4);
1192  user.can_login = conn->getData<bool>(0, 5);
1193  return true;
1194 }
1195 
1198  sqliteConnector_->query_with_text_param(
1199  "SELECT userid, name, passwd_hash, issuper, default_db, can_login FROM mapd_users "
1200  "WHERE name = ?",
1201  name);
1203 }
1204 
1205 bool SysCatalog::getMetadataForUserById(const int32_t idIn, UserMetadata& user) {
1207  sqliteConnector_->query_with_text_param(
1208  "SELECT userid, name, passwd_hash, issuper, default_db, can_login FROM mapd_users "
1209  "WHERE userid = ?",
1210  std::to_string(idIn));
1212 }
1213 
1214 list<DBMetadata> SysCatalog::getAllDBMetadata() {
1216  sqliteConnector_->query("SELECT dbid, name, owner FROM mapd_databases");
1217  int numRows = sqliteConnector_->getNumRows();
1218  list<DBMetadata> db_list;
1219  for (int r = 0; r < numRows; ++r) {
1220  DBMetadata db;
1221  db.dbId = sqliteConnector_->getData<int>(r, 0);
1222  db.dbName = sqliteConnector_->getData<string>(r, 1);
1223  db.dbOwner = sqliteConnector_->getData<int>(r, 2);
1224  db_list.push_back(db);
1225  }
1226  return db_list;
1227 }
1228 
1229 namespace {
1230 
1231 auto get_users(std::unique_ptr<SqliteConnector>& sqliteConnector,
1232  const int32_t dbId = -1) {
1233  sqliteConnector->query("SELECT userid, name, issuper, can_login FROM mapd_users");
1234  int numRows = sqliteConnector->getNumRows();
1235  list<UserMetadata> user_list;
1236  const bool return_all_users = dbId == -1;
1237  auto has_any_privilege = [&return_all_users, &dbId](const std::string& name) {
1238  if (!return_all_users) {
1239  const auto grantee = SysCatalog::instance().getUserGrantee(name);
1240  return grantee ? grantee->hasAnyPrivilegesOnDb(dbId, false) : false;
1241  }
1242  return true;
1243  };
1244  auto add_user = [&user_list, &has_any_privilege](const int32_t id,
1245  const std::string& name,
1246  const bool super,
1247  const bool can_login) {
1248  if (has_any_privilege(name)) {
1249  user_list.emplace_back(id, name, "", super, -1, can_login);
1250  };
1251  };
1252  for (int r = 0; r < numRows; ++r) {
1253  add_user(sqliteConnector->getData<int>(r, 0),
1254  sqliteConnector->getData<string>(r, 1),
1255  sqliteConnector->getData<bool>(r, 2),
1256  sqliteConnector->getData<bool>(r, 3));
1257  }
1258  return user_list;
1259 }
1260 
1261 } // namespace
1262 
1263 list<UserMetadata> SysCatalog::getAllUserMetadata(const int64_t dbId) {
1264  // this call is to return users that have some form of permissions to objects in the db
1265  // sadly mapd_object_permissions table is also misused to manage user roles.
1267  return get_users(sqliteConnector_, dbId);
1268 }
1269 
1270 list<UserMetadata> SysCatalog::getAllUserMetadata() {
1272  return get_users(sqliteConnector_);
1273 }
1274 
1275 void SysCatalog::getMetadataWithDefaultDB(std::string& dbname,
1276  const std::string& username,
1278  UserMetadata& user_meta) {
1279  if (!getMetadataForUser(username, user_meta)) {
1280  throw std::runtime_error("Invalid credentials.");
1281  }
1282 
1283  if (!dbname.empty()) {
1284  if (!getMetadataForDB(dbname, db_meta)) {
1285  throw std::runtime_error("Database name " + dbname + " does not exist.");
1286  }
1287  // loaded the requested database
1288  } else {
1289  if (user_meta.defaultDbId != -1) {
1290  if (!getMetadataForDBById(user_meta.defaultDbId, db_meta)) {
1291  throw std::runtime_error(
1292  "Server error: User #" + std::to_string(user_meta.userId) + " " +
1293  user_meta.userName + " has invalid default_db #" +
1294  std::to_string(user_meta.defaultDbId) + " which does not exist.");
1295  }
1296  dbname = db_meta.dbName;
1297  // loaded the user's default database
1298  } else {
1299  if (!getMetadataForDB(OMNISCI_DEFAULT_DB, db_meta)) {
1300  throw std::runtime_error(std::string("Database ") + OMNISCI_DEFAULT_DB +
1301  " does not exist.");
1302  }
1303  dbname = OMNISCI_DEFAULT_DB;
1304  // loaded the mapd database by default
1305  }
1306  }
1307 }
1308 
1311  sqliteConnector_->query_with_text_param(
1312  "SELECT dbid, name, owner FROM mapd_databases WHERE name = ?", name);
1313  int numRows = sqliteConnector_->getNumRows();
1314  if (numRows == 0) {
1315  return false;
1316  }
1317  db.dbId = sqliteConnector_->getData<int>(0, 0);
1318  db.dbName = sqliteConnector_->getData<string>(0, 1);
1319  db.dbOwner = sqliteConnector_->getData<int>(0, 2);
1320  return true;
1321 }
1322 
1323 bool SysCatalog::getMetadataForDBById(const int32_t idIn, DBMetadata& db) {
1325  sqliteConnector_->query_with_text_param(
1326  "SELECT dbid, name, owner FROM mapd_databases WHERE dbid = ?",
1327  std::to_string(idIn));
1328  int numRows = sqliteConnector_->getNumRows();
1329  if (numRows == 0) {
1330  return false;
1331  }
1332  db.dbId = sqliteConnector_->getData<int>(0, 0);
1333  db.dbName = sqliteConnector_->getData<string>(0, 1);
1334  db.dbOwner = sqliteConnector_->getData<int>(0, 2);
1335  return true;
1336 }
1337 
1339  DBSummaryList ret;
1340 
1341  std::list<Catalog_Namespace::DBMetadata> db_list = getAllDBMetadata();
1342  std::list<Catalog_Namespace::UserMetadata> user_list = getAllUserMetadata();
1343 
1344  for (auto d : db_list) {
1345  DBObject dbObject(d.dbName, DatabaseDBObjectType);
1346  dbObject.loadKey();
1348  if (!checkPrivileges(user, std::vector<DBObject>{dbObject})) {
1349  continue;
1350  }
1351  for (auto u : user_list) {
1352  if (d.dbOwner == u.userId) {
1353  ret.emplace_back(DBSummary{d.dbName, u.userName});
1354  break;
1355  }
1356  }
1357  }
1358 
1359  return ret;
1360 }
1361 
1363  const std::string& objectName,
1365  const Catalog_Namespace::Catalog& catalog,
1366  int32_t objectId) {
1367  sys_write_lock write_lock(this);
1369 
1370  DBObject object =
1371  objectId == -1 ? DBObject(objectName, type) : DBObject(objectId, type);
1372  object.loadKey(catalog);
1373  switch (type) {
1374  case TableDBObjectType:
1375  object.setPrivileges(AccessPrivileges::ALL_TABLE);
1376  break;
1377  case DashboardDBObjectType:
1378  object.setPrivileges(AccessPrivileges::ALL_DASHBOARD);
1379  break;
1380  default:
1381  object.setPrivileges(AccessPrivileges::ALL_DATABASE);
1382  break;
1383  }
1384  object.setOwner(user.userId);
1385  sqliteConnector_->query("BEGIN TRANSACTION");
1386  try {
1387  if (!user.isSuper) { // no need to grant to suser, has all privs by default
1388  grantDBObjectPrivileges_unsafe(user.userName, object, catalog);
1389  auto* grantee = instance().getUserGrantee(user.userName);
1390  if (!grantee) {
1391  throw runtime_error("User " + user.userName + " does not exist.");
1392  }
1393  grantee->grantPrivileges(object);
1394  }
1395  } catch (std::exception& e) {
1396  sqliteConnector_->query("ROLLBACK TRANSACTION");
1397  throw;
1398  }
1399  sqliteConnector_->query("END TRANSACTION");
1400 }
1401 
1403  const vector<string>& grantees,
1404  const vector<DBObject>& objects,
1405  const Catalog_Namespace::Catalog& catalog) {
1406  for (const auto& grantee : grantees) {
1407  for (const auto& object : objects) {
1408  grantDBObjectPrivileges_unsafe(grantee, object, catalog);
1409  }
1410  }
1411 }
1412 
1413 // GRANT INSERT ON TABLE payroll_table TO payroll_dept_role;
1415  const std::string& granteeName,
1416  DBObject object,
1417  const Catalog_Namespace::Catalog& catalog) {
1418  object.loadKey(catalog);
1419  if (object.getPrivileges().hasPermission(DatabasePrivileges::ALL) &&
1420  object.getObjectKey().permissionType == DatabaseDBObjectType) {
1421  return grantAllOnDatabase_unsafe(granteeName, object, catalog);
1422  }
1423 
1424  sys_write_lock write_lock(this);
1425 
1426  UserMetadata user_meta;
1427  if (instance().getMetadataForUser(granteeName, user_meta)) {
1428  if (user_meta.isSuper) {
1429  // super doesn't have explicit privileges so nothing to do
1430  return;
1431  }
1432  }
1433  auto* grantee = instance().getGrantee(granteeName);
1434  if (!grantee) {
1435  throw runtime_error("Request to grant privileges to " + granteeName +
1436  " failed because role or user with this name does not exist.");
1437  }
1438  grantee->grantPrivileges(object);
1439 
1440  /* apply grant privileges statement to sqlite DB */
1441  std::vector<std::string> objectKey = object.toString();
1442  object.resetPrivileges();
1443  grantee->getPrivileges(object, true);
1444 
1447  sqliteConnector_, granteeName, grantee->isUser(), object);
1448  updateObjectDescriptorMap(granteeName, object, grantee->isUser(), catalog);
1449 }
1450 
1451 void SysCatalog::grantAllOnDatabase_unsafe(const std::string& roleName,
1452  DBObject& object,
1453  const Catalog_Namespace::Catalog& catalog) {
1454  // It's a separate use case because it's easier for implementation to convert ALL ON
1455  // DATABASE into ALL ON DASHBOARDS, ALL ON VIEWS and ALL ON TABLES
1456  // Add DB Access privileges
1457  DBObject tmp_object = object;
1460  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1463  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1466  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1468  tmp_object.setPermissionType(ViewDBObjectType);
1469  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1472  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1473  return;
1474 }
1475 
1477  const vector<string>& grantees,
1478  const vector<DBObject>& objects,
1479  const Catalog_Namespace::Catalog& catalog) {
1480  for (const auto& grantee : grantees) {
1481  for (const auto& object : objects) {
1482  revokeDBObjectPrivileges_unsafe(grantee, object, catalog);
1483  }
1484  }
1485 }
1486 
1487 // REVOKE INSERT ON TABLE payroll_table FROM payroll_dept_role;
1489  const std::string& granteeName,
1490  DBObject object,
1491  const Catalog_Namespace::Catalog& catalog) {
1492  sys_write_lock write_lock(this);
1493 
1494  UserMetadata user_meta;
1495  if (instance().getMetadataForUser(granteeName, user_meta)) {
1496  if (user_meta.isSuper) {
1497  // super doesn't have explicit privileges so nothing to do
1498  return;
1499  }
1500  }
1501  auto* grantee = getGrantee(granteeName);
1502  if (!grantee) {
1503  throw runtime_error("Request to revoke privileges from " + granteeName +
1504  " failed because role or user with this name does not exist.");
1505  }
1506  object.loadKey(catalog);
1507 
1508  if (object.getPrivileges().hasPermission(DatabasePrivileges::ALL) &&
1509  object.getObjectKey().permissionType == DatabaseDBObjectType) {
1510  return revokeAllOnDatabase_unsafe(granteeName, object.getObjectKey().dbId, grantee);
1511  }
1512 
1513  auto ret_object = grantee->revokePrivileges(object);
1514  if (ret_object) {
1517  sqliteConnector_, granteeName, grantee->isUser(), *ret_object);
1518  updateObjectDescriptorMap(granteeName, *ret_object, grantee->isUser(), catalog);
1519  } else {
1521  deleteObjectPrivileges(sqliteConnector_, granteeName, grantee->isUser(), object);
1522  deleteObjectDescriptorMap(granteeName, object, catalog);
1523  }
1524 }
1525 
1526 void SysCatalog::revokeAllOnDatabase_unsafe(const std::string& roleName,
1527  int32_t dbId,
1528  Grantee* grantee) {
1530  sqliteConnector_->query_with_text_params(
1531  "DELETE FROM mapd_object_permissions WHERE roleName = ?1 and dbId = ?2",
1532  std::vector<std::string>{roleName, std::to_string(dbId)});
1533  grantee->revokeAllOnDatabase(dbId);
1534  for (auto d = objectDescriptorMap_.begin(); d != objectDescriptorMap_.end();) {
1535  if (d->second->roleName == roleName && d->second->dbId == dbId) {
1536  delete d->second;
1537  d = objectDescriptorMap_.erase(d);
1538  } else {
1539  d++;
1540  }
1541  }
1542 }
1543 
1545  Catalog* catalog) {
1546  sys_write_lock write_lock(this);
1547  dbObject.loadKey(*catalog);
1548  auto privs = (dbObject.getObjectKey().permissionType == TableDBObjectType)
1553  dbObject.setPrivileges(privs);
1554  for (const auto& grantee : granteeMap_) {
1555  if (grantee.second->findDbObject(dbObject.getObjectKey(), true)) {
1556  revokeDBObjectPrivileges_unsafe(grantee.second->getName(), dbObject, *catalog);
1557  }
1558  }
1559 }
1560 
1562  DBObject object,
1563  const Catalog_Namespace::Catalog& catalog) {
1564  sys_read_lock read_lock(this);
1565 
1566  auto* grantee = instance().getUserGrantee(user.userName);
1567  if (grantee) {
1568  object.loadKey(catalog);
1569  auto* found_object = grantee->findDbObject(object.getObjectKey(), false);
1570  if (found_object && found_object->getOwner() == user.userId) {
1571  return true;
1572  }
1573  }
1574  return false;
1575 }
1576 
1577 void SysCatalog::getDBObjectPrivileges(const std::string& granteeName,
1578  DBObject& object,
1579  const Catalog_Namespace::Catalog& catalog) const {
1580  sys_read_lock read_lock(this);
1581  UserMetadata user_meta;
1582 
1583  if (instance().getMetadataForUser(granteeName, user_meta)) {
1584  if (user_meta.isSuper) {
1585  throw runtime_error(
1586  "Request to show privileges from " + granteeName +
1587  " failed because user is super user and has all privileges by default.");
1588  }
1589  }
1590  auto* grantee = instance().getGrantee(granteeName);
1591  if (!grantee) {
1592  throw runtime_error("Request to show privileges for " + granteeName +
1593  " failed because role or user with this name does not exist.");
1594  }
1595  object.loadKey(catalog);
1596  grantee->getPrivileges(object, true);
1597 }
1598 
1599 void SysCatalog::createRole_unsafe(const std::string& roleName,
1600  const bool& userPrivateRole) {
1601  sys_write_lock write_lock(this);
1602 
1603  auto* grantee = getGrantee(roleName);
1604  if (grantee) {
1605  throw std::runtime_error("CREATE ROLE " + roleName +
1606  " failed because grantee with this name already exists.");
1607  }
1608  if (userPrivateRole) {
1609  grantee = new User(roleName);
1610  } else {
1611  grantee = new Role(roleName);
1612  }
1613  granteeMap_[to_upper(roleName)] = grantee;
1614 
1615  // NOTE (max): Why create an empty privileges record for a role?
1616  /* grant none privileges to this role and add it to sqlite DB */
1618  DBObjectKey objKey;
1619  // 0 is an id that does not exist
1620  objKey.dbId = 0;
1622  dbObject.setObjectKey(objKey);
1623  grantee->grantPrivileges(dbObject);
1624 
1626  insertOrUpdateObjectPrivileges(sqliteConnector_, roleName, userPrivateRole, dbObject);
1627 }
1628 
1629 void SysCatalog::dropRole_unsafe(const std::string& roleName) {
1630  sys_write_lock write_lock(this);
1631 
1632  // it may very well be a user "role", so keep it generic
1633  auto* rl = getGrantee(roleName);
1634  if (rl) { // admin super user may not exist in roles
1635  delete rl;
1636  }
1637  granteeMap_.erase(to_upper(roleName));
1638 
1640  sqliteConnector_->query_with_text_param("DELETE FROM mapd_roles WHERE roleName = ?",
1641  roleName);
1642  sqliteConnector_->query_with_text_param(
1643  "DELETE FROM mapd_object_permissions WHERE roleName = ?", roleName);
1644 }
1645 
1646 void SysCatalog::grantRoleBatch_unsafe(const std::vector<std::string>& roles,
1647  const std::vector<std::string>& grantees) {
1648  for (const auto& role : roles) {
1649  for (const auto& grantee : grantees) {
1650  grantRole_unsafe(role, grantee);
1651  }
1652  }
1653 }
1654 
1655 // GRANT ROLE payroll_dept_role TO joe;
1656 void SysCatalog::grantRole_unsafe(const std::string& roleName,
1657  const std::string& granteeName) {
1658  auto* rl = getRoleGrantee(roleName);
1659  if (!rl) {
1660  throw runtime_error("Request to grant role " + roleName +
1661  " failed because role with this name does not exist.");
1662  }
1663  auto* grantee = getGrantee(granteeName);
1664  if (!grantee) {
1665  throw runtime_error("Request to grant role " + roleName + " failed because grantee " +
1666  granteeName + " does not exist.");
1667  }
1668  sys_write_lock write_lock(this);
1669  if (!grantee->hasRole(rl, true)) {
1670  grantee->grantRole(rl);
1672  sqliteConnector_->query_with_text_params(
1673  "INSERT INTO mapd_roles(roleName, userName) VALUES (?, ?)",
1674  std::vector<std::string>{rl->getName(), grantee->getName()});
1675  }
1676 }
1677 
1678 void SysCatalog::revokeRoleBatch_unsafe(const std::vector<std::string>& roles,
1679  const std::vector<std::string>& grantees) {
1680  for (const auto& role : roles) {
1681  for (const auto& grantee : grantees) {
1682  revokeRole_unsafe(role, grantee);
1683  }
1684  }
1685 }
1686 
1687 // REVOKE ROLE payroll_dept_role FROM joe;
1688 void SysCatalog::revokeRole_unsafe(const std::string& roleName,
1689  const std::string& granteeName) {
1690  auto* rl = getRoleGrantee(roleName);
1691  if (!rl) {
1692  throw runtime_error("Request to revoke role " + roleName +
1693  " failed because role with this name does not exist.");
1694  }
1695  auto* grantee = getGrantee(granteeName);
1696  if (!grantee) {
1697  throw runtime_error("Request to revoke role from " + granteeName +
1698  " failed because grantee with this name does not exist.");
1699  }
1700  sys_write_lock write_lock(this);
1701  grantee->revokeRole(rl);
1703  sqliteConnector_->query_with_text_params(
1704  "DELETE FROM mapd_roles WHERE roleName = ? AND userName = ?",
1705  std::vector<std::string>{rl->getName(), grantee->getName()});
1706 }
1707 
1708 // Update or add element in ObjectRoleDescriptorMap
1709 void SysCatalog::updateObjectDescriptorMap(const std::string& roleName,
1710  DBObject& object,
1711  bool roleType,
1712  const Catalog_Namespace::Catalog& cat) {
1713  bool present = false;
1714  auto privs = object.getPrivileges();
1715  sys_write_lock write_lock(this);
1716  auto range = objectDescriptorMap_.equal_range(
1717  std::to_string(cat.getCurrentDB().dbId) + ":" +
1718  std::to_string(object.getObjectKey().permissionType) + ":" +
1719  std::to_string(object.getObjectKey().objectId));
1720  for (auto d = range.first; d != range.second; ++d) {
1721  if (d->second->roleName == roleName) {
1722  // overwrite permissions
1723  d->second->privs = privs;
1724  present = true;
1725  }
1726  }
1727  if (!present) {
1729  od->roleName = roleName;
1730  od->roleType = roleType;
1731  od->objectType = object.getObjectKey().permissionType;
1732  od->dbId = object.getObjectKey().dbId;
1733  od->objectId = object.getObjectKey().objectId;
1734  od->privs = object.getPrivileges();
1735  od->objectOwnerId = object.getOwner();
1736  od->objectName = object.getName();
1737  objectDescriptorMap_.insert(ObjectRoleDescriptorMap::value_type(
1738  std::to_string(od->dbId) + ":" + std::to_string(od->objectType) + ":" +
1739  std::to_string(od->objectId),
1740  od));
1741  }
1742 }
1743 
1744 // rename object descriptors
1746  const Catalog_Namespace::Catalog& cat) {
1747  sys_write_lock write_lock(this);
1749  auto range = objectDescriptorMap_.equal_range(
1750  std::to_string(cat.getCurrentDB().dbId) + ":" +
1751  std::to_string(object.getObjectKey().permissionType) + ":" +
1752  std::to_string(object.getObjectKey().objectId));
1753  for (auto d = range.first; d != range.second; ++d) {
1754  // rename object
1755  d->second->objectName = object.getName();
1756  }
1757 
1758  sqliteConnector_->query("BEGIN TRANSACTION");
1759  try {
1760  sqliteConnector_->query_with_text_params(
1761  "UPDATE mapd_object_permissions SET objectName = ?1 WHERE "
1762  "dbId = ?2 AND objectId = ?3",
1763  std::vector<std::string>{object.getName(),
1765  std::to_string(object.getObjectKey().objectId)});
1766  } catch (const std::exception& e) {
1767  sqliteConnector_->query("ROLLBACK TRANSACTION");
1768  throw;
1769  }
1770  sqliteConnector_->query("END TRANSACTION");
1771 }
1772 
1773 // Remove user/role from ObjectRoleDescriptorMap
1774 void SysCatalog::deleteObjectDescriptorMap(const std::string& roleName) {
1775  sys_write_lock write_lock(this);
1776 
1777  for (auto d = objectDescriptorMap_.begin(); d != objectDescriptorMap_.end();) {
1778  if (d->second->roleName == roleName) {
1779  delete d->second;
1780  d = objectDescriptorMap_.erase(d);
1781  } else {
1782  d++;
1783  }
1784  }
1785 }
1786 
1787 // Remove element from ObjectRoleDescriptorMap
1788 void SysCatalog::deleteObjectDescriptorMap(const std::string& roleName,
1789  DBObject& object,
1790  const Catalog_Namespace::Catalog& cat) {
1791  sys_write_lock write_lock(this);
1792  auto range = objectDescriptorMap_.equal_range(
1793  std::to_string(cat.getCurrentDB().dbId) + ":" +
1794  std::to_string(object.getObjectKey().permissionType) + ":" +
1795  std::to_string(object.getObjectKey().objectId));
1796  for (auto d = range.first; d != range.second;) {
1797  // remove the entry
1798  if (d->second->roleName == roleName) {
1799  delete d->second;
1800  d = objectDescriptorMap_.erase(d);
1801  } else {
1802  d++;
1803  }
1804  }
1805 }
1806 
1808  std::vector<DBObject>& privObjects) {
1809  sys_read_lock read_lock(this);
1810  if (user.isSuper) {
1811  return true;
1812  }
1813  auto* user_rl = instance().getUserGrantee(user.userName);
1814  if (!user_rl) {
1815  throw runtime_error("User " + user.userName + " does not exist.");
1816  }
1817  for (std::vector<DBObject>::iterator objectIt = privObjects.begin();
1818  objectIt != privObjects.end();
1819  ++objectIt) {
1820  if (!user_rl->hasAnyPrivileges(*objectIt, false)) {
1821  return false;
1822  }
1823  }
1824  return true;
1825 }
1826 
1828  const std::vector<DBObject>& privObjects) const {
1829  sys_read_lock read_lock(this);
1830  if (user.isSuper) {
1831  return true;
1832  }
1833 
1834  auto* user_rl = instance().getUserGrantee(user.userName);
1835  if (!user_rl) {
1836  throw runtime_error("User " + user.userName + " does not exist.");
1837  }
1838  for (auto& object : privObjects) {
1839  if (!user_rl->checkPrivileges(object)) {
1840  return false;
1841  }
1842  }
1843  return true;
1844 }
1845 
1846 bool SysCatalog::checkPrivileges(const std::string& userName,
1847  const std::vector<DBObject>& privObjects) const {
1848  UserMetadata user;
1849  if (!instance().getMetadataForUser(userName, user)) {
1850  throw runtime_error("Request to check privileges for user " + userName +
1851  " failed because user with this name does not exist.");
1852  }
1853  return (checkPrivileges(user, privObjects));
1854 }
1855 
1856 Grantee* SysCatalog::getGrantee(const std::string& name) const {
1857  sys_read_lock read_lock(this);
1858  auto grantee = granteeMap_.find(to_upper(name));
1859  if (grantee == granteeMap_.end()) { // check to make sure role exists
1860  return nullptr;
1861  }
1862  return grantee->second; // returns pointer to role
1863 }
1864 
1865 Role* SysCatalog::getRoleGrantee(const std::string& name) const {
1866  return dynamic_cast<Role*>(getGrantee(name));
1867 }
1868 
1869 User* SysCatalog::getUserGrantee(const std::string& name) const {
1870  return dynamic_cast<User*>(getGrantee(name));
1871 }
1872 
1873 std::vector<ObjectRoleDescriptor*>
1874 SysCatalog::getMetadataForObject(int32_t dbId, int32_t dbType, int32_t objectId) const {
1875  sys_read_lock read_lock(this);
1876  std::vector<ObjectRoleDescriptor*> objectsList;
1877 
1878  auto range = objectDescriptorMap_.equal_range(std::to_string(dbId) + ":" +
1879  std::to_string(dbType) + ":" +
1880  std::to_string(objectId));
1881  for (auto d = range.first; d != range.second; ++d) {
1882  objectsList.push_back(d->second);
1883  }
1884  return objectsList; // return pointers to objects
1885 }
1886 
1887 bool SysCatalog::isRoleGrantedToGrantee(const std::string& granteeName,
1888  const std::string& roleName,
1889  bool only_direct) const {
1890  sys_read_lock read_lock(this);
1891  if (roleName == granteeName) {
1892  return true;
1893  }
1894  bool is_role_granted = false;
1895  auto* target_role = instance().getRoleGrantee(roleName);
1896  auto has_role = [&](auto grantee_rl) {
1897  is_role_granted = target_role && grantee_rl->hasRole(target_role, only_direct);
1898  };
1899  if (auto* user_role = instance().getUserGrantee(granteeName); user_role) {
1900  has_role(user_role);
1901  } else if (auto* role = instance().getRoleGrantee(granteeName); role) {
1902  has_role(role);
1903  } else {
1904  CHECK(false);
1905  }
1906  return is_role_granted;
1907 }
1908 
1909 bool SysCatalog::isDashboardSystemRole(const std::string& roleName) {
1910  return boost::algorithm::ends_with(roleName, SYSTEM_ROLE_TAG);
1911 }
1912 
1913 std::vector<std::string> SysCatalog::getRoles(const std::string& userName,
1914  const int32_t dbId) {
1915  sys_sqlite_lock sqlite_lock(this);
1916  std::string sql =
1917  "SELECT DISTINCT roleName FROM mapd_object_permissions WHERE "
1918  "objectPermissions<>0 "
1919  "AND roleType=0 AND dbId=" +
1920  std::to_string(dbId);
1921  sqliteConnector_->query(sql);
1922  int numRows = sqliteConnector_->getNumRows();
1923  std::vector<std::string> roles(0);
1924  for (int r = 0; r < numRows; ++r) {
1925  auto roleName = sqliteConnector_->getData<string>(r, 0);
1926  if (isRoleGrantedToGrantee(userName, roleName, false) &&
1927  !isDashboardSystemRole(roleName)) {
1928  roles.push_back(roleName);
1929  }
1930  }
1931  return roles;
1932 }
1933 
1934 std::vector<std::string> SysCatalog::getRoles(bool userPrivateRole,
1935  bool isSuper,
1936  const std::string& userName) {
1937  sys_read_lock read_lock(this);
1938  std::vector<std::string> roles;
1939  for (auto& grantee : granteeMap_) {
1940  if (!userPrivateRole && grantee.second->isUser()) {
1941  continue;
1942  }
1943  if (!isSuper && !isRoleGrantedToGrantee(userName, grantee.second->getName(), false)) {
1944  continue;
1945  }
1946  if (isDashboardSystemRole(grantee.second->getName())) {
1947  continue;
1948  }
1949  roles.push_back(grantee.second->getName());
1950  }
1951  return roles;
1952 }
1953 
1954 void SysCatalog::revokeDashboardSystemRole(const std::string roleName,
1955  const std::vector<std::string> grantees) {
1956  auto* rl = getRoleGrantee(roleName);
1957  for (auto granteeName : grantees) {
1958  const auto* grantee = SysCatalog::instance().getGrantee(granteeName);
1959  if (rl && grantee->hasRole(rl, true)) {
1960  // Grantees existence have been already validated
1961  SysCatalog::instance().revokeRole(roleName, granteeName);
1962  }
1963  }
1964 }
1965 
1967  sys_write_lock write_lock(this);
1968  sys_sqlite_lock sqlite_lock(this);
1969  string roleQuery(
1970  "SELECT roleName, roleType, objectPermissionsType, dbId, objectId, "
1971  "objectPermissions, objectOwnerId, objectName "
1972  "from mapd_object_permissions");
1973  sqliteConnector_->query(roleQuery);
1974  size_t numRows = sqliteConnector_->getNumRows();
1975  std::vector<std::string> objectKeyStr(4);
1976  DBObjectKey objectKey;
1977  AccessPrivileges privs;
1978  bool userPrivateRole(false);
1979  for (size_t r = 0; r < numRows; ++r) {
1980  std::string roleName = sqliteConnector_->getData<string>(r, 0);
1981  userPrivateRole = sqliteConnector_->getData<bool>(r, 1);
1982  DBObjectType permissionType =
1983  static_cast<DBObjectType>(sqliteConnector_->getData<int>(r, 2));
1984  objectKeyStr[0] = sqliteConnector_->getData<string>(r, 2);
1985  objectKeyStr[1] = sqliteConnector_->getData<string>(r, 3);
1986  objectKeyStr[2] = sqliteConnector_->getData<string>(r, 4);
1987  objectKey = DBObjectKey::fromString(objectKeyStr, permissionType);
1988  privs.privileges = sqliteConnector_->getData<int>(r, 5);
1989  int32_t owner = sqliteConnector_->getData<int>(r, 6);
1990  std::string name = sqliteConnector_->getData<string>(r, 7);
1991 
1992  DBObject dbObject(objectKey, privs, owner);
1993  dbObject.setName(name);
1994  if (-1 == objectKey.objectId) {
1995  dbObject.setObjectType(DBObjectType::DatabaseDBObjectType);
1996  } else {
1997  dbObject.setObjectType(permissionType);
1998  }
1999 
2000  auto* rl = getGrantee(roleName);
2001  if (!rl) {
2002  if (userPrivateRole) {
2003  rl = new User(roleName);
2004  } else {
2005  rl = new Role(roleName);
2006  }
2007  granteeMap_[to_upper(roleName)] = rl;
2008  }
2009  rl->grantPrivileges(dbObject);
2010  }
2011 }
2012 
2013 void SysCatalog::populateRoleDbObjects(const std::vector<DBObject>& objects) {
2014  sys_write_lock write_lock(this);
2015  sys_sqlite_lock sqlite_lock(this);
2016  sqliteConnector_->query("BEGIN TRANSACTION");
2017  try {
2018  for (auto dbobject : objects) {
2019  UserMetadata user;
2020  CHECK(getMetadataForUserById(dbobject.getOwner(), user));
2021  auto* grantee = getUserGrantee(user.userName);
2022  if (grantee) {
2024  sqliteConnector_, grantee->getName(), true, dbobject);
2025  grantee->grantPrivileges(dbobject);
2026  }
2027  }
2028 
2029  } catch (const std::exception& e) {
2030  sqliteConnector_->query("ROLLBACK TRANSACTION");
2031  throw;
2032  }
2033  sqliteConnector_->query("END TRANSACTION");
2034 }
2035 
2037  sys_write_lock write_lock(this);
2038  sys_sqlite_lock sqlite_lock(this);
2039  std::vector<std::pair<std::string, std::string>> granteeRooles;
2040  string userRoleQuery("SELECT roleName, userName from mapd_roles");
2041  sqliteConnector_->query(userRoleQuery);
2042  size_t numRows = sqliteConnector_->getNumRows();
2043  for (size_t r = 0; r < numRows; ++r) {
2044  std::string roleName = sqliteConnector_->getData<string>(r, 0);
2045  std::string userName = sqliteConnector_->getData<string>(r, 1);
2046  // required for declared nomenclature before v4.0.0
2047  if ((boost::equals(roleName, "mapd_default_suser_role") &&
2048  boost::equals(userName, OMNISCI_ROOT_USER)) ||
2049  (boost::equals(roleName, "mapd_default_user_role") &&
2050  !boost::equals(userName, "mapd_default_user_role"))) {
2051  // grouprole already exists with roleName==userName in mapd_roles table
2052  // ignore duplicate instances of userRole which exists before v4.0.0
2053  continue;
2054  }
2055  auto* rl = getGrantee(roleName);
2056  if (!rl) {
2057  throw runtime_error("Data inconsistency when building role map. Role " + roleName +
2058  " from db not found in the map.");
2059  }
2060  std::pair<std::string, std::string> roleVecElem(roleName, userName);
2061  granteeRooles.push_back(roleVecElem);
2062  }
2063 
2064  for (size_t i = 0; i < granteeRooles.size(); i++) {
2065  std::string roleName = granteeRooles[i].first;
2066  std::string granteeName = granteeRooles[i].second;
2067  auto* grantee = getGrantee(granteeName);
2068  if (!grantee) {
2069  throw runtime_error("Data inconsistency when building role map. Grantee " +
2070  granteeName + " not found in the map.");
2071  }
2072  if (granteeName == roleName) {
2073  continue;
2074  }
2075  Role* rl = dynamic_cast<Role*>(getGrantee(roleName));
2076  if (!rl) {
2077  throw runtime_error("Data inconsistency when building role map. Role " + roleName +
2078  " not found in the map.");
2079  }
2080  grantee->grantRole(rl);
2081  }
2082 }
2083 
2085  sys_write_lock write_lock(this);
2086  sys_sqlite_lock sqlite_lock(this);
2087  string objectQuery(
2088  "SELECT roleName, roleType, objectPermissionsType, dbId, objectId, "
2089  "objectPermissions, objectOwnerId, objectName "
2090  "from mapd_object_permissions");
2091  sqliteConnector_->query(objectQuery);
2092  size_t numRows = sqliteConnector_->getNumRows();
2093  for (size_t r = 0; r < numRows; ++r) {
2095  od->roleName = sqliteConnector_->getData<string>(r, 0);
2096  od->roleType = sqliteConnector_->getData<bool>(r, 1);
2097  od->objectType = sqliteConnector_->getData<int>(r, 2);
2098  od->dbId = sqliteConnector_->getData<int>(r, 3);
2099  od->objectId = sqliteConnector_->getData<int>(r, 4);
2100  od->privs.privileges = sqliteConnector_->getData<int>(r, 5);
2101  od->objectOwnerId = sqliteConnector_->getData<int>(r, 6);
2102  od->objectName = sqliteConnector_->getData<string>(r, 7);
2103  objectDescriptorMap_.insert(ObjectRoleDescriptorMap::value_type(
2104  std::to_string(od->dbId) + ":" + std::to_string(od->objectType) + ":" +
2105  std::to_string(od->objectId),
2106  od));
2107  }
2108 }
2109 
2110 template <typename F, typename... Args>
2111 void SysCatalog::execInTransaction(F&& f, Args&&... args) {
2112  sys_write_lock write_lock(this);
2113  sys_sqlite_lock sqlite_lock(this);
2114  sqliteConnector_->query("BEGIN TRANSACTION");
2115  try {
2116  (this->*f)(std::forward<Args>(args)...);
2117  } catch (std::exception&) {
2118  sqliteConnector_->query("ROLLBACK TRANSACTION");
2119  throw;
2120  }
2121  sqliteConnector_->query("END TRANSACTION");
2122 }
2123 
2124 void SysCatalog::createRole(const std::string& roleName, const bool& userPrivateRole) {
2125  execInTransaction(&SysCatalog::createRole_unsafe, roleName, userPrivateRole);
2126 }
2127 
2128 void SysCatalog::dropRole(const std::string& roleName) {
2130 }
2131 
2132 void SysCatalog::grantRoleBatch(const std::vector<std::string>& roles,
2133  const std::vector<std::string>& grantees) {
2135 }
2136 
2137 void SysCatalog::grantRole(const std::string& role, const std::string& grantee) {
2139 }
2140 
2141 void SysCatalog::revokeRoleBatch(const std::vector<std::string>& roles,
2142  const std::vector<std::string>& grantees) {
2144 }
2145 
2146 void SysCatalog::revokeRole(const std::string& role, const std::string& grantee) {
2148 }
2149 
2150 void SysCatalog::grantDBObjectPrivileges(const string& grantee,
2151  const DBObject& object,
2152  const Catalog_Namespace::Catalog& catalog) {
2154  &SysCatalog::grantDBObjectPrivileges_unsafe, grantee, object, catalog);
2155 }
2156 
2157 void SysCatalog::grantDBObjectPrivilegesBatch(const vector<string>& grantees,
2158  const vector<DBObject>& objects,
2159  const Catalog_Namespace::Catalog& catalog) {
2161  &SysCatalog::grantDBObjectPrivilegesBatch_unsafe, grantees, objects, catalog);
2162 }
2163 
2164 void SysCatalog::revokeDBObjectPrivileges(const string& grantee,
2165  const DBObject& object,
2166  const Catalog_Namespace::Catalog& catalog) {
2168  &SysCatalog::revokeDBObjectPrivileges_unsafe, grantee, object, catalog);
2169 }
2170 
2172  const vector<string>& grantees,
2173  const vector<DBObject>& objects,
2174  const Catalog_Namespace::Catalog& catalog) {
2176  &SysCatalog::revokeDBObjectPrivilegesBatch_unsafe, grantees, objects, catalog);
2177 }
2178 
2181 }
2182 
2183 void SysCatalog::syncUserWithRemoteProvider(const std::string& user_name,
2184  std::vector<std::string> idp_roles,
2185  bool* is_super) {
2186  UserMetadata user_meta;
2187  bool is_super_user = is_super ? *is_super : false;
2188  if (!getMetadataForUser(user_name, user_meta)) {
2189  createUser(user_name, generate_random_string(72), is_super_user, "", true);
2190  LOG(INFO) << "User " << user_name << " has been created by remote identity provider"
2191  << " with IS_SUPER = " << (is_super_user ? "'TRUE'" : "'FALSE'");
2192  } else if (is_super && is_super_user != user_meta.isSuper) {
2193  alterUser(user_meta.userId, nullptr, is_super, nullptr, nullptr);
2194  LOG(INFO) << "IS_SUPER for user " << user_name << " has been changed to "
2195  << (is_super_user ? "TRUE" : "FALSE") << " by remote identity provider";
2196  }
2197  std::vector<std::string> current_roles = {};
2198  auto* user_rl = getUserGrantee(user_name);
2199  if (user_rl) {
2200  current_roles = user_rl->getRoles();
2201  }
2202  std::transform(
2203  current_roles.begin(), current_roles.end(), current_roles.begin(), to_upper);
2204  std::transform(idp_roles.begin(), idp_roles.end(), idp_roles.begin(), to_upper);
2205  std::list<std::string> roles_revoked, roles_granted;
2206  // first remove obsolete ones
2207  for (auto& current_role_name : current_roles) {
2208  if (std::find(idp_roles.begin(), idp_roles.end(), current_role_name) ==
2209  idp_roles.end()) {
2210  revokeRole(current_role_name, user_name);
2211  roles_revoked.push_back(current_role_name);
2212  }
2213  }
2214  for (auto& role_name : idp_roles) {
2215  if (std::find(current_roles.begin(), current_roles.end(), role_name) ==
2216  current_roles.end()) {
2217  auto* rl = getRoleGrantee(role_name);
2218  if (rl) {
2219  grantRole(role_name, user_name);
2220  roles_granted.push_back(role_name);
2221  } else {
2222  LOG(WARNING) << "Error synchronizing roles for user " << user_name << ": role "
2223  << role_name << " does not exist";
2224  }
2225  }
2226  }
2227  if (roles_granted.empty() && roles_revoked.empty()) {
2228  LOG(INFO) << "Roles for user " << user_name
2229  << " are up to date with remote identity provider";
2230  } else {
2231  if (!roles_revoked.empty()) {
2232  LOG(INFO) << "Roles revoked during synchronization with identity provider for user "
2233  << user_name << ": " << join(roles_revoked, " ");
2234  }
2235  if (!roles_granted.empty()) {
2236  LOG(INFO) << "Roles granted during synchronization with identity provider for user "
2237  << user_name << ": " << join(roles_granted, " ");
2238  }
2239  }
2240 }
2241 
2242 std::unordered_map<std::string, std::vector<std::string>>
2243 SysCatalog::getGranteesOfSharedDashboards(const std::vector<std::string>& dashboard_ids) {
2244  sys_sqlite_lock sqlite_lock(this);
2245  std::unordered_map<std::string, std::vector<std::string>> active_grantees;
2246  sqliteConnector_->query("BEGIN TRANSACTION");
2247  try {
2248  for (auto dash : dashboard_ids) {
2249  std::vector<std::string> grantees = {};
2250  sqliteConnector_->query_with_text_params(
2251  "SELECT roleName FROM mapd_object_permissions WHERE objectPermissions NOT IN "
2252  "(0,1) AND objectPermissionsType = ? AND objectId = ?",
2253  std::vector<std::string>{
2254  std::to_string(static_cast<int32_t>(DashboardDBObjectType)), dash});
2255  int num_rows = sqliteConnector_->getNumRows();
2256  if (num_rows == 0) {
2257  // no grantees
2258  continue;
2259  } else {
2260  for (size_t i = 0; i < sqliteConnector_->getNumRows(); ++i) {
2261  grantees.push_back(sqliteConnector_->getData<string>(i, 0));
2262  }
2263  active_grantees[dash] = grantees;
2264  }
2265  }
2266  } catch (const std::exception& e) {
2267  sqliteConnector_->query("ROLLBACK TRANSACTION");
2268  throw;
2269  }
2270  sqliteConnector_->query("END TRANSACTION");
2271  return active_grantees;
2272 }
2273 
2274 } // namespace Catalog_Namespace
static const AccessPrivileges VIEW_SQL_EDITOR
Definition: DBObject.h:145
bool hasAnyPrivilegesOnDb(int32_t dbId, bool only_direct) const
Definition: Grantee.cpp:82
void revokeAllOnDatabase_unsafe(const std::string &roleName, int32_t dbId, Grantee *grantee)
std::unique_ptr< LdapServer > ldap_server_
Definition: SysCatalog.h:357
void revokeDBObjectPrivilegesBatch_unsafe(const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
std::unique_ptr< RestServer > rest_server_
Definition: SysCatalog.h:358
bool isDashboardSystemRole(const std::string &roleName)
void dropUser(const std::string &name)
Definition: SysCatalog.cpp:818
DBObjectKey getObjectKey() const
Definition: DBObject.h:197
auto duplicateAndRenameCatalog(std::string const &current_name, std::string const &new_name)
Definition: SysCatalog.cpp:90
const int8_t const int64_t * num_rows
class for a per-database catalog. also includes metadata for the current database and the current use...
Definition: Catalog.h:81
static const AccessPrivileges ALL_DATABASE
Definition: DBObject.h:144
DBObjectType
Definition: DBObject.h:42
void revokeDashboardSystemRole(const std::string roleName, const std::vector< std::string > grantees)
void updatePrivileges(const DBObject &object)
Definition: DBObject.cpp:128
static const AccessPrivileges ALL_TABLE_MIGRATE
Definition: DBObject.h:149
#define LOG(tag)
Definition: Logger.h:188
void dropRole(const std::string &roleName)
static std::shared_ptr< Catalog > get(const std::string &dbName)
Definition: Catalog.cpp:3135
bool checkPasswordForUser(const std::string &passwd, std::string &name, UserMetadata &user)
static const int32_t ALL
Definition: DBObject.h:78
void revokeDBObjectPrivileges_unsafe(const std::string &granteeName, DBObject object, const Catalog_Namespace::Catalog &catalog)
void revokeDBObjectPrivilegesFromAll(DBObject object, Catalog *catalog)
bool getMetadataForUser(const std::string &name, UserMetadata &user)
void revokeDBObjectPrivileges(const std::string &grantee, const DBObject &object, const Catalog_Namespace::Catalog &catalog)
std::string name() const
Definition: SysCatalog.h:263
std::string join(T const &container, std::string const &delim)
specifies the object_roles content in-memory of a row in mapd_object_permissions table ...
void setObjectKey(const DBObjectKey &objectKey)
Definition: DBObject.h:201
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:353
const std::string OMNISCI_SYSTEM_CATALOG
Definition: SysCatalog.h:58
Definition: Grantee.h:70
void createRole_unsafe(const std::string &roleName, const bool &userPrivateRole=false)
Grantee * getGrantee(const std::string &name) const
void dropDatabase(const DBMetadata &db)
void loginImpl(std::string &username, const std::string &password, UserMetadata &user_meta)
Definition: SysCatalog.cpp:728
int32_t objectId
Definition: DBObject.h:56
void createUser(const std::string &name, const std::string &passwd, bool issuper, const std::string &dbname, bool can_login)
Definition: SysCatalog.cpp:766
void setName(std::string name)
Definition: DBObject.h:194
Definition: Grantee.h:76
bool getMetadataForUserById(const int32_t idIn, UserMetadata &user)
void setPrivileges(const AccessPrivileges &privs)
Definition: DBObject.h:203
void insertOrUpdateObjectPrivileges(std::unique_ptr< SqliteConnector > &sqliteConnector, std::string roleName, bool userRole, DBObject &object)
Definition: SysCatalog.cpp:336
void 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)
Definition: SysCatalog.cpp:107
void createDBObject(const UserMetadata &user, const std::string &objectName, DBObjectType type, const Catalog_Namespace::Catalog &catalog, int32_t objectId=-1)
DBObject * findDbObject(const DBObjectKey &objectKey, bool only_direct) const
Definition: Grantee.cpp:72
std::string to_string(char const *&&v)
void grantRole_unsafe(const std::string &roleName, const std::string &granteeName)
void getDBObjectPrivileges(const std::string &granteeName, DBObject &object, const Catalog_Namespace::Catalog &catalog) const
void grantDBObjectPrivileges_unsafe(const std::string &granteeName, const DBObject object, const Catalog_Namespace::Catalog &catalog)
void alterUser(const int32_t userid, const std::string *passwd, bool *issuper, const std::string *dbname, bool *can_login)
Definition: SysCatalog.cpp:855
static const AccessPrivileges ALL_VIEW
Definition: DBObject.h:170
void grantRoleBatch(const std::vector< std::string > &roles, const std::vector< std::string > &grantees)
std::unique_ptr< PkiServer > pki_server_
Definition: SysCatalog.h:359
void revokeDBObjectPrivilegesBatch(const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
const AuthMetadata * authMetadata_
Definition: SysCatalog.h:360
void createRole(const std::string &roleName, const bool &userPrivateRole=false)
void grantRoleBatch_unsafe(const std::vector< std::string > &roles, const std::vector< std::string > &grantees)
This file contains the class specification and related data structures for Catalog.
bool checkPrivileges(const UserMetadata &user, const std::vector< DBObject > &privObjects) const
static DBObjectKey fromString(const std::vector< std::string > &key, const DBObjectType &type)
Definition: DBObject.cpp:228
static SysCatalog & instance()
Definition: SysCatalog.h:257
This file contains the class specification and related data structures for SysCatalog.
auto assembleCatalogName(std::string const &name)
Definition: SysCatalog.cpp:78
static bool parseUserMetadataFromSQLite(const std::unique_ptr< SqliteConnector > &conn, UserMetadata &user)
CHECK(cgen_state)
void setPermissionType(const DBObjectType &permissionType)
Definition: DBObject.cpp:136
void getMetadataWithDefaultDB(std::string &dbname, const std::string &username, Catalog_Namespace::DBMetadata &db_meta, UserMetadata &user_meta)
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:176
void grantAllOnDatabase_unsafe(const std::string &roleName, DBObject &object, const Catalog_Namespace::Catalog &catalog)
const std::string OMNISCI_DEFAULT_DB
Definition: SysCatalog.h:59
std::string generate_random_string(const size_t len)
virtual void revokeAllOnDatabase(int32_t dbId)
Definition: Grantee.cpp:279
std::string hash_with_bcrypt(const std::string &pwd)
Definition: SysCatalog.cpp:61
void renameObjectsInDescriptorMap(DBObject &object, const Catalog_Namespace::Catalog &cat)
bool checkPasswordForUserImpl(const std::string &passwd, std::string &name, UserMetadata &user)
std::shared_ptr< Catalog > login(std::string &db, std::string &username, const std::string &password, UserMetadata &user_meta, bool check_password=true)
Definition: SysCatalog.cpp:700
void revokeRoleBatch_unsafe(const std::vector< std::string > &roles, const std::vector< std::string > &grantees)
void revokeRoleBatch(const std::vector< std::string > &roles, const std::vector< std::string > &grantees)
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: SysCatalog.h:356
DBSummaryList getDatabaseListForUser(const UserMetadata &user)
static const int32_t MAPD_VERSION
Definition: release.h:33
static const AccessPrivileges ALL_DASHBOARD_MIGRATE
Definition: DBObject.h:161
std::shared_ptr< Catalog > switchDatabase(std::string &dbname, const std::string &username)
Definition: SysCatalog.cpp:736
Role * getRoleGrantee(const std::string &name) const
User * getUserGrantee(const std::string &name) const
void grantDBObjectPrivilegesBatch(const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
void grantDBObjectPrivileges(const std::string &grantee, const DBObject &object, const Catalog_Namespace::Catalog &catalog)
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:354
static const AccessPrivileges NONE
Definition: DBObject.h:141
void updateUserRoleName(const std::string &roleName, const std::string &newName)
Definition: SysCatalog.cpp:924
std::list< UserMetadata > getAllUserMetadata()
void deleteObjectPrivileges(std::unique_ptr< SqliteConnector > &sqliteConnector, std::string roleName, bool userRole, DBObject &object)
Definition: SysCatalog.cpp:317
void grantDBObjectPrivilegesBatch_unsafe(const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
static const std::string SYSTEM_ROLE_TAG("#dash_system_role")
specifies the content in-memory of a row in the dashboard
void execInTransaction(F &&f, Args &&...args)
std::string to_upper(const std::string &str)
void check_for_session_encryption(const std::string &pki_cert, std::string &session)
Definition: SysCatalog.cpp:758
void syncUserWithRemoteProvider(const std::string &user_name, std::vector< std::string > idp_roles, bool *issuper)
void renameUser(std::string const &old_name, std::string const &new_name)
Definition: SysCatalog.cpp:936
void revokeRole_unsafe(const std::string &roleName, const std::string &granteeName)
void loadKey()
Definition: DBObject.cpp:165
bool isRoleGrantedToGrantee(const std::string &granteeName, const std::string &roleName, bool only_direct) const
void setObjectType(const DBObjectType &objectType)
Definition: DBObject.cpp:139
bool hasAnyPrivileges(const UserMetadata &user, std::vector< DBObject > &privObjects)
void deleteObjectDescriptorMap(const std::string &roleName)
static void remove(const std::string &dbName)
Definition: Catalog.cpp:3161
void removeCatalogByName(std::string const &name)
Definition: SysCatalog.cpp:86
const std::string OMNISCI_ROOT_USER
Definition: SysCatalog.h:60
static const AccessPrivileges ALL_VIEW_MIGRATE
Definition: DBObject.h:169
const std::string OMNISCI_ROOT_PASSWD_DEFAULT
Definition: SysCatalog.h:63
void updateObjectDescriptorMap(const std::string &roleName, DBObject &object, bool roleType, const Catalog_Namespace::Catalog &cat)
void grantRole(const std::string &role, const std::string &grantee)
const int OMNISCI_ROOT_USER_ID
Definition: SysCatalog.h:61
std::list< DBMetadata > getAllDBMetadata()
void renameDatabase(std::string const &old_name, std::string const &new_name)
Definition: SysCatalog.cpp:969
int32_t dbId
Definition: DBObject.h:55
void revokeDBObjectPrivilegesFromAll_unsafe(DBObject object, Catalog *catalog)
static const AccessPrivileges ALL_DASHBOARD
Definition: DBObject.h:162
static const AccessPrivileges ACCESS
Definition: DBObject.h:146
bool verifyDBObjectOwnership(const UserMetadata &user, DBObject object, const Catalog_Namespace::Catalog &catalog)
static const AccessPrivileges ALL_TABLE
Definition: DBObject.h:150
const std::string OMNISCI_ROOT_USER_ID_STR
Definition: SysCatalog.h:62
std::vector< LeafHostInfo > string_dict_hosts_
Definition: SysCatalog.h:362
bool hasRole(Role *role, bool only_direct) const
Definition: Grantee.cpp:42
auto get_users(std::unique_ptr< SqliteConnector > &sqliteConnector, const int32_t dbId=-1)
std::shared_ptr< Calcite > calciteMgr_
Definition: SysCatalog.h:361
std::unordered_map< std::string, std::vector< std::string > > getGranteesOfSharedDashboards(const std::vector< std::string > &dashboard_ids)
std::list< DBSummary > DBSummaryList
Definition: SysCatalog.h:121
int32_t permissionType
Definition: DBObject.h:54
void populateRoleDbObjects(const std::vector< DBObject > &objects)
static thread_local bool thread_holds_read_lock
Definition: SysCatalog.h:371
void revokeRole(const std::string &role, const std::string &grantee)
int64_t privileges
Definition: DBObject.h:126
bool getMetadataForDBById(const int32_t idIn, DBMetadata &db)
void createDatabase(const std::string &dbname, int owner)
void removeCatalogByFullPath(std::string const &full_path)
Definition: SysCatalog.cpp:82
std::vector< ObjectRoleDescriptor * > getMetadataForObject(int32_t dbId, int32_t dbType, int32_t objectId) const
std::atomic< bool > isSuper
Definition: SysCatalog.h:97
bool getMetadataForDB(const std::string &name, DBMetadata &db)
void dropRole_unsafe(const std::string &roleName)
std::vector< std::string > getRoles(bool userPrivateRole, bool isSuper, const std::string &userName)