# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. import pytest from superset.mcp_service.chart.schemas import ChartError from superset.mcp_service.dashboard.schemas import DashboardError from superset.mcp_service.dataset.schemas import DatasetError from superset.mcp_service.utils.sanitization import ( _check_dangerous_patterns, _check_sql_patterns, _remove_dangerous_unicode, _strip_html_tags, sanitize_filter_value, sanitize_user_input, ) # --- _strip_html_tags tests --- def test_strip_html_tags_plain_text(): assert _strip_html_tags("hello world") == "hello world" def test_strip_html_tags_preserves_ampersand(): assert _strip_html_tags("A & B") == "A & B" def test_strip_html_tags_preserves_multiple_ampersands(): assert _strip_html_tags("A & B & C") == "A & B & C" def test_strip_html_tags_strips_bold_tags(): assert _strip_html_tags("hello") == "hello" def test_strip_html_tags_strips_script_tags(): result = _strip_html_tags("") assert "" not in result def test_strip_html_tags_strips_entity_encoded_script(): """Entity-encoded tags must be decoded and stripped, not passed through.""" result = _strip_html_tags("<script>alert(1)</script>") assert "" for _ in range(10): value = value.replace("&", "&").replace("<", "<").replace(">", ">") result = _strip_html_tags(value) assert "") assert "" not in result def test_strip_html_tags_img_onerror_entity_bypass(): """Entity-encoded img/onerror should not survive sanitization.""" result = _strip_html_tags("<img src=x onerror=alert(1)>") assert " None: error = "Missing x y" response = error_schema(error=error, error_type="not_found") assert response.error == error # --------------------------------------------------------------------------- # sanitize_sql_expression — Ticket #3. # # Locks in three properties of the SQL-metric sanitizer: # 1. legitimate SQL aggregate expressions pass through unchanged, # 2. the on\w+= event-handler check is NOT inherited (would false-positive # on `monthly = 12`), # 3. statement stacking / comments / DDL+DML / XSS are rejected, while # subqueries pass through (subquery policy lives in Superset core's # ALLOW_ADHOC_SUBQUERY feature flag, not here). # --------------------------------------------------------------------------- def _sanitize_sql(): """Import lazily so the import error surfaces as a per-test failure.""" from superset.mcp_service.utils.sanitization import sanitize_sql_expression return sanitize_sql_expression def test_sanitize_sql_expression_allows_ticket_example(): sanitize_sql_expression = _sanitize_sql() expr = "COUNT(CASE WHEN closed_won THEN 1 END)::numeric / NULLIF(COUNT(*),0)" assert sanitize_sql_expression(expr, "sql_expression") == expr def test_sanitize_sql_expression_no_false_positive_on_equals(): """`monthly = 12` must pass; sanitize_user_input's on\\w+= check matches `on`+`thly`+`=` and would block it. This locks in that the new sanitizer is independent of sanitize_user_input.""" sanitize_sql_expression = _sanitize_sql() expr = "SUM(CASE WHEN monthly = 12 THEN 1 END)" assert sanitize_sql_expression(expr, "sql_expression") == expr def test_sanitize_sql_expression_allows_abs_and_casts(): sanitize_sql_expression = _sanitize_sql() expr = "ABS(SUM(amount))::numeric / 100.0" assert sanitize_sql_expression(expr, "sql_expression") == expr def test_sanitize_sql_expression_allows_subquery(): """Subquery policy belongs to Superset core (ALLOW_ADHOC_SUBQUERY). The MCP-layer sanitizer must NOT block SELECT — otherwise it would override the admin's feature-flag choice.""" sanitize_sql_expression = _sanitize_sql() expr = "(SELECT AVG(x) FROM other_table)" assert sanitize_sql_expression(expr, "sql_expression") == expr def test_sanitize_sql_expression_allows_backticks(): """MySQL/MariaDB use backticks for identifier quoting (``SUM(`Order Date`)``). The SQL execution path has no shell, so the shell-metacharacter concern that blocks backticks in filter values does not apply here. Regression test for an earlier defensive block that broke MySQL identifier syntax.""" sanitize_sql_expression = _sanitize_sql() expr = "SUM(`Order Date`)" assert sanitize_sql_expression(expr, "sql_expression") == expr def test_sanitize_sql_expression_blocks_statement_stacking(): sanitize_sql_expression = _sanitize_sql() with pytest.raises(ValueError, match="statement stacking"): sanitize_sql_expression("SUM(amount); DROP TABLE users", "sql_expression") def test_sanitize_sql_expression_blocks_line_comment(): sanitize_sql_expression = _sanitize_sql() with pytest.raises(ValueError, match="comment"): sanitize_sql_expression("SUM(amount) -- inject", "sql_expression") def test_sanitize_sql_expression_blocks_block_comment(): sanitize_sql_expression = _sanitize_sql() with pytest.raises(ValueError, match="comment"): sanitize_sql_expression("SUM(amount) /* inject */", "sql_expression") @pytest.mark.parametrize( "expr", [ "DROP TABLE users", "DELETE FROM users", "INSERT INTO users VALUES (1)", "UPDATE users SET x=1", "ALTER TABLE users ADD COLUMN x int", "TRUNCATE users", "GRANT ALL ON users TO public", "EXEC sp_helpdb", ], ) def test_sanitize_sql_expression_blocks_ddl_dml(expr: str): sanitize_sql_expression = _sanitize_sql() with pytest.raises(ValueError, match="disallowed"): sanitize_sql_expression(expr, "sql_expression") def test_sanitize_sql_expression_rejects_script_tag(): sanitize_sql_expression = _sanitize_sql() with pytest.raises(ValueError, match="tag-like"): sanitize_sql_expression( "SUM(amount)", "sql_expression" ) def test_sanitize_sql_expression_rejects_zwsp_smuggled_script_tag(): # Regression: `<​script>` previously reconstructed as `