From 764830ee9e34d36eabf978f498ea2bbf4d5c382b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Lizardo?= Date: Wed, 2 Dec 2026 16:29:29 +0100 Subject: [PATCH 1/9] Apply row policies to swarm reads of object storage tables MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `IStorageCluster::read` sent the user's query to the swarm nodes without any row policy. The initiator planner skips the row policy filter when the storage returns the `WithMergeableState` stage, and the swarm nodes read through a table function, so a policy defined on the table never matched there. A user with a row policy could read all rows with `object_storage_cluster` set. Add the effective `SELECT` row policy expression of the storage to the `PREWHERE` (if present) or `WHERE` of the query sent to the swarm nodes. Throw `NOT_IMPLEMENTED` if the sent query is not a single `SELECT` or still contains a `JOIN`, instead of sending it unfiltered. Add an integration test with a secret-protected cluster that checks that `SELECT` and `count` through `object_storage_cluster` return only the rows allowed by the row policy of each user. Signed-off-by: Luís Lizardo --- src/Storages/IStorageCluster.cpp | 44 +++++++++++ .../configs/cluster_swarm.xml | 13 ++++ .../integration/test_database_iceberg/test.py | 78 +++++++++++++++++++ 3 files changed, 135 insertions(+) create mode 100644 tests/integration/test_database_iceberg/configs/cluster_swarm.xml diff --git a/src/Storages/IStorageCluster.cpp b/src/Storages/IStorageCluster.cpp index b60c83de327e..5ba0c51c6cd7 100644 --- a/src/Storages/IStorageCluster.cpp +++ b/src/Storages/IStorageCluster.cpp @@ -59,6 +59,9 @@ #include #include +#include +#include +#include #include #include @@ -648,6 +651,46 @@ void IStorageCluster::readFromRemoteInitiator( query_plan, column_names, new_storage_snapshot, modified_query_info, storage_and_context.context, processed_stage, max_block_size, num_streams); } +namespace +{ + +void applyRowPolicyToQueryToSend(ASTPtr & query_to_send, const StorageID & storage_id, const ContextPtr & context) +{ + if (!storage_id.hasDatabase()) + return; + + const auto row_policy_filter + = context->getRowPolicyFilter(storage_id.getDatabaseName(), storage_id.getTableName(), RowPolicyFilterType::SELECT_FILTER); + if (!row_policy_filter || row_policy_filter->isAlwaysTrue()) + return; + + query_to_send = query_to_send->clone(); + + auto * select_query = query_to_send->as(); + if (!select_query) + { + if (auto * union_query = query_to_send->as(); + union_query && union_query->list_of_selects && union_query->list_of_selects->children.size() == 1) + { + select_query = union_query->list_of_selects->children[0]->as(); + } + } + + if (!select_query || select_query->hasJoin()) + throw Exception( + ErrorCodes::NOT_IMPLEMENTED, + "Row policies on {} cannot be applied to a query sent to cluster nodes that is not a single SELECT without JOIN", + storage_id.getNameForLogs()); + + const auto expression = select_query->prewhere() ? ASTSelectQuery::Expression::PREWHERE : ASTSelectQuery::Expression::WHERE; + auto conditions = ASTs{row_policy_filter->expression->clone()}; + if (auto existing = select_query->getExpression(expression, /*with_alias=*/false)) + conditions.push_back(std::move(existing)); + select_query->setExpression(expression, makeASTForLogicalAnd(std::move(conditions))); +} + +} + /// The code executes on initiator void IStorageCluster::read( QueryPlan & query_plan, @@ -740,6 +783,7 @@ void IStorageCluster::read( /// A join kept on the initiator replaces `query_to_send` but already has a resolved left-scan tree. QueryTreeNodePtr resolved_query_tree; updateQueryWithJoinToSendIfNeeded(query_to_send, query_info, context, &resolved_query_tree); + applyRowPolicyToQueryToSend(query_to_send, getStorageID(), context); if (settings[Setting::allow_experimental_analyzer]) { diff --git a/tests/integration/test_database_iceberg/configs/cluster_swarm.xml b/tests/integration/test_database_iceberg/configs/cluster_swarm.xml new file mode 100644 index 000000000000..62037dc983e7 --- /dev/null +++ b/tests/integration/test_database_iceberg/configs/cluster_swarm.xml @@ -0,0 +1,13 @@ + + + + swarm_secret + + + node2 + 9000 + + + + + diff --git a/tests/integration/test_database_iceberg/test.py b/tests/integration/test_database_iceberg/test.py index 6ee0e9dcacae..fd1f8bbb8a61 100644 --- a/tests/integration/test_database_iceberg/test.py +++ b/tests/integration/test_database_iceberg/test.py @@ -194,6 +194,7 @@ def started_cluster(): main_configs=[ "configs/backups.xml", "configs/cluster.xml", + "configs/cluster_swarm.xml", "configs/text_log.xml", "configs/display_secrets.xml", ], @@ -208,6 +209,7 @@ def started_cluster(): main_configs=[ "configs/backups.xml", "configs/cluster.xml", + "configs/cluster_swarm.xml", "configs/text_log.xml", ], user_configs=[], @@ -1820,6 +1822,82 @@ def test_object_storage_cluster_right_in_subquery_loads_rest_catalog_table_once( ) +def test_row_policy_enforced_with_object_storage_cluster(started_cluster): + node1 = started_cluster.instances["node1"] + node2 = started_cluster.instances["node2"] + + suffix = uuid.uuid4().hex[:8] + namespace = f"test_row_policy_swarm_{suffix}" + table_name = f"events_{suffix}" + table = f"{CATALOG_NAME}.`{namespace}.{table_name}`" + users = {f"tenant_user_{suffix}_{tenant}": tenant for tenant in (1, 2)} + password = "pass" + + load_catalog_impl(started_cluster) + create_clickhouse_iceberg_database(started_cluster, node1, CATALOG_NAME) + create_clickhouse_iceberg_database(started_cluster, node2, CATALOG_NAME) + create_clickhouse_iceberg_table( + started_cluster, node1, namespace, table_name, "(tenant_id UInt32, value String)" + ) + node1.query( + f"INSERT INTO {table} VALUES (1, 'a'), (1, 'b'), (2, 'c'), (2, 'd'), (2, 'e')", + settings={ + "allow_insert_into_iceberg": 1, + "write_full_path_in_iceberg_metadata": 1, + }, + ) + + expected = { + 1: "1\ta\n1\tb\n", + 2: "2\tc\n2\td\n2\te\n", + } + + try: + for node in (node1, node2): + for user, tenant in users.items(): + node.query(f"CREATE USER {user} IDENTIFIED BY '{password}'") + node.query(f"GRANT SELECT ON {table} TO {user}") + node.query(f"GRANT S3 ON *.* TO {user}") + node.query(f"GRANT CREATE TEMPORARY TABLE ON *.* TO {user}") + node.query( + f"CREATE ROW POLICY policy_{user} ON {table} " + f"USING tenant_id = {tenant} TO {user}" + ) + + for user, tenant in users.items(): + query = f"SELECT * FROM {table} ORDER BY value" + + assert ( + node1.query(query, user=user, password=password) == expected[tenant] + ) + + assert ( + node1.query( + query, + user=user, + password=password, + settings={"object_storage_cluster": "cluster_swarm"}, + ) + == expected[tenant] + ) + + assert ( + node1.query( + f"SELECT count() FROM {table}", + user=user, + password=password, + settings={"object_storage_cluster": "cluster_swarm"}, + ) + == f"{len(expected[tenant].splitlines())}\n" + ) + finally: + for node in (node1, node2): + for user in users: + node.query(f"DROP ROW POLICY IF EXISTS policy_{user} ON {table}") + node.query(f"DROP USER IF EXISTS {user}") + node1.query(f"DROP TABLE IF EXISTS {table}") + + def test_object_storage_cluster_secondary_query_returns_shard_identifiers(started_cluster): node1 = started_cluster.instances["node1"] node2 = started_cluster.instances["node2"] From 56cca2208e8dd432360d8b4bc97b14d370dc93d5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Lizardo?= Date: Thu, 3 Dec 2026 13:26:17 +0100 Subject: [PATCH 2/9] Do not require the initial user on swarm nodes MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Swarm nodes are meant to be stateless, but the sub-query sent by `IStorageCluster` carried the `initial_user` of the initiator. A node without that user failed in `TCPHandler` with `UNKNOWN_USER` or `AUTHENTICATION_FAILED`, so every user had to be created on every swarm node. When the cluster is protected by a ``, clear the initial user of the context used for the sub-query. The swarm node then skips user authentication and runs the sub-query through the existing interserver path, trusting the cluster secret. Access checks and the row policy are applied on the initiator. Add integration tests where the user and its row policy exist only on the initiator, including a scenario that mirrors the report. Signed-off-by: Luís Lizardo --- src/Storages/IStorageCluster.cpp | 2 + .../integration/test_database_iceberg/test.py | 147 ++++++++++++++++++ 2 files changed, 149 insertions(+) diff --git a/src/Storages/IStorageCluster.cpp b/src/Storages/IStorageCluster.cpp index 5ba0c51c6cd7..4ddec7b23b60 100644 --- a/src/Storages/IStorageCluster.cpp +++ b/src/Storages/IStorageCluster.cpp @@ -1499,6 +1499,8 @@ ContextPtr ReadFromCluster::updateSettings(const Settings & settings) auto new_context = Context::createCopy(context); new_context->setSettings(new_settings); + if (!cluster->getSecret().empty()) + new_context->setInitialUserName({}); return new_context; } diff --git a/tests/integration/test_database_iceberg/test.py b/tests/integration/test_database_iceberg/test.py index fd1f8bbb8a61..ce8c44abda66 100644 --- a/tests/integration/test_database_iceberg/test.py +++ b/tests/integration/test_database_iceberg/test.py @@ -1898,6 +1898,153 @@ def test_row_policy_enforced_with_object_storage_cluster(started_cluster): node1.query(f"DROP TABLE IF EXISTS {table}") +def test_object_storage_cluster_does_not_require_user_on_swarm_nodes(started_cluster): + node1 = started_cluster.instances["node1"] + node2 = started_cluster.instances["node2"] + + suffix = uuid.uuid4().hex[:8] + namespace = f"test_stateless_swarm_{suffix}" + table_name = f"events_{suffix}" + table = f"{CATALOG_NAME}.`{namespace}.{table_name}`" + user = f"tenant_user_{suffix}" + password = "pass" + + load_catalog_impl(started_cluster) + create_clickhouse_iceberg_database(started_cluster, node1, CATALOG_NAME) + create_clickhouse_iceberg_table( + started_cluster, node1, namespace, table_name, "(tenant_id UInt32, value String)" + ) + node1.query( + f"INSERT INTO {table} VALUES (1, 'a'), (1, 'b'), (2, 'c'), (2, 'd'), (2, 'e')", + settings={ + "allow_insert_into_iceberg": 1, + "write_full_path_in_iceberg_metadata": 1, + }, + ) + + try: + node1.query(f"CREATE USER {user} IDENTIFIED BY '{password}'") + node1.query(f"GRANT SELECT ON {table} TO {user}") + node1.query(f"GRANT S3 ON *.* TO {user}") + node1.query(f"GRANT CREATE TEMPORARY TABLE ON *.* TO {user}") + node1.query( + f"CREATE ROW POLICY policy_{user} ON {table} USING tenant_id = 1 TO {user}" + ) + + assert node2.query(f"SELECT count() FROM system.users WHERE name = '{user}'") == "0\n" + assert node2.query("SELECT count() FROM system.row_policies") == "0\n" + + swarm_settings = {"object_storage_cluster": "cluster_swarm"} + + assert ( + node1.query( + f"SELECT * FROM {table} ORDER BY value", + user=user, + password=password, + settings=swarm_settings, + ) + == "1\ta\n1\tb\n" + ) + + assert ( + node1.query( + f"SELECT count() FROM {table}", + user=user, + password=password, + settings=swarm_settings, + ) + == "2\n" + ) + finally: + node1.query(f"DROP ROW POLICY IF EXISTS policy_{user} ON {table}") + node1.query(f"DROP USER IF EXISTS {user}") + node1.query(f"DROP TABLE IF EXISTS {table}") + + +def test_issue_1710_row_policy_with_stateless_swarm(started_cluster): + node1 = started_cluster.instances["node1"] + node2 = started_cluster.instances["node2"] + + namespace = "default" + table_name = "events" + table = f"{CATALOG_NAME}.`{namespace}.{table_name}`" + swarm_settings = {"object_storage_cluster": "cluster_swarm"} + users = {"user_1": ("pass1", 1), "user_2": ("pass2", 2)} + + events = [ + (1, "7b7e0439-99d0-4590-a4f7-1cfea1e192d1", "user_login", 1742371200, 1001, '{"device": "desktop", "location": "LA"}'), + (1, "846aa71f-f631-47b4-8429-ee8af87b4182", "purchase", 1742371500, 1002, '{"item": "phone", "amount": 799}'), + (1, "6b4d12e4-447d-4398-b3fa-1c1e94d71a2f", "user_logout", 1742371800, 1001, '{"device": "desktop", "location": "LA"}'), + (1, "83b5eb72-aba3-4038-bc52-6c08b6423615", "purchase", 1742373900, 1003, '{"item": "monitor", "amount": 450}'), + (1, "975fb0c8-55bd-4df4-843b-34f5cfeed0a9", "user_login", 1742374200, 1004, '{"device": "desktop", "location": "LA"}'), + (2, "7162f8ea-8bfd-486a-a45e-edfc3398ca93", "user_login", 1742371920, 2001, '{"device": "mobile", "location": "SF"}'), + (2, "6b5f3e55-5add-479e-b89d-762aa017f067", "purchase", 1742372100, 2002, '{"item": "headphones", "amount": 199}'), + (2, "43ad35a1-926c-4543-a133-8672ddd504bf", "user_logout", 1742372400, 2001, '{"device": "mobile", "location": "SF"}'), + (2, "f50aa430-4898-43d0-9d82-41e7397ba9b8", "purchase", 1742374500, 2003, '{"item": "laptop", "amount": 1200}'), + (2, "5c150ceb-b869-4ebb-843d-ab42d3cb5410", "user_login", 1742374800, 2004, '{"device": "mobile", "location": "SF"}'), + ] + values = ", ".join( + f"({tenant_id}, '{event_uuid}', '{mcc}', {timestamp}, {user_id}, '{data}')" + for tenant_id, event_uuid, mcc, timestamp, user_id, data in events + ) + + def expected_rows(tenant_id): + return "".join( + f"{t}\t{u}\t{m}\t{ts}\t{uid}\t{d}\n" + for t, u, m, ts, uid, d in sorted(events, key=lambda e: e[3]) + if t == tenant_id + ) + + load_catalog_impl(started_cluster) + create_clickhouse_iceberg_database(started_cluster, node1, CATALOG_NAME) + create_clickhouse_iceberg_table( + started_cluster, + node1, + namespace, + table_name, + "(tenant_id Int32, `UUID` String, mcc String, `timestamp` Int64, user_id Int32, data String)", + ) + node1.query( + f"INSERT INTO {table} VALUES {values}", + settings={ + "allow_insert_into_iceberg": 1, + "write_full_path_in_iceberg_metadata": 1, + }, + ) + + try: + for user, (password, tenant_id) in users.items(): + node1.query(f"CREATE USER {user} IDENTIFIED BY '{password}'") + node1.query( + f"CREATE ROW POLICY user_filter_{tenant_id} ON {table} USING tenant_id={tenant_id} TO {user}" + ) + node1.query("CREATE ROLE user_role") + node1.query(f"GRANT SELECT ON {table} TO user_role") + for user in users: + node1.query(f"GRANT user_role TO {user}") + + assert node2.query("SELECT count() FROM system.users WHERE name IN ('user_1', 'user_2')") == "0\n" + assert node2.query("SELECT count() FROM system.row_policies") == "0\n" + + query = f"SELECT * FROM {table} ORDER BY timestamp" + + for user, (password, tenant_id) in users.items(): + assert node1.query(query, user=user, password=password) == expected_rows(tenant_id) + + for user, (password, tenant_id) in users.items(): + assert ( + node1.query(query, user=user, password=password, settings=swarm_settings) + == expected_rows(tenant_id) + ) + finally: + for tenant_id in (1, 2): + node1.query(f"DROP ROW POLICY IF EXISTS user_filter_{tenant_id} ON {table}") + for user in users: + node1.query(f"DROP USER IF EXISTS {user}") + node1.query("DROP ROLE IF EXISTS user_role") + node1.query(f"DROP TABLE IF EXISTS {table}") + + def test_object_storage_cluster_secondary_query_returns_shard_identifiers(started_cluster): node1 = started_cluster.instances["node1"] node2 = started_cluster.instances["node2"] From 78ff39bbaf39400cd0fdf1a72b26868f304f3b9c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Lizardo?= Date: Thu, 3 Dec 2026 17:23:46 +0100 Subject: [PATCH 3/9] Harden row policy handling for swarm reads of object storage tables MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Reject a query sent to swarm nodes when one of its aliases shadows a column used by the row policy, because the injected policy shares the alias scope of the query and `SELECT 1 AS tenant_id` turned `tenant_id = 1` into `1 = 1`. Aliases that only repeat the column, such as `__table1.tenant_id AS tenant_id`, are accepted. Compute the sample header before the policy is injected, so the access check of the original query does not see the policy. Skip the repeated access check in the analyze-only re-plan that the planner runs after a storage returns a stage beyond `FetchColumns`. That re-plan shares the planner context with the outer pass, which has already added the policy columns to the columns to read, so a user with `SELECT` on a single column was denied for the policy column. Add integration tests for the alias shadowing, with both analyzers, and for a user that has no grant on the policy column. Signed-off-by: Luís Lizardo --- src/Planner/PlannerJoinTree.cpp | 9 +- src/Storages/IStorageCluster.cpp | 53 ++++++- .../integration/test_database_iceberg/test.py | 138 ++++++++++++++++++ 3 files changed, 196 insertions(+), 4 deletions(-) diff --git a/src/Planner/PlannerJoinTree.cpp b/src/Planner/PlannerJoinTree.cpp index dd8d9d750f5b..0f1352afe823 100644 --- a/src/Planner/PlannerJoinTree.cpp +++ b/src/Planner/PlannerJoinTree.cpp @@ -979,8 +979,11 @@ void prepareBuildQueryPlanForTableExpression(const QueryTreeNodePtr & table_expr if (table_node) { const auto & column_names_with_aliases = table_expression_data.getSelectedColumnsNames(); - columns_names_allowed_to_select = checkAccessRights( - table_node->getStorage(), table_node->getStorageID(), table_node->getStorageSnapshot(), column_names_with_aliases, query_context); + const auto is_access_already_checked + = select_query_options.ignore_access_check && select_query_options.only_analyze && !column_names_with_aliases.empty(); + if (!is_access_already_checked) + columns_names_allowed_to_select = checkAccessRights( + table_node->getStorage(), table_node->getStorageID(), table_node->getStorageSnapshot(), column_names_with_aliases, query_context); checkAccessRightsForColumnsResolvedAway(*table_node, table_expression_data, query_context); } @@ -3171,7 +3174,7 @@ JoinTreeQueryPlan buildQueryPlanForTableExpression(TableExpressionNodePtr table_ /// Trivial count already emits the column with the aggregate's action-node name /// (see `applyTrivialCountIfPossible`), so the structure matches the expected /// header by construction and we can skip the recursive planner entirely. - SelectQueryOptions analyze_query_options = SelectQueryOptions(till_stage).analyze(); + SelectQueryOptions analyze_query_options = SelectQueryOptions(till_stage).analyze().ignoreAccessCheck(); Planner planner(select_query_info.query_tree, analyze_query_options, select_query_info.planner_context); diff --git a/src/Storages/IStorageCluster.cpp b/src/Storages/IStorageCluster.cpp index 4ddec7b23b60..98d317457cc3 100644 --- a/src/Storages/IStorageCluster.cpp +++ b/src/Storages/IStorageCluster.cpp @@ -57,6 +57,7 @@ #include #include #include +#include #include #include @@ -654,6 +655,40 @@ void IStorageCluster::readFromRemoteInitiator( namespace { +void collectIdentifierNames(const ASTPtr & ast, NameSet & names) +{ + if (const auto * identifier = ast->as()) + { + names.insert(identifier->name()); + if (!identifier->name_parts.empty()) + names.insert(identifier->name_parts.front()); + } + + for (const auto & child : ast->children) + collectIdentifierNames(child, names); +} + +void collectAliases(const ASTPtr & ast, const String & table_alias, NameSet & aliases) +{ + if (const auto * with_alias = dynamic_cast(ast.get())) + { + const auto alias = with_alias->tryGetAlias(); + const auto * identifier = ast->as(); + const auto is_identity_alias = identifier + && (identifier->name() == alias + || (!table_alias.empty() && identifier->name_parts.size() == 2 && identifier->name_parts[0] == table_alias + && identifier->name_parts[1] == alias)); + if (!alias.empty() && !is_identity_alias) + aliases.insert(alias); + } + + if (ast->as() || ast->as()) + return; + + for (const auto & child : ast->children) + collectAliases(child, table_alias, aliases); +} + void applyRowPolicyToQueryToSend(ASTPtr & query_to_send, const StorageID & storage_id, const ContextPtr & context) { if (!storage_id.hasDatabase()) @@ -682,6 +717,21 @@ void applyRowPolicyToQueryToSend(ASTPtr & query_to_send, const StorageID & stora "Row policies on {} cannot be applied to a query sent to cluster nodes that is not a single SELECT without JOIN", storage_id.getNameForLogs()); + auto policy_names = NameSet{}; + collectIdentifierNames(row_policy_filter->expression, policy_names); + auto aliases = NameSet{}; + const auto table_alias = DatabaseAndTableWithAlias(*getTableExpression(*select_query, 0)).alias; + collectAliases(query_to_send, table_alias, aliases); + for (const auto & alias : aliases) + { + if (policy_names.contains(alias)) + throw Exception( + ErrorCodes::NOT_IMPLEMENTED, + "Row policy on {} cannot be applied because the query defines the alias `{}` that shadows a column used by the policy", + storage_id.getNameForLogs(), + alias); + } + const auto expression = select_query->prewhere() ? ASTSelectQuery::Expression::PREWHERE : ASTSelectQuery::Expression::WHERE; auto conditions = ASTs{row_policy_filter->expression->clone()}; if (auto existing = select_query->getExpression(expression, /*with_alias=*/false)) @@ -783,7 +833,6 @@ void IStorageCluster::read( /// A join kept on the initiator replaces `query_to_send` but already has a resolved left-scan tree. QueryTreeNodePtr resolved_query_tree; updateQueryWithJoinToSendIfNeeded(query_to_send, query_info, context, &resolved_query_tree); - applyRowPolicyToQueryToSend(query_to_send, getStorageID(), context); if (settings[Setting::allow_experimental_analyzer]) { @@ -823,6 +872,8 @@ void IStorageCluster::read( query_to_send = interpreter.getQueryInfo().query->clone(); } + applyRowPolicyToQueryToSend(query_to_send, getStorageID(), context); + updateQueryToSendIfNeeded( query_to_send, storage_snapshot, context, /*make_cluster_function=*/true, /*add_structure_and_format=*/true); diff --git a/tests/integration/test_database_iceberg/test.py b/tests/integration/test_database_iceberg/test.py index ce8c44abda66..6afd8c5a62f1 100644 --- a/tests/integration/test_database_iceberg/test.py +++ b/tests/integration/test_database_iceberg/test.py @@ -5259,4 +5259,142 @@ def annotations(schema_id=None): assert annotations() == {"id": None, "s": "", "m": "SimpleAggregateFunction(max, Nullable(Int64))"} # The schema the first rows were written with keeps its annotation. assert annotations(0) == {"id": None, "s": "SimpleAggregateFunction(sum, Int64)"} +@pytest.mark.parametrize("enable_analyzer", [0, 1]) +def test_row_policy_not_bypassed_by_select_alias_with_object_storage_cluster( + started_cluster, enable_analyzer +): + node1 = started_cluster.instances["node1"] + + suffix = uuid.uuid4().hex[:8] + namespace = f"test_policy_alias_{suffix}" + table_name = f"events_{suffix}" + table = f"{CATALOG_NAME}.`{namespace}.{table_name}`" + user = f"tenant_user_{suffix}" + password = "pass" + + load_catalog_impl(started_cluster) + create_clickhouse_iceberg_database(started_cluster, node1, CATALOG_NAME) + create_clickhouse_iceberg_table( + started_cluster, node1, namespace, table_name, "(tenant_id UInt32, value String)" + ) + node1.query( + f"INSERT INTO {table} VALUES (1, 'a'), (1, 'b'), (2, 'c'), (2, 'd'), (2, 'e')", + settings={ + "allow_insert_into_iceberg": 1, + "write_full_path_in_iceberg_metadata": 1, + }, + ) + + try: + node1.query(f"CREATE USER {user} IDENTIFIED BY '{password}'") + node1.query(f"GRANT SELECT ON {table} TO {user}") + node1.query(f"GRANT S3 ON *.* TO {user}") + node1.query(f"GRANT CREATE TEMPORARY TABLE ON *.* TO {user}") + node1.query( + f"CREATE ROW POLICY policy_{user} ON {table} USING tenant_id = 1 TO {user}" + ) + + settings = { + "object_storage_cluster": "cluster_swarm", + "enable_analyzer": enable_analyzer, + "prefer_column_name_to_alias": 0, + } + + answer, error = node1.query_and_get_answer_with_error( + f"SELECT 1 AS tenant_id, value FROM {table} ORDER BY value", + user=user, + password=password, + settings=settings, + ) + assert "NOT_IMPLEMENTED" in error + assert "shadows a column used by the policy" in error + + answer, error = node1.query_and_get_answer_with_error( + f"WITH 1 AS tenant_id SELECT count() FROM {table}", + user=user, + password=password, + settings=settings, + ) + assert answer == "2\n" or "NOT_IMPLEMENTED" in error + + assert ( + node1.query( + f"SELECT value AS v FROM {table} ORDER BY v", + user=user, + password=password, + settings=settings, + ) + == "a\nb\n" + ) + finally: + node1.query(f"DROP ROW POLICY IF EXISTS policy_{user} ON {table}") + node1.query(f"DROP USER IF EXISTS {user}") + node1.query(f"DROP TABLE IF EXISTS {table}") + + +def test_row_policy_does_not_require_grant_on_policy_column_with_object_storage_cluster( + started_cluster, +): + node1 = started_cluster.instances["node1"] + + suffix = uuid.uuid4().hex[:8] + namespace = f"test_policy_column_grant_{suffix}" + table_name = f"events_{suffix}" + table = f"{CATALOG_NAME}.`{namespace}.{table_name}`" + user = f"tenant_user_{suffix}" + password = "pass" + + load_catalog_impl(started_cluster) + create_clickhouse_iceberg_database(started_cluster, node1, CATALOG_NAME) + create_clickhouse_iceberg_table( + started_cluster, node1, namespace, table_name, "(tenant_id UInt32, value String)" + ) + node1.query( + f"INSERT INTO {table} VALUES (1, 'a'), (1, 'b'), (2, 'c'), (2, 'd'), (2, 'e')", + settings={ + "allow_insert_into_iceberg": 1, + "write_full_path_in_iceberg_metadata": 1, + }, + ) + + try: + node1.query(f"CREATE USER {user} IDENTIFIED BY '{password}'") + node1.query(f"GRANT SELECT(value) ON {table} TO {user}") + node1.query(f"GRANT S3 ON *.* TO {user}") + node1.query(f"GRANT CREATE TEMPORARY TABLE ON *.* TO {user}") + node1.query( + f"CREATE ROW POLICY policy_{user} ON {table} USING tenant_id = 1 TO {user}" + ) + + assert ( + node1.query( + f"SELECT value FROM {table} ORDER BY value", + user=user, + password=password, + ) + == "a\nb\n" + ) + + assert ( + node1.query( + f"SELECT value FROM {table} ORDER BY value", + user=user, + password=password, + settings={"object_storage_cluster": "cluster_swarm"}, + ) + == "a\nb\n" + ) + + assert ( + node1.query( + f"SELECT count() FROM {table}", + user=user, + password=password, + settings={"object_storage_cluster": "cluster_swarm"}, + ) + == "2\n" + ) + finally: + node1.query(f"DROP ROW POLICY IF EXISTS policy_{user} ON {table}") + node1.query(f"DROP USER IF EXISTS {user}") assert node.query(f"SELECT id, s, toTypeName(s) FROM {CATALOG_NAME}.`{ns}.{tbl}`") == "1\t2\tInt64\n" From 0f0893d3c0ce22030b69156480f2f10a4a0690f9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Lizardo?= Date: Thu, 3 Dec 2026 18:01:19 +0100 Subject: [PATCH 4/9] Reject ARRAY JOIN when a row policy applies to a swarm read MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `ASTSelectQuery::hasJoin` does not cover `ARRAY JOIN`. The row policy is injected into the `WHERE` of the query sent to the swarm nodes, which is evaluated after the `ARRAY JOIN`, so the policy saw the expanded elements instead of the original column. For example, `USING empty(tags)` with `ARRAY JOIN tags` evaluated `empty('')` instead of `empty([''])`. Throw `NOT_IMPLEMENTED` for a query sent to the swarm nodes that contains an `ARRAY JOIN` while a row policy applies, until policies are evaluated before the expansion. Add an integration test for both analyzers. With the new analyzer the `ARRAY JOIN` runs above the storage read and returns only the rows allowed by the policy. Signed-off-by: Luís Lizardo --- src/Storages/IStorageCluster.cpp | 18 ++++- .../integration/test_database_iceberg/test.py | 71 ++++++++++++++++++- 2 files changed, 86 insertions(+), 3 deletions(-) diff --git a/src/Storages/IStorageCluster.cpp b/src/Storages/IStorageCluster.cpp index 98d317457cc3..5cfa541c9817 100644 --- a/src/Storages/IStorageCluster.cpp +++ b/src/Storages/IStorageCluster.cpp @@ -689,6 +689,20 @@ void collectAliases(const ASTPtr & ast, const String & table_alias, NameSet & al collectAliases(child, table_alias, aliases); } +bool selectHasArrayJoin(const ASTSelectQuery & select_query) +{ + const auto tables = select_query.tables(); + if (!tables) + return false; + + for (const auto & child : tables->children) + { + if (child->as().array_join) + return true; + } + return false; +} + void applyRowPolicyToQueryToSend(ASTPtr & query_to_send, const StorageID & storage_id, const ContextPtr & context) { if (!storage_id.hasDatabase()) @@ -711,10 +725,10 @@ void applyRowPolicyToQueryToSend(ASTPtr & query_to_send, const StorageID & stora } } - if (!select_query || select_query->hasJoin()) + if (!select_query || select_query->hasJoin() || selectHasArrayJoin(*select_query)) throw Exception( ErrorCodes::NOT_IMPLEMENTED, - "Row policies on {} cannot be applied to a query sent to cluster nodes that is not a single SELECT without JOIN", + "Row policies on {} cannot be applied to a query sent to cluster nodes that is not a single SELECT without JOIN or ARRAY JOIN", storage_id.getNameForLogs()); auto policy_names = NameSet{}; diff --git a/tests/integration/test_database_iceberg/test.py b/tests/integration/test_database_iceberg/test.py index 6afd8c5a62f1..fa79d0834b7b 100644 --- a/tests/integration/test_database_iceberg/test.py +++ b/tests/integration/test_database_iceberg/test.py @@ -5397,4 +5397,73 @@ def test_row_policy_does_not_require_grant_on_policy_column_with_object_storage_ finally: node1.query(f"DROP ROW POLICY IF EXISTS policy_{user} ON {table}") node1.query(f"DROP USER IF EXISTS {user}") - assert node.query(f"SELECT id, s, toTypeName(s) FROM {CATALOG_NAME}.`{ns}.{tbl}`") == "1\t2\tInt64\n" + node1.query(f"DROP TABLE IF EXISTS {table}") + + +@pytest.mark.parametrize("enable_analyzer", [0, 1]) +def test_row_policy_rejects_array_join_with_object_storage_cluster( + started_cluster, enable_analyzer +): + node1 = started_cluster.instances["node1"] + + suffix = uuid.uuid4().hex[:8] + namespace = f"test_policy_array_join_{suffix}" + table_name = f"events_{suffix}" + table = f"{CATALOG_NAME}.`{namespace}.{table_name}`" + user = f"tenant_user_{suffix}" + password = "pass" + + load_catalog_impl(started_cluster) + create_clickhouse_iceberg_database(started_cluster, node1, CATALOG_NAME) + create_clickhouse_iceberg_table( + started_cluster, node1, namespace, table_name, "(tenant_id UInt32, value String)" + ) + node1.query( + f"INSERT INTO {table} VALUES (1, 'a'), (1, 'b'), (2, 'c'), (2, 'd'), (2, 'e')", + settings={ + "allow_insert_into_iceberg": 1, + "write_full_path_in_iceberg_metadata": 1, + }, + ) + + try: + node1.query(f"CREATE USER {user} IDENTIFIED BY '{password}'") + node1.query(f"GRANT SELECT ON {table} TO {user}") + node1.query(f"GRANT S3 ON *.* TO {user}") + node1.query(f"GRANT CREATE TEMPORARY TABLE ON *.* TO {user}") + node1.query( + f"CREATE ROW POLICY policy_{user} ON {table} USING tenant_id = 1 TO {user}" + ) + + settings = {"enable_analyzer": enable_analyzer} + swarm_settings = {**settings, "object_storage_cluster": "cluster_swarm"} + + assert ( + node1.query( + f"SELECT value FROM {table} ARRAY JOIN [1, 2] AS n ORDER BY value, n", + user=user, + password=password, + settings=settings, + ) + == "a\na\nb\nb\n" + ) + + for query, expected in ( + ( + f"SELECT value FROM {table} ARRAY JOIN [1, 2] AS n ORDER BY value, n", + "a\na\nb\nb\n", + ), + (f"SELECT count() FROM {table} ARRAY JOIN [1, 2] AS n", "4\n"), + ): + answer, error = node1.query_and_get_answer_with_error( + query, user=user, password=password, settings=swarm_settings + ) + if enable_analyzer == 0: + assert "NOT_IMPLEMENTED" in error + assert "ARRAY JOIN" in error + else: + assert answer == expected or "NOT_IMPLEMENTED" in error + finally: + node1.query(f"DROP ROW POLICY IF EXISTS policy_{user} ON {table}") + node1.query(f"DROP USER IF EXISTS {user}") + node1.query(f"DROP TABLE IF EXISTS {table}") From c5b59a39dba102ae4c41a30ea87224756340d3d6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Lizardo?= Date: Fri, 4 Dec 2026 10:48:01 +0100 Subject: [PATCH 5/9] Reuse existing AST helpers in the swarm row policy check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Collect policy identifiers with `IAST::collectIdentifierNames`, detect `ARRAY JOIN` with `ASTSelectQuery::arrayJoinExpressionList` and collect query aliases with `QueryAliasesNoSubqueriesVisitor` instead of local copies of the same logic. Signed-off-by: Luís Lizardo --- src/Storages/IStorageCluster.cpp | 73 +++++++++----------------------- 1 file changed, 19 insertions(+), 54 deletions(-) diff --git a/src/Storages/IStorageCluster.cpp b/src/Storages/IStorageCluster.cpp index 5cfa541c9817..e6fdade2a765 100644 --- a/src/Storages/IStorageCluster.cpp +++ b/src/Storages/IStorageCluster.cpp @@ -19,6 +19,7 @@ #include #include #include +#include #include #include #include @@ -655,54 +656,6 @@ void IStorageCluster::readFromRemoteInitiator( namespace { -void collectIdentifierNames(const ASTPtr & ast, NameSet & names) -{ - if (const auto * identifier = ast->as()) - { - names.insert(identifier->name()); - if (!identifier->name_parts.empty()) - names.insert(identifier->name_parts.front()); - } - - for (const auto & child : ast->children) - collectIdentifierNames(child, names); -} - -void collectAliases(const ASTPtr & ast, const String & table_alias, NameSet & aliases) -{ - if (const auto * with_alias = dynamic_cast(ast.get())) - { - const auto alias = with_alias->tryGetAlias(); - const auto * identifier = ast->as(); - const auto is_identity_alias = identifier - && (identifier->name() == alias - || (!table_alias.empty() && identifier->name_parts.size() == 2 && identifier->name_parts[0] == table_alias - && identifier->name_parts[1] == alias)); - if (!alias.empty() && !is_identity_alias) - aliases.insert(alias); - } - - if (ast->as() || ast->as()) - return; - - for (const auto & child : ast->children) - collectAliases(child, table_alias, aliases); -} - -bool selectHasArrayJoin(const ASTSelectQuery & select_query) -{ - const auto tables = select_query.tables(); - if (!tables) - return false; - - for (const auto & child : tables->children) - { - if (child->as().array_join) - return true; - } - return false; -} - void applyRowPolicyToQueryToSend(ASTPtr & query_to_send, const StorageID & storage_id, const ContextPtr & context) { if (!storage_id.hasDatabase()) @@ -725,20 +678,32 @@ void applyRowPolicyToQueryToSend(ASTPtr & query_to_send, const StorageID & stora } } - if (!select_query || select_query->hasJoin() || selectHasArrayJoin(*select_query)) + if (!select_query || select_query->hasJoin() || select_query->arrayJoinExpressionList().first) throw Exception( ErrorCodes::NOT_IMPLEMENTED, "Row policies on {} cannot be applied to a query sent to cluster nodes that is not a single SELECT without JOIN or ARRAY JOIN", storage_id.getNameForLogs()); + auto policy_identifiers = IdentifierNameSet{}; + row_policy_filter->expression->collectIdentifierNames(policy_identifiers); auto policy_names = NameSet{}; - collectIdentifierNames(row_policy_filter->expression, policy_names); - auto aliases = NameSet{}; + for (const auto & identifier : policy_identifiers) + { + policy_names.insert(identifier); + policy_names.insert(identifier.substr(0, identifier.find('.'))); + } + const auto table_alias = DatabaseAndTableWithAlias(*getTableExpression(*select_query, 0)).alias; - collectAliases(query_to_send, table_alias, aliases); - for (const auto & alias : aliases) + auto aliases = Aliases{}; + QueryAliasesNoSubqueriesVisitor(aliases).visit(select_query->clone()); + for (const auto & [alias, alias_ast] : aliases) { - if (policy_names.contains(alias)) + const auto * identifier = alias_ast->as(); + const auto is_identity_alias = identifier + && (identifier->name() == alias + || (!table_alias.empty() && identifier->name_parts.size() == 2 && identifier->name_parts[0] == table_alias + && identifier->name_parts[1] == alias)); + if (!is_identity_alias && policy_names.contains(alias)) throw Exception( ErrorCodes::NOT_IMPLEMENTED, "Row policy on {} cannot be applied because the query defines the alias `{}` that shadows a column used by the policy", From 02a678fd6f950364da974d730e759b18a9aee2e2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Lizardo?= Date: Fri, 4 Dec 2026 11:09:17 +0100 Subject: [PATCH 6/9] Apply the row policy on swarm nodes with `additional_table_filters` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pass the row policy to the swarm nodes as an `additional_table_filters` entry for the table function alias instead of adding it to the `WHERE` or `PREWHERE` of the query sent to them. The worker then applies it as a separate table filter, resolved against the source table, the way a row policy is applied to a local read. This removes the alias shadowing check and the `ARRAY JOIN` rejection, because a filter resolved against the table is not affected by aliases of the query nor evaluated after the expansion of `ARRAY JOIN`, and it keeps the policy out of the user predicates, so a user expression cannot observe rows the policy removes. A filter already set by the user for the same table alias is combined with the policy using `AND`. A query that joins the swarm table is still rejected. Signed-off-by: Luís Lizardo --- src/Storages/IStorageCluster.cpp | 76 ++++++------- .../integration/test_database_iceberg/test.py | 101 ++++++++++++++---- 2 files changed, 120 insertions(+), 57 deletions(-) diff --git a/src/Storages/IStorageCluster.cpp b/src/Storages/IStorageCluster.cpp index e6fdade2a765..6be1b03558c9 100644 --- a/src/Storages/IStorageCluster.cpp +++ b/src/Storages/IStorageCluster.cpp @@ -19,7 +19,6 @@ #include #include #include -#include #include #include #include @@ -80,6 +79,7 @@ namespace DB namespace Setting { extern const SettingsBool allow_experimental_analyzer; + extern const SettingsMap additional_table_filters; extern const SettingsBool async_query_sending_for_remote; extern const SettingsBool async_socket_for_remote; extern const SettingsBool skip_unavailable_shards; @@ -656,15 +656,15 @@ void IStorageCluster::readFromRemoteInitiator( namespace { -void applyRowPolicyToQueryToSend(ASTPtr & query_to_send, const StorageID & storage_id, const ContextPtr & context) +ContextPtr applyRowPolicyToQueryToSend(ASTPtr & query_to_send, const StorageID & storage_id, const ContextPtr & context) { if (!storage_id.hasDatabase()) - return; + return context; const auto row_policy_filter = context->getRowPolicyFilter(storage_id.getDatabaseName(), storage_id.getTableName(), RowPolicyFilterType::SELECT_FILTER); if (!row_policy_filter || row_policy_filter->isAlwaysTrue()) - return; + return context; query_to_send = query_to_send->clone(); @@ -678,44 +678,46 @@ void applyRowPolicyToQueryToSend(ASTPtr & query_to_send, const StorageID & stora } } - if (!select_query || select_query->hasJoin() || select_query->arrayJoinExpressionList().first) + if (!select_query || select_query->hasJoin()) throw Exception( ErrorCodes::NOT_IMPLEMENTED, - "Row policies on {} cannot be applied to a query sent to cluster nodes that is not a single SELECT without JOIN or ARRAY JOIN", + "Row policies on {} cannot be applied to a query sent to cluster nodes that is not a single SELECT without JOIN", storage_id.getNameForLogs()); - auto policy_identifiers = IdentifierNameSet{}; - row_policy_filter->expression->collectIdentifierNames(policy_identifiers); - auto policy_names = NameSet{}; - for (const auto & identifier : policy_identifiers) + auto * table_function = getTableExpression(*select_query, 0)->table_function.get(); + auto * table_function_with_alias = dynamic_cast(table_function); + if (!table_function_with_alias) + throw Exception( + ErrorCodes::LOGICAL_ERROR, + "Expected a table function in the query sent to cluster nodes for {}, got '{}'", + storage_id.getNameForLogs(), + query_to_send->formatForErrorMessage()); + + auto table_alias = table_function_with_alias->tryGetAlias(); + if (table_alias.empty()) { - policy_names.insert(identifier); - policy_names.insert(identifier.substr(0, identifier.find('.'))); + table_alias = "__row_policy_table"; + table_function_with_alias->setAlias(table_alias); } - const auto table_alias = DatabaseAndTableWithAlias(*getTableExpression(*select_query, 0)).alias; - auto aliases = Aliases{}; - QueryAliasesNoSubqueriesVisitor(aliases).visit(select_query->clone()); - for (const auto & [alias, alias_ast] : aliases) + auto policy_expression = row_policy_filter->expression->formatWithSecretsOneLine(); + + auto new_settings = Settings{context->getSettingsRef()}; + auto filters = Map{}; + for (const auto & filter : new_settings[Setting::additional_table_filters].value) { - const auto * identifier = alias_ast->as(); - const auto is_identity_alias = identifier - && (identifier->name() == alias - || (!table_alias.empty() && identifier->name_parts.size() == 2 && identifier->name_parts[0] == table_alias - && identifier->name_parts[1] == alias)); - if (!is_identity_alias && policy_names.contains(alias)) - throw Exception( - ErrorCodes::NOT_IMPLEMENTED, - "Row policy on {} cannot be applied because the query defines the alias `{}` that shadows a column used by the policy", - storage_id.getNameForLogs(), - alias); + const auto & tuple = filter.safeGet(); + if (tuple.at(0).safeGet() == table_alias) + policy_expression = fmt::format("({}) AND ({})", policy_expression, tuple.at(1).safeGet()); + else + filters.push_back(filter); } + filters.push_back(Tuple{table_alias, std::move(policy_expression)}); + new_settings[Setting::additional_table_filters] = std::move(filters); - const auto expression = select_query->prewhere() ? ASTSelectQuery::Expression::PREWHERE : ASTSelectQuery::Expression::WHERE; - auto conditions = ASTs{row_policy_filter->expression->clone()}; - if (auto existing = select_query->getExpression(expression, /*with_alias=*/false)) - conditions.push_back(std::move(existing)); - select_query->setExpression(expression, makeASTForLogicalAnd(std::move(conditions))); + auto new_context = Context::createCopy(context); + new_context->setSettings(new_settings); + return new_context; } } @@ -851,11 +853,13 @@ void IStorageCluster::read( query_to_send = interpreter.getQueryInfo().query->clone(); } - applyRowPolicyToQueryToSend(query_to_send, getStorageID(), context); - updateQueryToSendIfNeeded( query_to_send, storage_snapshot, context, /*make_cluster_function=*/true, /*add_structure_and_format=*/true); + const auto worker_context = applyRowPolicyToQueryToSend(query_to_send, getStorageID(), context); + + const auto worker_context = applyRowPolicyToQueryToSend(query_to_send, getStorageID(), context); + /// In case the current node is not supposed to initiate the clustered query /// Sends this query to a remote initiator using the `remote` table function if (settings[Setting::object_storage_remote_initiator]) @@ -879,7 +883,7 @@ void IStorageCluster::read( column_names, storage_snapshot, query_info, - context, + worker_context, processed_stage, max_block_size, num_streams, @@ -920,7 +924,7 @@ void IStorageCluster::read( column_names, query_info, storage_snapshot, - context, + worker_context, sample_block, std::move(this_ptr), std::move(query_to_send), diff --git a/tests/integration/test_database_iceberg/test.py b/tests/integration/test_database_iceberg/test.py index fa79d0834b7b..2b47498df307 100644 --- a/tests/integration/test_database_iceberg/test.py +++ b/tests/integration/test_database_iceberg/test.py @@ -5300,22 +5300,25 @@ def test_row_policy_not_bypassed_by_select_alias_with_object_storage_cluster( "prefer_column_name_to_alias": 0, } - answer, error = node1.query_and_get_answer_with_error( - f"SELECT 1 AS tenant_id, value FROM {table} ORDER BY value", - user=user, - password=password, - settings=settings, + assert ( + node1.query( + f"SELECT 1 AS tenant_id, value FROM {table} ORDER BY value", + user=user, + password=password, + settings=settings, + ) + == "1\ta\n1\tb\n" ) - assert "NOT_IMPLEMENTED" in error - assert "shadows a column used by the policy" in error - answer, error = node1.query_and_get_answer_with_error( - f"WITH 1 AS tenant_id SELECT count() FROM {table}", - user=user, - password=password, - settings=settings, + assert ( + node1.query( + f"WITH 1 AS tenant_id SELECT count() FROM {table}", + user=user, + password=password, + settings=settings, + ) + == "2\n" ) - assert answer == "2\n" or "NOT_IMPLEMENTED" in error assert ( node1.query( @@ -5401,7 +5404,7 @@ def test_row_policy_does_not_require_grant_on_policy_column_with_object_storage_ @pytest.mark.parametrize("enable_analyzer", [0, 1]) -def test_row_policy_rejects_array_join_with_object_storage_cluster( +def test_row_policy_applies_before_array_join_with_object_storage_cluster( started_cluster, enable_analyzer ): node1 = started_cluster.instances["node1"] @@ -5455,14 +5458,70 @@ def test_row_policy_rejects_array_join_with_object_storage_cluster( ), (f"SELECT count() FROM {table} ARRAY JOIN [1, 2] AS n", "4\n"), ): - answer, error = node1.query_and_get_answer_with_error( - query, user=user, password=password, settings=swarm_settings + assert ( + node1.query( + query, user=user, password=password, settings=swarm_settings + ) + == expected + ) + finally: + node1.query(f"DROP ROW POLICY IF EXISTS policy_{user} ON {table}") + node1.query(f"DROP USER IF EXISTS {user}") + node1.query(f"DROP TABLE IF EXISTS {table}") + + +def test_row_policy_is_applied_before_user_predicates_with_object_storage_cluster( + started_cluster, +): + node1 = started_cluster.instances["node1"] + + suffix = uuid.uuid4().hex[:8] + namespace = f"test_policy_side_channel_{suffix}" + table_name = f"events_{suffix}" + table = f"{CATALOG_NAME}.`{namespace}.{table_name}`" + user = f"tenant_user_{suffix}" + password = "pass" + + load_catalog_impl(started_cluster) + create_clickhouse_iceberg_database(started_cluster, node1, CATALOG_NAME) + create_clickhouse_iceberg_table( + started_cluster, node1, namespace, table_name, "(tenant_id UInt32, value String)" + ) + node1.query( + f"INSERT INTO {table} VALUES (1, 'a'), (1, 'b'), (2, 'c'), (2, 'd'), (2, 'e')", + settings={ + "allow_insert_into_iceberg": 1, + "write_full_path_in_iceberg_metadata": 1, + }, + ) + + try: + node1.query(f"CREATE USER {user} IDENTIFIED BY '{password}'") + node1.query(f"GRANT SELECT ON {table} TO {user}") + node1.query(f"GRANT S3 ON *.* TO {user}") + node1.query(f"GRANT CREATE TEMPORARY TABLE ON *.* TO {user}") + node1.query( + f"CREATE ROW POLICY policy_{user} ON {table} USING tenant_id = 1 TO {user}" + ) + + for enable_analyzer in (0, 1): + assert ( + node1.query( + f"SELECT value FROM {table} WHERE throwIf(tenant_id = 2) = 0 ORDER BY value", + user=user, + password=password, + settings={ + "object_storage_cluster": "cluster_swarm", + "enable_analyzer": enable_analyzer, + "short_circuit_function_evaluation": "disable", + "query_plan_optimize_prewhere": 0, + "optimize_move_to_prewhere": 0, + "query_plan_merge_filters": 0, + "query_plan_filter_push_down": 0, + }, + ) + == "a\nb\n" ) - if enable_analyzer == 0: - assert "NOT_IMPLEMENTED" in error - assert "ARRAY JOIN" in error - else: - assert answer == expected or "NOT_IMPLEMENTED" in error finally: node1.query(f"DROP ROW POLICY IF EXISTS policy_{user} ON {table}") node1.query(f"DROP USER IF EXISTS {user}") From 2cb38551334b54acfd9aadd07296d2de18d3247f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Lizardo?= Date: Fri, 4 Dec 2026 11:55:50 +0100 Subject: [PATCH 7/9] Keep the row policy when the client sets `additional_table_filters` MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Merge every client filter that targets the worker table, by the alias of the table function or by `_table_function.`, into the policy entry, so the first match on the worker always carries the policy and the restrictions of the client are retained. Rewrite `additional_table_filters` in the `SETTINGS` clause of the query sent to the swarm nodes when it is present, including `DEFAULT`, because with the old analyzer the clause is applied over the received context and removed the policy. Add a regression test with both analyzers. Signed-off-by: Luís Lizardo --- src/Storages/IStorageCluster.cpp | 18 +++- .../integration/test_database_iceberg/test.py | 83 +++++++++++++++++++ 2 files changed, 98 insertions(+), 3 deletions(-) diff --git a/src/Storages/IStorageCluster.cpp b/src/Storages/IStorageCluster.cpp index 6be1b03558c9..51dc8d9a9ae9 100644 --- a/src/Storages/IStorageCluster.cpp +++ b/src/Storages/IStorageCluster.cpp @@ -52,6 +52,7 @@ #include #include #include +#include #include #include #include @@ -700,20 +701,31 @@ ContextPtr applyRowPolicyToQueryToSend(ASTPtr & query_to_send, const StorageID & table_function_with_alias->setAlias(table_alias); } + const auto * function = table_function->as(); + const auto worker_table_name = fmt::format("_table_function.{}", function ? function->name : String{}); + auto policy_expression = row_policy_filter->expression->formatWithSecretsOneLine(); auto new_settings = Settings{context->getSettingsRef()}; auto filters = Map{}; + filters.push_back(Tuple{table_alias, String{}}); for (const auto & filter : new_settings[Setting::additional_table_filters].value) { const auto & tuple = filter.safeGet(); - if (tuple.at(0).safeGet() == table_alias) + const auto & key = tuple.at(0).safeGet(); + if (key == table_alias || key == worker_table_name) policy_expression = fmt::format("({}) AND ({})", policy_expression, tuple.at(1).safeGet()); else filters.push_back(filter); } - filters.push_back(Tuple{table_alias, std::move(policy_expression)}); - new_settings[Setting::additional_table_filters] = std::move(filters); + filters.front() = Tuple{table_alias, std::move(policy_expression)}; + new_settings[Setting::additional_table_filters] = filters; + + if (auto * settings_ast = select_query->settings() ? select_query->settings()->as() : nullptr) + { + if (settings_ast->changes.removeSetting("additional_table_filters") || std::erase(settings_ast->default_settings, "additional_table_filters")) + settings_ast->changes.setSetting("additional_table_filters", Field{filters}); + } auto new_context = Context::createCopy(context); new_context->setSettings(new_settings); diff --git a/tests/integration/test_database_iceberg/test.py b/tests/integration/test_database_iceberg/test.py index 2b47498df307..459dd3e269a6 100644 --- a/tests/integration/test_database_iceberg/test.py +++ b/tests/integration/test_database_iceberg/test.py @@ -5526,3 +5526,86 @@ def test_row_policy_is_applied_before_user_predicates_with_object_storage_cluste node1.query(f"DROP ROW POLICY IF EXISTS policy_{user} ON {table}") node1.query(f"DROP USER IF EXISTS {user}") node1.query(f"DROP TABLE IF EXISTS {table}") + + +@pytest.mark.parametrize("enable_analyzer", [0, 1]) +def test_row_policy_not_overridden_by_additional_table_filters_with_object_storage_cluster( + started_cluster, enable_analyzer +): + node1 = started_cluster.instances["node1"] + + suffix = uuid.uuid4().hex[:8] + namespace = f"test_policy_additional_filters_{suffix}" + table_name = f"events_{suffix}" + table = f"{CATALOG_NAME}.`{namespace}.{table_name}`" + user = f"tenant_user_{suffix}" + password = "pass" + + load_catalog_impl(started_cluster) + create_clickhouse_iceberg_database(started_cluster, node1, CATALOG_NAME) + create_clickhouse_iceberg_table( + started_cluster, node1, namespace, table_name, "(tenant_id UInt32, value String)" + ) + node1.query( + f"INSERT INTO {table} VALUES (1, 'a'), (1, 'b'), (2, 'c'), (2, 'd'), (2, 'e')", + settings={ + "allow_insert_into_iceberg": 1, + "write_full_path_in_iceberg_metadata": 1, + }, + ) + + try: + node1.query(f"CREATE USER {user} IDENTIFIED BY '{password}'") + node1.query(f"GRANT SELECT ON {table} TO {user}") + node1.query(f"GRANT S3 ON *.* TO {user}") + node1.query(f"GRANT CREATE TEMPORARY TABLE ON *.* TO {user}") + node1.query( + f"CREATE ROW POLICY policy_{user} ON {table} USING tenant_id = 1 TO {user}" + ) + + settings = { + "object_storage_cluster": "cluster_swarm", + "enable_analyzer": enable_analyzer, + } + + def select(query, extra_settings=None): + return node1.query( + query, + user=user, + password=password, + settings={**settings, **(extra_settings or {})}, + ) + + select_values = f"SELECT value FROM {table} ORDER BY value" + + assert ( + select( + select_values, + {"additional_table_filters": "{'_table_function.icebergS3Cluster':'1'}"}, + ) + == "a\nb\n" + ) + + assert ( + select( + select_values, + { + "additional_table_filters": "{'_table_function.icebergS3Cluster':'value = \\'a\\''}" + }, + ) + == "a\n" + ) + + assert ( + select(f"{select_values} SETTINGS additional_table_filters = {{}}") + == "a\nb\n" + ) + + assert ( + select(f"{select_values} SETTINGS additional_table_filters = DEFAULT") + == "a\nb\n" + ) + finally: + node1.query(f"DROP ROW POLICY IF EXISTS policy_{user} ON {table}") + node1.query(f"DROP USER IF EXISTS {user}") + node1.query(f"DROP TABLE IF EXISTS {table}") From b038c260a4d19d6ca85b77c97de818f8aefcde4a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Lizardo?= Date: Fri, 4 Dec 2026 12:39:38 +0100 Subject: [PATCH 8/9] Parse client table filters and drop every duplicate setting for swarm reads MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Parse each client `additional_table_filters` entry that targets the worker table as a complete expression and combine its AST with the row policy, instead of interpolating the text, so a filter such as `1) OR (1` is rejected rather than widening the policy. Remove every assignment and reset of `additional_table_filters` from the `SETTINGS` clause of the query sent to the swarm nodes before adding the policy-bearing map, because a clause with several assignments kept a trailing empty map. Add regression tests for both cases. Signed-off-by: Luís Lizardo --- src/Storages/IStorageCluster.cpp | 35 +++++++++++++++---- .../integration/test_database_iceberg/test.py | 19 ++++++++++ 2 files changed, 47 insertions(+), 7 deletions(-) diff --git a/src/Storages/IStorageCluster.cpp b/src/Storages/IStorageCluster.cpp index 51dc8d9a9ae9..01feca85b918 100644 --- a/src/Storages/IStorageCluster.cpp +++ b/src/Storages/IStorageCluster.cpp @@ -64,6 +64,8 @@ #include #include #include +#include +#include #include #include @@ -81,6 +83,9 @@ namespace Setting { extern const SettingsBool allow_experimental_analyzer; extern const SettingsMap additional_table_filters; + extern const SettingsUInt64 max_parser_backtracks; + extern const SettingsUInt64 max_parser_depth; + extern const SettingsUInt64 max_query_size; extern const SettingsBool async_query_sending_for_remote; extern const SettingsBool async_socket_for_remote; extern const SettingsBool skip_unavailable_shards; @@ -704,26 +709,42 @@ ContextPtr applyRowPolicyToQueryToSend(ASTPtr & query_to_send, const StorageID & const auto * function = table_function->as(); const auto worker_table_name = fmt::format("_table_function.{}", function ? function->name : String{}); - auto policy_expression = row_policy_filter->expression->formatWithSecretsOneLine(); - auto new_settings = Settings{context->getSettingsRef()}; + auto conditions = ASTs{row_policy_filter->expression->clone()}; auto filters = Map{}; filters.push_back(Tuple{table_alias, String{}}); for (const auto & filter : new_settings[Setting::additional_table_filters].value) { const auto & tuple = filter.safeGet(); const auto & key = tuple.at(0).safeGet(); - if (key == table_alias || key == worker_table_name) - policy_expression = fmt::format("({}) AND ({})", policy_expression, tuple.at(1).safeGet()); - else + if (key != table_alias && key != worker_table_name) + { filters.push_back(filter); + continue; + } + + const auto & client_filter = tuple.at(1).safeGet(); + auto parser = ParserExpression{}; + conditions.push_back(parseQuery( + parser, + client_filter.data(), + client_filter.data() + client_filter.size(), + "additional filter", + new_settings[Setting::max_query_size], + new_settings[Setting::max_parser_depth], + new_settings[Setting::max_parser_backtracks])); } - filters.front() = Tuple{table_alias, std::move(policy_expression)}; + filters.front() = Tuple{table_alias, makeASTForLogicalAnd(std::move(conditions))->formatWithSecretsOneLine()}; new_settings[Setting::additional_table_filters] = filters; if (auto * settings_ast = select_query->settings() ? select_query->settings()->as() : nullptr) { - if (settings_ast->changes.removeSetting("additional_table_filters") || std::erase(settings_ast->default_settings, "additional_table_filters")) + auto has_assignment = false; + while (settings_ast->changes.removeSetting("additional_table_filters")) + has_assignment = true; + if (std::erase(settings_ast->default_settings, "additional_table_filters")) + has_assignment = true; + if (has_assignment) settings_ast->changes.setSetting("additional_table_filters", Field{filters}); } diff --git a/tests/integration/test_database_iceberg/test.py b/tests/integration/test_database_iceberg/test.py index 459dd3e269a6..2d71ab71ae3d 100644 --- a/tests/integration/test_database_iceberg/test.py +++ b/tests/integration/test_database_iceberg/test.py @@ -5605,6 +5605,25 @@ def select(query, extra_settings=None): select(f"{select_values} SETTINGS additional_table_filters = DEFAULT") == "a\nb\n" ) + + for clause in ( + "additional_table_filters = {}, additional_table_filters = DEFAULT", + "additional_table_filters = DEFAULT, additional_table_filters = {}", + "additional_table_filters = {}, additional_table_filters = {}, additional_table_filters = {}", + ): + assert select(f"{select_values} SETTINGS {clause}") == "a\nb\n" + + answer, error = node1.query_and_get_answer_with_error( + select_values, + user=user, + password=password, + settings={ + **settings, + "additional_table_filters": "{'_table_function.icebergS3Cluster':'1) OR (1'}", + }, + ) + assert "SYNTAX_ERROR" in error + assert answer == "" finally: node1.query(f"DROP ROW POLICY IF EXISTS policy_{user} ON {table}") node1.query(f"DROP USER IF EXISTS {user}") From 0b9b1f1beb277f1c5b44b5917bfd02c524967cd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Lu=C3=ADs=20Lizardo?= Date: Fri, 4 Dec 2026 17:14:09 +0100 Subject: [PATCH 9/9] Fix the merge of the swarm row policy changes with antalya-26.8 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Remove a duplicated declaration of `worker_context` and restore the last assertion of `test_clickhouse_type_annotation_survives_catalog`, which moved into the new tests when they were replayed onto the branch. Signed-off-by: Luís Lizardo --- src/Storages/IStorageCluster.cpp | 2 -- tests/integration/test_database_iceberg/test.py | 3 +++ 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Storages/IStorageCluster.cpp b/src/Storages/IStorageCluster.cpp index 01feca85b918..85fa243a17d6 100644 --- a/src/Storages/IStorageCluster.cpp +++ b/src/Storages/IStorageCluster.cpp @@ -891,8 +891,6 @@ void IStorageCluster::read( const auto worker_context = applyRowPolicyToQueryToSend(query_to_send, getStorageID(), context); - const auto worker_context = applyRowPolicyToQueryToSend(query_to_send, getStorageID(), context); - /// In case the current node is not supposed to initiate the clustered query /// Sends this query to a remote initiator using the `remote` table function if (settings[Setting::object_storage_remote_initiator]) diff --git a/tests/integration/test_database_iceberg/test.py b/tests/integration/test_database_iceberg/test.py index 2d71ab71ae3d..ed56238ce804 100644 --- a/tests/integration/test_database_iceberg/test.py +++ b/tests/integration/test_database_iceberg/test.py @@ -5259,6 +5259,9 @@ def annotations(schema_id=None): assert annotations() == {"id": None, "s": "", "m": "SimpleAggregateFunction(max, Nullable(Int64))"} # The schema the first rows were written with keeps its annotation. assert annotations(0) == {"id": None, "s": "SimpleAggregateFunction(sum, Int64)"} + assert node.query(f"SELECT id, s, toTypeName(s) FROM {CATALOG_NAME}.`{ns}.{tbl}`") == "1\t2\tInt64\n" + + @pytest.mark.parametrize("enable_analyzer", [0, 1]) def test_row_policy_not_bypassed_by_select_alias_with_object_storage_cluster( started_cluster, enable_analyzer