Распространённые вопросы по управлению доступом
Если вы работаете с самостоятельно управляемым (self-managed) ClickHouse, см. раздел SQL-пользователи и роли.
В этой статье рассматриваются основы создания SQL-пользователей и ролей и назначения привилегий и прав доступа к базам данных, таблицам, строкам и столбцам.
Пользователь-администратор
В сервисах ClickHouse Cloud есть пользователь-администратор default, который создаётся при создании сервиса. Пароль задаётся при создании сервиса, и его могут сбросить пользователи ClickHouse Cloud с ролью Admin.
Когда вы добавляете дополнительных SQL‑пользователей для своего сервиса ClickHouse Cloud, им понадобятся имя SQL‑пользователя и пароль. Если вы хотите предоставить им привилегии уровня администратора, назначьте новому пользователю (пользователям) роль default_role. Например, добавление пользователя clickhouse_admin:
При использовании SQL Console ваши SQL-запросы не будут выполняться от имени пользователя default. Вместо этого они будут выполняться от имени пользователя с именем sql-console:${cloud_login_email}, где cloud_login_email — это адрес электронной почты пользователя, который в данный момент выполняет запрос.
Эти автоматически создаваемые пользователи SQL Console имеют роль default.
Аутентификация без пароля
Для SQL-консоли доступны две роли: sql_console_admin с правами, идентичными default_role, и sql_console_read_only с правами только на чтение.
Пользователи-администраторы по умолчанию получают роль sql_console_admin, поэтому для них ничего не меняется. Однако роль sql_console_read_only позволяет предоставлять пользователям без прав администратора доступ только на чтение или полный доступ к любому экземпляру. Настроить этот доступ должен администратор. Роли можно изменять с помощью команд GRANT или REVOKE, чтобы лучше соответствовать требованиям конкретного экземпляра; все изменения этих ролей будут сохраняться.
Тонкий контроль доступа
Эту функциональность контроля доступа также можно настроить вручную с точностью до отдельных пользователей. Перед назначением пользователям новых ролей sql_console_* необходимо создать роли баз данных для пользователей SQL-консоли, соответствующие пространству имен sql-console-role:<email>. Например:
Когда обнаруживается подходящая роль, она назначается пользователю вместо базовых ролей. Это позволяет настраивать более сложное управление доступом, например создавать роли sql_console_sa_role и sql_console_pm_role и назначать их конкретным пользователям. Например:
Test admin privileges
Log out as the user default and log back in as user clickhouse_admin.
All of these should succeed:
Non-admin users
Users should have the privileges necessary, and not all be admin users. The rest of this document provides example scenarios and the roles required.
Preparation
Create these tables and users to be used in the examples.
Creating a sample database, table, and rows
Create a test database
Create a table
Populate the table with sample rows
Create column_user
Create a regular user that will be used to demonstrate restrict access to certain columns:
Create row_user
Create a regular user that will be used to demonstrate restricting access to rows with certain values:
Creating roles
With this set of examples:
- roles for different privileges, such as columns and rows will be created
- privileges will be granted to the roles
- users will be assigned to each role
Roles are used to define groups of users for certain privileges instead of managing each user separately.
Create a role to restrict users of this role to only see column1 in database db1 and table1:
Set privileges to allow view on column1
Add the column_user user to the column1_users role
Create a role to restrict users of this role to only see selected rows, in this case, only rows containing A in column1
Add the row_user to the A_rows_users role
Create a policy to allow view on only where column1 has the values of A
Set privileges to the database and table
Grant explicit permissions for other roles to still have access to all rows
When attaching a policy to a table, the system will apply that policy, and only those users and roles defined will be able to do operations on the table, all others will be denied any operations. In order to not have the restrictive row policy applied to other users, another policy must be defined to allow other users and roles to have regular or other types of access.
Verification
Testing role privileges with column restricted user
Log into the clickhouse client using the clickhouse_admin user
Log into the ClickHouse client using the column_user user
Test SELECT using all columns
Access is denied since all columns were specified and the user only has access to id and column1
Testing role privileges with row restricted user
Log into the ClickHouse client using row_user
View rows available
Verify that only the above two rows are returned, rows with the value B in column1 should be excluded.
Modifying users and roles
Users can be assigned multiple roles for a combination of privileges needed. When using multiple roles, the system will combine the roles to determine privileges, the net effect will be that the role permissions will be cumulative.
For example, if one role1 allows for only select on column1 and role2 allows for select on column1 and column2 then the user will have access to both columns.
Using the admin account, create new user to restrict by both row and column with default roles
Remove prior privileges for A_rows_users role
Allow A_row_users role to only select from column1
Log into the ClickHouse client using row_and_column_user
Troubleshooting
There are occasions when privileges intersect or combine to produce unexpected results, the following commands can be used to narrow the issue using an admin account
Listing the grants and roles for a user
List roles in ClickHouse
Display the policies
View how a policy was defined and current privileges
Example commands to manage roles, policies, and users
The following commands can be used to:
- delete privileges
- delete policies
- unassign users from roles
- delete users and roles
Run these commands as an admin user or the default user
Remove privilege from a role
Delete a policy
Unassign a user from a role
Delete a role
Delete a user
Summary
This article demonstrated the basics of creating SQL users and roles and provided steps to set and modify privileges for users and roles. For more detailed information on each please refer to our user guides and reference documentation.