From 89d25c461c737d82f123d7c9c5601e987672814c Mon Sep 17 00:00:00 2001 From: jannisd07 Date: Sat, 5 Dec 2026 14:28:57 +0100 Subject: [PATCH] fix: resolve CTE references by scope in SQL table check A CTE name no longer hides a real table with the same name: schema-qualified tables, tables outside the CTE's scope and the non-recursive self-reference inside a CTE body are now checked against the allowed tables. When extraction fails, no partial result is returned, so the query is rejected. Fixes #1543 --- backend/apps/chat/task/llm.py | 20 ++++++++++-------- backend/tests/test_table_check.py | 34 +++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 8 deletions(-) diff --git a/backend/apps/chat/task/llm.py b/backend/apps/chat/task/llm.py index ab9b390d..529149b1 100644 --- a/backend/apps/chat/task/llm.py +++ b/backend/apps/chat/task/llm.py @@ -26,6 +26,7 @@ from sqlbot_xpack.custom_prompt.models.custom_prompt_model import CustomPromptTypeEnum from sqlbot_xpack.license.license_manage import SQLBotLicenseUtil from sqlglot import exp +from sqlglot.optimizer.scope import traverse_scope from sqlmodel import Session from apps.ai_model.model_factory import LLMConfig, LLMFactory, get_default_config @@ -75,23 +76,26 @@ def extract_tables_from_sql(sql: str, ds_type: str = None) -> set: - """从 SQL 中提取真实表名(排除 CTE 别名)""" + """从 SQL 中提取真实表名(排除 CTE 引用)""" tables = set() dialect = get_sqlglot_dialect(ds_type) try: statements = sqlglot.parse(sql, dialect=dialect) for stmt in statements: if stmt: - # 收集 CTE 别名,排除嵌套 CTE - cte_names = set() - for cte in stmt.find_all(exp.CTE): - if cte.alias: - cte_names.add(cte.alias) + # 只排除在所在作用域内可见的 CTE 引用;带 schema/catalog 的表名不会是 CTE, + # 同名的 CTE 不能遮蔽真实表 + cte_refs = set() + for scope in traverse_scope(stmt): + for table in scope.tables: + if not table.db and not table.catalog and table.name in scope.cte_sources: + cte_refs.add(id(table)) for table in stmt.find_all(exp.Table): - if table.name and table.name not in cte_names: + if table.name and id(table) not in cte_refs: tables.add(table.name) except Exception: - pass + # 解析失败时不返回部分结果,调用方会拒绝执行 + return set() return tables diff --git a/backend/tests/test_table_check.py b/backend/tests/test_table_check.py index e4d03c5c..6ba06c06 100644 --- a/backend/tests/test_table_check.py +++ b/backend/tests/test_table_check.py @@ -6,6 +6,7 @@ import pytest import sqlbot_xpack # noqa: F401 # Initialize the published wheel before app imports. from pydantic import ValidationError +from sqlglot.errors import OptimizeError from apps.chat.models.chat_model import ChatFinishStep from apps.chat.task import llm @@ -74,6 +75,11 @@ def run(task, sql, reported_tables=None): [ "SELECT id FROM sales", "WITH totals AS (SELECT id FROM sales) SELECT * FROM totals", + "WITH a AS (SELECT id FROM sales), b AS (SELECT id FROM a) SELECT * FROM b", + "SELECT * FROM (WITH totals AS (SELECT id FROM sales) SELECT * FROM totals) t", + "WITH t AS (SELECT id FROM sales) SELECT * FROM sales WHERE id IN (SELECT id FROM t)", + "WITH RECURSIVE n(i) AS (SELECT 1 UNION ALL SELECT i + 1 FROM n WHERE i < 3) " + "SELECT * FROM n JOIN sales ON true", ], ) def test_default_allows_known_tables_and_cte_aliases(task, sql): @@ -92,6 +98,22 @@ def test_default_allows_known_tables_and_cte_aliases(task, sql): "SELECT id FROM sales UNION ALL SELECT id FROM secret_payroll", "unauthorized tables: secret_payroll", ), + # A CTE must not hide a real table with the same name (#1543). + ( + "WITH secret_payroll AS (SELECT 1) " + "SELECT * FROM public.secret_payroll JOIN sales ON true", + "unauthorized tables: secret_payroll", + ), + ( + "SELECT * FROM (WITH secret_payroll AS (SELECT 1) SELECT * FROM secret_payroll) t " + "CROSS JOIN secret_payroll JOIN sales ON true", + "unauthorized tables: secret_payroll", + ), + ( + "WITH secret_payroll AS (SELECT * FROM secret_payroll) " + "SELECT * FROM secret_payroll JOIN sales ON true", + "unauthorized tables: secret_payroll", + ), ], ) def test_default_rejects_invalid_or_unknown_tables_before_save_and_execute( @@ -120,6 +142,18 @@ def test_missing_tables_are_rejected_even_when_whitelist_check_is_skipped( task.execute_sql.assert_not_called() +def test_extraction_error_does_not_return_partial_tables(task, monkeypatch): + # The second statement fails after the first one has already been collected. + traverse = Mock(side_effect=[[], OptimizeError("scope error")]) + monkeypatch.setattr(llm, "traverse_scope", traverse) + result = run(task, "SELECT id FROM sales; SELECT id FROM secret_payroll") + assert result["success"] is False + assert "unable to extract table names" in result["message"] + assert traverse.call_count == 2 + task.check_save_sql.assert_not_called() + task.execute_sql.assert_not_called() + + @pytest.mark.parametrize( "sql", [