8000 23.3 Backport of #47640 - Row policy for database by ilejn · Pull Request #300 · Altinity/ClickHouse · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion docs/en/operations/system-tables/row_policies.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ Columns:

- `database` ([String](../../sql-reference/data-types/string.md)) — Database name.

- `table` ([String](../../sql-reference/data-types/string.md)) — Table name.
- `table` ([String](../../sql-reference/data-types/string.md)) — Table name. Empty if policy for database.

- `id` ([UUID](../../sql-reference/data-types/uuid.md)) — Row policy ID.

Expand Down
20 changes: 18 additions & 2 deletions docs/en/sql-reference/statements/create/row-policy.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ Row policies makes sense only for users with readonly access. If user can modify
Syntax:

``` sql
CREATE [ROW] POLICY [IF NOT EXISTS | OR REPLACE] policy_name1 [ON CLUSTER cluster_name1] ON [db1.]table1
[, policy_name2 [ON CLUSTER cluster_name2] ON [db2.]table2 ...]
CREATE [ROW] POLICY [IF NOT EXISTS | OR REPLACE] policy_name1 [ON CLUSTER cluster_name1] ON [db1.]table1|db1.*
[, policy_name2 [ON CLUSTER cluster_name2] ON [db2.]table2|db2.* ...]
[FOR SELECT] USING condition
[AS {PERMISSIVE | RESTRICTIVE}]
[TO {role1 [, role2 ...] | ALL | ALL EXCEPT role1 [, role2 ...]}]
Expand Down Expand Up @@ -76,6 +76,20 @@ CREATE ROW POLICY pol2 ON mydb.table1 USING c=2 AS RESTRICTIVE TO peter, antonio

enables the user `peter` to see rows only if both `b=1` AND `c=2`.

Database policies are combined with table policies.

For example, the following policies

``` sql
CREATE ROW POLICY pol1 ON mydb.* USING b=1 TO mira, peter
CREATE ROW POLICY pol2 ON mydb.table1 USING c=2 AS RESTRICTIVE TO peter, antonio
```

enables the user `peter` to see table1 rows only if both `b=1` AND `c=2`, although
any other table in mydb would have only `b=1` policy applied for the user.



## ON CLUSTER Clause

Allows creating row policies on a cluster, see [Distributed DDL](../../../sql-reference/distributed-ddl.md).
Expand All @@ -88,3 +102,5 @@ Allows creating row policies on a cluster, see [Distributed DDL](../../../sql-re
`CREATE ROW POLICY filter2 ON mydb.mytable USING a<1000 AND b=5 TO ALL EXCEPT mira`

`CREATE ROW POLICY filter3 ON mydb.mytable USING 1 TO admin`

`CREATE ROW POLICY filter4 ON mydb.* USING 1 TO admin`
2 changes: 1 addition & 1 deletion src/Access/Common/RowPolicyDefs.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ String RowPolicyName::toString() const
name += backQuoteIfNeed(database);
name += '.';
}
name += backQuoteIfNeed(table_name);
name += (table_name == RowPolicyName::ANY_TABLE_MARK ? "*" : backQuoteIfNeed(table_name));
return name;
}

Expand Down
2 changes: 2 additions & 0 deletions src/Access/Common/RowPolicyDefs.h
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ namespace DB
/// Represents the full name of a row policy, e.g. "myfilter ON mydb.mytable".
struct RowPolicyName
{
static constexpr char ANY_TABLE_MARK[] = "";

String short_name;
String database;
String table_name;
Expand Down
8 changes: 7 additions & 1 deletion src/Access/EnabledRowPolicies.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,13 @@ RowPolicyFilterPtr EnabledRowPolicies::getFilter(const String & database, const
auto loaded = mixed_filters.load();
auto it = loaded->find({database, table_name, filter_type});
if (it == loaded->end())
return {};
{ /// Look for a policy for database if a table policy not found
it = loaded->find({database, RowPolicyName::ANY_TABLE_MARK, filter_type});
if (it == loaded->end())
{
return {};
}
}

return it->second;
}
Expand Down
10 changes: 5 additions & 5 deletions src/Access/RolesOrUsersSet.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -228,25 +228,25 @@ void RolesOrUsersSet::add(const std::vector<UUID> & ids_)

bool RolesOrUsersSet::match(const UUID & id) const
{
return (all || ids.count(id)) && !except_ids.count(id);
return (all || ids.contains(id)) && !except_ids.contains(id);
}


bool RolesOrUsersSet::match(const UUID & user_id, const boost::container::flat_set<UUID> & enabled_roles) const
{
if (!all && !ids.count(user_id))
if (!all && !ids.contains(user_id))
{
bool found_enabled_role = std::any_of(
enabled_roles.begin(), enabled_roles.end(), [this](const UUID & enabled_role) { return ids.count(enabled_role); });
enabled_roles.begin(), enabled_roles.end(), [this](const UUID & enabled_role) { return ids.contains(enabled_role); });
if (!found_enabled_role)
return false;
}

if (except_ids.count(user_id))
if (except_ids.contains(user_id))
return false;

bool in_except_list = std::any_of(
enabled_roles.begin(), enabled_roles.end(), [this](const UUID & enabled_role) { return except_ids.count(enabled_role); });
enabled_roles.begin(), enabled_roles.end(), [this](const UUID & enabled_role) { return except_ids.contains(enabled_role); });
return !in_except_list;
}

Expand Down
3 changes: 3 additions & 0 deletions src/Access/RowPolicy.h
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ struct RowPolicy : public IAccessEntity
void setPermissive(bool permissive_ = true) { setRestrictive(!permissive_); }
bool isPermissive() const { return !isRestrictive(); }

/// Applied for entire database
bool isForDatabase() const { return full_name.table_name == RowPolicyName::ANY_TABLE_MARK; }

/// Sets that the policy is restrictive.
/// A row is only accessible if at least one of the permissive policies passes,
/// in addition to all the restrictive policies.
Expand Down
118 changes: 93 additions & 25 deletions src/Access/RowPolicyCache.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,8 @@ namespace DB
{
namespace
{
/// Accumulates filters from multiple row policies and joins them using the AND logical operation.
/// Helper to accumulate filters from multiple row policies and join them together
/// by AND or OR logical operations.
class FiltersMixer
{
public:
Expand Down Expand Up @@ -148,9 +149,11 @@ void RowPolicyCache::ensureAllRowPoliciesRead()

for (const UUID & id : access_control.findAll<RowPolicy>())
{
auto quota = access_control.tryRead<RowPolicy>(id);
if (quota)
all_policies.emplace(id, PolicyInfo(quota));
auto policy = access_control.tryRead<RowPolicy>(id);
if (policy)
{
all_policies.emplace(id, PolicyInfo(policy));
}
}
}

Expand Down Expand Up @@ -215,40 +218,105 @@ void RowPolicyCache::mixFiltersFor(EnabledRowPolicies & enabled)
std::vector<RowPolicyPtr> policies;
};

std::unordered_map<MixedFiltersKey, MixerWithNames, Hash> mixers;
std::unordered_map<MixedFiltersKey, MixerWithNames, Hash> database_mixers;

/// populate database_mixers using database-level policies
/// to aggregate (mix) rules per database
for (const auto & [policy_id, info] : all_policies)
{
if (info.isForDatabase())
{
const auto & policy = *info.policy;
bool match = info.roles->match(enabled.params.user_id, enabled.params.enabled_roles);
for (auto filter_type : collections::range(0, RowPolicyFilterType::MAX))
{
auto filter_type_i = static_cast<size_t>(filter_type);
if (info.parsed_filters[filter_type_i])
{
MixedFiltersKey key{info.database_and_table_name->first,
info.database_and_table_name->second,
filter_type};

auto & mixer = database_mixers[key];
mixer.database_and_table_name = info.database_and_table_name;
if (match)
{
mixer.mixer.add(info.parsed_filters[filter_type_i], policy.isRestrictive());
mixer.policies.push_back(info.policy);
}
}
}
}
}

std::unordered_map<MixedFiltersKey, MixerWithNames, Hash> table_mixers;

/// populate table_mixers using database_mixers and table-level policies
for (const auto & [policy_id, info] : all_policies)
{
const auto & policy = *info.policy;
bool match = info.roles->match(enabled.params.user_id, enabled.params.enabled_roles);
MixedFiltersKey key;
key.database = info.database_and_table_name->first;
key.table_name = info.database_and_table_name->second;
for (auto filter_type : collections::range(0, RowPolicyFilterType::MAX))
if (!info.isForDatabase())
{
auto filter_type_i = static_cast<size_t>(filter_type);
if (info.parsed_filters[filter_type_i])
const auto & policy = *info.policy;
bool match = info.roles->match(enabled.params.user_id, enabled.params.enabled_roles);
for (auto filter_type : collections::range(0, RowPolicyFilterType::MAX))
{
key.filter_type = filter_type;
auto & mixer = mixers[key];
mixer.database_and_table_name = info.database_and_table_name;
if (match)
auto filter_type_i = static_cast<size_t>(filter_type);
if (info.parsed_filters[filter_type_i])
{
mixer.mixer.add(info.parsed_filters[filter_type_i], policy.isRestrictive());
mixer.policies.push_back(info.policy);
MixedFiltersKey key{info.database_and_table_name->first,
info.database_and_table_name->second,
filter_type};
auto table_it = table_mixers.find(key);
if (table_it == table_mixers.end())
{ /// no exact match - create new mixer
MixedFiltersKey database_key = key;
database_key.table_name = RowPolicyName::ANY_TABLE_MARK;

auto database_it = database_mixers.find(database_key);

if (database_it == database_mixers.end())
{
table_it = table_mixers.try_emplace(key).first;
}
else
{
/// table policies are based on database ones
table_it = table_mixers.insert({key, database_it->second}).first;
}
}

auto & mixer = table_it->second; /// getting table level mixer
mixer.database_and_table_name = info.database_and_table_name;
if (match)
{
mixer.mixer.add(info.parsed_filters[filter_type_i], policy.isRestrictive());
mixer.policies.push_back(info.policy);
}
}
}
}
}

auto mixed_filters = boost::make_shared<MixedFiltersMap>();
for (auto & [key, mixer] : mixers)

/// Retrieve aggregated policies from mixers
/// if a table has a policy for this particular table, we have all needed information in table_mixers
/// (policies for the database are already applied)
/// otherwise we would look for a policy for database using RowPolicy::ANY_TABLE_MARK
/// Consider restrictive policies a=1 for db.t, b=2 for db.* and c=3 for db.*
/// We are going to have two items in mixed_filters:
/// 1. a=1 AND b=2 AND c=3 for db.t (comes from table_mixers, where it had been created with the help of database_mixers)
/// 2. b=2 AND c=3 for db.* (comes directly from database_mixers)
for (auto * mixer_map_ptr : {&table_mixers, &database_mixers})
{
auto mixed_filter = std::make_shared<RowPolicyFilter>();
mixed_filter->database_and_table_name = std::move(mixer.database_and_table_name);
mixed_filter->expression = std::move(mixer.mixer).getResult(access_control.isEnabledUsersWithoutRowPoliciesCanReadRows());
mixed_filter->policies = std::move(mixer.policies);
mixed_filters->emplace(key, std::move(mixed_filter));
for (auto & [key, mixer] : *mixer_map_ptr)
{
auto mixed_filter = std::make_shared<RowPolicyFilter>();
mixed_filter->database_and_table_name = std::move(mixer.database_and_table_name);
mixed_filter->expression = std::move(mixer.mixer).getResult(access_control.isEnabledUsersWithoutRowPoliciesCanReadRows());
mixed_filter->policies = std::move(mixer.policies);
mixed_filters->emplace(key, std::move(mixed_filter));
}
}

enabled.mixed_filters.store(mixed_filters);
Expand Down
1 change: 1 addition & 0 deletions src/Access/RowPolicyCache.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ class RowPolicyCache
explicit PolicyInfo(const RowPolicyPtr & policy_) { setPolicy(policy_); }
void setPolicy(const RowPolicyPtr & policy_);

bool isForDatabase() const { return policy->isForDatabase(); }
RowPolicyPtr policy;
const RolesOrUsersSet * roles = nullptr;
std::shared_ptr<const std::pair<String, String>> database_and_table_name;
Expand Down
11 changes: 8 additions & 3 deletions src/Parsers/Access/ASTRowPolicyName.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@ void ASTRowPolicyName::replaceEmptyDatabase(const String & current_database)
full_name.database = current_database;
}

String ASTRowPolicyNames::tableOrAsterisk(const String & table_name) const
{
return table_name == RowPolicyName::ANY_TABLE_MARK ? "*" : backQuoteIfNeed(table_name);
}


void ASTRowPolicyNames::formatImpl(const FormatSettings & settings, FormatState &, FormatStateStacked) const
{
Expand Down Expand Up @@ -73,7 +78,7 @@ void ASTRowPolicyNames::formatImpl(const FormatSettings & settings, FormatState
const String & table_name = full_name.table_name;
if (!database.empty())
settings.ostr << backQuoteIfNeed(database) + ".";
settings.ostr << backQuoteIfNeed(table_name);
settings.ostr << tableOrAsterisk(table_name);
}
}
else if (same_db_and_table_name)
Expand All @@ -92,7 +97,7 @@ void ASTRowPolicyNames::formatImpl(const FormatSettings & settings, FormatState
settings.ostr << (settings.hilite ? hilite_keyword : "") << " ON " << (settings.hilite ? hilite_none : "");
if (!database.empty())
settings.ostr << backQuoteIfNeed(database) + ".";
settings.ostr << backQuoteIfNeed(table_name);
settings.ostr << tableOrAsterisk(table_name);
}
else
{
Expand All @@ -108,7 +113,7 @@ void ASTRowPolicyNames::formatImpl(const FormatSettings & settings, FormatState
<< (settings.hilite ? hilite_none : "");
10BC8 if (!database.empty())
settings.ostr << backQuoteIfNeed(database) + ".";
settings.ostr << backQuoteIfNeed(table_name);
settings.ostr << tableOrAsterisk(table_name);
}
}

Expand Down
3 changes: 3 additions & 0 deletions src/Parsers/Access/ASTRowPolicyName.h
Original file line number Diff line number Diff line change
Expand Up @@ -45,5 +45,8 @@ class ASTRowPolicyNames : public IAST, public ASTQueryWithOnCluster
ASTPtr getRewrittenASTWithoutOnCluster(const WithoutOnClusterASTRewriteParams &) const override { return removeOnCluster<ASTRowPolicyNames>(clone()); }

void replaceEmptyDatabase(const String & current_database);

private:
String tableOrAsterisk(const String & table_name) const;
};
}
12 changes: 11 additions & 1 deletion src/Parsers/Access/ParserRowPolicyName.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,18 @@ namespace
return IParserBase::wrapParseImpl(pos, [&]
{
String res_database, res_table_name;
if (!parseDatabaseAndTableName(pos, expected, res_database, res_table_name))
bool is_any_database = false;
bool is_any_table = false;

if (!parseDatabaseAndTableNameOrAsterisks(pos, expected, res_database, is_any_database, res_table_name, is_any_table)
|| is_any_database)
{
return false;
}
else if (is_any_table)
{
res_table_name = RowPolicyName::ANY_TABLE_MARK;
}

/// If table is specified without DB it cannot be followed by "ON"
/// (but can be followed by "ON CLUSTER").
Expand Down
92C9
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Policy for table `*` does not affect other tables in the database
other 100 20
11 changes: 11 additions & 0 deletions tests/queries/0_stateless/02703_row_policies_for_asterisk.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
-- Tags: no-parallel

SELECT 'Policy for table `*` does not affect other tables in the database';
CREATE DATABASE 02703_db_asterisk;
CREATE ROW POLICY 02703_asterisk ON 02703_db_asterisk.`*` USING x=1 AS permissive TO ALL;
CREATE TABLE 02703_db_asterisk.`*` (x UInt8, y UInt8) ENGINE = MergeTree ORDER BY x AS SELECT 100, 20;
CREATE TABLE 02703_db_asterisk.`other` (x UInt8, y UInt8) ENGINE = MergeTree ORDER BY x AS SELECT 100, 20;
SELECT 'star', * FROM 02703_db_asterisk.`*`;
SELECT 'other', * FROM 02703_db_asterisk.other;
DROP ROW POLICY 02703_asterisk ON 02703_db_asterisk.`*`;
DROP DATABASE 02703_db_asterisk;
Loading
0