OmniSciDB  085a039ca4
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
Catalog_Namespace::SysCatalog Class Reference

#include <SysCatalog.h>

+ Inheritance diagram for Catalog_Namespace::SysCatalog:
+ Collaboration diagram for Catalog_Namespace::SysCatalog:

Public Member Functions

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)
 
std::shared_ptr< Cataloglogin (std::string &db, std::string &username, const std::string &password, UserMetadata &user_meta, bool check_password=true)
 
std::shared_ptr< CatalogswitchDatabase (std::string &dbname, const std::string &username)
 
UserMetadata createUser (std::string const &name, UserAlterations alts, bool is_temporary)
 
void dropUser (const std::string &name)
 
UserMetadata alterUser (std::string const &name, UserAlterations alts)
 
void renameUser (std::string const &old_name, std::string const &new_name)
 
void createDatabase (const std::string &dbname, int owner)
 
void renameDatabase (std::string const &old_name, std::string const &new_name)
 
void dropDatabase (const DBMetadata &db)
 
std::optional< UserMetadatagetUser (std::string const &uname)
 
std::optional< UserMetadatagetUser (int32_t const uid)
 
std::optional< DBMetadatagetDB (std::string const &dbname)
 
std::optional< DBMetadatagetDB (int32_t const dbid)
 
bool getMetadataForUser (const std::string &name, UserMetadata &user)
 
bool getMetadataForUserById (const int32_t idIn, UserMetadata &user)
 
bool checkPasswordForUser (const std::string &passwd, std::string &name, UserMetadata &user)
 
bool getMetadataForDB (const std::string &name, DBMetadata &db)
 
bool getMetadataForDBById (const int32_t idIn, DBMetadata &db)
 
Data_Namespace::DataMgrgetDataMgr () const
 
CalcitegetCalciteMgr () const
 
const std::string & getCatalogBasePath () const
 
SqliteConnectorgetSqliteConnector ()
 
std::list< DBMetadatagetAllDBMetadata ()
 
std::list< UserMetadatagetAllUserMetadata ()
 
std::list< UserMetadatagetAllUserMetadata (const int64_t dbId)
 
DBSummaryList getDatabaseListForUser (const UserMetadata &user)
 
void createDBObject (const UserMetadata &user, const std::string &objectName, DBObjectType type, const Catalog_Namespace::Catalog &catalog, int32_t objectId=-1)
 
void renameDBObject (const std::string &objectName, const std::string &newName, DBObjectType type, int32_t objectId, const Catalog_Namespace::Catalog &catalog)
 
void grantDBObjectPrivileges (const std::string &grantee, const DBObject &object, const Catalog_Namespace::Catalog &catalog)
 
void grantDBObjectPrivilegesBatch (const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
 
void revokeDBObjectPrivileges (const std::string &grantee, const DBObject &object, const Catalog_Namespace::Catalog &catalog)
 
void revokeDBObjectPrivilegesBatch (const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
 
void revokeDBObjectPrivilegesFromAll (DBObject object, Catalog *catalog)
 
void revokeDBObjectPrivilegesFromAll_unsafe (DBObject object, Catalog *catalog)
 
void revokeDBObjectPrivilegesFromAllBatch (std::vector< DBObject > &objects, Catalog *catalog)
 
void revokeDBObjectPrivilegesFromAllBatch_unsafe (std::vector< DBObject > &objects, Catalog *catalog)
 
void getDBObjectPrivileges (const std::string &granteeName, DBObject &object, const Catalog_Namespace::Catalog &catalog) const
 
bool verifyDBObjectOwnership (const UserMetadata &user, DBObject object, const Catalog_Namespace::Catalog &catalog)
 
void changeDBObjectOwnership (const UserMetadata &new_owner, const UserMetadata &previous_owner, DBObject object, const Catalog_Namespace::Catalog &catalog, bool revoke_privileges=true)
 
void createRole (const std::string &roleName, const bool user_private_role, const bool is_temporary=false)
 
void dropRole (const std::string &roleName, const bool is_temporary=false)
 
void grantRoleBatch (const std::vector< std::string > &roles, const std::vector< std::string > &grantees)
 
void grantRole (const std::string &role, const std::string &grantee, const bool is_temporary=false)
 
void revokeRoleBatch (const std::vector< std::string > &roles, const std::vector< std::string > &grantees)
 
void revokeRole (const std::string &role, const std::string &grantee, const bool is_temporary=false)
 
bool hasAnyPrivileges (const UserMetadata &user, std::vector< DBObject > &privObjects)
 
bool checkPrivileges (const UserMetadata &user, const std::vector< DBObject > &privObjects) const
 
bool checkPrivileges (const std::string &userName, const std::vector< DBObject > &privObjects) const
 
GranteegetGrantee (const std::string &name) const
 
RolegetRoleGrantee (const std::string &name) const
 
UsergetUserGrantee (const std::string &name) const
 
std::vector
< ObjectRoleDescriptor * > 
getMetadataForObject (int32_t dbId, int32_t dbType, int32_t objectId) const
 
std::vector< ObjectRoleDescriptorgetMetadataForAllObjects () const
 
bool isRoleGrantedToGrantee (const std::string &granteeName, const std::string &roleName, bool only_direct) const
 
std::vector< std::string > getRoles (const std::string &user_name, bool effective=true)
 
std::vector< std::string > getRoles (bool include_user_private_role, bool is_super, const std::string &user_name, bool ignore_deleted_user=false)
 
std::vector< std::string > getRoles (const std::string &userName, const int32_t dbId)
 
std::set< std::string > getCreatedRoles () const
 
bool isAggregator () const
 
void populateRoleDbObjects (const std::vector< DBObject > &objects)
 
std::string name () const
 
void renameObjectsInDescriptorMap (DBObject &object, const Catalog_Namespace::Catalog &cat)
 
void syncUserWithRemoteProvider (const std::string &user_name, std::vector< std::string > idp_roles, UserAlterations alts)
 
std::unordered_map
< std::string, std::vector
< std::string > > 
getGranteesOfSharedDashboards (const std::vector< std::string > &dashboard_ids)
 
void check_for_session_encryption (const std::string &pki_cert, std::string &session)
 
std::vector< Catalog * > getCatalogsForAllDbs ()
 
std::shared_ptr< CataloggetDummyCatalog ()
 
std::shared_ptr< CataloggetCatalog (const std::string &dbName)
 
std::shared_ptr< CataloggetCatalog (const int32_t db_id)
 
std::shared_ptr< CataloggetCatalog (const DBMetadata &curDB, bool is_new_db)
 
void removeCatalog (const std::string &dbName)
 
virtual ~SysCatalog ()
 
void reassignObjectOwners (const std::map< int32_t, std::vector< DBObject >> &old_owner_db_objects, int32_t new_owner_id, const Catalog_Namespace::Catalog &catalog)
 
bool hasExecutedMigration (const std::string &migration_name) const
 

Static Public Member Functions

static SysCataloginstance ()
 
static void destroy ()
 

Public Attributes

std::mutex sqliteMutex_
 
mapd_shared_mutex sharedMutex_
 
std::atomic< std::thread::id > thread_holding_sqlite_lock
 
std::atomic< std::thread::id > thread_holding_write_lock
 
std::shared_ptr< CatalogdummyCatalog_
 
std::unordered_map
< std::string, std::shared_ptr
< UserMetadata > > 
temporary_users_by_name_
 
std::unordered_map< int32_t,
std::shared_ptr< UserMetadata > > 
temporary_users_by_id_
 
int32_t next_temporary_user_id_ {shared::kTempUserIdRange}
 

Static Public Attributes

static thread_local bool thread_holds_read_lock = false
 

Private Types

using GranteeMap = std::map< std::string, std::unique_ptr< Grantee >>
 
using ObjectRoleDescriptorMap = std::multimap< std::string, std::unique_ptr< ObjectRoleDescriptor >>
 
using dbid_to_cat_map = tbb::concurrent_hash_map< std::string, std::shared_ptr< Catalog >>
 

Private Member Functions

 SysCatalog ()
 
void initDB ()
 
void buildRoleMap ()
 
void buildUserRoleMap ()
 
void buildObjectDescriptorMap ()
 
void rebuildObjectMaps ()
 
void checkAndExecuteMigrations ()
 
void importDataFromOldMapdDB ()
 
void createRoles ()
 
void fixRolesMigration ()
 
void addAdminUserRole ()
 
void migratePrivileges ()
 
void migratePrivileged_old ()
 
void updateUserSchema ()
 
void updatePasswordsToHashes ()
 
void updateBlankPasswordsToRandom ()
 
void updateSupportUserDeactivation ()
 
void migrateDBAccessPrivileges ()
 
void loginImpl (std::string &username, const std::string &password, UserMetadata &user_meta)
 
bool checkPasswordForUserImpl (const std::string &passwd, std::string &name, UserMetadata &user)
 
void grantDefaultPrivilegesToRole_unsafe (const std::string &name, bool issuper)
 
void createRole_unsafe (const std::string &roleName, const bool userPrivateRole, const bool is_temporary)
 
void dropRole_unsafe (const std::string &roleName, const bool is_temporary)
 
void grantRoleBatch_unsafe (const std::vector< std::string > &roles, const std::vector< std::string > &grantees)
 
void grantRole_unsafe (const std::string &roleName, const std::string &granteeName, const bool is_temporary)
 
void revokeRoleBatch_unsafe (const std::vector< std::string > &roles, const std::vector< std::string > &grantees)
 
void revokeRole_unsafe (const std::string &roleName, const std::string &granteeName, const bool is_temporary)
 
void updateObjectDescriptorMap (const std::string &roleName, DBObject &object, bool roleType, const Catalog_Namespace::Catalog &cat)
 
void deleteObjectDescriptorMap (const std::string &roleName)
 
void deleteObjectDescriptorMap (const std::string &roleName, DBObject &object, const Catalog_Namespace::Catalog &cat)
 
void grantDBObjectPrivilegesBatch_unsafe (const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
 
void grantDBObjectPrivileges_unsafe (const std::string &granteeName, const DBObject object, const Catalog_Namespace::Catalog &catalog)
 
void revokeDBObjectPrivilegesBatch_unsafe (const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
 
void revokeDBObjectPrivileges_unsafe (const std::string &granteeName, DBObject object, const Catalog_Namespace::Catalog &catalog)
 
void grantAllOnDatabase_unsafe (const std::string &roleName, DBObject &object, const Catalog_Namespace::Catalog &catalog)
 
void revokeAllOnDatabase_unsafe (const std::string &roleName, int32_t dbId, Grantee *grantee)
 
bool isDashboardSystemRole (const std::string &roleName) const
 
void updateUserRoleName (const std::string &roleName, const std::string &newName)
 
void getMetadataWithDefaultDB (std::string &dbname, const std::string &username, Catalog_Namespace::DBMetadata &db_meta, UserMetadata &user_meta)
 
bool allowLocalLogin () const
 
template<typename F , typename... Args>
void execInTransaction (F &&f, Args &&...args)
 
void initializeInformationSchemaDb ()
 
void recordExecutedMigration (const std::string &migration_name) const
 
bool hasVersionHistoryTable () const
 
void createVersionHistoryTable () const
 
auto yieldTransactionStreamer ()
 
- Private Member Functions inherited from Catalog_Namespace::CommonFileOperations
 CommonFileOperations (std::string const &base_path)
 
void removeCatalogByFullPath (std::string const &full_path)
 
void removeCatalogByName (std::string const &name)
 
auto duplicateAndRenameCatalog (std::string const &current_name, std::string const &new_name)
 
auto assembleCatalogName (std::string const &name)
 

Private Attributes

std::string basePath_
 
GranteeMap granteeMap_
 
ObjectRoleDescriptorMap objectDescriptorMap_
 
std::unique_ptr< SqliteConnectorsqliteConnector_
 
std::shared_ptr
< Data_Namespace::DataMgr
dataMgr_
 
std::unique_ptr< PkiServerpki_server_
 
const AuthMetadataauthMetadata_
 
std::shared_ptr< CalcitecalciteMgr_
 
std::vector< LeafHostInfostring_dict_hosts_
 
bool aggregator_
 
dbid_to_cat_map cat_map_
 

Static Private Attributes

static std::unique_ptr
< SysCatalog
instance_
 

Detailed Description

Definition at line 166 of file SysCatalog.h.

Member Typedef Documentation

using Catalog_Namespace::SysCatalog::dbid_to_cat_map = tbb::concurrent_hash_map<std::string, std::shared_ptr<Catalog>>
private

Definition at line 494 of file SysCatalog.h.

using Catalog_Namespace::SysCatalog::GranteeMap = std::map<std::string, std::unique_ptr<Grantee>>
private

Definition at line 385 of file SysCatalog.h.

using Catalog_Namespace::SysCatalog::ObjectRoleDescriptorMap = std::multimap<std::string, std::unique_ptr<ObjectRoleDescriptor>>
private

Definition at line 387 of file SysCatalog.h.

Constructor & Destructor Documentation

Catalog_Namespace::SysCatalog::~SysCatalog ( )
virtual

Definition at line 217 of file SysCatalog.cpp.

References cat_map_, granteeMap_, and objectDescriptorMap_.

217  {
219  granteeMap_.clear();
220  objectDescriptorMap_.clear();
221  cat_map_.clear();
222 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:480
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
mapd_unique_lock< mapd_shared_mutex > write_lock
Catalog_Namespace::SysCatalog::SysCatalog ( )
private

Definition at line 208 of file SysCatalog.cpp.

References basePath_.

Referenced by instance().

210  , aggregator_{false}
211  , sqliteMutex_{}
212  , sharedMutex_{}
213  , thread_holding_sqlite_lock{std::thread::id()}
214  , thread_holding_write_lock{std::thread::id()}
215  , dummyCatalog_{std::make_shared<Catalog>()} {}
std::atomic< std::thread::id > thread_holding_sqlite_lock
Definition: SysCatalog.h:502
mapd_shared_mutex sharedMutex_
Definition: SysCatalog.h:501
CommonFileOperations(std::string const &base_path)
Definition: SysCatalog.h:149
std::shared_ptr< Catalog > dummyCatalog_
Definition: SysCatalog.h:506
std::atomic< std::thread::id > thread_holding_write_lock
Definition: SysCatalog.h:503

+ Here is the caller graph for this function:

Member Function Documentation

void Catalog_Namespace::SysCatalog::addAdminUserRole ( )
private

Definition at line 562 of file SysCatalog.cpp.

References createRole_unsafe(), shared::kRootUsername, and sqliteConnector_.

Referenced by checkAndExecuteMigrations().

562  {
563  sys_sqlite_lock sqlite_lock(this);
564  sqliteConnector_->query("BEGIN TRANSACTION");
565  try {
566  sqliteConnector_->query(
567  "SELECT roleName FROM mapd_object_permissions WHERE roleName = \'" +
568  shared::kRootUsername + "\'");
569  if (sqliteConnector_->getNumRows() != 0) {
570  // already done
571  sqliteConnector_->query("END TRANSACTION");
572  return;
573  }
574 
576  shared::kRootUsername, /*userPrivateRole=*/true, /*is_temporary=*/false);
577  } catch (const std::exception&) {
578  sqliteConnector_->query("ROLLBACK TRANSACTION");
579  throw;
580  }
581  sqliteConnector_->query("END TRANSACTION");
582 }
void createRole_unsafe(const std::string &roleName, const bool userPrivateRole, const bool is_temporary)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
const std::string kRootUsername

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::allowLocalLogin ( ) const
private

For servers configured to use external authentication providers, determine whether users will be allowed to fallback to local login accounts. If no external providers are configured, returns true.

UserMetadata Catalog_Namespace::SysCatalog::alterUser ( std::string const &  name,
UserAlterations  alts 
)

Definition at line 1080 of file SysCatalog.cpp.

References Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::append_with_commas, Catalog_Namespace::UserMetadata::can_login, Catalog_Namespace::UserAlterations::can_login, CHECK, Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::UserAlterations::default_db, Catalog_Namespace::UserMetadata::defaultDbId, Catalog_Namespace::g_log_user_id, getMetadataForDB(), getMetadataForUser(), getUser(), anonymous_namespace{SysCatalog.cpp}::hash_with_bcrypt(), Catalog_Namespace::UserAlterations::is_super, Catalog_Namespace::UserMetadata::is_temporary, Catalog_Namespace::UserMetadata::isSuper, name(), Catalog_Namespace::UserAlterations::passwd, Catalog_Namespace::UserMetadata::passwd_hash, sqliteConnector_, temporary_users_by_name_, to_string(), Catalog_Namespace::UserMetadata::userId, VLOG, and Catalog_Namespace::UserAlterations::wouldChange().

Referenced by syncUserWithRemoteProvider().

1080  {
1081  sys_write_lock write_lock(this);
1082  sys_sqlite_lock sqlite_lock(this);
1083 
1084  UserMetadata user;
1085  if (!getMetadataForUser(name, user)) {
1086  std::string const loggable = g_log_user_id ? std::string("") : name + ' ';
1087  throw runtime_error("Cannot alter user. User " + loggable + "does not exist.");
1088  }
1089  if (!alts.wouldChange(user)) {
1090  return user;
1091  }
1092 
1093  // Temporary user.
1094  if (user.is_temporary) {
1095  if (alts.passwd) {
1096  user.passwd_hash = hash_with_bcrypt(*alts.passwd);
1097  }
1098  if (alts.is_super) {
1099  user.isSuper = *alts.is_super;
1100  }
1101  if (alts.default_db) {
1102  if (!alts.default_db->empty()) {
1103  DBMetadata db;
1104  if (!getMetadataForDB(*alts.default_db, db)) {
1105  throw runtime_error(string("DEFAULT_DB ") + *alts.default_db + " not found.");
1106  }
1107  user.defaultDbId = db.dbId;
1108  } else {
1109  user.defaultDbId = -1;
1110  }
1111  }
1112  if (alts.can_login) {
1113  user.can_login = *alts.can_login;
1114  }
1115  *temporary_users_by_name_[name] = user;
1116  return user;
1117  }
1118 
1119  // Normal user.
1120  sqliteConnector_->query("BEGIN TRANSACTION");
1121  try {
1122  string sql;
1123  std::vector<std::string> values;
1124  if (alts.passwd) {
1125  append_with_commas(sql, "passwd_hash = ?");
1126  values.push_back(hash_with_bcrypt(*alts.passwd));
1127  }
1128  if (alts.is_super) {
1129  append_with_commas(sql, "issuper = ?");
1130  values.push_back(std::to_string(*alts.is_super));
1131  }
1132  if (alts.default_db) {
1133  if (!alts.default_db->empty()) {
1134  append_with_commas(sql, "default_db = ?");
1135  DBMetadata db;
1136  if (!getMetadataForDB(*alts.default_db, db)) {
1137  throw runtime_error(string("DEFAULT_DB ") + *alts.default_db + " not found.");
1138  }
1139  values.push_back(std::to_string(db.dbId));
1140  } else {
1141  append_with_commas(sql, "default_db = NULL");
1142  }
1143  }
1144  if (alts.can_login) {
1145  append_with_commas(sql, "can_login = ?");
1146  values.push_back(std::to_string(*alts.can_login));
1147  }
1148 
1149  sql = "UPDATE mapd_users SET " + sql + " WHERE userid = ?";
1150  values.push_back(std::to_string(user.userId));
1151 
1152  sqliteConnector_->query_with_text_params(sql, values);
1153  } catch (const std::exception& e) {
1154  sqliteConnector_->query("ROLLBACK TRANSACTION");
1155  throw;
1156  }
1157  sqliteConnector_->query("END TRANSACTION");
1158  auto u = getUser(name);
1159  CHECK(u);
1160  VLOG(1) << "Altered user: " << u->userLoggable();
1161  return *u;
1162 }
std::optional< UserMetadata > getUser(std::string const &uname)
Definition: SysCatalog.h:197
bool getMetadataForUser(const std::string &name, UserMetadata &user)
std::string name() const
Definition: SysCatalog.h:347
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unordered_map< std::string, std::shared_ptr< UserMetadata > > temporary_users_by_name_
Definition: SysCatalog.h:507
std::string hash_with_bcrypt(const std::string &pwd)
Definition: SysCatalog.cpp:73
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
#define CHECK(condition)
Definition: Logger.h:223
mapd_unique_lock< mapd_shared_mutex > write_lock
#define VLOG(n)
Definition: Logger.h:317
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::buildObjectDescriptorMap ( )
private

Definition at line 2612 of file SysCatalog.cpp.

References objectDescriptorMap_, sqliteConnector_, and to_string().

Referenced by rebuildObjectMaps().

2612  {
2613  sys_write_lock write_lock(this);
2614  sys_sqlite_lock sqlite_lock(this);
2615  string objectQuery(
2616  "SELECT roleName, roleType, objectPermissionsType, dbId, objectId, "
2617  "objectPermissions, objectOwnerId, objectName "
2618  "from mapd_object_permissions");
2619  sqliteConnector_->query(objectQuery);
2620  size_t numRows = sqliteConnector_->getNumRows();
2621  for (size_t r = 0; r < numRows; ++r) {
2622  auto od = std::make_unique<ObjectRoleDescriptor>();
2623  od->roleName = sqliteConnector_->getData<string>(r, 0);
2624  od->roleType = sqliteConnector_->getData<bool>(r, 1);
2625  od->objectType = sqliteConnector_->getData<int>(r, 2);
2626  od->dbId = sqliteConnector_->getData<int>(r, 3);
2627  od->objectId = sqliteConnector_->getData<int>(r, 4);
2628  od->privs.privileges = sqliteConnector_->getData<int>(r, 5);
2629  od->objectOwnerId = sqliteConnector_->getData<int>(r, 6);
2630  od->objectName = sqliteConnector_->getData<string>(r, 7);
2631  objectDescriptorMap_.insert(ObjectRoleDescriptorMap::value_type(
2632  std::to_string(od->dbId) + ":" + std::to_string(od->objectType) + ":" +
2633  std::to_string(od->objectId),
2634  std::move(od)));
2635  }
2636 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:480
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::buildRoleMap ( )
private

Definition at line 2494 of file SysCatalog.cpp.

References DatabaseDBObjectType, DBObjectKey::fromString(), getGrantee(), granteeMap_, name(), AccessPrivileges::privileges, sqliteConnector_, and to_upper().

Referenced by rebuildObjectMaps().

2494  {
2495  sys_write_lock write_lock(this);
2496  sys_sqlite_lock sqlite_lock(this);
2497  string roleQuery(
2498  "SELECT roleName, roleType, objectPermissionsType, dbId, objectId, "
2499  "objectPermissions, objectOwnerId, objectName "
2500  "from mapd_object_permissions");
2501  sqliteConnector_->query(roleQuery);
2502  size_t numRows = sqliteConnector_->getNumRows();
2503  std::vector<std::string> objectKeyStr(4);
2504  DBObjectKey objectKey;
2505  AccessPrivileges privs;
2506  bool userPrivateRole{false};
2507  for (size_t r = 0; r < numRows; ++r) {
2508  std::string roleName = sqliteConnector_->getData<string>(r, 0);
2509  userPrivateRole = sqliteConnector_->getData<bool>(r, 1);
2510  DBObjectType permissionType =
2511  static_cast<DBObjectType>(sqliteConnector_->getData<int>(r, 2));
2512  objectKeyStr[0] = sqliteConnector_->getData<string>(r, 2);
2513  objectKeyStr[1] = sqliteConnector_->getData<string>(r, 3);
2514  objectKeyStr[2] = sqliteConnector_->getData<string>(r, 4);
2515  objectKey = DBObjectKey::fromString(objectKeyStr, permissionType);
2516  privs.privileges = sqliteConnector_->getData<int>(r, 5);
2517  int32_t owner = sqliteConnector_->getData<int>(r, 6);
2518  std::string name = sqliteConnector_->getData<string>(r, 7);
2519 
2520  DBObject dbObject(objectKey, privs, owner);
2521  dbObject.setName(name);
2522  if (-1 == objectKey.objectId) {
2523  dbObject.setObjectType(DBObjectType::DatabaseDBObjectType);
2524  } else {
2525  dbObject.setObjectType(permissionType);
2526  }
2527 
2528  auto* rl = getGrantee(roleName);
2529  if (!rl) {
2530  std::unique_ptr<Grantee> g;
2531  if (userPrivateRole) {
2532  g.reset(new User(roleName));
2533  } else {
2534  g.reset(new Role(roleName));
2535  }
2536  rl = g.get();
2537  granteeMap_[to_upper(roleName)] = std::move(g);
2538  }
2539  rl->grantPrivileges(dbObject);
2540  }
2541 }
DBObjectType
Definition: DBObject.h:42
std::string name() const
Definition: SysCatalog.h:347
Definition: Grantee.h:75
Grantee * getGrantee(const std::string &name) const
Definition: Grantee.h:81
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
static DBObjectKey fromString(const std::vector< std::string > &key, const DBObjectType &type)
Definition: DBObject.cpp:261
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
std::string to_upper(const std::string &str)
mapd_unique_lock< mapd_shared_mutex > write_lock
int64_t privileges
Definition: DBObject.h:135

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::buildUserRoleMap ( )
private

Definition at line 2566 of file SysCatalog.cpp.

References getGrantee(), shared::kRootUsername, and sqliteConnector_.

2566  {
2567  sys_write_lock write_lock(this);
2568  sys_sqlite_lock sqlite_lock(this);
2569  std::vector<std::pair<std::string, std::string>> granteeRoles;
2570  string userRoleQuery("SELECT roleName, userName from mapd_roles");
2571  sqliteConnector_->query(userRoleQuery);
2572  size_t numRows = sqliteConnector_->getNumRows();
2573  for (size_t r = 0; r < numRows; ++r) {
2574  std::string roleName = sqliteConnector_->getData<string>(r, 0);
2575  std::string userName = sqliteConnector_->getData<string>(r, 1);
2576  // required for declared nomenclature before v4.0.0
2577  if ((boost::equals(roleName, "mapd_default_suser_role") &&
2578  boost::equals(userName, shared::kRootUsername)) ||
2579  (boost::equals(roleName, "mapd_default_user_role") &&
2580  !boost::equals(userName, "mapd_default_user_role"))) {
2581  // grouprole already exists with roleName==userName in mapd_roles table
2582  // ignore duplicate instances of userRole which exists before v4.0.0
2583  continue;
2584  }
2585  auto* rl = getGrantee(roleName);
2586  if (!rl) {
2587  throw runtime_error("Data inconsistency when building role map. Role " + roleName +
2588  " from db not found in the map.");
2589  }
2590  std::pair<std::string, std::string> roleVecElem(roleName, userName);
2591  granteeRoles.push_back(roleVecElem);
2592  }
2593 
2594  for (const auto& [roleName, granteeName] : granteeRoles) {
2595  auto* grantee = getGrantee(granteeName);
2596  if (!grantee) {
2597  throw runtime_error("Data inconsistency when building role map. Grantee " +
2598  granteeName + " not found in the map.");
2599  }
2600  if (granteeName == roleName) {
2601  continue;
2602  }
2603  Role* rl = dynamic_cast<Role*>(getGrantee(roleName));
2604  if (!rl) {
2605  throw runtime_error("Data inconsistency when building role map. Role " + roleName +
2606  " not found in the map.");
2607  }
2608  grantee->grantRole(rl);
2609  }
2610 }
Grantee * getGrantee(const std::string &name) const
Definition: Grantee.h:81
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
const std::string kRootUsername
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::changeDBObjectOwnership ( const UserMetadata new_owner,
const UserMetadata previous_owner,
DBObject  object,
const Catalog_Namespace::Catalog catalog,
bool  revoke_privileges = true 
)

Change ownership of a DBObject

Parameters
new_owner- new owner of DBObject
previous_owner- previous owner of DBObject
object- DBObject to change ownership of
catalog- Catalog instance object exists in
revoke_privileges- if true, revoke previous_owner's privileges

Definition at line 1979 of file SysCatalog.cpp.

References AccessPrivileges::ALL_DASHBOARD, AccessPrivileges::ALL_DATABASE, AccessPrivileges::ALL_SERVER, AccessPrivileges::ALL_TABLE, AccessPrivileges::ALL_VIEW, DashboardDBObjectType, DatabaseDBObjectType, grantDBObjectPrivileges_unsafe(), granteeMap_, Catalog_Namespace::UserMetadata::is_temporary, Catalog_Namespace::UserMetadata::isSuper, objectDescriptorMap_, rebuildObjectMaps(), revokeDBObjectPrivileges_unsafe(), ServerDBObjectType, sqliteConnector_, TableDBObjectType, to_string(), UNREACHABLE, Catalog_Namespace::UserMetadata::userId, Catalog_Namespace::UserMetadata::userName, and ViewDBObjectType.

1983  {
1984  sys_write_lock write_lock(this);
1985  if (new_owner.is_temporary || previous_owner.is_temporary) {
1986  throw std::runtime_error("ownership change not allowed for temporary user(s)");
1987  }
1988  sys_sqlite_lock sqlite_lock(this);
1989  object.loadKey(catalog);
1990  switch (object.getType()) {
1991  case TableDBObjectType:
1992  object.setPrivileges(AccessPrivileges::ALL_TABLE);
1993  break;
1994  case DashboardDBObjectType:
1995  object.setPrivileges(AccessPrivileges::ALL_DASHBOARD);
1996  break;
1997  case ServerDBObjectType:
1998  object.setPrivileges(AccessPrivileges::ALL_SERVER);
1999  break;
2000  case DatabaseDBObjectType:
2001  object.setPrivileges(AccessPrivileges::ALL_DATABASE);
2002  break;
2003  case ViewDBObjectType:
2004  object.setPrivileges(AccessPrivileges::ALL_VIEW);
2005  break;
2006  default:
2007  UNREACHABLE(); // unkown object type
2008  break;
2009  }
2010  sqliteConnector_->query("BEGIN TRANSACTION");
2011  try {
2012  if (!new_owner.isSuper) { // no need to grant to suser, has all privs by default
2013  grantDBObjectPrivileges_unsafe(new_owner.userName, object, catalog);
2014  }
2015  if (!previous_owner.isSuper && revoke_privileges) { // no need to revoke from suser
2016  revokeDBObjectPrivileges_unsafe(previous_owner.userName, object, catalog);
2017  }
2018  auto object_key = object.getObjectKey();
2019  sqliteConnector_->query_with_text_params(
2020  "UPDATE mapd_object_permissions SET objectOwnerId = ? WHERE dbId = ? AND "
2021  "objectId = ? AND objectPermissionsType = ?",
2022  std::vector<std::string>{std::to_string(new_owner.userId),
2023  std::to_string(object_key.dbId),
2024  std::to_string(object_key.objectId),
2025  std::to_string(object_key.permissionType)});
2026 
2027  for (const auto& [user_or_role, grantee] : granteeMap_) {
2028  grantee->reassignObjectOwner(object_key, new_owner.userId);
2029  }
2030 
2031  for (const auto& [map_object_key, map_object_descriptor] : objectDescriptorMap_) {
2032  if (map_object_descriptor->objectId == object_key.objectId &&
2033  map_object_descriptor->objectType == object_key.permissionType &&
2034  map_object_descriptor->dbId == object_key.dbId) {
2035  map_object_descriptor->objectOwnerId = new_owner.userId;
2036  }
2037  }
2038  } catch (std::exception& e) {
2039  sqliteConnector_->query("ROLLBACK TRANSACTION");
2041  throw;
2042  }
2043  sqliteConnector_->query("END TRANSACTION");
2044 }
static const AccessPrivileges ALL_DATABASE
Definition: DBObject.h:153
void revokeDBObjectPrivileges_unsafe(const std::string &granteeName, DBObject object, const Catalog_Namespace::Catalog &catalog)
#define UNREACHABLE()
Definition: Logger.h:267
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:480
std::string to_string(char const *&&v)
void grantDBObjectPrivileges_unsafe(const std::string &granteeName, const DBObject object, const Catalog_Namespace::Catalog &catalog)
static const AccessPrivileges ALL_VIEW
Definition: DBObject.h:179
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
static const AccessPrivileges ALL_SERVER
Definition: DBObject.h:189
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
static const AccessPrivileges ALL_DASHBOARD
Definition: DBObject.h:171
static const AccessPrivileges ALL_TABLE
Definition: DBObject.h:159
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::check_for_session_encryption ( const std::string &  pki_cert,
std::string &  session 
)

Definition at line 861 of file SysCatalog.cpp.

References pki_server_.

862  {
863  if (!pki_server_->inUse()) {
864  return;
865  }
866  pki_server_->encrypt_session(pki_cert, session);
867 }
std::unique_ptr< PkiServer > pki_server_
Definition: SysCatalog.h:484
void Catalog_Namespace::SysCatalog::checkAndExecuteMigrations ( )
private

Definition at line 264 of file SysCatalog.cpp.

References addAdminUserRole(), createRoles(), fixRolesMigration(), migrateDBAccessPrivileges(), migratePrivileged_old(), migratePrivileges(), updateBlankPasswordsToRandom(), updatePasswordsToHashes(), updateSupportUserDeactivation(), and updateUserSchema().

264  {
266  createRoles();
270  updateUserSchema(); // must come before updatePasswordsToHashes()
272  updateBlankPasswordsToRandom(); // must come after updatePasswordsToHashes()
275 }

+ Here is the call graph for this function:

bool Catalog_Namespace::SysCatalog::checkPasswordForUser ( const std::string &  passwd,
std::string &  name,
UserMetadata user 
)

Definition at line 1465 of file SysCatalog.cpp.

References checkPasswordForUserImpl().

Referenced by loginImpl().

1467  {
1468  return checkPasswordForUserImpl(passwd, name, user);
1469 }
std::string name() const
Definition: SysCatalog.h:347
bool checkPasswordForUserImpl(const std::string &passwd, std::string &name, UserMetadata &user)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::checkPasswordForUserImpl ( const std::string &  passwd,
std::string &  name,
UserMetadata user 
)
private

Definition at line 1471 of file SysCatalog.cpp.

References CHECK, getMetadataForUser(), LOG, Catalog_Namespace::UserMetadata::passwd_hash, and logger::WARNING.

Referenced by checkPasswordForUser().

1473  {
1474  sys_read_lock read_lock(this);
1475  if (!getMetadataForUser(name, user)) {
1476  // Check password against some fake hash just to waste time so that response times
1477  // for invalid password and invalid user are similar and a caller can't say the
1478  // difference
1479  char fake_hash[BCRYPT_HASHSIZE];
1480  CHECK(bcrypt_gensalt(-1, fake_hash) == 0);
1481  bcrypt_checkpw(passwd.c_str(), fake_hash);
1482  LOG(WARNING) << "Local login failed";
1483  return false;
1484  }
1485  int pwd_check_result = bcrypt_checkpw(passwd.c_str(), user.passwd_hash.c_str());
1486  // if the check fails there is a good chance that data on disc is broken
1487  CHECK(pwd_check_result >= 0);
1488  return pwd_check_result == 0;
1489 }
#define LOG(tag)
Definition: Logger.h:217
bool getMetadataForUser(const std::string &name, UserMetadata &user)
std::string name() const
Definition: SysCatalog.h:347
mapd_shared_lock< mapd_shared_mutex > read_lock
#define CHECK(condition)
Definition: Logger.h:223
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:120

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::checkPrivileges ( const UserMetadata user,
const std::vector< DBObject > &  privObjects 
) const

Definition at line 2322 of file SysCatalog.cpp.

References getUserGrantee(), instance(), Catalog_Namespace::UserMetadata::isSuper, Catalog_Namespace::UserMetadata::userLoggable(), and Catalog_Namespace::UserMetadata::userName.

Referenced by Catalog_Namespace::SessionInfo::checkDBAccessPrivileges(), checkPrivileges(), getDatabaseListForUser(), and switchDatabase().

2323  {
2324  sys_read_lock read_lock(this);
2325  if (user.isSuper) {
2326  return true;
2327  }
2328 
2329  auto* user_rl = instance().getUserGrantee(user.userName);
2330  if (!user_rl) {
2331  throw runtime_error("Cannot check privileges. User " + user.userLoggable() +
2332  " does not exist.");
2333  }
2334  for (auto& object : privObjects) {
2335  if (!user_rl->checkPrivileges(object)) {
2336  return false;
2337  }
2338  }
2339  return true;
2340 }
static SysCatalog & instance()
Definition: SysCatalog.h:337
User * getUserGrantee(const std::string &name) const
mapd_shared_lock< mapd_shared_mutex > read_lock
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:120

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::checkPrivileges ( const std::string &  userName,
const std::vector< DBObject > &  privObjects 
) const

Definition at line 2342 of file SysCatalog.cpp.

References checkPrivileges(), Catalog_Namespace::g_log_user_id, getMetadataForUser(), and instance().

2343  {
2344  UserMetadata user;
2345  if (!instance().getMetadataForUser(userName, user)) {
2346  std::string const loggable = g_log_user_id ? std::string("") : userName + ' ';
2347  throw runtime_error("Request to check privileges for user " + loggable +
2348  "failed because user with this name does not exist.");
2349  }
2350  return (checkPrivileges(user, privObjects));
2351 }
bool getMetadataForUser(const std::string &name, UserMetadata &user)
bool checkPrivileges(const UserMetadata &user, const std::vector< DBObject > &privObjects) const
static SysCatalog & instance()
Definition: SysCatalog.h:337

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::createDatabase ( const std::string &  dbname,
int  owner 
)

Definition at line 1299 of file SysCatalog.cpp.

References basePath_, cat(), CHECK, DatabaseDBObjectType, g_enable_fsi, getCatalog(), Catalog_Namespace::Catalog::getCustomExpressionsSchema(), Catalog_Namespace::Catalog::getForeignServerSchema(), Catalog_Namespace::Catalog::getForeignTableSchema(), getMetadataForDB(), getMetadataForUserById(), grantAllOnDatabase_unsafe(), shared::kCatalogDirectoryName, shared::kRootUserId, shared::kSystemCatalogName, removeCatalog(), sqliteConnector_, to_string(), to_upper(), and Catalog_Namespace::UserMetadata::userName.

Referenced by initDB(), and initializeInformationSchemaDb().

1299  {
1300  sys_write_lock write_lock(this);
1301  sys_sqlite_lock sqlite_lock(this);
1302 
1303  DBMetadata db;
1304  if (getMetadataForDB(name, db)) {
1305  throw runtime_error("Database " + name + " already exists.");
1306  }
1308  throw runtime_error("Database name " + name + " is reserved.");
1309  }
1310 
1311  std::unique_ptr<SqliteConnector> dbConn(
1313  // NOTE(max): it's okay to run this in a separate transaction. If we fail later
1314  // we delete the database anyways.
1315  // If we run it in the same transaction as SysCatalog functions, then Catalog
1316  // constructor won't find the tables we have just created.
1317  dbConn->query("BEGIN TRANSACTION");
1318  try {
1319  dbConn->query(
1320  "CREATE TABLE mapd_tables (tableid integer primary key, name text unique, userid "
1321  "integer, ncolumns integer, "
1322  "isview boolean, "
1323  "fragments text, frag_type integer, max_frag_rows integer, max_chunk_size "
1324  "bigint, "
1325  "frag_page_size integer, "
1326  "max_rows bigint, partitions text, shard_column_id integer, shard integer, "
1327  "sort_column_id integer default 0, storage_type text default '', "
1328  "max_rollback_epochs integer default -1, "
1329  "is_system_table boolean default 0, "
1330  "num_shards integer, key_metainfo TEXT, version_num "
1331  "BIGINT DEFAULT 1) ");
1332  dbConn->query(
1333  "CREATE TABLE mapd_columns (tableid integer references mapd_tables, columnid "
1334  "integer, name text, coltype "
1335  "integer, colsubtype integer, coldim integer, colscale integer, is_notnull "
1336  "boolean, compression integer, "
1337  "comp_param integer, size integer, chunks text, is_systemcol boolean, "
1338  "is_virtualcol boolean, virtual_expr "
1339  "text, is_deletedcol boolean, version_num BIGINT, default_value text, "
1340  "primary key(tableid, columnid), unique(tableid, name))");
1341  dbConn->query(
1342  "CREATE TABLE mapd_views (tableid integer references mapd_tables, sql text)");
1343  dbConn->query(
1344  "CREATE TABLE mapd_dashboards (id integer primary key autoincrement, name text , "
1345  "userid integer references mapd_users, state text, image_hash text, update_time "
1346  "timestamp, "
1347  "metadata text, UNIQUE(userid, name) )");
1348  dbConn->query(
1349  "CREATE TABLE mapd_links (linkid integer primary key, userid integer references "
1350  "mapd_users, "
1351  "link text unique, view_state text, update_time timestamp, view_metadata text)");
1352  dbConn->query(
1353  "CREATE TABLE mapd_dictionaries (dictid integer primary key, name text unique, "
1354  "nbits int, is_shared boolean, "
1355  "refcount int, version_num BIGINT DEFAULT 1)");
1356  dbConn->query(
1357  "CREATE TABLE mapd_logical_to_physical(logical_table_id integer, "
1358  "physical_table_id "
1359  "integer)");
1360  dbConn->query("CREATE TABLE mapd_record_ownership_marker (dummy integer)");
1361  dbConn->query_with_text_params(
1362  "INSERT INTO mapd_record_ownership_marker (dummy) VALUES (?1)",
1363  std::vector<std::string>{std::to_string(owner)});
1364 
1365  if (g_enable_fsi) {
1366  dbConn->query(Catalog::getForeignServerSchema());
1367  dbConn->query(Catalog::getForeignTableSchema());
1368  }
1369  dbConn->query(Catalog::getCustomExpressionsSchema());
1370  } catch (const std::exception&) {
1371  dbConn->query("ROLLBACK TRANSACTION");
1372  boost::filesystem::remove(basePath_ + "/" + shared::kCatalogDirectoryName + "/" +
1373  name);
1374  throw;
1375  }
1376  dbConn->query("END TRANSACTION");
1377 
1378  std::shared_ptr<Catalog> cat;
1379  // Now update SysCatalog with privileges and the new database
1380  sqliteConnector_->query("BEGIN TRANSACTION");
1381  try {
1382  sqliteConnector_->query_with_text_param(
1383  "INSERT INTO mapd_databases (name, owner) VALUES (?, " + std::to_string(owner) +
1384  ")",
1385  name);
1386  CHECK(getMetadataForDB(name, db));
1387 
1388  cat = getCatalog(db, true);
1389 
1390  if (owner != shared::kRootUserId) {
1392  object.loadKey(*cat);
1393  UserMetadata user;
1394  CHECK(getMetadataForUserById(owner, user));
1395  grantAllOnDatabase_unsafe(user.userName, object, *cat);
1396  }
1397  } catch (const std::exception&) {
1398  sqliteConnector_->query("ROLLBACK TRANSACTION");
1399  boost::filesystem::remove(basePath_ + "/" + shared::kCatalogDirectoryName + "/" +
1400  name);
1401  throw;
1402  }
1403  sqliteConnector_->query("END TRANSACTION");
1404 
1405  // force a migration on the new database
1407  cat = getCatalog(db, false);
1408 
1409  if (g_enable_fsi) {
1410  try {
1411  cat->createDefaultServersIfNotExists();
1412  } catch (...) {
1413  boost::filesystem::remove(basePath_ + "/" + shared::kCatalogDirectoryName + "/" +
1414  name);
1415  throw;
1416  }
1417  }
1418 }
const int kRootUserId
std::string cat(Ts &&...args)
void removeCatalog(const std::string &dbName)
std::string name() const
Definition: SysCatalog.h:347
const std::string kSystemCatalogName
bool getMetadataForUserById(const int32_t idIn, UserMetadata &user)
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
void grantAllOnDatabase_unsafe(const std::string &roleName, DBObject &object, const Catalog_Namespace::Catalog &catalog)
static const std::string getForeignTableSchema(bool if_not_exists=false)
Definition: Catalog.cpp:763
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
static const std::string getForeignServerSchema(bool if_not_exists=false)
Definition: Catalog.cpp:756
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
std::string to_upper(const std::string &str)
std::shared_ptr< Catalog > getCatalog(const std::string &dbName)
static const std::string getCustomExpressionsSchema(bool if_not_exists=false)
Definition: Catalog.cpp:771
const std::string kCatalogDirectoryName
#define CHECK(condition)
Definition: Logger.h:223
mapd_unique_lock< mapd_shared_mutex > write_lock
bool g_enable_fsi
Definition: Catalog.cpp:97
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::createDBObject ( const UserMetadata user,
const std::string &  objectName,
DBObjectType  type,
const Catalog_Namespace::Catalog catalog,
int32_t  objectId = -1 
)

Definition at line 1708 of file SysCatalog.cpp.

References AccessPrivileges::ALL_DASHBOARD, AccessPrivileges::ALL_DATABASE, AccessPrivileges::ALL_SERVER, AccessPrivileges::ALL_TABLE, DashboardDBObjectType, getUserGrantee(), grantDBObjectPrivileges_unsafe(), Grantee::grantPrivileges(), instance(), Catalog_Namespace::UserMetadata::isSuper, ServerDBObjectType, sqliteConnector_, TableDBObjectType, Catalog_Namespace::UserMetadata::userId, Catalog_Namespace::UserMetadata::userLoggable(), and Catalog_Namespace::UserMetadata::userName.

Referenced by CreateForeignServerCommand::execute(), CreateForeignTableCommand::execute(), and EmbeddedDatabase::DBEngineImpl::importArrowTable().

1712  {
1713  sys_write_lock write_lock(this);
1714  sys_sqlite_lock sqlite_lock(this);
1715 
1716  DBObject object =
1717  objectId == -1 ? DBObject(objectName, type) : DBObject(objectId, type);
1718  object.loadKey(catalog);
1719  switch (type) {
1720  case TableDBObjectType:
1721  object.setPrivileges(AccessPrivileges::ALL_TABLE);
1722  break;
1723  case DashboardDBObjectType:
1724  object.setPrivileges(AccessPrivileges::ALL_DASHBOARD);
1725  break;
1726  case ServerDBObjectType:
1727  object.setPrivileges(AccessPrivileges::ALL_SERVER);
1728  break;
1729  default:
1730  object.setPrivileges(AccessPrivileges::ALL_DATABASE);
1731  break;
1732  }
1733  object.setOwner(user.userId);
1734  sqliteConnector_->query("BEGIN TRANSACTION");
1735  try {
1736  if (!user.isSuper) { // no need to grant to suser, has all privs by default
1737  grantDBObjectPrivileges_unsafe(user.userName, object, catalog);
1738  auto* grantee = instance().getUserGrantee(user.userName);
1739  if (!grantee) {
1740  throw runtime_error("Cannot create DBObject. User " + user.userLoggable() +
1741  " does not exist.");
1742  }
1743  grantee->grantPrivileges(object);
1744  }
1745  } catch (std::exception& e) {
1746  sqliteConnector_->query("ROLLBACK TRANSACTION");
1747  throw;
1748  }
1749  sqliteConnector_->query("END TRANSACTION");
1750 }
static const AccessPrivileges ALL_DATABASE
Definition: DBObject.h:153
virtual void grantPrivileges(const DBObject &object)
Definition: Grantee.cpp:105
void grantDBObjectPrivileges_unsafe(const std::string &granteeName, const DBObject object, const Catalog_Namespace::Catalog &catalog)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
static SysCatalog & instance()
Definition: SysCatalog.h:337
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
static const AccessPrivileges ALL_SERVER
Definition: DBObject.h:189
User * getUserGrantee(const std::string &name) const
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
void loadKey()
Definition: DBObject.cpp:181
static const AccessPrivileges ALL_DASHBOARD
Definition: DBObject.h:171
static const AccessPrivileges ALL_TABLE
Definition: DBObject.h:159
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::createRole ( const std::string &  roleName,
const bool  user_private_role,
const bool  is_temporary = false 
)

Definition at line 2652 of file SysCatalog.cpp.

References createRole_unsafe(), and execInTransaction().

Referenced by Catalog_Namespace::Catalog::createOrUpdateDashboardSystemRole().

2654  {
2656  &SysCatalog::createRole_unsafe, roleName, user_private_role, is_temporary);
2657 }
void createRole_unsafe(const std::string &roleName, const bool userPrivateRole, const bool is_temporary)
void execInTransaction(F &&f, Args &&...args)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::createRole_unsafe ( const std::string &  roleName,
const bool  userPrivateRole,
const bool  is_temporary 
)
private

Definition at line 2068 of file SysCatalog.cpp.

References DatabaseDBObjectType, DBObjectKey::dbId, getGrantee(), granteeMap_, Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::insertOrUpdateObjectPrivileges(), shared::kDefaultDbName, DBObjectKey::permissionType, DBObject::setObjectKey(), sqliteConnector_, and to_upper().

Referenced by addAdminUserRole(), createRole(), createUser(), and initDB().

2070  {
2071  sys_write_lock write_lock(this);
2072 
2073  auto* grantee = getGrantee(roleName);
2074  if (grantee) {
2075  throw std::runtime_error("CREATE ROLE " + roleName +
2076  " failed because grantee with this name already exists.");
2077  }
2078  std::unique_ptr<Grantee> g;
2079  if (user_private_role) {
2080  g.reset(new User(roleName));
2081  } else {
2082  g.reset(new Role(roleName));
2083  }
2084  grantee = g.get();
2085  granteeMap_[to_upper(roleName)] = std::move(g);
2086 
2087  // NOTE (max): Why create an empty privileges record for a role?
2088  /* grant none privileges to this role and add it to sqlite DB */
2090  DBObjectKey objKey;
2091  // 0 is an id that does not exist
2092  objKey.dbId = 0;
2094  dbObject.setObjectKey(objKey);
2095  grantee->grantPrivileges(dbObject);
2096 
2097  if (!is_temporary) {
2098  sys_sqlite_lock sqlite_lock(this);
2100  sqliteConnector_, roleName, user_private_role, dbObject);
2101  }
2102 }
Definition: Grantee.h:75
Grantee * getGrantee(const std::string &name) const
Definition: Grantee.h:81
void insertOrUpdateObjectPrivileges(std::unique_ptr< SqliteConnector > &sqliteConnector, std::string roleName, bool userRole, const DBObject &object)
Definition: SysCatalog.cpp:419
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
const std::string kDefaultDbName
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
std::string to_upper(const std::string &str)
int32_t dbId
Definition: DBObject.h:56
int32_t permissionType
Definition: DBObject.h:55
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::createRoles ( )
private

Definition at line 350 of file SysCatalog.cpp.

References sqliteConnector_.

Referenced by checkAndExecuteMigrations().

350  {
351  sys_sqlite_lock sqlite_lock(this);
352  sqliteConnector_->query("BEGIN TRANSACTION");
353  try {
354  sqliteConnector_->query(
355  "SELECT name FROM sqlite_master WHERE type='table' AND name='mapd_roles'");
356  if (sqliteConnector_->getNumRows() != 0) {
357  // already done
358  sqliteConnector_->query("END TRANSACTION");
359  return;
360  }
361  sqliteConnector_->query(
362  "CREATE TABLE mapd_roles(roleName text, userName text, UNIQUE(roleName, "
363  "userName))");
364  } catch (const std::exception&) {
365  sqliteConnector_->query("ROLLBACK TRANSACTION");
366  throw;
367  }
368  sqliteConnector_->query("END TRANSACTION");
369 }
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481

+ Here is the caller graph for this function:

UserMetadata Catalog_Namespace::SysCatalog::createUser ( std::string const &  name,
UserAlterations  alts,
bool  is_temporary 
)

Definition at line 869 of file SysCatalog.cpp.

References Catalog_Namespace::UserAlterations::can_login, CHECK, createRole_unsafe(), Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::UserAlterations::default_db, Catalog_Namespace::g_log_user_id, g_read_only, getGrantee(), getMetadataForDB(), getMetadataForUser(), getUser(), anonymous_namespace{SysCatalog.cpp}::hash_with_bcrypt(), Catalog_Namespace::UserAlterations::is_super, name(), next_temporary_user_id_, Catalog_Namespace::UserAlterations::passwd, sqliteConnector_, temporary_users_by_id_, temporary_users_by_name_, to_string(), Catalog_Namespace::UserMetadata::userLoggable(), and VLOG.

Referenced by syncUserWithRemoteProvider().

871  {
873  sys_sqlite_lock sqlite_lock(this);
874 
875  if (!alts.passwd) {
876  alts.passwd = "";
877  }
878  if (!alts.is_super) {
879  alts.is_super = false;
880  }
881  if (!alts.default_db) {
882  alts.default_db = "";
883  }
884  if (!alts.can_login) {
885  alts.can_login = true;
886  }
887 
888  UserMetadata user;
889  if (getMetadataForUser(name, user)) {
890  throw runtime_error("User " + user.userLoggable() + " already exists.");
891  }
892  if (getGrantee(name)) {
893  std::string const loggable = g_log_user_id ? std::string("") : name + ' ';
894  throw runtime_error(
895  "User " + loggable +
896  "is same as one of existing grantees. User and role names should be unique.");
897  }
898  DBMetadata db;
899  if (!alts.default_db->empty()) {
900  if (!getMetadataForDB(*alts.default_db, db)) {
901  throw runtime_error("DEFAULT_DB " + *alts.default_db + " not found.");
902  }
903  }
904 
905  // Temporary user.
906  if (is_temporary) {
907  if (!g_read_only) {
908  throw std::runtime_error("Temporary users require read-only mode.");
909  // NOTE(sy): We can remove this restriction when we're confident that
910  // nothing permanent can depend on a temporary user.
911  }
912  auto user2 = std::make_shared<UserMetadata>(next_temporary_user_id_++,
913  name,
914  hash_with_bcrypt(*alts.passwd),
915  *alts.is_super,
916  !alts.default_db->empty() ? db.dbId : -1,
917  *alts.can_login,
918  true);
920  temporary_users_by_id_[user2->userId] = user2;
921  createRole_unsafe(name, /*userPrivateRole=*/true, /*is_temporary=*/true);
922  VLOG(1) << "Created temporary user: " << user2->userLoggable();
923  return *user2;
924  }
925 
926  // Normal user.
927  sqliteConnector_->query("BEGIN TRANSACTION");
928  try {
929  std::vector<std::string> vals;
930  if (!alts.default_db->empty()) {
931  vals = {name,
932  hash_with_bcrypt(*alts.passwd),
933  std::to_string(*alts.is_super),
934  std::to_string(db.dbId),
935  std::to_string(*alts.can_login)};
936  sqliteConnector_->query_with_text_params(
937  "INSERT INTO mapd_users (name, passwd_hash, issuper, default_db, can_login) "
938  "VALUES (?, ?, ?, ?, ?)",
939  vals);
940  } else {
941  vals = {name,
942  hash_with_bcrypt(*alts.passwd),
943  std::to_string(*alts.is_super),
944  std::to_string(*alts.can_login)};
945  sqliteConnector_->query_with_text_params(
946  "INSERT INTO mapd_users (name, passwd_hash, issuper, can_login) "
947  "VALUES (?, ?, ?, ?)",
948  vals);
949  }
950  createRole_unsafe(name, /*userPrivateRole=*/true, /*is_temporary=*/false);
951  } catch (const std::exception& e) {
952  sqliteConnector_->query("ROLLBACK TRANSACTION");
953  throw;
954  }
955  sqliteConnector_->query("END TRANSACTION");
956  auto u = getUser(name);
957  CHECK(u);
958  VLOG(1) << "Created user: " << u->userLoggable();
959  return *u;
960 }
std::optional< UserMetadata > getUser(std::string const &uname)
Definition: SysCatalog.h:197
void createRole_unsafe(const std::string &roleName, const bool userPrivateRole, const bool is_temporary)
bool getMetadataForUser(const std::string &name, UserMetadata &user)
std::string name() const
Definition: SysCatalog.h:347
Grantee * getGrantee(const std::string &name) const
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unordered_map< std::string, std::shared_ptr< UserMetadata > > temporary_users_by_name_
Definition: SysCatalog.h:507
std::string hash_with_bcrypt(const std::string &pwd)
Definition: SysCatalog.cpp:73
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
bool g_read_only
Definition: File.cpp:40
std::unordered_map< int32_t, std::shared_ptr< UserMetadata > > temporary_users_by_id_
Definition: SysCatalog.h:508
#define CHECK(condition)
Definition: Logger.h:223
mapd_unique_lock< mapd_shared_mutex > write_lock
#define VLOG(n)
Definition: Logger.h:317
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::createVersionHistoryTable ( ) const
private

Definition at line 2985 of file SysCatalog.cpp.

References sqliteConnector_.

Referenced by recordExecutedMigration().

2985  {
2986  sys_sqlite_lock sqlite_lock(this);
2987  sqliteConnector_->query(
2988  "CREATE TABLE mapd_version_history(version integer, migration_history text "
2989  "unique)");
2990 }
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::deleteObjectDescriptorMap ( const std::string &  roleName)
private

Definition at line 2270 of file SysCatalog.cpp.

References objectDescriptorMap_.

Referenced by dropUser(), and revokeDBObjectPrivileges_unsafe().

2270  {
2271  sys_write_lock write_lock(this);
2272 
2273  for (auto d = objectDescriptorMap_.begin(); d != objectDescriptorMap_.end();) {
2274  if (d->second->roleName == roleName) {
2275  d = objectDescriptorMap_.erase(d);
2276  } else {
2277  d++;
2278  }
2279  }
2280 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:480
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::deleteObjectDescriptorMap ( const std::string &  roleName,
DBObject object,
const Catalog_Namespace::Catalog cat 
)
private

Definition at line 2283 of file SysCatalog.cpp.

References Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::Catalog::getCurrentDB(), objectDescriptorMap_, and to_string().

2285  {
2286  sys_write_lock write_lock(this);
2287  auto range = objectDescriptorMap_.equal_range(
2288  std::to_string(cat.getCurrentDB().dbId) + ":" +
2289  std::to_string(object.getObjectKey().permissionType) + ":" +
2290  std::to_string(object.getObjectKey().objectId));
2291  for (auto d = range.first; d != range.second;) {
2292  // remove the entry
2293  if (d->second->roleName == roleName) {
2294  d = objectDescriptorMap_.erase(d);
2295  } else {
2296  d++;
2297  }
2298  }
2299 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:480
std::string to_string(char const *&&v)
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:228
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the call graph for this function:

static void Catalog_Namespace::SysCatalog::destroy ( )
inlinestatic

Definition at line 344 of file SysCatalog.h.

References instance_.

Referenced by main(), EmbeddedDatabase::DBEngineImpl::reset(), and startHeavyDBServer().

344 { instance_.reset(); }
static std::unique_ptr< SysCatalog > instance_
Definition: SysCatalog.h:497

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::dropDatabase ( const DBMetadata db)

Definition at line 1420 of file SysCatalog.cpp.

References cat(), DashboardDBObjectType, Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::DBMetadata::dbName, getCatalog(), granteeMap_, removeCatalog(), revokeAllOnDatabase_unsafe(), revokeDBObjectPrivilegesFromAll_unsafe(), sqliteConnector_, TableDBObjectType, run_benchmark_import::tables, and to_string().

Referenced by initializeInformationSchemaDb().

1420  {
1421  auto cat = getCatalog(db, false);
1422  cat->eraseDbPhysicalData();
1423  sys_write_lock write_lock(this);
1424  sys_sqlite_lock sqlite_lock(this);
1425  sqliteConnector_->query("BEGIN TRANSACTION");
1426  try {
1427  // remove this database ID from any users that have it set as their default database
1428  sqliteConnector_->query_with_text_param(
1429  "UPDATE mapd_users SET default_db = NULL WHERE default_db = ?",
1430  std::to_string(db.dbId));
1431  /* revoke object privileges to all tables of the database being dropped */
1432  const auto tables = cat->getAllTableMetadata();
1433  for (const auto table : tables) {
1434  if (table->shard >= 0) {
1435  // skip shards, they're not standalone tables
1436  continue;
1437  }
1439  DBObject(table->tableName, TableDBObjectType), cat.get());
1440  }
1441  const auto dashboards = cat->getAllDashboardsMetadata();
1442  for (const auto dashboard : dashboards) {
1444  DBObject(dashboard->dashboardId, DashboardDBObjectType), cat.get());
1445  }
1446  /* revoke object privileges to the database being dropped */
1447  for (const auto& grantee : granteeMap_) {
1448  if (grantee.second->hasAnyPrivilegesOnDb(db.dbId, true)) {
1450  grantee.second->getName(), db.dbId, grantee.second.get());
1451  }
1452  }
1453  sqliteConnector_->query_with_text_param("DELETE FROM mapd_databases WHERE dbid = ?",
1454  std::to_string(db.dbId));
1455  cat->eraseDbMetadata();
1456  removeCatalog(db.dbName);
1457  } catch (const std::exception&) {
1458  sqliteConnector_->query("ROLLBACK TRANSACTION");
1459  throw;
1460  }
1461  sqliteConnector_->query("END TRANSACTION");
1462 }
void revokeAllOnDatabase_unsafe(const std::string &roleName, int32_t dbId, Grantee *grantee)
std::string cat(Ts &&...args)
void removeCatalog(const std::string &dbName)
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
std::shared_ptr< Catalog > getCatalog(const std::string &dbName)
void revokeDBObjectPrivilegesFromAll_unsafe(DBObject object, Catalog *catalog)
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::dropRole ( const std::string &  roleName,
const bool  is_temporary = false 
)

Definition at line 2659 of file SysCatalog.cpp.

References dropRole_unsafe(), and execInTransaction().

2659  {
2660  execInTransaction(&SysCatalog::dropRole_unsafe, roleName, is_temporary);
2661 }
void execInTransaction(F &&f, Args &&...args)
void dropRole_unsafe(const std::string &roleName, const bool is_temporary)

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::dropRole_unsafe ( const std::string &  roleName,
const bool  is_temporary 
)
private

Definition at line 2104 of file SysCatalog.cpp.

References granteeMap_, objectDescriptorMap_, sqliteConnector_, and to_upper().

Referenced by dropRole(), and dropUser().

2104  {
2105  sys_write_lock write_lock(this);
2106 
2107  for (auto d = objectDescriptorMap_.begin(); d != objectDescriptorMap_.end();) {
2108  if (d->second->roleName == roleName) {
2109  d = objectDescriptorMap_.erase(d);
2110  } else {
2111  d++;
2112  }
2113  }
2114  // it may very well be a user "role", so keep it generic
2115  granteeMap_.erase(to_upper(roleName));
2116 
2117  if (!is_temporary) {
2118  sys_sqlite_lock sqlite_lock(this);
2119  sqliteConnector_->query_with_text_param("DELETE FROM mapd_roles WHERE roleName = ?",
2120  roleName);
2121  sqliteConnector_->query_with_text_param(
2122  "DELETE FROM mapd_object_permissions WHERE roleName = ?", roleName);
2123  }
2124 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:480
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
std::string to_upper(const std::string &str)
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::dropUser ( const std::string &  name)

Definition at line 962 of file SysCatalog.cpp.

References CHECK, deleteObjectDescriptorMap(), dropRole_unsafe(), Catalog_Namespace::g_log_user_id, getMetadataForUser(), Catalog_Namespace::UserMetadata::is_temporary, sqliteConnector_, temporary_users_by_id_, temporary_users_by_name_, to_string(), and Catalog_Namespace::UserMetadata::userId.

962  {
964  sys_sqlite_lock sqlite_lock(this);
965 
966  UserMetadata user;
967  if (!getMetadataForUser(name, user)) {
968  std::string const loggable = g_log_user_id ? std::string("") : name + ' ';
969  throw runtime_error("Cannot drop user. User " + loggable + "does not exist.");
970  }
971 
972  // Temporary user.
973  if (user.is_temporary) {
974  auto it1 = temporary_users_by_name_.find(name);
975  CHECK(it1 != temporary_users_by_name_.end());
976  auto it2 = temporary_users_by_id_.find(it1->second->userId);
977  CHECK(it2 != temporary_users_by_id_.end());
978  dropRole_unsafe(name, /*is_temporary=*/true);
980  temporary_users_by_name_.erase(it1);
981  temporary_users_by_id_.erase(it2);
982  return;
983  }
984 
985  // Normal user.
986  sqliteConnector_->query("BEGIN TRANSACTION");
987  try {
988  dropRole_unsafe(name, /*is_temporary=*/false);
990  const std::string& roleName(name);
991  sqliteConnector_->query_with_text_param("DELETE FROM mapd_roles WHERE userName = ?",
992  roleName);
993  sqliteConnector_->query("DELETE FROM mapd_users WHERE userid = " +
994  std::to_string(user.userId));
995  sqliteConnector_->query("DELETE FROM mapd_privileges WHERE userid = " +
996  std::to_string(user.userId));
997  } catch (const std::exception& e) {
998  sqliteConnector_->query("ROLLBACK TRANSACTION");
999  throw;
1000  }
1001  sqliteConnector_->query("END TRANSACTION");
1002 }
bool getMetadataForUser(const std::string &name, UserMetadata &user)
std::string name() const
Definition: SysCatalog.h:347
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unordered_map< std::string, std::shared_ptr< UserMetadata > > temporary_users_by_name_
Definition: SysCatalog.h:507
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
void dropRole_unsafe(const std::string &roleName, const bool is_temporary)
void deleteObjectDescriptorMap(const std::string &roleName)
std::unordered_map< int32_t, std::shared_ptr< UserMetadata > > temporary_users_by_id_
Definition: SysCatalog.h:508
#define CHECK(condition)
Definition: Logger.h:223
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the call graph for this function:

template<typename F , typename... Args>
void Catalog_Namespace::SysCatalog::execInTransaction ( F &&  f,
Args &&...  args 
)
private

Definition at line 2639 of file SysCatalog.cpp.

References run_benchmark_import::args, anonymous_namespace{Utm.h}::f, and sqliteConnector_.

Referenced by createRole(), dropRole(), grantDBObjectPrivileges(), grantDBObjectPrivilegesBatch(), grantRole(), grantRoleBatch(), revokeDBObjectPrivileges(), revokeDBObjectPrivilegesBatch(), revokeDBObjectPrivilegesFromAll(), revokeDBObjectPrivilegesFromAllBatch(), revokeRole(), and revokeRoleBatch().

2639  {
2640  sys_write_lock write_lock(this);
2641  sys_sqlite_lock sqlite_lock(this);
2642  sqliteConnector_->query("BEGIN TRANSACTION");
2643  try {
2644  (this->*f)(std::forward<Args>(args)...);
2645  } catch (std::exception&) {
2646  sqliteConnector_->query("ROLLBACK TRANSACTION");
2647  throw;
2648  }
2649  sqliteConnector_->query("END TRANSACTION");
2650 }
constexpr double f
Definition: Utm.h:31
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::fixRolesMigration ( )
private

Definition at line 377 of file SysCatalog.cpp.

References sqliteConnector_.

Referenced by checkAndExecuteMigrations().

377  {
378  sys_sqlite_lock sqlite_lock(this);
379  sqliteConnector_->query("BEGIN TRANSACTION");
380  try {
381  sqliteConnector_->query("SELECT name FROM mapd_users");
382  auto num_rows = sqliteConnector_->getNumRows();
383  std::vector<std::string> user_names;
384  for (size_t i = 0; i < num_rows; ++i) {
385  user_names.push_back(sqliteConnector_->getData<std::string>(i, 0));
386  }
387  for (const auto& user_name : user_names) {
388  sqliteConnector_->query_with_text_param("DELETE FROM mapd_roles WHERE roleName = ?",
389  user_name);
390  }
391  } catch (const std::exception&) {
392  sqliteConnector_->query("ROLLBACK TRANSACTION");
393  throw;
394  }
395  sqliteConnector_->query("END TRANSACTION");
396 }
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481

+ Here is the caller graph for this function:

list< DBMetadata > Catalog_Namespace::SysCatalog::getAllDBMetadata ( )

Definition at line 1553 of file SysCatalog.cpp.

References Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::DBMetadata::dbName, Catalog_Namespace::DBMetadata::dbOwner, and sqliteConnector_.

Referenced by getCatalogsForAllDbs(), and getDatabaseListForUser().

1553  {
1554  sys_sqlite_lock sqlite_lock(this);
1555  sqliteConnector_->query("SELECT dbid, name, owner FROM mapd_databases");
1556  int numRows = sqliteConnector_->getNumRows();
1557  list<DBMetadata> db_list;
1558  for (int r = 0; r < numRows; ++r) {
1559  DBMetadata db;
1560  db.dbId = sqliteConnector_->getData<int>(r, 0);
1561  db.dbName = sqliteConnector_->getData<string>(r, 1);
1562  db.dbOwner = sqliteConnector_->getData<int>(r, 2);
1563  db_list.push_back(db);
1564  }
1565  return db_list;
1566 }
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481

+ Here is the caller graph for this function:

list< UserMetadata > Catalog_Namespace::SysCatalog::getAllUserMetadata ( )

Definition at line 1613 of file SysCatalog.cpp.

References Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::get_users(), and sqliteConnector_.

Referenced by Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_user_id_to_user_name_map(), and getDatabaseListForUser().

1613  {
1614  sys_sqlite_lock sqlite_lock(this);
1615  return get_users(*this, sqliteConnector_);
1616 }
auto get_users(SysCatalog &syscat, std::unique_ptr< SqliteConnector > &sqliteConnector, const int32_t dbId=-1)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

list< UserMetadata > Catalog_Namespace::SysCatalog::getAllUserMetadata ( const int64_t  dbId)

return the users associated with the given DB

Definition at line 1606 of file SysCatalog.cpp.

References Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::get_users(), and sqliteConnector_.

1606  {
1607  // this call is to return users that have some form of permissions to objects in the db
1608  // sadly mapd_object_permissions table is also misused to manage user roles.
1609  sys_sqlite_lock sqlite_lock(this);
1610  return get_users(*this, sqliteConnector_, dbId);
1611 }
auto get_users(SysCatalog &syscat, std::unique_ptr< SqliteConnector > &sqliteConnector, const int32_t dbId=-1)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481

+ Here is the call graph for this function:

Calcite& Catalog_Namespace::SysCatalog::getCalciteMgr ( ) const
inline

Definition at line 229 of file SysCatalog.h.

References calciteMgr_.

229 { return *calciteMgr_; }
std::shared_ptr< Calcite > calciteMgr_
Definition: SysCatalog.h:486
std::shared_ptr< Catalog > Catalog_Namespace::SysCatalog::getCatalog ( const std::string &  dbName)

Definition at line 2826 of file SysCatalog.cpp.

References cat_map_, and getMetadataForDB().

Referenced by foreign_storage::cache_blocks(), createDatabase(), foreign_storage::ForeignDataWrapperFactory::createForeignTableProxy(), foreign_storage::AbstractTextFileDataWrapper::createRenderGroupAnalyzers(), foreign_storage::ParquetDataWrapper::createRenderGroupAnalyzers(), dropDatabase(), foreign_storage::ParquetDataWrapper::fetchChunkMetadata(), foreign_storage::ForeignTableSchema::ForeignTableSchema(), foreign_storage::anonymous_namespace{InternalMemoryStatsDataWrapper.cpp}::get_column_name(), foreign_storage::get_foreign_table_for_key(), foreign_storage::anonymous_namespace{InternalCatalogDataWrapper.cpp}::get_table_ddl(), foreign_storage::get_table_name(), foreign_storage::ParseBufferRequest::getCatalog(), getCatalogsForAllDbs(), foreign_storage::ParquetImportBatchResult::getChunksAndDictionaries(), foreign_storage::ParquetDataWrapper::getColumnsToInitialize(), foreign_storage::init_chunk_for_column(), foreign_storage::Csv::init_chunk_for_column(), PersistentStorageMgr::isForeignStorage(), foreign_storage::ParquetDataWrapper::loadBuffersUsingLazyParquetChunkLoader(), login(), foreign_storage::AbstractTextFileDataWrapper::populateChunkBuffers(), foreign_storage::AbstractTextFileDataWrapper::populateChunkMetadata(), switchDatabase(), and foreign_storage::AbstractTextFileDataWrapper::updateMetadata().

2826  {
2827  dbid_to_cat_map::const_accessor cata;
2828  if (cat_map_.find(cata, dbName)) {
2829  return cata->second;
2830  } else {
2832  if (getMetadataForDB(dbName, db_meta)) {
2833  return getCatalog(db_meta, false);
2834  } else {
2835  return nullptr;
2836  }
2837  }
2838 }
std::shared_ptr< Catalog > getCatalog(const std::string &dbName)
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::shared_ptr< Catalog > Catalog_Namespace::SysCatalog::getCatalog ( const int32_t  db_id)

Definition at line 2840 of file SysCatalog.cpp.

References cat_map_.

2840  {
2841  dbid_to_cat_map::const_accessor cata;
2842  for (dbid_to_cat_map::iterator cat_it = cat_map_.begin(); cat_it != cat_map_.end();
2843  ++cat_it) {
2844  if (cat_it->second->getDatabaseId() == db_id) {
2845  return cat_it->second;
2846  }
2847  }
2848  return nullptr;
2849 }
std::shared_ptr< Catalog > Catalog_Namespace::SysCatalog::getCatalog ( const DBMetadata curDB,
bool  is_new_db 
)

Definition at line 2851 of file SysCatalog.cpp.

References basePath_, calciteMgr_, cat(), cat_map_, dataMgr_, Catalog_Namespace::DBMetadata::dbName, and string_dict_hosts_.

2851  {
2852  {
2853  dbid_to_cat_map::const_accessor cata;
2854  if (cat_map_.find(cata, curDB.dbName)) {
2855  return cata->second;
2856  }
2857  }
2858 
2859  // Catalog doesnt exist
2860  // has to be made outside of lock as migration uses cat
2861  auto cat = std::make_shared<Catalog>(
2862  basePath_, curDB, dataMgr_, string_dict_hosts_, calciteMgr_, is_new_db);
2863 
2864  dbid_to_cat_map::accessor cata;
2865 
2866  if (cat_map_.find(cata, curDB.dbName)) {
2867  return cata->second;
2868  }
2869 
2870  cat_map_.insert(cata, curDB.dbName);
2871  cata->second = cat;
2872 
2873  return cat;
2874 }
std::string cat(Ts &&...args)
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: SysCatalog.h:483
std::vector< LeafHostInfo > string_dict_hosts_
Definition: SysCatalog.h:487
std::shared_ptr< Calcite > calciteMgr_
Definition: SysCatalog.h:486

+ Here is the call graph for this function:

const std::string& Catalog_Namespace::SysCatalog::getCatalogBasePath ( ) const
inline

Definition at line 230 of file SysCatalog.h.

References basePath_.

230 { return basePath_; }
std::vector< Catalog * > Catalog_Namespace::SysCatalog::getCatalogsForAllDbs ( )

Definition at line 1004 of file SysCatalog.cpp.

References getAllDBMetadata(), and getCatalog().

1004  {
1005  std::vector<Catalog*> catalogs{};
1006  const auto& db_metadata_list = getAllDBMetadata();
1007  for (const auto& db_metadata : db_metadata_list) {
1008  catalogs.emplace_back(getCatalog(db_metadata, false).get());
1009  }
1010  return catalogs;
1011 }
std::shared_ptr< Catalog > getCatalog(const std::string &dbName)
std::list< DBMetadata > getAllDBMetadata()

+ Here is the call graph for this function:

std::set< std::string > Catalog_Namespace::SysCatalog::getCreatedRoles ( ) const

Definition at line 2483 of file SysCatalog.cpp.

References granteeMap_, and isDashboardSystemRole().

2483  {
2484  sys_read_lock read_lock(this);
2485  std::set<std::string> roles; // Sorted for human readers.
2486  for (const auto& [key, grantee] : granteeMap_) {
2487  if (!grantee->isUser() && !isDashboardSystemRole(grantee->getName())) {
2488  roles.emplace(grantee->getName());
2489  }
2490  }
2491  return roles;
2492 }
mapd_shared_lock< mapd_shared_mutex > read_lock
bool isDashboardSystemRole(const std::string &roleName) const
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:120

+ Here is the call graph for this function:

DBSummaryList Catalog_Namespace::SysCatalog::getDatabaseListForUser ( const UserMetadata user)

Definition at line 1684 of file SysCatalog.cpp.

References AccessPrivileges::ACCESS, checkPrivileges(), DatabaseDBObjectType, Catalog_Namespace::DBSummary::dbName, getAllDBMetadata(), getAllUserMetadata(), DBObject::loadKey(), and DBObject::setPrivileges().

Referenced by ShowDatabasesCommand::execute().

1684  {
1685  DBSummaryList ret;
1686 
1687  std::list<Catalog_Namespace::DBMetadata> db_list = getAllDBMetadata();
1688  std::list<Catalog_Namespace::UserMetadata> user_list = getAllUserMetadata();
1689 
1690  for (auto d : db_list) {
1691  DBObject dbObject(d.dbName, DatabaseDBObjectType);
1692  dbObject.loadKey();
1693  dbObject.setPrivileges(AccessPrivileges::ACCESS);
1694  if (!checkPrivileges(user, std::vector<DBObject>{dbObject})) {
1695  continue;
1696  }
1697  for (auto u : user_list) {
1698  if (d.dbOwner == u.userId) {
1699  ret.emplace_back(DBSummary{d.dbName, u.userName});
1700  break;
1701  }
1702  }
1703  }
1704 
1705  return ret;
1706 }
bool checkPrivileges(const UserMetadata &user, const std::vector< DBObject > &privObjects) const
std::list< UserMetadata > getAllUserMetadata()
std::list< DBMetadata > getAllDBMetadata()
static const AccessPrivileges ACCESS
Definition: DBObject.h:155
std::list< DBSummary > DBSummaryList
Definition: SysCatalog.h:145

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Data_Namespace::DataMgr& Catalog_Namespace::SysCatalog::getDataMgr ( ) const
inline

Definition at line 228 of file SysCatalog.h.

References dataMgr_.

Referenced by Executor::clearMemory(), Executor::getExecutor(), foreign_storage::InternalMemoryStatsDataWrapper::initializeObjectsForTable(), and foreign_storage::InternalStorageStatsDataWrapper::initializeObjectsForTable().

228 { return *dataMgr_; }
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: SysCatalog.h:483

+ Here is the caller graph for this function:

std::optional<DBMetadata> Catalog_Namespace::SysCatalog::getDB ( std::string const &  dbname)
inline

Definition at line 209 of file SysCatalog.h.

References getMetadataForDB().

209  {
210  if (DBMetadata db; getMetadataForDB(dbname, db)) {
211  return db;
212  }
213  return {};
214  }
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

std::optional<DBMetadata> Catalog_Namespace::SysCatalog::getDB ( int32_t const  dbid)
inline

Definition at line 215 of file SysCatalog.h.

References getMetadataForDBById().

215  {
216  if (DBMetadata db; getMetadataForDBById(dbid, db)) {
217  return db;
218  }
219  return {};
220  }
bool getMetadataForDBById(const int32_t idIn, DBMetadata &db)

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::getDBObjectPrivileges ( const std::string &  granteeName,
DBObject object,
const Catalog_Namespace::Catalog catalog 
) const

Definition at line 2046 of file SysCatalog.cpp.

References getGrantee(), getMetadataForUser(), instance(), and Catalog_Namespace::UserMetadata::isSuper.

2048  {
2049  sys_read_lock read_lock(this);
2050  UserMetadata user_meta;
2051 
2052  if (instance().getMetadataForUser(granteeName, user_meta)) {
2053  if (user_meta.isSuper) {
2054  throw runtime_error(
2055  "Request to show privileges from " + granteeName +
2056  " failed because user is super user and has all privileges by default.");
2057  }
2058  }
2059  auto* grantee = instance().getGrantee(granteeName);
2060  if (!grantee) {
2061  throw runtime_error("Request to show privileges for " + granteeName +
2062  " failed because role or user with this name does not exist.");
2063  }
2064  object.loadKey(catalog);
2065  grantee->getPrivileges(object, true);
2066 }
bool getMetadataForUser(const std::string &name, UserMetadata &user)
Grantee * getGrantee(const std::string &name) const
static SysCatalog & instance()
Definition: SysCatalog.h:337
mapd_shared_lock< mapd_shared_mutex > read_lock
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:120

+ Here is the call graph for this function:

std::shared_ptr<Catalog> Catalog_Namespace::SysCatalog::getDummyCatalog ( )
inline

Definition at line 358 of file SysCatalog.h.

References dummyCatalog_.

Referenced by Catalog_Namespace::Catalog::getObjForLock().

358 { return dummyCatalog_; }
std::shared_ptr< Catalog > dummyCatalog_
Definition: SysCatalog.h:506

+ Here is the caller graph for this function:

Grantee * Catalog_Namespace::SysCatalog::getGrantee ( const std::string &  name) const

Definition at line 2353 of file SysCatalog.cpp.

References granteeMap_, and to_upper().

Referenced by buildRoleMap(), buildUserRoleMap(), createRole_unsafe(), createUser(), getDBObjectPrivileges(), getRoleGrantee(), getRoles(), getUserGrantee(), grantDBObjectPrivileges_unsafe(), grantRole_unsafe(), renameDBObject(), renameUser(), revokeDBObjectPrivileges_unsafe(), and revokeRole_unsafe().

2353  {
2354  sys_read_lock read_lock(this);
2355  auto grantee = granteeMap_.find(to_upper(name));
2356  if (grantee == granteeMap_.end()) { // check to make sure role exists
2357  return nullptr;
2358  }
2359  return grantee->second.get(); // returns pointer to role
2360 }
std::string name() const
Definition: SysCatalog.h:347
std::string to_upper(const std::string &str)
mapd_shared_lock< mapd_shared_mutex > read_lock
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:120

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::unordered_map< std::string, std::vector< std::string > > Catalog_Namespace::SysCatalog::getGranteesOfSharedDashboards ( const std::vector< std::string > &  dashboard_ids)

Definition at line 2795 of file SysCatalog.cpp.

References DashboardDBObjectType, sqliteConnector_, and to_string().

Referenced by Catalog_Namespace::Catalog::createDashboardSystemRoles().

2795  {
2796  sys_sqlite_lock sqlite_lock(this);
2797  std::unordered_map<std::string, std::vector<std::string>> active_grantees;
2798  sqliteConnector_->query("BEGIN TRANSACTION");
2799  try {
2800  for (auto dash : dashboard_ids) {
2801  std::vector<std::string> grantees = {};
2802  sqliteConnector_->query_with_text_params(
2803  "SELECT roleName FROM mapd_object_permissions WHERE objectPermissions NOT IN "
2804  "(0,1) AND objectPermissionsType = ? AND objectId = ?",
2805  std::vector<std::string>{
2806  std::to_string(static_cast<int32_t>(DashboardDBObjectType)), dash});
2807  int num_rows = sqliteConnector_->getNumRows();
2808  if (num_rows == 0) {
2809  // no grantees
2810  continue;
2811  } else {
2812  for (size_t i = 0; i < sqliteConnector_->getNumRows(); ++i) {
2813  grantees.push_back(sqliteConnector_->getData<string>(i, 0));
2814  }
2815  active_grantees[dash] = grantees;
2816  }
2817  }
2818  } catch (const std::exception& e) {
2819  sqliteConnector_->query("ROLLBACK TRANSACTION");
2820  throw;
2821  }
2822  sqliteConnector_->query("END TRANSACTION");
2823  return active_grantees;
2824 }
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::vector< ObjectRoleDescriptor > Catalog_Namespace::SysCatalog::getMetadataForAllObjects ( ) const

Definition at line 2384 of file SysCatalog.cpp.

References isDashboardSystemRole(), and objectDescriptorMap_.

2384  {
2385  sys_read_lock read_lock(this);
2386  std::vector<ObjectRoleDescriptor> objects;
2387  for (const auto& entry : objectDescriptorMap_) {
2388  auto object_role = entry.second.get();
2389  if (object_role->dbId != 0 && !isDashboardSystemRole(object_role->roleName)) {
2390  objects.emplace_back(*object_role);
2391  }
2392  }
2393  return objects;
2394 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:480
mapd_shared_lock< mapd_shared_mutex > read_lock
bool isDashboardSystemRole(const std::string &roleName) const
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:120

+ Here is the call graph for this function:

bool Catalog_Namespace::SysCatalog::getMetadataForDB ( const std::string &  name,
DBMetadata db 
)

Definition at line 1654 of file SysCatalog.cpp.

References Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::DBMetadata::dbName, Catalog_Namespace::DBMetadata::dbOwner, and sqliteConnector_.

Referenced by alterUser(), createDatabase(), createUser(), getCatalog(), getDB(), getMetadataWithDefaultDB(), initializeInformationSchemaDb(), migrateDBAccessPrivileges(), renameDatabase(), and Catalog_Namespace::UserAlterations::wouldChange().

1654  {
1655  sys_read_lock read_lock(this);
1656  sys_sqlite_lock sqlite_lock(this);
1657  sqliteConnector_->query_with_text_param(
1658  "SELECT dbid, name, owner FROM mapd_databases WHERE name = ?", name);
1659  int numRows = sqliteConnector_->getNumRows();
1660  if (numRows == 0) {
1661  return false;
1662  }
1663  db.dbId = sqliteConnector_->getData<int>(0, 0);
1664  db.dbName = sqliteConnector_->getData<string>(0, 1);
1665  db.dbOwner = sqliteConnector_->getData<int>(0, 2);
1666  return true;
1667 }
std::string name() const
Definition: SysCatalog.h:347
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
mapd_shared_lock< mapd_shared_mutex > read_lock
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:120

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::getMetadataForDBById ( const int32_t  idIn,
DBMetadata db 
)

Definition at line 1669 of file SysCatalog.cpp.

References Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::DBMetadata::dbName, Catalog_Namespace::DBMetadata::dbOwner, sqliteConnector_, and to_string().

Referenced by getDB(), and getMetadataWithDefaultDB().

1669  {
1670  sys_sqlite_lock sqlite_lock(this);
1671  sqliteConnector_->query_with_text_param(
1672  "SELECT dbid, name, owner FROM mapd_databases WHERE dbid = ?",
1673  std::to_string(idIn));
1674  int numRows = sqliteConnector_->getNumRows();
1675  if (numRows == 0) {
1676  return false;
1677  }
1678  db.dbId = sqliteConnector_->getData<int>(0, 0);
1679  db.dbName = sqliteConnector_->getData<string>(0, 1);
1680  db.dbOwner = sqliteConnector_->getData<int>(0, 2);
1681  return true;
1682 }
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::vector< ObjectRoleDescriptor * > Catalog_Namespace::SysCatalog::getMetadataForObject ( int32_t  dbId,
int32_t  dbType,
int32_t  objectId 
) const

Definition at line 2371 of file SysCatalog.cpp.

References objectDescriptorMap_, and to_string().

Referenced by renameDBObject().

2371  {
2372  sys_read_lock read_lock(this);
2373  std::vector<ObjectRoleDescriptor*> objectsList;
2374 
2375  auto range = objectDescriptorMap_.equal_range(std::to_string(dbId) + ":" +
2376  std::to_string(dbType) + ":" +
2377  std::to_string(objectId));
2378  for (auto d = range.first; d != range.second; ++d) {
2379  objectsList.push_back(d->second.get());
2380  }
2381  return objectsList; // return pointers to objects
2382 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:480
std::string to_string(char const *&&v)
mapd_shared_lock< mapd_shared_mutex > read_lock
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:120

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::getMetadataForUser ( const std::string &  name,
UserMetadata user 
)

Definition at line 1514 of file SysCatalog.cpp.

References Catalog_Namespace::parseUserMetadataFromSQLite(), sqliteConnector_, and temporary_users_by_name_.

Referenced by alterUser(), checkPasswordForUserImpl(), checkPrivileges(), createUser(), dropUser(), getDBObjectPrivileges(), getMetadataWithDefaultDB(), getRoles(), getUser(), grantDBObjectPrivileges_unsafe(), grantRoleBatch_unsafe(), login(), renameUser(), revokeDBObjectPrivileges_unsafe(), and revokeRoleBatch_unsafe().

1514  {
1515  sys_read_lock read_lock(this);
1516  sys_sqlite_lock sqlite_lock(this);
1517  sqliteConnector_->query_with_text_param(
1518  "SELECT userid, name, passwd_hash, issuper, default_db, can_login FROM mapd_users "
1519  "WHERE name = ?",
1520  name);
1521  int numRows = sqliteConnector_->getNumRows();
1522  if (numRows == 0) {
1523  auto userit = temporary_users_by_name_.find(name);
1524  if (userit != temporary_users_by_name_.end()) {
1525  user = *userit->second;
1526  return true;
1527  } else {
1528  return false;
1529  }
1530  }
1532 }
static bool parseUserMetadataFromSQLite(const std::unique_ptr< SqliteConnector > &conn, UserMetadata &user, int row)
std::string name() const
Definition: SysCatalog.h:347
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unordered_map< std::string, std::shared_ptr< UserMetadata > > temporary_users_by_name_
Definition: SysCatalog.h:507
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
mapd_shared_lock< mapd_shared_mutex > read_lock
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:120

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::getMetadataForUserById ( const int32_t  idIn,
UserMetadata user 
)

Definition at line 1534 of file SysCatalog.cpp.

References Catalog_Namespace::parseUserMetadataFromSQLite(), sqliteConnector_, temporary_users_by_id_, and to_string().

Referenced by createDatabase(), getUser(), populateRoleDbObjects(), and reassignObjectOwners().

1534  {
1535  sys_sqlite_lock sqlite_lock(this);
1536  sqliteConnector_->query_with_text_param(
1537  "SELECT userid, name, passwd_hash, issuper, default_db, can_login FROM mapd_users "
1538  "WHERE userid = ?",
1539  std::to_string(idIn));
1540  int numRows = sqliteConnector_->getNumRows();
1541  if (numRows == 0) {
1542  auto userit = temporary_users_by_id_.find(idIn);
1543  if (userit != temporary_users_by_id_.end()) {
1544  user = *userit->second;
1545  return true;
1546  } else {
1547  return false;
1548  }
1549  }
1551 }
static bool parseUserMetadataFromSQLite(const std::unique_ptr< SqliteConnector > &conn, UserMetadata &user, int row)
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
std::unordered_map< int32_t, std::shared_ptr< UserMetadata > > temporary_users_by_id_
Definition: SysCatalog.h:508

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::getMetadataWithDefaultDB ( std::string &  dbname,
const std::string &  username,
Catalog_Namespace::DBMetadata db_meta,
UserMetadata user_meta 
)
private

Definition at line 1618 of file SysCatalog.cpp.

References Catalog_Namespace::DBMetadata::dbName, Catalog_Namespace::UserMetadata::defaultDbId, Catalog_Namespace::g_log_user_id, getMetadataForDB(), getMetadataForDBById(), getMetadataForUser(), shared::kDefaultDbName, to_string(), Catalog_Namespace::UserMetadata::userId, and Catalog_Namespace::UserMetadata::userName.

Referenced by login(), and switchDatabase().

1621  {
1622  sys_read_lock read_lock(this);
1623  if (!getMetadataForUser(username, user_meta)) {
1624  throw std::runtime_error("Invalid credentials.");
1625  }
1626 
1627  if (!dbname.empty()) {
1628  if (!getMetadataForDB(dbname, db_meta)) {
1629  throw std::runtime_error("Database name " + dbname + " does not exist.");
1630  }
1631  // loaded the requested database
1632  } else {
1633  if (user_meta.defaultDbId != -1) {
1634  if (!getMetadataForDBById(user_meta.defaultDbId, db_meta)) {
1635  std::string loggable = g_log_user_id ? std::string("") : ' ' + user_meta.userName;
1636  throw std::runtime_error(
1637  "Server error: User #" + std::to_string(user_meta.userId) + loggable +
1638  " has invalid default_db #" + std::to_string(user_meta.defaultDbId) +
1639  " which does not exist.");
1640  }
1641  dbname = db_meta.dbName;
1642  // loaded the user's default database
1643  } else {
1644  if (!getMetadataForDB(shared::kDefaultDbName, db_meta)) {
1645  throw std::runtime_error(std::string("Database ") + shared::kDefaultDbName +
1646  " does not exist.");
1647  }
1648  dbname = shared::kDefaultDbName;
1649  // loaded the mapd database by default
1650  }
1651  }
1652 }
bool getMetadataForUser(const std::string &name, UserMetadata &user)
std::string to_string(char const *&&v)
const std::string kDefaultDbName
mapd_shared_lock< mapd_shared_mutex > read_lock
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:120
bool getMetadataForDBById(const int32_t idIn, DBMetadata &db)
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

Role * Catalog_Namespace::SysCatalog::getRoleGrantee ( const std::string &  name) const

Definition at line 2362 of file SysCatalog.cpp.

References getGrantee().

Referenced by Catalog_Namespace::Catalog::createDashboardSystemRoles(), Catalog_Namespace::Catalog::createOrUpdateDashboardSystemRole(), grantRole_unsafe(), isRoleGrantedToGrantee(), revokeRole_unsafe(), and syncUserWithRemoteProvider().

2362  {
2363  return dynamic_cast<Role*>(getGrantee(name));
2364 }
std::string name() const
Definition: SysCatalog.h:347
Grantee * getGrantee(const std::string &name) const
Definition: Grantee.h:81

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::vector< std::string > Catalog_Namespace::SysCatalog::getRoles ( const std::string &  user_name,
bool  effective = true 
)

Definition at line 2422 of file SysCatalog.cpp.

References getGrantee().

2423  {
2424  sys_read_lock read_lock(this);
2425  auto* grantee = getGrantee(user_name);
2426  if (!grantee) {
2427  throw std::runtime_error("user or role not found");
2428  }
2429  return grantee->getRoles(/*only_direct=*/!effective);
2430 }
Grantee * getGrantee(const std::string &name) const
mapd_shared_lock< mapd_shared_mutex > read_lock
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:120

+ Here is the call graph for this function:

std::vector< std::string > Catalog_Namespace::SysCatalog::getRoles ( bool  include_user_private_role,
bool  is_super,
const std::string &  user_name,
bool  ignore_deleted_user = false 
)

Definition at line 2453 of file SysCatalog.cpp.

References getMetadataForUser(), granteeMap_, isDashboardSystemRole(), and isRoleGrantedToGrantee().

2456  {
2457  sys_read_lock read_lock(this);
2458  if (ignore_deleted_user) {
2459  // In certain cases, it is possible to concurrently call this method while the user is
2460  // being dropped. In such a case, return an empty result.
2461  UserMetadata user;
2462  if (!getMetadataForUser(user_name, user)) {
2463  return {};
2464  }
2465  }
2466  std::vector<std::string> roles;
2467  for (auto& grantee : granteeMap_) {
2468  if (!include_user_private_role && grantee.second->isUser()) {
2469  continue;
2470  }
2471  if (!is_super &&
2472  !isRoleGrantedToGrantee(user_name, grantee.second->getName(), false)) {
2473  continue;
2474  }
2475  if (isDashboardSystemRole(grantee.second->getName())) {
2476  continue;
2477  }
2478  roles.push_back(grantee.second->getName());
2479  }
2480  return roles;
2481 }
bool getMetadataForUser(const std::string &name, UserMetadata &user)
bool isRoleGrantedToGrantee(const std::string &granteeName, const std::string &roleName, bool only_direct) const
mapd_shared_lock< mapd_shared_mutex > read_lock
bool isDashboardSystemRole(const std::string &roleName) const
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:120

+ Here is the call graph for this function:

std::vector< std::string > Catalog_Namespace::SysCatalog::getRoles ( const std::string &  userName,
const int32_t  dbId 
)

Definition at line 2432 of file SysCatalog.cpp.

References isDashboardSystemRole(), isRoleGrantedToGrantee(), sqliteConnector_, and to_string().

2433  {
2434  sys_sqlite_lock sqlite_lock(this);
2435  std::string sql =
2436  "SELECT DISTINCT roleName FROM mapd_object_permissions WHERE "
2437  "objectPermissions<>0 "
2438  "AND roleType=0 AND dbId=" +
2439  std::to_string(dbId);
2440  sqliteConnector_->query(sql);
2441  int numRows = sqliteConnector_->getNumRows();
2442  std::vector<std::string> roles(0);
2443  for (int r = 0; r < numRows; ++r) {
2444  auto roleName = sqliteConnector_->getData<string>(r, 0);
2445  if (isRoleGrantedToGrantee(userName, roleName, false) &&
2446  !isDashboardSystemRole(roleName)) {
2447  roles.push_back(roleName);
2448  }
2449  }
2450  return roles;
2451 }
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
bool isRoleGrantedToGrantee(const std::string &granteeName, const std::string &roleName, bool only_direct) const
bool isDashboardSystemRole(const std::string &roleName) const

+ Here is the call graph for this function:

SqliteConnector* Catalog_Namespace::SysCatalog::getSqliteConnector ( )
inline

Definition at line 231 of file SysCatalog.h.

References sqliteConnector_.

231 { return sqliteConnector_.get(); }
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
std::optional<UserMetadata> Catalog_Namespace::SysCatalog::getUser ( std::string const &  uname)
inline

Definition at line 197 of file SysCatalog.h.

References getMetadataForUser().

Referenced by alterUser(), createUser(), and syncUserWithRemoteProvider().

197  {
198  if (UserMetadata user; getMetadataForUser(uname, user)) {
199  return user;
200  }
201  return {};
202  }
bool getMetadataForUser(const std::string &name, UserMetadata &user)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::optional<UserMetadata> Catalog_Namespace::SysCatalog::getUser ( int32_t const  uid)
inline

Definition at line 203 of file SysCatalog.h.

References getMetadataForUserById().

203  {
204  if (UserMetadata user; getMetadataForUserById(uid, user)) {
205  return user;
206  }
207  return {};
208  }
bool getMetadataForUserById(const int32_t idIn, UserMetadata &user)

+ Here is the call graph for this function:

User * Catalog_Namespace::SysCatalog::getUserGrantee ( const std::string &  name) const

Definition at line 2366 of file SysCatalog.cpp.

References getGrantee().

Referenced by checkPrivileges(), createDBObject(), Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::get_users(), hasAnyPrivileges(), isRoleGrantedToGrantee(), populateRoleDbObjects(), syncUserWithRemoteProvider(), and verifyDBObjectOwnership().

2366  {
2367  return dynamic_cast<User*>(getGrantee(name));
2368 }
std::string name() const
Definition: SysCatalog.h:347
Definition: Grantee.h:75
Grantee * getGrantee(const std::string &name) const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::grantAllOnDatabase_unsafe ( const std::string &  roleName,
DBObject object,
const Catalog_Namespace::Catalog catalog 
)
private

Definition at line 1829 of file SysCatalog.cpp.

References AccessPrivileges::ACCESS, AccessPrivileges::ALL_DASHBOARD, AccessPrivileges::ALL_SERVER, AccessPrivileges::ALL_TABLE, AccessPrivileges::ALL_VIEW, DashboardDBObjectType, DatabaseDBObjectType, g_enable_fsi, grantDBObjectPrivileges_unsafe(), ServerDBObjectType, DBObject::setPermissionType(), DBObject::setPrivileges(), TableDBObjectType, AccessPrivileges::VIEW_SQL_EDITOR, and ViewDBObjectType.

Referenced by createDatabase(), and grantDBObjectPrivileges_unsafe().

1831  {
1832  // It's a separate use case because it's easier for implementation to convert ALL ON
1833  // DATABASE into ALL ON DASHBOARDS, ALL ON VIEWS and ALL ON TABLES
1834  // Add DB Access privileges
1835  DBObject tmp_object = object;
1838  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1841  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1844  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1846  tmp_object.setPermissionType(ViewDBObjectType);
1847  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1848 
1849  if (g_enable_fsi) {
1852  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1853  }
1854 
1857  grantDBObjectPrivileges_unsafe(roleName, tmp_object, catalog);
1858  return;
1859 }
static const AccessPrivileges VIEW_SQL_EDITOR
Definition: DBObject.h:154
void setPrivileges(const AccessPrivileges &privs)
Definition: DBObject.h:229
void grantDBObjectPrivileges_unsafe(const std::string &granteeName, const DBObject object, const Catalog_Namespace::Catalog &catalog)
static const AccessPrivileges ALL_VIEW
Definition: DBObject.h:179
void setPermissionType(const DBObjectType &permissionType)
Definition: DBObject.cpp:151
static const AccessPrivileges ALL_SERVER
Definition: DBObject.h:189
static const AccessPrivileges ALL_DASHBOARD
Definition: DBObject.h:171
static const AccessPrivileges ACCESS
Definition: DBObject.h:155
static const AccessPrivileges ALL_TABLE
Definition: DBObject.h:159
bool g_enable_fsi
Definition: Catalog.cpp:97

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::grantDBObjectPrivileges ( const std::string &  grantee,
const DBObject object,
const Catalog_Namespace::Catalog catalog 
)

Definition at line 2685 of file SysCatalog.cpp.

References execInTransaction(), and grantDBObjectPrivileges_unsafe().

2687  {
2689  &SysCatalog::grantDBObjectPrivileges_unsafe, grantee, object, catalog);
2690 }
void grantDBObjectPrivileges_unsafe(const std::string &granteeName, const DBObject object, const Catalog_Namespace::Catalog &catalog)
void execInTransaction(F &&f, Args &&...args)

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::grantDBObjectPrivileges_unsafe ( const std::string &  granteeName,
const DBObject  object,
const Catalog_Namespace::Catalog catalog 
)
private

Definition at line 1787 of file SysCatalog.cpp.

References DatabasePrivileges::ALL, CHECK, DatabaseDBObjectType, getGrantee(), getMetadataForUser(), grantAllOnDatabase_unsafe(), Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::insertOrUpdateObjectPrivileges(), instance(), Catalog_Namespace::UserMetadata::is_temporary, Catalog_Namespace::UserMetadata::isSuper, sqliteConnector_, and updateObjectDescriptorMap().

Referenced by changeDBObjectOwnership(), createDBObject(), grantAllOnDatabase_unsafe(), grantDBObjectPrivileges(), and grantDBObjectPrivilegesBatch_unsafe().

1790  {
1791  object.loadKey(catalog);
1792  CHECK(object.valid());
1793  if (object.getPrivileges().hasPermission(DatabasePrivileges::ALL) &&
1794  object.getObjectKey().permissionType == DatabaseDBObjectType) {
1795  return grantAllOnDatabase_unsafe(granteeName, object, catalog);
1796  }
1797 
1798  sys_write_lock write_lock(this);
1799 
1800  UserMetadata user_meta;
1801  bool is_temporary_user{false};
1802  if (instance().getMetadataForUser(granteeName, user_meta)) {
1803  if (user_meta.isSuper) {
1804  // super doesn't have explicit privileges so nothing to do
1805  return;
1806  }
1807  is_temporary_user = user_meta.is_temporary;
1808  }
1809  auto* grantee = instance().getGrantee(granteeName);
1810  if (!grantee) {
1811  throw runtime_error("Request to grant privileges to " + granteeName +
1812  " failed because role or user with this name does not exist.");
1813  }
1814  grantee->grantPrivileges(object);
1815 
1816  /* apply grant privileges statement to sqlite DB */
1817  std::vector<std::string> objectKey = object.toString();
1818  object.resetPrivileges();
1819  grantee->getPrivileges(object, true);
1820 
1821  if (!is_temporary_user) {
1822  sys_sqlite_lock sqlite_lock(this);
1824  sqliteConnector_, granteeName, grantee->isUser(), object);
1825  }
1826  updateObjectDescriptorMap(granteeName, object, grantee->isUser(), catalog);
1827 }
static const int32_t ALL
Definition: DBObject.h:79
bool getMetadataForUser(const std::string &name, UserMetadata &user)
Grantee * getGrantee(const std::string &name) const
void insertOrUpdateObjectPrivileges(std::unique_ptr< SqliteConnector > &sqliteConnector, std::string roleName, bool userRole, const DBObject &object)
Definition: SysCatalog.cpp:419
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
static SysCatalog & instance()
Definition: SysCatalog.h:337
void grantAllOnDatabase_unsafe(const std::string &roleName, DBObject &object, const Catalog_Namespace::Catalog &catalog)
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
void updateObjectDescriptorMap(const std::string &roleName, DBObject &object, bool roleType, const Catalog_Namespace::Catalog &cat)
#define CHECK(condition)
Definition: Logger.h:223
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::grantDBObjectPrivilegesBatch ( const std::vector< std::string > &  grantees,
const std::vector< DBObject > &  objects,
const Catalog_Namespace::Catalog catalog 
)

Definition at line 2692 of file SysCatalog.cpp.

References execInTransaction(), and grantDBObjectPrivilegesBatch_unsafe().

Referenced by Catalog_Namespace::Catalog::createOrUpdateDashboardSystemRole().

2694  {
2696  &SysCatalog::grantDBObjectPrivilegesBatch_unsafe, grantees, objects, catalog);
2697 }
void grantDBObjectPrivilegesBatch_unsafe(const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
void execInTransaction(F &&f, Args &&...args)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::grantDBObjectPrivilegesBatch_unsafe ( const std::vector< std::string > &  grantees,
const std::vector< DBObject > &  objects,
const Catalog_Namespace::Catalog catalog 
)
private

Definition at line 1775 of file SysCatalog.cpp.

References grantDBObjectPrivileges_unsafe().

Referenced by grantDBObjectPrivilegesBatch(), and reassignObjectOwners().

1778  {
1779  for (const auto& grantee : grantees) {
1780  for (const auto& object : objects) {
1781  grantDBObjectPrivileges_unsafe(grantee, object, catalog);
1782  }
1783  }
1784 }
void grantDBObjectPrivileges_unsafe(const std::string &granteeName, const DBObject object, const Catalog_Namespace::Catalog &catalog)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::grantDefaultPrivilegesToRole_unsafe ( const std::string &  name,
bool  issuper 
)
private
void Catalog_Namespace::SysCatalog::grantRole ( const std::string &  role,
const std::string &  grantee,
const bool  is_temporary = false 
)

Definition at line 2668 of file SysCatalog.cpp.

References execInTransaction(), and grantRole_unsafe().

Referenced by syncUserWithRemoteProvider().

2670  {
2671  execInTransaction(&SysCatalog::grantRole_unsafe, role, grantee, is_temporary);
2672 }
void grantRole_unsafe(const std::string &roleName, const std::string &granteeName, const bool is_temporary)
void execInTransaction(F &&f, Args &&...args)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::grantRole_unsafe ( const std::string &  roleName,
const std::string &  granteeName,
const bool  is_temporary 
)
private

Definition at line 2141 of file SysCatalog.cpp.

References getGrantee(), getRoleGrantee(), and sqliteConnector_.

Referenced by grantRole(), and grantRoleBatch_unsafe().

2143  {
2144  auto* rl = getRoleGrantee(roleName);
2145  if (!rl) {
2146  throw runtime_error("Request to grant role " + roleName +
2147  " failed because role with this name does not exist.");
2148  }
2149  auto* grantee = getGrantee(granteeName);
2150  if (!grantee) {
2151  throw runtime_error("Request to grant role " + roleName + " failed because grantee " +
2152  granteeName + " does not exist.");
2153  }
2154  sys_write_lock write_lock(this);
2155  if (!grantee->hasRole(rl, true)) {
2156  grantee->grantRole(rl);
2157  if (!is_temporary) {
2158  sys_sqlite_lock sqlite_lock(this);
2159  sqliteConnector_->query_with_text_params(
2160  "INSERT INTO mapd_roles(roleName, userName) VALUES (?, ?)",
2161  std::vector<std::string>{rl->getName(), grantee->getName()});
2162  }
2163  }
2164 }
Grantee * getGrantee(const std::string &name) const
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
Role * getRoleGrantee(const std::string &name) const
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::grantRoleBatch ( const std::vector< std::string > &  roles,
const std::vector< std::string > &  grantees 
)

Definition at line 2663 of file SysCatalog.cpp.

References execInTransaction(), and grantRoleBatch_unsafe().

Referenced by Catalog_Namespace::Catalog::createDashboardSystemRoles().

2664  {
2666 }
void grantRoleBatch_unsafe(const std::vector< std::string > &roles, const std::vector< std::string > &grantees)
void execInTransaction(F &&f, Args &&...args)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::grantRoleBatch_unsafe ( const std::vector< std::string > &  roles,
const std::vector< std::string > &  grantees 
)
private

Definition at line 2126 of file SysCatalog.cpp.

References getMetadataForUser(), grantRole_unsafe(), and Catalog_Namespace::UserMetadata::is_temporary.

Referenced by grantRoleBatch().

2127  {
2128  for (const auto& role : roles) {
2129  for (const auto& grantee : grantees) {
2130  bool is_temporary_user{false};
2131  UserMetadata user;
2132  if (getMetadataForUser(grantee, user)) {
2133  is_temporary_user = user.is_temporary;
2134  }
2135  grantRole_unsafe(role, grantee, is_temporary_user);
2136  }
2137  }
2138 }
bool getMetadataForUser(const std::string &name, UserMetadata &user)
void grantRole_unsafe(const std::string &roleName, const std::string &granteeName, const bool is_temporary)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::hasAnyPrivileges ( const UserMetadata user,
std::vector< DBObject > &  privObjects 
)

Definition at line 2301 of file SysCatalog.cpp.

References getUserGrantee(), instance(), Catalog_Namespace::UserMetadata::isSuper, Catalog_Namespace::UserMetadata::userLoggable(), and Catalog_Namespace::UserMetadata::userName.

2302  {
2303  sys_read_lock read_lock(this);
2304  if (user.isSuper) {
2305  return true;
2306  }
2307  auto* user_rl = instance().getUserGrantee(user.userName);
2308  if (!user_rl) {
2309  throw runtime_error("Cannot check privileges. User " + user.userLoggable() +
2310  " does not exist.");
2311  }
2312  for (std::vector<DBObject>::iterator objectIt = privObjects.begin();
2313  objectIt != privObjects.end();
2314  ++objectIt) {
2315  if (!user_rl->hasAnyPrivileges(*objectIt, false)) {
2316  return false;
2317  }
2318  }
2319  return true;
2320 }
static SysCatalog & instance()
Definition: SysCatalog.h:337
User * getUserGrantee(const std::string &name) const
mapd_shared_lock< mapd_shared_mutex > read_lock
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:120

+ Here is the call graph for this function:

bool Catalog_Namespace::SysCatalog::hasExecutedMigration ( const std::string &  migration_name) const

Definition at line 2956 of file SysCatalog.cpp.

References hasVersionHistoryTable(), and sqliteConnector_.

Referenced by initializeInformationSchemaDb().

2956  {
2957  if (hasVersionHistoryTable()) {
2958  sys_sqlite_lock sqlite_lock(this);
2959  sqliteConnector_->query_with_text_params(
2960  "SELECT migration_history FROM mapd_version_history WHERE migration_history = ?",
2961  std::vector<std::string>{migration_name});
2962  return (sqliteConnector_->getNumRows() > 0);
2963  }
2964  return false;
2965 }
bool hasVersionHistoryTable() const
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::hasVersionHistoryTable ( ) const
private

Definition at line 2977 of file SysCatalog.cpp.

References sqliteConnector_.

Referenced by hasExecutedMigration(), and recordExecutedMigration().

2977  {
2978  sys_sqlite_lock sqlite_lock(this);
2979  sqliteConnector_->query(
2980  "select name from sqlite_master WHERE type='table' AND "
2981  "name='mapd_version_history'");
2982  return (sqliteConnector_->getNumRows() > 0);
2983 }
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::importDataFromOldMapdDB ( )
private

Definition at line 301 of file SysCatalog.cpp.

References basePath_, logger::ERROR, logger::INFO, shared::kCatalogDirectoryName, shared::kSystemCatalogName, LOG, and sqliteConnector_.

301  {
302  sys_sqlite_lock sqlite_lock(this);
303  std::string mapd_db_path = basePath_ + "/" + shared::kCatalogDirectoryName + "/mapd";
304  sqliteConnector_->query("ATTACH DATABASE `" + mapd_db_path + "` as old_cat");
305  sqliteConnector_->query("BEGIN TRANSACTION");
306  LOG(INFO) << "Moving global metadata into a separate catalog";
307  try {
308  auto moveTableIfExists = [conn = sqliteConnector_.get()](const std::string& tableName,
309  bool deleteOld = true) {
310  conn->query("SELECT sql FROM old_cat.sqlite_master WHERE type='table' AND name='" +
311  tableName + "'");
312  if (conn->getNumRows() != 0) {
313  conn->query(conn->getData<string>(0, 0));
314  conn->query("INSERT INTO " + tableName + " SELECT * FROM old_cat." + tableName);
315  if (deleteOld) {
316  conn->query("DROP TABLE old_cat." + tableName);
317  }
318  }
319  };
320  moveTableIfExists("mapd_users");
321  moveTableIfExists("mapd_databases");
322  moveTableIfExists("mapd_roles");
323  moveTableIfExists("mapd_object_permissions");
324  moveTableIfExists("mapd_privileges");
325  moveTableIfExists("mapd_version_history", false);
326  } catch (const std::exception& e) {
327  LOG(ERROR) << "Failed to move global metadata into a separate catalog: " << e.what();
328  sqliteConnector_->query("ROLLBACK TRANSACTION");
329  try {
330  sqliteConnector_->query("DETACH DATABASE old_cat");
331  } catch (const std::exception&) {
332  // nothing to do here
333  }
334  throw;
335  }
336  sqliteConnector_->query("END TRANSACTION");
337  const std::string sys_catalog_path =
338  basePath_ + "/" + shared::kCatalogDirectoryName + "/" + shared::kSystemCatalogName;
339  LOG(INFO) << "Global metadata has been successfully moved into a separate catalog: "
340  << sys_catalog_path
341  << ". Using this database with an older version of heavydb "
342  "is now impossible.";
343  try {
344  sqliteConnector_->query("DETACH DATABASE old_cat");
345  } catch (const std::exception&) {
346  // nothing to do here
347  }
348 }
#define LOG(tag)
Definition: Logger.h:217
const std::string kSystemCatalogName
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
const std::string kCatalogDirectoryName
void Catalog_Namespace::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 
)

Definition at line 162 of file SysCatalog.cpp.

References anonymous_namespace{SysCatalog.cpp}::copy_catalog_if_read_only(), shared::kCatalogDirectoryName, and shared::kSystemCatalogName.

168  {
169  {
171  sys_sqlite_lock sqlite_lock(this);
172 
173  basePath_ = copy_catalog_if_read_only(basePath).string();
174  dataMgr_ = dataMgr;
175  authMetadata_ = &authMetadata;
176  pki_server_.reset(new PkiServer(*authMetadata_));
177  calciteMgr_ = calcite;
178  string_dict_hosts_ = string_dict_hosts;
179  aggregator_ = aggregator;
180  bool db_exists =
181  boost::filesystem::exists(basePath_ + "/" + shared::kCatalogDirectoryName + "/" +
183  sqliteConnector_.reset(
186  if (is_new_db) {
187  initDB();
188  } else {
189  if (!db_exists) {
191  }
193  }
194  buildRoleMap();
197  if (!is_new_db) {
198  // We don't want to create the information schema db during database initialization
199  // because we don't have the appropriate context to intialize the tables. For
200  // instance if the server is intended to run in distributed mode, initializing the
201  // table as part of initdb will be missing information such as the location of the
202  // string dictionary server.
204  }
205  }
206 }
const std::string kSystemCatalogName
std::unique_ptr< PkiServer > pki_server_
Definition: SysCatalog.h:484
const AuthMetadata * authMetadata_
Definition: SysCatalog.h:485
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::shared_ptr< Data_Namespace::DataMgr > dataMgr_
Definition: SysCatalog.h:483
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
const std::string kCatalogDirectoryName
std::vector< LeafHostInfo > string_dict_hosts_
Definition: SysCatalog.h:487
std::shared_ptr< Calcite > calciteMgr_
Definition: SysCatalog.h:486
mapd_unique_lock< mapd_shared_mutex > write_lock
std::filesystem::path copy_catalog_if_read_only(std::filesystem::path base_data_path)
Definition: SysCatalog.cpp:81

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::initDB ( )
private

Definition at line 224 of file SysCatalog.cpp.

References createDatabase(), createRole_unsafe(), anonymous_namespace{SysCatalog.cpp}::hash_with_bcrypt(), shared::kDefaultDbName, shared::kDefaultRootPasswd, shared::kRootUserId, shared::kRootUserIdStr, shared::kRootUsername, and sqliteConnector_.

224  {
225  sys_sqlite_lock sqlite_lock(this);
226  sqliteConnector_->query("BEGIN TRANSACTION");
227  try {
228  sqliteConnector_->query(
229  "CREATE TABLE mapd_users (userid integer primary key, name text unique, "
230  "passwd_hash text, issuper boolean, default_db integer references "
231  "mapd_databases, can_login boolean)");
232  sqliteConnector_->query_with_text_params(
233  "INSERT INTO mapd_users VALUES (?, ?, ?, 1, NULL, 1)",
234  std::vector<std::string>{shared::kRootUserIdStr,
237  sqliteConnector_->query(
238  "CREATE TABLE mapd_databases (dbid integer primary key, name text unique, owner "
239  "integer references mapd_users)");
240  sqliteConnector_->query(
241  "CREATE TABLE mapd_roles(roleName text, userName text, UNIQUE(roleName, "
242  "userName))");
243  sqliteConnector_->query(
244  "CREATE TABLE mapd_object_permissions ("
245  "roleName text, "
246  "roleType bool, "
247  "dbId integer references mapd_databases, "
248  "objectName text, "
249  "objectId integer, "
250  "objectPermissionsType integer, "
251  "objectPermissions integer, "
252  "objectOwnerId integer, UNIQUE(roleName, objectPermissionsType, dbId, "
253  "objectId))");
254  } catch (const std::exception&) {
255  sqliteConnector_->query("ROLLBACK TRANSACTION");
256  throw;
257  }
258  sqliteConnector_->query("END TRANSACTION");
261  shared::kRootUsername, /*userPrivateRole=*/true, /*is_temporary=*/false);
262 }
const int kRootUserId
void createRole_unsafe(const std::string &roleName, const bool userPrivateRole, const bool is_temporary)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
const std::string kDefaultDbName
std::string hash_with_bcrypt(const std::string &pwd)
Definition: SysCatalog.cpp:73
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
const std::string kRootUsername
const std::string kDefaultRootPasswd
const std::string kRootUserIdStr
void createDatabase(const std::string &dbname, int owner)

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::initializeInformationSchemaDb ( )
private

Definition at line 2935 of file SysCatalog.cpp.

References createDatabase(), dropDatabase(), g_enable_system_tables, getMetadataForDB(), hasExecutedMigration(), shared::kInfoSchemaDbName, shared::kInfoSchemaMigrationName, shared::kRootUserId, LOG, recordExecutedMigration(), and logger::WARNING.

2935  {
2937  sys_write_lock write_lock(this);
2938  DBMetadata db_metadata;
2939  if (getMetadataForDB(shared::kInfoSchemaDbName, db_metadata)) {
2940  LOG(WARNING) << "A database with name \"" << shared::kInfoSchemaDbName
2941  << "\" already exists. System table creation will be skipped. Rename "
2942  "this database in order to use system tables.";
2943  } else {
2945  try {
2947  } catch (...) {
2949  dropDatabase(db_metadata);
2950  throw;
2951  }
2952  }
2953  }
2954 }
void recordExecutedMigration(const std::string &migration_name) const
const int kRootUserId
#define LOG(tag)
Definition: Logger.h:217
void dropDatabase(const DBMetadata &db)
const std::string kInfoSchemaDbName
bool g_enable_system_tables
Definition: SysCatalog.cpp:66
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
mapd_unique_lock< mapd_shared_mutex > write_lock
bool hasExecutedMigration(const std::string &migration_name) const
void createDatabase(const std::string &dbname, int owner)
const std::string kInfoSchemaMigrationName
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

static SysCatalog& Catalog_Namespace::SysCatalog::instance ( )
inlinestatic

Definition at line 337 of file SysCatalog.h.

References instance_, and SysCatalog().

Referenced by foreign_storage::cache_blocks(), AlterForeignServerCommand::changeForeignServerOwner(), Catalog_Namespace::SessionInfo::checkDBAccessPrivileges(), checkPermissionForTables(), checkPrivileges(), QueryRunner::QueryRunner::clearCpuMemory(), QueryRunner::QueryRunner::clearGpuMemory(), Executor::clearMemory(), Catalog_Namespace::Catalog::createDashboardSystemRoles(), createDBObject(), foreign_storage::ForeignDataWrapperFactory::createForeignTableProxy(), Catalog_Namespace::Catalog::createOrUpdateDashboardSystemRole(), foreign_storage::AbstractTextFileDataWrapper::createRenderGroupAnalyzers(), foreign_storage::ParquetDataWrapper::createRenderGroupAnalyzers(), QueryRunner::QueryRunner::createStatement(), Catalog_Namespace::Catalog::deleteMetadataForDashboards(), CreateForeignServerCommand::execute(), DropForeignServerCommand::execute(), CreateForeignTableCommand::execute(), ShowDatabasesCommand::execute(), ShowUserDetailsCommand::execute(), ShowRolesCommand::execute(), RefreshForeignTablesCommand::execute(), foreign_storage::ParquetDataWrapper::fetchChunkMetadata(), foreign_storage::ForeignTableSchema::ForeignTableSchema(), foreign_storage::anonymous_namespace{InternalCatalogDataWrapper.cpp}::get_all_dashboards(), foreign_storage::anonymous_namespace{InternalCatalogDataWrapper.cpp}::get_all_role_assignments(), foreign_storage::anonymous_namespace{InternalCatalogDataWrapper.cpp}::get_all_tables(), foreign_storage::anonymous_namespace{InternalMemoryStatsDataWrapper.cpp}::get_column_name(), foreign_storage::get_db_name(), foreign_storage::get_foreign_table_for_key(), foreign_storage::anonymous_namespace{InternalCatalogDataWrapper.cpp}::get_table_ddl(), foreign_storage::get_table_name(), Catalog_Namespace::anonymous_namespace{Catalog.cpp}::get_user_id_to_user_name_map(), foreign_storage::anonymous_namespace{InternalCatalogDataWrapper.cpp}::get_user_name(), QueryRunner::QueryRunner::getBufferPoolStats(), foreign_storage::ParseBufferRequest::getCatalog(), foreign_storage::ParquetImportBatchResult::getChunksAndDictionaries(), foreign_storage::ParquetDataWrapper::getColumnsToInitialize(), getDBObjectPrivileges(), QueryRunner::QueryRunner::getExecutor(), Executor::getExecutor(), QueryRunner::QueryRunner::getMemoryInfo(), Catalog_Namespace::Catalog::getObjForLock(), QueryRunner::QueryRunner::getParsedGlobalQueryHints(), QueryRunner::QueryRunner::getParsedQueryHint(), QueryRunner::QueryRunner::getParsedQueryHints(), QueryRunner::QueryRunner::getQueryInfoForDataRecyclerTest(), QueryRunner::QueryRunner::getRaExecutionSequence(), QueryRunner::QueryRunner::getRelAlgTranslator(), QueryRunner::QueryRunner::getRootNodeFromParsedQuery(), grantDBObjectPrivileges_unsafe(), hasAnyPrivileges(), EmbeddedDatabase::DBEngineImpl::importArrowTable(), foreign_storage::init_chunk_for_column(), foreign_storage::Csv::init_chunk_for_column(), foreign_storage::InternalCatalogDataWrapper::initializeObjectsForTable(), foreign_storage::InternalMemoryStatsDataWrapper::initializeObjectsForTable(), foreign_storage::InternalStorageStatsDataWrapper::initializeObjectsForTable(), PersistentStorageMgr::isForeignStorage(), isRoleGrantedToGrantee(), foreign_storage::ParquetDataWrapper::loadBuffersUsingLazyParquetChunkLoader(), DBObject::loadKey(), main(), foreign_storage::InternalSystemDataWrapper::populateChunkBuffers(), foreign_storage::AbstractTextFileDataWrapper::populateChunkBuffers(), foreign_storage::InternalSystemDataWrapper::populateChunkMetadata(), foreign_storage::AbstractTextFileDataWrapper::populateChunkMetadata(), QueryRunner::QueryRunner::QueryRunner(), Catalog_Namespace::Catalog::recordOwnershipOfObjectsInObjectPermissions(), Catalog_Namespace::Catalog::removeTableFromMap(), AlterForeignServerCommand::renameForeignServer(), revokeDBObjectPrivileges_unsafe(), QueryRunner::QueryRunner::runDDLStatement(), QueryRunner::QueryRunner::runSelectQuery(), QueryRunner::QueryRunner::runSQL(), QueryRunner::QueryRunner::runSQLWithAllowingInterrupt(), EmbeddedDatabase::DBEngineImpl::setDatabase(), foreign_storage::ForeignTableRefreshScheduler::start(), foreign_storage::AbstractTextFileDataWrapper::updateMetadata(), verifyDBObjectOwnership(), and Catalog_Namespace::UserAlterations::wouldChange().

337  {
338  if (!instance_) {
339  instance_.reset(new SysCatalog());
340  }
341  return *instance_;
342  }
static std::unique_ptr< SysCatalog > instance_
Definition: SysCatalog.h:497

+ Here is the call graph for this function:

bool Catalog_Namespace::SysCatalog::isAggregator ( ) const
inline

Definition at line 336 of file SysCatalog.h.

References aggregator_.

336 { return aggregator_; }
bool Catalog_Namespace::SysCatalog::isDashboardSystemRole ( const std::string &  roleName) const
private

Definition at line 2418 of file SysCatalog.cpp.

References SYSTEM_ROLE_TAG().

Referenced by getCreatedRoles(), getMetadataForAllObjects(), and getRoles().

2418  {
2419  return boost::algorithm::ends_with(roleName, SYSTEM_ROLE_TAG);
2420 }
static const std::string SYSTEM_ROLE_TAG("#dash_system_role")
specifies the content in-memory of a row in the dashboard

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

bool Catalog_Namespace::SysCatalog::isRoleGrantedToGrantee ( const std::string &  granteeName,
const std::string &  roleName,
bool  only_direct 
) const

Definition at line 2396 of file SysCatalog.cpp.

References CHECK, getRoleGrantee(), getUserGrantee(), Grantee::hasRole(), and instance().

Referenced by getRoles().

2398  {
2399  sys_read_lock read_lock(this);
2400  if (roleName == granteeName) {
2401  return true;
2402  }
2403  bool is_role_granted = false;
2404  auto* target_role = instance().getRoleGrantee(roleName);
2405  auto has_role = [&](auto grantee_rl) {
2406  is_role_granted = target_role && grantee_rl->hasRole(target_role, only_direct);
2407  };
2408  if (auto* user_role = instance().getUserGrantee(granteeName); user_role) {
2409  has_role(user_role);
2410  } else if (auto* role = instance().getRoleGrantee(granteeName); role) {
2411  has_role(role);
2412  } else {
2413  CHECK(false);
2414  }
2415  return is_role_granted;
2416 }
static SysCatalog & instance()
Definition: SysCatalog.h:337
Role * getRoleGrantee(const std::string &name) const
User * getUserGrantee(const std::string &name) const
bool hasRole(Role *role, bool only_direct) const
Definition: Grantee.cpp:55
mapd_shared_lock< mapd_shared_mutex > read_lock
#define CHECK(condition)
Definition: Logger.h:223
read_lock< SysCatalog > sys_read_lock
Definition: Catalog.cpp:120

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::shared_ptr< Catalog > Catalog_Namespace::SysCatalog::login ( std::string &  db,
std::string &  username,
const std::string &  password,
UserMetadata user_meta,
bool  check_password = true 
)

logins (connects) a user against a database.

throws a std::exception in all error cases! (including wrong password)

Definition at line 805 of file SysCatalog.cpp.

References Catalog_Namespace::UserMetadata::can_login, getCatalog(), getMetadataForUser(), getMetadataWithDefaultDB(), and loginImpl().

809  {
810  // NOTE(sy): The dbname isn't const because getMetadataWithDefaultDB()
811  // can reset it. The username isn't const because SamlServer's
812  // login()/authenticate_user() can reset it.
813 
814  if (check_password) {
815  loginImpl(username, password, user_meta);
816  } else { // not checking for password so user must exist
817  if (!getMetadataForUser(username, user_meta)) {
818  throw std::runtime_error("Invalid credentials.");
819  }
820  }
821  // we should have a user and user_meta by now
822  if (!user_meta.can_login) {
823  throw std::runtime_error("Unauthorized Access: User " + username + " is deactivated");
824  }
826  getMetadataWithDefaultDB(dbname, username, db_meta, user_meta);
827  return getCatalog(db_meta, false);
828 }
bool getMetadataForUser(const std::string &name, UserMetadata &user)
void loginImpl(std::string &username, const std::string &password, UserMetadata &user_meta)
Definition: SysCatalog.cpp:831
void getMetadataWithDefaultDB(std::string &dbname, const std::string &username, Catalog_Namespace::DBMetadata &db_meta, UserMetadata &user_meta)
std::shared_ptr< Catalog > getCatalog(const std::string &dbName)

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::loginImpl ( std::string &  username,
const std::string &  password,
UserMetadata user_meta 
)
private

Definition at line 831 of file SysCatalog.cpp.

References checkPasswordForUser().

Referenced by login().

833  {
834  if (!checkPasswordForUser(password, username, user_meta)) {
835  throw std::runtime_error("Authentication failure");
836  }
837 }
bool checkPasswordForUser(const std::string &passwd, std::string &name, UserMetadata &user)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::migrateDBAccessPrivileges ( )
private

Definition at line 710 of file SysCatalog.cpp.

References AccessPrivileges::ACCESS, CHECK, DatabaseDBObjectType, DBObjectKey::dbId, Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::DBMetadata::dbName, Catalog_Namespace::DBMetadata::dbOwner, logger::ERROR, getMetadataForDB(), logger::INFO, Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::insertOrUpdateObjectPrivileges(), shared::kRootUserId, LOG, MAPD_VERSION, DBObjectKey::permissionType, DBObject::setName(), DBObject::setObjectType(), sqliteConnector_, to_string(), DBObject::updatePrivileges(), and AccessPrivileges::VIEW_SQL_EDITOR.

Referenced by checkAndExecuteMigrations().

710  {
711  sys_sqlite_lock sqlite_lock(this);
712  sqliteConnector_->query("BEGIN TRANSACTION");
713  try {
714  sqliteConnector_->query(
715  "select name from sqlite_master WHERE type='table' AND "
716  "name='mapd_version_history'");
717  if (sqliteConnector_->getNumRows() == 0) {
718  sqliteConnector_->query(
719  "CREATE TABLE mapd_version_history(version integer, migration_history text "
720  "unique)");
721  } else {
722  sqliteConnector_->query(
723  "select * from mapd_version_history where migration_history = "
724  "'db_access_privileges'");
725  if (sqliteConnector_->getNumRows() != 0) {
726  // both privileges migrated
727  // no need for further execution
728  sqliteConnector_->query("END TRANSACTION");
729  return;
730  }
731  }
732  // Insert check for migration
733  sqliteConnector_->query_with_text_params(
734  "INSERT INTO mapd_version_history(version, migration_history) values(?,?)",
735  std::vector<std::string>{std::to_string(MAPD_VERSION), "db_access_privileges"});
736 
737  sqliteConnector_->query("select dbid, name from mapd_databases");
738  std::unordered_map<int, string> databases;
739  for (size_t i = 0; i < sqliteConnector_->getNumRows(); ++i) {
740  databases[sqliteConnector_->getData<int>(i, 0)] =
741  sqliteConnector_->getData<string>(i, 1);
742  }
743 
744  sqliteConnector_->query("select userid, name from mapd_users");
745  std::unordered_map<int, string> users;
746  for (size_t i = 0; i < sqliteConnector_->getNumRows(); ++i) {
747  users[sqliteConnector_->getData<int>(i, 0)] =
748  sqliteConnector_->getData<string>(i, 1);
749  }
750 
751  // All existing users by default will be granted DB Access permissions
752  // and view sql editor privileges
753  DBMetadata dbmeta;
754  for (auto db_ : databases) {
755  CHECK(getMetadataForDB(db_.second, dbmeta));
756  for (auto user : users) {
757  if (user.first != shared::kRootUserId) {
758  {
759  DBObjectKey key;
761  key.dbId = dbmeta.dbId;
762 
763  // access permission;
764  DBObject object_access(key, AccessPrivileges::ACCESS, dbmeta.dbOwner);
765  object_access.setObjectType(DBObjectType::DatabaseDBObjectType);
766  object_access.setName(dbmeta.dbName);
767  // sql_editor permission
768  DBObject object_editor(
769  key, AccessPrivileges::VIEW_SQL_EDITOR, dbmeta.dbOwner);
770  object_editor.setObjectType(DBObjectType::DatabaseDBObjectType);
771  object_editor.setName(dbmeta.dbName);
772  object_editor.updatePrivileges(object_access);
774  sqliteConnector_, user.second, true, object_editor);
775  }
776  }
777  }
778  }
779  } catch (const std::exception& e) {
780  LOG(ERROR) << "Failed to migrate db access privileges: " << e.what();
781  sqliteConnector_->query("ROLLBACK TRANSACTION");
782  throw;
783  }
784  sqliteConnector_->query("END TRANSACTION");
785  LOG(INFO) << "Successfully migrated db access privileges";
786 }
static const AccessPrivileges VIEW_SQL_EDITOR
Definition: DBObject.h:154
const int kRootUserId
#define LOG(tag)
Definition: Logger.h:217
void insertOrUpdateObjectPrivileges(std::unique_ptr< SqliteConnector > &sqliteConnector, std::string roleName, bool userRole, const DBObject &object)
Definition: SysCatalog.cpp:419
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
static const int32_t MAPD_VERSION
Definition: release.h:33
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
int32_t dbId
Definition: DBObject.h:56
static const AccessPrivileges ACCESS
Definition: DBObject.h:155
#define CHECK(condition)
Definition: Logger.h:223
int32_t permissionType
Definition: DBObject.h:55
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::migratePrivileged_old ( )
private

Definition at line 788 of file SysCatalog.cpp.

References sqliteConnector_.

Referenced by checkAndExecuteMigrations().

788  {
789  sys_sqlite_lock sqlite_lock(this);
790 
791  sqliteConnector_->query("BEGIN TRANSACTION");
792  try {
793  sqliteConnector_->query(
794  "CREATE TABLE IF NOT EXISTS mapd_privileges (userid integer references "
795  "mapd_users, dbid integer references "
796  "mapd_databases, select_priv boolean, insert_priv boolean, UNIQUE(userid, "
797  "dbid))");
798  } catch (const std::exception& e) {
799  sqliteConnector_->query("ROLLBACK TRANSACTION");
800  throw;
801  }
802  sqliteConnector_->query("END TRANSACTION");
803 }
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::migratePrivileges ( )
private

Definition at line 452 of file SysCatalog.cpp.

References AccessPrivileges::ALL_DASHBOARD_MIGRATE, AccessPrivileges::ALL_TABLE_MIGRATE, AccessPrivileges::ALL_VIEW_MIGRATE, DashboardDBObjectType, DatabaseDBObjectType, Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::insertOrUpdateObjectPrivileges(), shared::kRootUserId, AccessPrivileges::NONE, sqliteConnector_, TableDBObjectType, run_benchmark_import::type, and ViewDBObjectType.

Referenced by checkAndExecuteMigrations().

452  {
453  sys_sqlite_lock sqlite_lock(this);
454  sqliteConnector_->query("BEGIN TRANSACTION");
455  try {
456  sqliteConnector_->query(
457  "SELECT name FROM sqlite_master WHERE type='table' AND "
458  "name='mapd_object_permissions'");
459  if (sqliteConnector_->getNumRows() != 0) {
460  // already done
461  sqliteConnector_->query("END TRANSACTION");
462  return;
463  }
464 
465  sqliteConnector_->query(
466  "CREATE TABLE IF NOT EXISTS mapd_object_permissions ("
467  "roleName text, "
468  "roleType bool, "
469  "dbId integer references mapd_databases, "
470  "objectName text, "
471  "objectId integer, "
472  "objectPermissionsType integer, "
473  "objectPermissions integer, "
474  "objectOwnerId integer, UNIQUE(roleName, objectPermissionsType, dbId, "
475  "objectId))");
476 
477  // get the list of databases and their grantees
478  sqliteConnector_->query(
479  "SELECT userid, dbid FROM mapd_privileges WHERE select_priv = 1 and insert_priv "
480  "= 1");
481  size_t numRows = sqliteConnector_->getNumRows();
482  vector<pair<int, int>> db_grantees(numRows);
483  for (size_t i = 0; i < numRows; ++i) {
484  db_grantees[i].first = sqliteConnector_->getData<int>(i, 0);
485  db_grantees[i].second = sqliteConnector_->getData<int>(i, 1);
486  }
487  // map user names to user ids
488  sqliteConnector_->query("select userid, name from mapd_users");
489  numRows = sqliteConnector_->getNumRows();
490  std::unordered_map<int, string> users_by_id;
491  std::unordered_map<int, bool> user_has_privs;
492  for (size_t i = 0; i < numRows; ++i) {
493  users_by_id[sqliteConnector_->getData<int>(i, 0)] =
494  sqliteConnector_->getData<string>(i, 1);
495  user_has_privs[sqliteConnector_->getData<int>(i, 0)] = false;
496  }
497  // map db names to db ids
498  sqliteConnector_->query("select dbid, name from mapd_databases");
499  numRows = sqliteConnector_->getNumRows();
500  std::unordered_map<int, string> dbs_by_id;
501  for (size_t i = 0; i < numRows; ++i) {
502  dbs_by_id[sqliteConnector_->getData<int>(i, 0)] =
503  sqliteConnector_->getData<string>(i, 1);
504  }
505  // migrate old privileges to new privileges: if user had insert access to database, he
506  // was a grantee
507  for (const auto& grantee : db_grantees) {
508  user_has_privs[grantee.first] = true;
509  auto dbName = dbs_by_id[grantee.second];
510  {
511  // table level permissions
513  DBObjectKey key{type, grantee.second};
514  DBObject object(
517  sqliteConnector_, users_by_id[grantee.first], true, object);
518  }
519 
520  {
521  // dashboard level permissions
523  DBObjectKey key{type, grantee.second};
524  DBObject object(dbName,
525  type,
526  key,
530  sqliteConnector_, users_by_id[grantee.first], true, object);
531  }
532 
533  {
534  // view level permissions
536  DBObjectKey key{type, grantee.second};
537  DBObject object(
540  sqliteConnector_, users_by_id[grantee.first], true, object);
541  }
542  }
543  for (auto user : user_has_privs) {
544  auto dbName = dbs_by_id[0];
545  if (user.second == false && user.first != shared::kRootUserId) {
546  {
548  DBObjectKey key{type, 0};
551  sqliteConnector_, users_by_id[user.first], true, object);
552  }
553  }
554  }
555  } catch (const std::exception&) {
556  sqliteConnector_->query("ROLLBACK TRANSACTION");
557  throw;
558  }
559  sqliteConnector_->query("END TRANSACTION");
560 }
const int kRootUserId
static const AccessPrivileges ALL_TABLE_MIGRATE
Definition: DBObject.h:158
void insertOrUpdateObjectPrivileges(std::unique_ptr< SqliteConnector > &sqliteConnector, std::string roleName, bool userRole, const DBObject &object)
Definition: SysCatalog.cpp:419
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
static const AccessPrivileges ALL_DASHBOARD_MIGRATE
Definition: DBObject.h:170
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
static const AccessPrivileges NONE
Definition: DBObject.h:150
static const AccessPrivileges ALL_VIEW_MIGRATE
Definition: DBObject.h:178

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

std::string Catalog_Namespace::SysCatalog::name ( ) const
inline

Definition at line 347 of file SysCatalog.h.

References shared::kDefaultDbName.

Referenced by alterUser(), buildRoleMap(), createUser(), and Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::get_users().

347 { return shared::kDefaultDbName; }
const std::string kDefaultDbName

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::populateRoleDbObjects ( const std::vector< DBObject > &  objects)

Definition at line 2543 of file SysCatalog.cpp.

References CHECK, getMetadataForUserById(), getUserGrantee(), Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::insertOrUpdateObjectPrivileges(), sqliteConnector_, and Catalog_Namespace::UserMetadata::userName.

Referenced by Catalog_Namespace::Catalog::recordOwnershipOfObjectsInObjectPermissions().

2543  {
2544  sys_write_lock write_lock(this);
2545  sys_sqlite_lock sqlite_lock(this);
2546  sqliteConnector_->query("BEGIN TRANSACTION");
2547  try {
2548  for (auto dbobject : objects) {
2549  UserMetadata user;
2550  CHECK(getMetadataForUserById(dbobject.getOwner(), user));
2551  auto* grantee = getUserGrantee(user.userName);
2552  if (grantee) {
2554  sqliteConnector_, grantee->getName(), true, dbobject);
2555  grantee->grantPrivileges(dbobject);
2556  }
2557  }
2558 
2559  } catch (const std::exception& e) {
2560  sqliteConnector_->query("ROLLBACK TRANSACTION");
2561  throw;
2562  }
2563  sqliteConnector_->query("END TRANSACTION");
2564 }
bool getMetadataForUserById(const int32_t idIn, UserMetadata &user)
void insertOrUpdateObjectPrivileges(std::unique_ptr< SqliteConnector > &sqliteConnector, std::string roleName, bool userRole, const DBObject &object)
Definition: SysCatalog.cpp:419
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
User * getUserGrantee(const std::string &name) const
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
#define CHECK(condition)
Definition: Logger.h:223
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::reassignObjectOwners ( const std::map< int32_t, std::vector< DBObject >> &  old_owner_db_objects,
int32_t  new_owner_id,
const Catalog_Namespace::Catalog catalog 
)

Reassigns database object ownership from a set of users (old owners) to another user (new owner).

Parameters
old_owner_db_objects- map of user ids and database objects whose ownership will be reassigned
new_owner_id- id of user who will own reassigned database objects
catalog- catalog for database where ownership reassignment occurred

Definition at line 2880 of file SysCatalog.cpp.

References CHECK, shared::contains(), Catalog_Namespace::Catalog::getDatabaseId(), getMetadataForUserById(), grantDBObjectPrivilegesBatch_unsafe(), granteeMap_, Catalog_Namespace::UserMetadata::isSuper, objectDescriptorMap_, rebuildObjectMaps(), revokeDBObjectPrivilegesBatch_unsafe(), sqliteConnector_, to_string(), and Catalog_Namespace::UserMetadata::userName.

2883  {
2884  sys_write_lock write_lock(this);
2885  sys_sqlite_lock sqlite_lock(this);
2886 
2887  sqliteConnector_->query("BEGIN TRANSACTION");
2888  try {
2889  UserMetadata new_owner;
2890  CHECK(getMetadataForUserById(new_owner_id, new_owner));
2891  for (const auto& [old_owner_id, db_objects] : old_owner_db_objects) {
2892  UserMetadata old_owner;
2893  CHECK(getMetadataForUserById(old_owner_id, old_owner));
2894  if (!old_owner.isSuper) {
2895  revokeDBObjectPrivilegesBatch_unsafe({old_owner.userName}, db_objects, catalog);
2896  }
2897  if (!new_owner.isSuper) {
2898  grantDBObjectPrivilegesBatch_unsafe({new_owner.userName}, db_objects, catalog);
2899  }
2900  }
2901 
2902  std::set<int32_t> old_owner_ids;
2903  for (const auto& [old_owner_id, db_objects] : old_owner_db_objects) {
2904  old_owner_ids.emplace(old_owner_id);
2905  }
2906 
2907  auto db_id = catalog.getDatabaseId();
2908  for (const auto old_user_id : old_owner_ids) {
2909  sqliteConnector_->query_with_text_params(
2910  "UPDATE mapd_object_permissions SET objectOwnerId = ? WHERE objectOwnerId = ? "
2911  "AND dbId = ? AND objectId != -1",
2912  std::vector<std::string>{std::to_string(new_owner_id),
2913  std::to_string(old_user_id),
2914  std::to_string(db_id)});
2915  }
2916 
2917  for (const auto& [user_or_role, grantee] : granteeMap_) {
2918  grantee->reassignObjectOwners(old_owner_ids, new_owner_id, db_id);
2919  }
2920 
2921  for (const auto& [object_key, object_descriptor] : objectDescriptorMap_) {
2922  if (object_descriptor->objectId != -1 && object_descriptor->dbId == db_id &&
2923  shared::contains(old_owner_ids, object_descriptor->objectOwnerId)) {
2924  object_descriptor->objectOwnerId = new_owner_id;
2925  }
2926  }
2927  } catch (std::exception& e) {
2928  sqliteConnector_->query("ROLLBACK TRANSACTION");
2930  throw;
2931  }
2932  sqliteConnector_->query("END TRANSACTION");
2933 }
bool contains(const T &container, const U &element)
Definition: misc.h:196
void revokeDBObjectPrivilegesBatch_unsafe(const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:480
bool getMetadataForUserById(const int32_t idIn, UserMetadata &user)
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
int getDatabaseId() const
Definition: Catalog.h:284
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
void grantDBObjectPrivilegesBatch_unsafe(const std::vector< std::string > &grantees, const std::vector< DBObject > &objects, const Catalog_Namespace::Catalog &catalog)
#define CHECK(condition)
Definition: Logger.h:223
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::rebuildObjectMaps ( )
private

Definition at line 2992 of file SysCatalog.cpp.

References buildObjectDescriptorMap(), buildRoleMap(), granteeMap_, and objectDescriptorMap_.

Referenced by changeDBObjectOwnership(), and reassignObjectOwners().

2992  {
2993  // Rebuild updated maps from storage
2994  granteeMap_.clear();
2995  buildRoleMap();
2996  objectDescriptorMap_.clear();
2998 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:480

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::recordExecutedMigration ( const std::string &  migration_name) const
private

Definition at line 2967 of file SysCatalog.cpp.

References createVersionHistoryTable(), hasVersionHistoryTable(), MAPD_VERSION, sqliteConnector_, and to_string().

Referenced by initializeInformationSchemaDb().

2967  {
2968  if (!hasVersionHistoryTable()) {
2970  }
2971  sys_sqlite_lock sqlite_lock(this);
2972  sqliteConnector_->query_with_text_params(
2973  "INSERT INTO mapd_version_history(version, migration_history) values(?, ?)",
2974  std::vector<std::string>{std::to_string(MAPD_VERSION), migration_name});
2975 }
std::string to_string(char const *&&v)
bool hasVersionHistoryTable() const
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
static const int32_t MAPD_VERSION
Definition: release.h:33
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
void createVersionHistoryTable() const

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::removeCatalog ( const std::string &  dbName)

Definition at line 2876 of file SysCatalog.cpp.

References cat_map_.

Referenced by createDatabase(), dropDatabase(), and renameDatabase().

2876  {
2877  cat_map_.erase(dbName);
2878 }

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::renameDatabase ( std::string const &  old_name,
std::string const &  new_name 
)

Definition at line 1255 of file SysCatalog.cpp.

References DatabaseDBObjectType, Catalog_Namespace::CommonFileOperations::duplicateAndRenameCatalog(), getMetadataForDB(), shared::kSystemCatalogName, removeCatalog(), Catalog_Namespace::CommonFileOperations::removeCatalogByFullPath(), sqliteConnector_, to_string(), to_upper(), and yieldTransactionStreamer().

1256  {
1257  using namespace std::string_literals;
1258  sys_write_lock write_lock(this);
1259  sys_sqlite_lock sqlite_lock(this);
1260 
1261  DBMetadata new_db;
1262  if (getMetadataForDB(new_name, new_db)) {
1263  throw std::runtime_error("Database " + new_name + " already exists.");
1264  }
1265  if (to_upper(new_name) == to_upper(shared::kSystemCatalogName)) {
1266  throw std::runtime_error("Database name " + new_name + "is reserved.");
1267  }
1268 
1269  DBMetadata old_db;
1270  if (!getMetadataForDB(old_name, old_db)) {
1271  throw std::runtime_error("Database " + old_name + " does not exists.");
1272  }
1273 
1274  removeCatalog(old_db.dbName);
1275 
1276  std::string old_catalog_path, new_catalog_path;
1277  std::tie(old_catalog_path, new_catalog_path) =
1278  duplicateAndRenameCatalog(old_name, new_name);
1279 
1280  auto transaction_streamer = yieldTransactionStreamer();
1281  auto failure_handler = [this, new_catalog_path] {
1282  removeCatalogByFullPath(new_catalog_path);
1283  };
1284  auto success_handler = [this, old_catalog_path] {
1285  removeCatalogByFullPath(old_catalog_path);
1286  };
1287 
1288  auto q1 = {"UPDATE mapd_databases SET name=?1 WHERE name=?2;"s, new_name, old_name};
1289  auto q2 = {
1290  "UPDATE mapd_object_permissions SET objectName=?1 WHERE objectNAME=?2 and (objectPermissionsType=?3 or objectId = -1) and dbId=?4;"s,
1291  new_name,
1292  old_name,
1294  std::to_string(old_db.dbId)};
1295 
1296  transaction_streamer(sqliteConnector_, success_handler, failure_handler, q1, q2);
1297 }
auto duplicateAndRenameCatalog(std::string const &current_name, std::string const &new_name)
Definition: SysCatalog.cpp:145
void removeCatalog(const std::string &dbName)
const std::string kSystemCatalogName
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
std::string to_upper(const std::string &str)
mapd_unique_lock< mapd_shared_mutex > write_lock
void removeCatalogByFullPath(std::string const &full_path)
Definition: SysCatalog.cpp:137
bool getMetadataForDB(const std::string &name, DBMetadata &db)

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::renameDBObject ( const std::string &  objectName,
const std::string &  newName,
DBObjectType  type,
int32_t  objectId,
const Catalog_Namespace::Catalog catalog 
)

Renames an DBObject

Parameters
objectName- original DBObject name
newName- new name of DBObject
type- type of DBObject
objectId- original DBObject ID
catalog- Catalog instance object exists in

Definition at line 1752 of file SysCatalog.cpp.

References DBObjectKey::dbId, Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::Catalog::getCurrentDB(), getGrantee(), getMetadataForObject(), DBObjectKey::objectId, DBObjectKey::permissionType, Grantee::renameDbObject(), renameObjectsInDescriptorMap(), DBObject::setObjectKey(), and run_benchmark_import::type.

1756  {
1757  sys_write_lock write_lock(this);
1758  DBObject new_object(newName, type);
1759  DBObjectKey key;
1760  key.dbId = catalog.getCurrentDB().dbId;
1761  key.objectId = objectId;
1762  key.permissionType = type;
1763  new_object.setObjectKey(key);
1764  auto objdescs =
1765  getMetadataForObject(key.dbId, static_cast<int32_t>(type), key.objectId);
1766  for (auto obj : objdescs) {
1767  Grantee* grnt = getGrantee(obj->roleName);
1768  if (grnt) {
1769  grnt->renameDbObject(new_object);
1770  }
1771  }
1772  renameObjectsInDescriptorMap(new_object, catalog);
1773 }
Grantee * getGrantee(const std::string &name) const
int32_t objectId
Definition: DBObject.h:57
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:228
void renameObjectsInDescriptorMap(DBObject &object, const Catalog_Namespace::Catalog &cat)
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
int32_t dbId
Definition: DBObject.h:56
int32_t permissionType
Definition: DBObject.h:55
mapd_unique_lock< mapd_shared_mutex > write_lock
std::vector< ObjectRoleDescriptor * > getMetadataForObject(int32_t dbId, int32_t dbType, int32_t objectId) const
virtual void renameDbObject(const DBObject &object)
Definition: Grantee.cpp:121

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::renameObjectsInDescriptorMap ( DBObject object,
const Catalog_Namespace::Catalog cat 
)

Definition at line 2241 of file SysCatalog.cpp.

References Catalog_Namespace::DBMetadata::dbId, Catalog_Namespace::Catalog::getCurrentDB(), objectDescriptorMap_, sqliteConnector_, and to_string().

Referenced by renameDBObject().

2242  {
2243  sys_write_lock write_lock(this);
2244  sys_sqlite_lock sqlite_lock(this);
2245  auto range = objectDescriptorMap_.equal_range(
2246  std::to_string(cat.getCurrentDB().dbId) + ":" +
2247  std::to_string(object.getObjectKey().permissionType) + ":" +
2248  std::to_string(object.getObjectKey().objectId));
2249  for (auto d = range.first; d != range.second; ++d) {
2250  // rename object
2251  d->second->objectName = object.getName();
2252  }
2253 
2254  sqliteConnector_->query("BEGIN TRANSACTION");
2255  try {
2256  sqliteConnector_->query_with_text_params(
2257  "UPDATE mapd_object_permissions SET objectName = ?1 WHERE "
2258  "dbId = ?2 AND objectId = ?3",
2259  std::vector<std::string>{object.getName(),
2261  std::to_string(object.getObjectKey().objectId)});
2262  } catch (const std::exception& e) {
2263  sqliteConnector_->query("ROLLBACK TRANSACTION");
2264  throw;
2265  }
2266  sqliteConnector_->query("END TRANSACTION");
2267 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:480
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
const DBMetadata & getCurrentDB() const
Definition: Catalog.h:228
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::renameUser ( std::string const &  old_name,
std::string const &  new_name 
)

Definition at line 1206 of file SysCatalog.cpp.

References CHECK, Catalog_Namespace::g_log_user_id, getGrantee(), getMetadataForUser(), sqliteConnector_, temporary_users_by_name_, updateUserRoleName(), and yieldTransactionStreamer().

1206  {
1207  using namespace std::string_literals;
1208  sys_write_lock write_lock(this);
1209  sys_sqlite_lock sqlite_lock(this);
1210 
1211  UserMetadata old_user;
1212  if (!getMetadataForUser(old_name, old_user)) {
1213  std::string const loggable = g_log_user_id ? std::string("") : old_name + ' ';
1214  throw std::runtime_error("User " + loggable + "doesn't exist.");
1215  }
1216 
1217  UserMetadata new_user;
1218  if (getMetadataForUser(new_name, new_user)) {
1219  throw std::runtime_error("User " + new_user.userLoggable() + " already exists.");
1220  }
1221 
1222  if (getGrantee(new_name)) {
1223  std::string const loggable = g_log_user_id ? std::string("") : new_name + ' ';
1224  throw runtime_error(
1225  "Username " + loggable +
1226  "is same as one of existing grantees. User and role names should be unique.");
1227  }
1228 
1229  // Temporary user.
1230  if (old_user.is_temporary) {
1231  auto userit = temporary_users_by_name_.find(old_name);
1232  CHECK(userit != temporary_users_by_name_.end());
1233  auto node = temporary_users_by_name_.extract(userit);
1234  node.key() = new_name;
1235  temporary_users_by_name_.insert(std::move(node));
1236  userit->second->userName = new_name;
1237  updateUserRoleName(old_name, new_name);
1238  return;
1239  }
1240 
1241  // Normal user.
1242  auto transaction_streamer = yieldTransactionStreamer();
1243  auto failure_handler = [] {};
1244  auto success_handler = [this, &old_name, &new_name] {
1245  updateUserRoleName(old_name, new_name);
1246  };
1247  auto q1 = {"UPDATE mapd_users SET name=?1 where name=?2;"s, new_name, old_name};
1248  auto q2 = {"UPDATE mapd_object_permissions set roleName=?1 WHERE roleName=?2;"s,
1249  new_name,
1250  old_name};
1251  auto q3 = {"UPDATE mapd_roles set userName=?1 WHERE userName=?2;"s, new_name, old_name};
1252  transaction_streamer(sqliteConnector_, success_handler, failure_handler, q1, q2, q3);
1253 }
bool getMetadataForUser(const std::string &name, UserMetadata &user)
Grantee * getGrantee(const std::string &name) const
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unordered_map< std::string, std::shared_ptr< UserMetadata > > temporary_users_by_name_
Definition: SysCatalog.h:507
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
void updateUserRoleName(const std::string &roleName, const std::string &newName)
#define CHECK(condition)
Definition: Logger.h:223
mapd_unique_lock< mapd_shared_mutex > write_lock

+ Here is the call graph for this function:

void Catalog_Namespace::SysCatalog::revokeAllOnDatabase_unsafe ( const std::string &  roleName,
int32_t  dbId,
Grantee grantee 
)
private

Definition at line 1925 of file SysCatalog.cpp.

References objectDescriptorMap_, Grantee::revokeAllOnDatabase(), sqliteConnector_, temporary_users_by_name_, and to_string().

Referenced by dropDatabase(), and revokeDBObjectPrivileges_unsafe().

1927  {
1928  bool is_temporary =
1929  (temporary_users_by_name_.find(roleName) != temporary_users_by_name_.end());
1930  if (!is_temporary) {
1931  sys_sqlite_lock sqlite_lock(this);
1932  sqliteConnector_->query_with_text_params(
1933  "DELETE FROM mapd_object_permissions WHERE roleName = ?1 and dbId = ?2",
1934  std::vector<std::string>{roleName, std::to_string(dbId)});
1935  }
1936  grantee->revokeAllOnDatabase(dbId);
1937  for (auto d = objectDescriptorMap_.begin(); d != objectDescriptorMap_.end();) {
1938  if (d->second->roleName == roleName && d->second->dbId == dbId) {
1939  d = objectDescriptorMap_.erase(d);
1940  } else {
1941  d++;
1942  }
1943  }
1944 }
ObjectRoleDescriptorMap objectDescriptorMap_
Definition: SysCatalog.h:480
std::string to_string(char const *&&v)
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
std::unordered_map< std::string, std::shared_ptr< UserMetadata > > temporary_users_by_name_
Definition: SysCatalog.h:507
virtual void revokeAllOnDatabase(int32_t dbId)
Definition: Grantee.cpp:296
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::revokeDBObjectPrivileges ( const std::string &  grantee,
const DBObject object,
const Catalog_Namespace::Catalog catalog 
)

Definition at line 2699 of file SysCatalog.cpp.

References execInTransaction(), and revokeDBObjectPrivileges_unsafe().

Referenced by Catalog_Namespace::Catalog::createOrUpdateDashboardSystemRole().

2701  {
2703  &SysCatalog::revokeDBObjectPrivileges_unsafe, grantee, object, catalog);
2704 }
void revokeDBObjectPrivileges_unsafe(const std::string &granteeName, DBObject object, const Catalog_Namespace::Catalog &catalog)
void execInTransaction(F &&f, Args &&...args)

+ Here is the call graph for this function:

+ Here is the caller graph for this function:

void Catalog_Namespace::SysCatalog::revokeDBObjectPrivileges_unsafe ( const std::string &  granteeName,
DBObject  object,
const Catalog_Namespace::Catalog catalog 
)
private

Definition at line 1881 of file SysCatalog.cpp.

References DatabasePrivileges::ALL, DatabaseDBObjectType, deleteObjectDescriptorMap(), Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::deleteObjectPrivileges(), getGrantee(), getMetadataForUser(), Catalog_Namespace::anonymous_namespace{SysCatalog.cpp}::insertOrUpdateObjectPrivileges(), instance(), Catalog_Namespace::UserMetadata::is_temporary, Catalog_Namespace::UserMetadata::isSuper, revokeAllOnDatabase_unsafe(), sqliteConnector_, and updateObjectDescriptorMap().

Referenced by changeDBObjectOwnership(), revokeDBObjectPrivileges(), revokeDBObjectPrivilegesBatch_unsafe(), and revokeDBObjectPrivilegesFromAll_unsafe().

1884  {
1885  sys_write_lock write_lock(this);
1886 
1887  UserMetadata user_meta;
1888  bool is_temporary_user{false};
1889  if (instance().getMetadataForUser(granteeName, user_meta)) {
1890  if (user_meta.isSuper) {
1891  // super doesn't have explicit privileges so nothing to do
1892  return;
1893  }
1894  is_temporary_user = user_meta.is_temporary;
1895  }
1896  auto* grantee = getGrantee(granteeName);
1897  if (!grantee) {
1898  throw runtime_error("Request to revoke privileges from " + granteeName +
1899  " failed because role or user with this name does not exist.");
1900  }
1901  object.loadKey(catalog);
1902 
1903  if (object.getPrivileges().hasPermission(DatabasePrivileges::ALL) &&
1904  object.getObjectKey().permissionType == DatabaseDBObjectType) {
1905  return revokeAllOnDatabase_unsafe(granteeName, object.getObjectKey().dbId, grantee);
1906  }
1907 
1908  auto ret_object = grantee->revokePrivileges(object);
1909  if (ret_object) {
1910  if (!is_temporary_user) {
1911  sys_sqlite_lock sqlite_lock(this);
1913  sqliteConnector_, granteeName, grantee->isUser(), *ret_object);
1914  }
1915  updateObjectDescriptorMap(granteeName, *ret_object, grantee->isUser(), catalog);
1916  } else {
1917  if (!is_temporary_user) {
1918  sys_sqlite_lock sqlite_lock(this);
1919  deleteObjectPrivileges(sqliteConnector_, granteeName, grantee->isUser(), object);
1920  }
1921  deleteObjectDescriptorMap(granteeName, object, catalog);
1922  }
1923 }
void revokeAllOnDatabase_unsafe(const std::string &roleName, int32_t dbId, Grantee *grantee)
static const int32_t ALL
Definition: DBObject.h:79
bool getMetadataForUser(const std::string &name, UserMetadata &user)
Grantee * getGrantee(const std::string &name) const
void insertOrUpdateObjectPrivileges(std::unique_ptr< SqliteConnector > &sqliteConnector, std::string roleName, bool userRole, const DBObject &object)
Definition: SysCatalog.cpp:419
sqlite_lock< SysCatalog > sys_sqlite_lock
Definition: SysCatalog.cpp:125
static SysCatalog & instance()
Definition: SysCatalog.h:337
write_lock< SysCatalog > sys_write_lock
Definition: SysCatalog.cpp:124
std::unique_ptr< SqliteConnector > sqliteConnector_
Definition: SysCatalog.h:481
void deleteObjectDescriptorMap(const std::string &roleName)
void updateObjectDescriptorMap(const std::string &roleName, DBObject &object, bool roleType, const Catalog_Namespace::Catalog &cat)
void deleteObjectPrivileges(std::unique_ptr< SqliteConnector > &sqliteConnector, std::string roleName, bool userRole, D