This is an automated email from the ASF dual-hosted git repository. villebro pushed a commit to branch 7.0 in repository https://gitbox.apache.org/repos/asf/superset.git
commit d079eb5d5e44612bd3cd5b5328bed697d6a6f5be Author: Elizabeth Thompson <[email protected]> AuthorDate: Wed Nov 11 17:16:00 2026 -0800 fix(reports): keep native filters with quoted values in report permalinks (#46060) Co-authored-by: Claude Sonnet 5.5 <[email protected]> Co-authored-by: sadpandajoe <[email protected]> (cherry picked from commit 005534bedfc0b956aec62a7a871bd208f07e35ab) --- superset/reports/models.py | 7 +- tests/unit_tests/commands/report/execute_test.py | 81 +++++++++++++ tests/unit_tests/reports/model_test.py | 128 ++++++++++++++++++--- .../test_dashboard_permalink_native_filters.py | 103 +++++++++++++++++ 4 files changed, 302 insertions(+), 17 deletions(-) diff --git a/superset/reports/models.py b/superset/reports/models.py index 886f89bc52a..46067575a1d 100644 --- a/superset/reports/models.py +++ b/superset/reports/models.py @@ -235,10 +235,9 @@ class ReportSchedule(AuditMixinNullable, ExtraJSONMixin, Model): if filter_warning: warnings.append(filter_warning) params = {**params, **filter_config} - # hack(hughhh): workaround for escaping prison not handling quotes right - decoded = rison.dumps(params) - decoded = decoded.replace("'", "%27") - return decoded, warnings + # The value is URL-encoded exactly once when the permalink redirect + # builds the dashboard URL, so it must stay raw rison here. + return rison.dumps(params), warnings def _generate_native_filter( self, diff --git a/tests/unit_tests/commands/report/execute_test.py b/tests/unit_tests/commands/report/execute_test.py index 127c75af67e..2e0871f2a6b 100644 --- a/tests/unit_tests/commands/report/execute_test.py +++ b/tests/unit_tests/commands/report/execute_test.py @@ -22,9 +22,11 @@ from typing import Any from unittest import mock from unittest.mock import MagicMock, Mock, patch from urllib.error import URLError +from urllib.parse import parse_qs, urlencode from uuid import UUID, uuid4 import pytest +import rison from celery.exceptions import SoftTimeLimitExceeded from pytest_mock import MockerFixture @@ -1177,6 +1179,85 @@ def test_get_dashboard_urls_flag_off_preserves_url_params( ] +@patch("superset.commands.report.execute.CreateDashboardPermalinkCommand") [email protected]("tabs_enabled", [True, False]) +def test_get_dashboard_urls_native_filters_needing_quotes_round_trip( + mock_permalink_cls, + tabs_enabled: bool, + mocker: MockerFixture, + app, +) -> None: + """Filters whose rison needs quoting must reach the permalink state raw, so + the redirect's single URL-encoding is decoded exactly once by the browser.""" + report_schedule = ReportSchedule() + report_schedule.chart = None + report_schedule.chart_id = None + report_schedule.dashboard_id = 123 + report_schedule.dashboard = mocker.MagicMock( + uuid=UUID("12345678-1234-1234-1234-123456789abc") + ) + native_filters: list[dict[str, Any]] = [ + { + "nativeFilterId": "NATIVE_FILTER-text", + "filterType": "filter_select", + "columnName": "region", + "filterValues": ["North America", "O'Brien", "a,b"], + }, + { + "nativeFilterId": "NATIVE_FILTER-range", + "filterType": "filter_range", + "columnName": "num", + "filterValues": [3000, 5000], + }, + { + "nativeFilterId": "NATIVE_FILTER-time", + "filterType": "filter_time", + "columnName": "ds", + "filterValues": ["2004-01-01 : 2005-01-01"], + }, + ] + extra: dict[str, Any] = {"dashboard": {"nativeFilters": native_filters}} + report_schedule.extra = extra # type: ignore[assignment] + mock_permalink_cls.return_value.run.return_value = "permalink_key" + + state_obj = BaseReportState(report_schedule, "January 1, 2021", "execution_id") + with ( + app.test_request_context(), + mock.patch("superset.commands.report.execute.db"), + mock.patch.object( + BaseReportState, "_raise_for_executor_dashboard_access", return_value=None + ), + ): + from superset.extensions import feature_flag_manager # noqa: PLC0415 + + with mock.patch.object( + feature_flag_manager, + "is_feature_enabled", + side_effect=lambda flag: tabs_enabled and flag == "ALERT_REPORT_TABS", + ): + urls = state_obj.get_dashboard_urls() + + assert len(urls) == 1 + assert state_obj._execution_warnings == [] + url_params: list[list[str]] = mock_permalink_cls.call_args_list[0].kwargs["state"][ + "urlParams" + ] + (key, value) = next(p for p in url_params if p[0] == "native_filters") + assert key == "native_filters" + assert "%27" not in value + query = urlencode([(key, value)]) + decoded: dict[str, Any] = rison.loads(parse_qs(query)[key][0]) + assert set(decoded) == {f["nativeFilterId"] for f in native_filters} + assert decoded["NATIVE_FILTER-text"]["filterState"]["value"] == [ + "North America", + "O'Brien", + "a,b", + ] + assert decoded["NATIVE_FILTER-time"]["filterState"]["value"] == ( + "2004-01-01 : 2005-01-01" + ) + + def create_report_schedule( mocker: MockerFixture, custom_width: int | None = None, diff --git a/tests/unit_tests/reports/model_test.py b/tests/unit_tests/reports/model_test.py index 892aaafd835..d2b3904171f 100644 --- a/tests/unit_tests/reports/model_test.py +++ b/tests/unit_tests/reports/model_test.py @@ -15,6 +15,12 @@ # specific language governing permissions and limitations # under the License. +from typing import Any +from urllib import parse + +import pytest +import rison + from superset.reports.models import ReportDataFormat, ReportSchedule @@ -459,24 +465,120 @@ def test_get_native_filters_params_null_native_filters(): assert warnings == [] -def test_get_native_filters_params_rison_quote_escaping(): +def _select(filter_id: str, values: list[Any]) -> dict[str, Any]: + return { + "nativeFilterId": filter_id, + "filterType": "filter_select", + "columnName": "col", + "filterValues": values, + } + + +def _schedule_with(native_filters: list[dict[str, Any]]) -> ReportSchedule: + extra: dict[str, Any] = {"dashboard": {"nativeFilters": native_filters}} report_schedule = ReportSchedule() - report_schedule.extra = { - "dashboard": { - "nativeFilters": [ - { - "nativeFilterId": "F1", - "filterType": "filter_select", - "columnName": "name", - "filterValues": ["O'Brien"], - } - ] - } + report_schedule.extra = extra # type: ignore[assignment] + return report_schedule + + +def _range(filter_id: str) -> dict[str, Any]: + return { + "nativeFilterId": filter_id, + "filterType": "filter_range", + "columnName": "num", + "filterValues": [3000, 5000], + } + + +def _time(filter_id: str, value: str) -> dict[str, Any]: + return { + "nativeFilterId": filter_id, + "filterType": "filter_time", + "columnName": "ds", + "filterValues": [value], } + + +NATIVE_FILTER_ROUND_TRIP_CASES = { + "single_word": [_select("F1", ["Asia"])], + "multi_word": [_select("F1", ["North America", "Electronic Arts"])], + "comma": [_select("F1", ["Smith, John", "a,b"])], + "single_quote": [_select("F1", ["O'Brien"])], + "bang": [_select("F1", ["Hello!"])], + "non_ascii": [_select("F1", ["Zürich", "東京 都"])], + "numeric_range": [_range("F2")], + "time_range_relative": [_time("F3", "Last week")], + "time_range_absolute": [_time("F3", "2004-01-01 : 2005-01-01")], + "combined": [ + _select("F1", ["North America", "O'Brien", "a,b"]), + _select("F4", ["Asia"]), + _range("F2"), + _time("F3", "Last week"), + ], +} + + +def _decode_like_browser(rison_params: str) -> str: + """Encode as the permalink redirect does, then decode once as a browser would.""" + query = parse.urlencode([("native_filters", rison_params)]) + return parse.parse_qs(query)["native_filters"][0] + + [email protected]( + "native_filters", + list(NATIVE_FILTER_ROUND_TRIP_CASES.values()), + ids=list(NATIVE_FILTER_ROUND_TRIP_CASES), +) +def test_get_native_filters_params_round_trips_through_redirect( + native_filters: list[dict[str, Any]], +) -> None: + report_schedule = _schedule_with(native_filters) result, warnings = report_schedule.get_native_filters_params() + + expected: dict[str, Any] = {} + for native_filter in native_filters: + config, _ = report_schedule._generate_native_filter( + native_filter["nativeFilterId"], + native_filter["filterType"], + native_filter["columnName"], + native_filter["filterValues"], + ) + expected.update(config) + + assert warnings == [] + assert rison.loads(_decode_like_browser(result)) == expected + + +def test_get_native_filters_params_single_word_unchanged() -> None: + report_schedule = _schedule_with([_select("F1", ["Asia"])]) + result, _ = report_schedule.get_native_filters_params() + assert "%" not in result assert "'" not in result - assert "%27" in result + assert "!(Asia)" in result + + +def test_get_native_filters_params_does_not_pre_escape_quotes() -> None: + """ + The redirect URL-encodes the value, so a pre-escaped ``%27`` would be + double-encoded and fail to decode in the browser. + """ + report_schedule = _schedule_with([_select("F1", ["O'Brien"])]) + result, warnings = report_schedule.get_native_filters_params() + assert "%27" not in result + assert warnings == [] + + +def test_get_native_filters_params_newline_value_does_not_warn() -> None: + """ + Python ``rison`` is stricter than the frontend decoder and cannot parse the + unquoted ``!(a\\nb)`` it emits for a newline, but the dashboard decodes it + fine, so no "not applied" warning may be raised for it. + """ + report_schedule = _schedule_with([_select("F1", ["a\nb"])]) + result, warnings = report_schedule.get_native_filters_params() assert warnings == [] + assert "%" not in result + assert "a\nb" in result def test_get_native_filters_params_unknown_filter_type(): diff --git a/tests/unit_tests/views/test_dashboard_permalink_native_filters.py b/tests/unit_tests/views/test_dashboard_permalink_native_filters.py new file mode 100644 index 00000000000..5c663ad84ab --- /dev/null +++ b/tests/unit_tests/views/test_dashboard_permalink_native_filters.py @@ -0,0 +1,103 @@ +# 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. +"""Report native filters must survive the dashboard permalink redirect.""" + +from typing import Any +from urllib.parse import parse_qs, urlsplit + +import pytest +import rison +from pytest_mock import MockerFixture + +from superset.reports.models import ReportSchedule + +NATIVE_FILTERS: dict[str, list[dict[str, Any]]] = { + "multi_word": [ + { + "nativeFilterId": "F1", + "filterType": "filter_select", + "columnName": "region", + "filterValues": ["North America", "Electronic Arts"], + } + ], + "comma_and_quote": [ + { + "nativeFilterId": "F1", + "filterType": "filter_select", + "columnName": "name", + "filterValues": ["Smith, John", "O'Brien"], + } + ], + "numeric_range": [ + { + "nativeFilterId": "F2", + "filterType": "filter_range", + "columnName": "num", + "filterValues": [3000, 5000], + } + ], + "time_range": [ + { + "nativeFilterId": "F3", + "filterType": "filter_time", + "columnName": "ds", + "filterValues": ["2004-01-01 : 2005-01-01"], + }, + { + "nativeFilterId": "F4", + "filterType": "filter_time", + "columnName": "ds", + "filterValues": ["Last week"], + }, + ], +} + + [email protected]("case", list(NATIVE_FILTERS)) +def test_dashboard_permalink_redirect_native_filters_round_trip( + case: str, + client: Any, + full_api_access: None, + mocker: MockerFixture, +) -> None: + report_schedule = ReportSchedule() + extra: dict[str, Any] = {"dashboard": {"nativeFilters": NATIVE_FILTERS[case]}} + report_schedule.extra = extra # type: ignore[assignment] + native_filters, warnings = report_schedule.get_native_filters_params() + assert warnings == [] + + mocker.patch( + "superset.commands.dashboard.permalink.get.GetDashboardPermalinkCommand.run", + return_value={ + "dashboardId": 1, + "state": {"urlParams": [["native_filters", native_filters]]}, + }, + ) + response = client.get("/dashboard/p/abc/") + + assert response.status_code == 302 + query = parse_qs(urlsplit(response.headers["Location"]).query) + expected: dict[str, Any] = {} + for native_filter in NATIVE_FILTERS[case]: + config, _ = report_schedule._generate_native_filter( + native_filter["nativeFilterId"], + native_filter["filterType"], + native_filter["columnName"], + native_filter["filterValues"], + ) + expected.update(config) + assert rison.loads(query["native_filters"][0]) == expected
