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 faa312530a7f072ca5ba6c4c3cca9f85ad746cd1 Author: Joe Li <[email protected]> AuthorDate: Mon Nov 9 14:27:55 2026 -0800 fix(dashboard): keep guest identity independent of username value (#45644) Co-authored-by: Claude <[email protected]> On 7.0 the dashboards API keeps its GuestUser import, the dispatch test drops a mock of a master-only helper, and the MCP layout test fixture pins its mock user as a non-guest, as master did for similar fixtures in #46125. (cherry picked from commit 5a0e884b30ff71907dd4e83534d1bcb992610581) --- superset/dashboards/api.py | 9 +- superset/security/manager.py | 10 +- superset/thumbnails/digest.py | 35 ++- superset/utils/screenshots.py | 38 ++- .../dashboards/screenshot_guest_dispatch_test.py | 320 +++++++++++++++++++++ .../dashboard/tool/test_get_dashboard_layout.py | 1 + .../security/guest_user_detection_test.py | 228 +++++++++++++++ tests/unit_tests/thumbnails/guest_digest_test.py | 131 +++++++++ tests/unit_tests/utils/screenshot_test.py | 13 + 9 files changed, 752 insertions(+), 33 deletions(-) diff --git a/superset/dashboards/api.py b/superset/dashboards/api.py index e4947257b32..d1d5a93ae06 100644 --- a/superset/dashboards/api.py +++ b/superset/dashboards/api.py @@ -163,6 +163,7 @@ from superset.tasks.export_dashboard_excel import ( export_lock_params, EXPORT_LOCK_TTL_SECONDS, ) +from superset.tasks.guest import get_current_guest_subscriber_key from superset.tasks.thumbnails import ( cache_dashboard_screenshot, cache_dashboard_thumbnail, @@ -2050,6 +2051,7 @@ class DashboardRestApi( thumb_size, permalink_key, cache_scope, + guest_key=get_current_guest_subscriber_key(), ) def build_response( @@ -2230,14 +2232,11 @@ class DashboardRestApi( ) return lock_response + guest_user = security_manager.get_current_guest_user_if_guest() try: cache_dashboard_screenshot.delay( username=get_current_user(), - guest_token=( - g.user.guest_token - if get_current_user() and isinstance(g.user, GuestUser) - else None - ), + guest_token=guest_user.guest_token if guest_user else None, dashboard_id=dashboard.id, dashboard_url=dashboard_url, thumb_size=thumb_size, diff --git a/superset/security/manager.py b/superset/security/manager.py index e26e1ea5466..4365e9fec32 100644 --- a/superset/security/manager.py +++ b/superset/security/manager.py @@ -6469,11 +6469,15 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods # no JWT/guest token definitionally cannot be an embedded guest # viewer, so returning ``False`` is the semantically correct answer. try: - if not get_current_user(): - return False - user = g.user + # Evaluating the current user is what may raise; its username is + # deliberately not consulted, as guest tokens may carry any + # username value (including an empty one). + get_current_user() + user = getattr(g, "user", None) except NoAuthorizationError: return False + if not user: + return False return hasattr(user, "is_guest_user") and user.is_guest_user diff --git a/superset/thumbnails/digest.py b/superset/thumbnails/digest.py index 5cea4c9ddd5..016530e6b44 100644 --- a/superset/thumbnails/digest.py +++ b/superset/thumbnails/digest.py @@ -105,16 +105,34 @@ def _adjust_string_with_rls( return unique_string -def get_dashboard_digest(dashboard: Dashboard) -> str | None: +def _get_thumbnail_executor( + model: Dashboard | Slice, +) -> tuple[ExecutorType, str] | None: + """ + Resolve the thumbnail executor, keying an embedded guest on itself when + ``CURRENT_USER`` cannot resolve from its username (guest tokens may carry + an empty one), so the guest's row level rules still enter the digest. + """ + executors = app.config["THUMBNAIL_EXECUTORS"] try: - executor_type, executor = get_executor( - executors=app.config["THUMBNAIL_EXECUTORS"], - model=dashboard, + return get_executor( + executors=executors, + model=model, current_user=get_current_user(), ) except ExecutorNotFoundError: + if ExecutorType.CURRENT_USER in executors and ( + guest := security_manager.get_current_guest_user_if_guest() + ): + return ExecutorType.CURRENT_USER, guest.username return None + +def get_dashboard_digest(dashboard: Dashboard) -> str | None: + if not (chosen := _get_thumbnail_executor(dashboard)): + return None + executor_type, executor = chosen + if func := app.config["THUMBNAIL_DASHBOARD_DIGEST_FUNC"]: return func(dashboard, executor_type, executor) @@ -132,14 +150,9 @@ def get_dashboard_digest(dashboard: Dashboard) -> str | None: def get_chart_digest(chart: Slice) -> str | None: - try: - executor_type, executor = get_executor( - executors=app.config["THUMBNAIL_EXECUTORS"], - model=chart, - current_user=get_current_user(), - ) - except ExecutorNotFoundError: + if not (chosen := _get_thumbnail_executor(chart)): return None + executor_type, executor = chosen if func := app.config["THUMBNAIL_CHART_DIGEST_FUNC"]: return func(chart, executor_type, executor) diff --git a/superset/utils/screenshots.py b/superset/utils/screenshots.py index cd331a8b3e6..647ddbde043 100644 --- a/superset/utils/screenshots.py +++ b/superset/utils/screenshots.py @@ -22,7 +22,7 @@ import uuid from datetime import datetime from enum import Enum from io import BytesIO -from typing import cast, TYPE_CHECKING, TypedDict +from typing import Any, cast, TYPE_CHECKING, TypedDict from flask import current_app as app @@ -738,21 +738,31 @@ class DashboardScreenshot(BaseScreenshot): thumb_size: bool | WindowSize | None, permalink_key: str, scope: str, + guest_key: str | None = None, ) -> str: - """Return the stable pointer key for one API screenshot request state.""" + """ + Return the stable pointer key for one API screenshot request state. - return hash_from_dict( - { - "type": "dashboard_screenshot_api_request", - "version": 1, - "legacy_cache_key": self.get_cache_key( - window_size, - thumb_size, - permalink_key, - ), - "scope": scope, - } - ) + ``guest_key`` identifies the embedded guest the screenshot is rendered + for. The digest does not cover every claim that can change a guest's + rendering (e.g. user attributes) and may be unavailable, so guests are + kept apart by their own key. It is omitted for other callers, which + leaves their keys unchanged. + """ + + args: dict[str, Any] = { + "type": "dashboard_screenshot_api_request", + "version": 1, + "legacy_cache_key": self.get_cache_key( + window_size, + thumb_size, + permalink_key, + ), + "scope": scope, + } + if guest_key: + args["guest"] = guest_key + return hash_from_dict(args) @staticmethod def get_next_api_generation_cache_key( diff --git a/tests/unit_tests/dashboards/screenshot_guest_dispatch_test.py b/tests/unit_tests/dashboards/screenshot_guest_dispatch_test.py new file mode 100644 index 00000000000..b77d9868add --- /dev/null +++ b/tests/unit_tests/dashboards/screenshot_guest_dispatch_test.py @@ -0,0 +1,320 @@ +# 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. + +""" +The dashboard screenshot task must receive the guest token of an embedded guest, +whatever the token's username claim is, so the task renders as that guest. +""" + +# pylint: disable=redefined-outer-name + +from typing import Any, cast +from unittest.mock import MagicMock, PropertyMock +from uuid import uuid4 + +import pytest +from flask import g +from flask_appbuilder.security.sqla.models import Role +from pytest_mock import MockerFixture +from sqlalchemy import text + +from superset import security_manager +from superset.extensions import feature_flag_manager +from superset.models.dashboard import Dashboard +from superset.security.guest_token import ( + GuestToken, + GuestTokenResourceType, + GuestTokenRlsRule, +) + +USERNAMES = ["embedded_viewer", ""] +USERNAME_IDS = ["non-empty-username", "empty-username"] + +DASHBOARD_ID = 7 +RLS_RULES: list[GuestTokenRlsRule] = [{"dataset": "3", "clause": "region = 'EU'"}] +DATASETS = [3] + + [email protected] +def dashboard() -> MagicMock: + return MagicMock(id=DASHBOARD_ID, digest="digest") + + [email protected] +def screenshot_task( + mocker: MockerFixture, full_api_access: None, dashboard: MagicMock +) -> MagicMock: + """ + Enable the endpoint and stub everything around the task dispatch (dashboard + lookup, permalink, cache bookkeeping, lock) so the dispatch arguments are + the only moving part. Returns the mocked task. + """ + flags = { + "THUMBNAILS": True, + "ENABLE_DASHBOARD_SCREENSHOT_ENDPOINTS": True, + "EMBEDDED_SUPERSET": True, + } + mocker.patch.object( + feature_flag_manager, + "get_feature_flags", + side_effect=lambda: {**(feature_flag_manager._feature_flags or {}), **flags}, + ) + mocker.patch.object(security_manager, "find_role", return_value=Role(name="Public")) + mocker.patch.object(security_manager, "_is_guest_token_revoked", return_value=False) + + mocker.patch( + "flask_appbuilder.models.sqla.interface.SQLAInterface.get" + ).return_value = dashboard + mocker.patch( + "superset.dashboards.api.CreateDashboardPermalinkCommand" + ).return_value.run.return_value = "permalink-key" + mocker.patch("superset.dashboards.api.DistributedLock") + + screenshot_cls = "superset.dashboards.api.DashboardScreenshot" + mocker.patch( + f"{screenshot_cls}.get_current_api_generation_cache_key", return_value=None + ) + mocker.patch( + f"{screenshot_cls}.get_next_api_generation_cache_key", return_value="next-key" + ) + mocker.patch(f"{screenshot_cls}.store_cache_payload") + mocker.patch( + f"{screenshot_cls}.set_current_api_generation_cache_key", return_value=True + ) + + return mocker.patch("superset.dashboards.api.cache_dashboard_screenshot") + + [email protected] +def request_key_lookup(mocker: MockerFixture, screenshot_task: MagicMock) -> MagicMock: + """ + The mocked generation lookup; its first positional argument is the request + cache key the endpoint derived for the caller. + """ + return mocker.patch( + "superset.dashboards.api.DashboardScreenshot" + ".get_current_api_generation_cache_key", + return_value=None, + ) + + [email protected] +def real_digest(mocker: MockerFixture, request_key_lookup: MagicMock) -> None: + """ + Serve a real dashboard so ``dashboard.digest`` is computed rather than + stubbed. Only the datasource, whose rules are resolved from the guest, is a + stand-in. + """ + datasource = MagicMock(id=3, is_rls_supported=True) + datasource.get_sqla_row_level_filters.side_effect = lambda: [ + text(rule["clause"]) + for rule in security_manager.get_guest_rls_filters(datasource) + ] + mocker.patch.object( + Dashboard, "datasources", new_callable=PropertyMock, return_value={datasource} + ) + mocker.patch.object(security_manager, "prefetch_rls_filters", return_value=None) + mocker.patch( + "flask_appbuilder.models.sqla.interface.SQLAInterface.get" + ).return_value = Dashboard( + id=DASHBOARD_ID, + dashboard_title="Embedded dashboard", + slices=[], + position_json="{}", + css="", + json_metadata="{}", + ) + + +def _guest_token( + username: str, + attributes: dict[str, Any] | None = None, + rls: list[GuestTokenRlsRule] | None = None, +) -> bytes: + return security_manager.create_guest_access_token( + user={"username": username, "attributes": attributes or {}}, + resources=[{"type": GuestTokenResourceType.DASHBOARD, "id": "embedded-uuid"}], + rls=RLS_RULES if rls is None else rls, + datasets=DATASETS, + ) + + +def _request_key(client: Any, lookup: MagicMock, raw_token: bytes) -> str: + lookup.reset_mock() + # The app context (and its ``g``) outlives a single request in these tests, + # so drop the guest resolved for an earlier request. + for attribute in ("_login_user", "user"): + g.pop(attribute, None) + response = client.post( + f"/api/v1/dashboard/{DASHBOARD_ID}/cache_dashboard_screenshot/", + json={"dataMask": {}, "activeTabs": [], "anchor": "", "urlParams": []}, + headers={client.application.config["GUEST_TOKEN_HEADER_NAME"]: raw_token}, + ) + assert response.status_code == 202, response.json + return str(lookup.call_args.args[0]) + + [email protected]("username", USERNAMES, ids=USERNAME_IDS) +def test_screenshot_request_key_is_stable_for_the_same_guest( + client: Any, request_key_lookup: MagicMock, username: str +) -> None: + first = _request_key(client, request_key_lookup, _guest_token(username)) + second = _request_key(client, request_key_lookup, _guest_token(username)) + + assert first == second + + [email protected]("username", USERNAMES, ids=USERNAME_IDS) +def test_screenshot_request_key_differs_for_guests_with_different_attributes( + client: Any, request_key_lookup: MagicMock, username: str +) -> None: + """ + Guest attributes can change rendered content, so guests sharing a dashboard, + state, username and digest still need separate screenshots. + """ + first = _request_key( + client, request_key_lookup, _guest_token(username, {"tenant": "a"}) + ) + second = _request_key( + client, request_key_lookup, _guest_token(username, {"tenant": "b"}) + ) + + assert first != second + + [email protected]("username", USERNAMES, ids=USERNAME_IDS) +def test_screenshot_request_key_differs_for_guests_with_different_rls_without_digest( + client: Any, + request_key_lookup: MagicMock, + dashboard: MagicMock, + username: str, +) -> None: + """ + The digest is ``None`` when no thumbnail executor resolves for the caller; + the request key must still separate guests with different row level rules. + """ + dashboard.digest = None + other_rls: list[GuestTokenRlsRule] = [{"dataset": "3", "clause": "region = 'US'"}] + + first = _request_key(client, request_key_lookup, _guest_token(username)) + second = _request_key( + client, request_key_lookup, _guest_token(username, rls=other_rls) + ) + + assert first != second + + [email protected]("username", USERNAMES, ids=USERNAME_IDS) +def test_screenshot_request_key_with_real_digest_separates_guests_by_rls( + client: Any, request_key_lookup: MagicMock, real_digest: None, username: str +) -> None: + other_rls: list[GuestTokenRlsRule] = [{"dataset": "3", "clause": "region = 'US'"}] + + first = _request_key(client, request_key_lookup, _guest_token(username)) + again = _request_key(client, request_key_lookup, _guest_token(username)) + other = _request_key( + client, request_key_lookup, _guest_token(username, rls=other_rls) + ) + + assert first == again + assert first != other + + [email protected]("username", USERNAMES, ids=USERNAME_IDS) +def test_screenshot_request_key_with_real_digest_separates_guests_by_attributes( + client: Any, request_key_lookup: MagicMock, real_digest: None, username: str +) -> None: + first = _request_key( + client, request_key_lookup, _guest_token(username, {"tenant": "a"}) + ) + other = _request_key( + client, request_key_lookup, _guest_token(username, {"tenant": "b"}) + ) + + assert first != other + + [email protected]("username", USERNAMES, ids=USERNAME_IDS) +def test_screenshot_task_receives_guest_token_for_any_username( + client: Any, screenshot_task: MagicMock, username: str +) -> None: + raw_token = security_manager.create_guest_access_token( + user={"username": username}, + resources=[{"type": GuestTokenResourceType.DASHBOARD, "id": str(uuid4())}], + rls=RLS_RULES, + datasets=DATASETS, + ) + + response = client.post( + f"/api/v1/dashboard/{DASHBOARD_ID}/cache_dashboard_screenshot/", + json={"dataMask": {}, "activeTabs": [], "anchor": "", "urlParams": []}, + headers={client.application.config["GUEST_TOKEN_HEADER_NAME"]: raw_token}, + ) + + assert response.status_code == 202, response.json + screenshot_task.delay.assert_called_once() + forwarded = screenshot_task.delay.call_args.kwargs["guest_token"] + assert forwarded is not None + assert forwarded["user"]["username"] == username + assert forwarded["rls_rules"] == RLS_RULES + assert forwarded["datasets"] == DATASETS + + [email protected]("with_guest_token", [True, False], ids=["guest", "no-guest"]) +def test_screenshot_task_renders_as_guest_only_when_token_is_forwarded( + mocker: MockerFixture, with_guest_token: bool +) -> None: + """ + The task renders as the guest rebuilt from the forwarded token; without one + it falls back to the executor configured in ``THUMBNAIL_EXECUTORS``. + """ + from flask import current_app + + from superset.tasks.thumbnails import cache_dashboard_screenshot + from superset.tasks.types import FixedExecutor + + guest_user, executor_user = MagicMock(name="guest"), MagicMock(name="executor") + mocker.patch("superset.tasks.thumbnails.thumbnail_cache", MagicMock()) + mocker.patch("superset.tasks.thumbnails.override_user") + screenshot_cls = mocker.patch("superset.tasks.thumbnails.DashboardScreenshot") + mocker.patch("superset.models.dashboard.Dashboard.get") + mocker.patch.dict( + current_app.config, {"THUMBNAIL_EXECUTORS": [FixedExecutor("executor")]} + ) + mocker.patch.object(security_manager, "find_user", return_value=executor_user) + mocker.patch.object( + security_manager, "get_guest_user_from_token", return_value=guest_user + ) + + cache_dashboard_screenshot( + username="", + dashboard_id=DASHBOARD_ID, + dashboard_url="/dashboard/p/key/", + force=False, + cache_key="cache-key", + guest_token=( + cast( + GuestToken, + {"user": {"username": ""}, "resources": [], "rls_rules": RLS_RULES}, + ) + if with_guest_token + else None + ), + ) + + rendered_as = screenshot_cls.return_value.compute_and_cache.call_args.kwargs["user"] + assert rendered_as is (guest_user if with_guest_token else executor_user) diff --git a/tests/unit_tests/mcp_service/dashboard/tool/test_get_dashboard_layout.py b/tests/unit_tests/mcp_service/dashboard/tool/test_get_dashboard_layout.py index 4a3af4eb2df..e6f28949a92 100644 --- a/tests/unit_tests/mcp_service/dashboard/tool/test_get_dashboard_layout.py +++ b/tests/unit_tests/mcp_service/dashboard/tool/test_get_dashboard_layout.py @@ -60,6 +60,7 @@ def mock_auth(): mock_user = Mock() mock_user.id = 1 mock_user.username = "admin" + mock_user.is_guest_user = False mock_get_user.return_value = mock_user yield mock_get_user diff --git a/tests/unit_tests/security/guest_user_detection_test.py b/tests/unit_tests/security/guest_user_detection_test.py new file mode 100644 index 00000000000..8f4c732e2ee --- /dev/null +++ b/tests/unit_tests/security/guest_user_detection_test.py @@ -0,0 +1,228 @@ +# 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. + +""" +Guest user detection must not depend on the value of the token's username. + +Every guest token produces a ``GuestUser`` regardless of the ``username`` claim +(including an empty string), so the guest-specific handling (dashboard access +rules, response field filtering, error sanitization) has to apply to all of them. +""" + +# pylint: disable=redefined-outer-name + +from typing import Any +from uuid import uuid4 + +import pytest +from flask import current_app, g, request +from flask_appbuilder.security.sqla.models import Role +from flask_login import AnonymousUserMixin +from pytest_mock import MockerFixture + +from superset import security_manager +from superset.commands.dashboard.exceptions import DashboardAccessDeniedError +from superset.daos.dashboard import DashboardDAO +from superset.dashboards.schemas import DashboardGetResponseSchema +from superset.exceptions import SupersetSecurityException +from superset.models.dashboard import Dashboard +from superset.models.embedded_dashboard import EmbeddedDashboard +from superset.security.guest_token import GuestTokenResourceType, GuestUser +from superset.utils.error_sanitization import is_sanitization_required + +USERNAMES = ["embedded_viewer", ""] +USERNAME_IDS = ["non-empty-username", "empty-username"] + + [email protected] +def embedded_feature_enabled(mocker: MockerFixture) -> None: + mocker.patch( + "superset.is_feature_enabled", + side_effect=lambda feature: feature == "EMBEDDED_SUPERSET", + ) + + +def _guest_user_from_token( + mocker: MockerFixture, username: str, resource_ids: list[str] +) -> GuestUser: + """ + Build the guest user the same way the request loader does: sign a token with + the given ``user.username`` claim and dashboard resources, and parse it from + the request headers. + """ + mocker.patch.object(security_manager, "find_role", return_value=Role(name="Public")) + mocker.patch.object(security_manager, "_is_guest_token_revoked", return_value=False) + token = security_manager.create_guest_access_token( + user={"username": username}, + resources=[ + {"type": GuestTokenResourceType.DASHBOARD, "id": resource_id} + for resource_id in resource_ids + ], + rls=[], + ) + header_name = current_app.config["GUEST_TOKEN_HEADER_NAME"] + with current_app.test_request_context(headers={header_name: token}): + guest_user = security_manager.get_guest_user_from_request(request) + assert isinstance(guest_user, GuestUser) + assert guest_user.username == username + return guest_user + + [email protected] +def guest_user_factory(mocker: MockerFixture, embedded_feature_enabled: None) -> Any: + def _make(username: str, resource_ids: list[str] | None = None) -> GuestUser: + guest_user = _guest_user_from_token( + mocker, username, resource_ids if resource_ids is not None else [] + ) + g.user = guest_user + return guest_user + + return _make + + +def _embedded_dashboard() -> Dashboard: + """ + A published, chart-less dashboard with an embedded configuration, so that + guest access depends only on whether the token lists the embedded UUID. + """ + dashboard = Dashboard( + id=42, + dashboard_title="Embedded dashboard", + published=True, + slices=[], + ) + dashboard.uuid = uuid4() + dashboard.embedded = [EmbeddedDashboard(uuid=uuid4(), allow_domain_list="")] + return dashboard + + +def _unlisted_resource_ids() -> list[str]: + """Resource ids that do not match the embedded dashboard under test.""" + return [str(uuid4())] + + [email protected]("username", USERNAMES, ids=USERNAME_IDS) +def test_is_guest_user_does_not_depend_on_username( + guest_user_factory: Any, username: str +) -> None: + guest_user_factory(username) + + assert security_manager.is_guest_user() is True + assert security_manager.get_current_guest_user_if_guest() is not None + + [email protected]( + "current_user", + [None, AnonymousUserMixin()], + ids=["no-user", "anonymous-user"], +) +def test_is_guest_user_is_false_without_a_guest( + embedded_feature_enabled: None, current_user: Any +) -> None: + g.user = current_user + + assert security_manager.is_guest_user() is False + + +def test_is_guest_user_is_false_when_no_user_is_set( + embedded_feature_enabled: None, +) -> None: + g.pop("user", None) + + assert security_manager.is_guest_user() is False + + [email protected]("username", USERNAMES, ids=USERNAME_IDS) +def test_dashboard_access_denied_when_embedded_uuid_not_in_token( + guest_user_factory: Any, username: str +) -> None: + """ + A guest whose token does not list the embedded dashboard is denied, whatever + the token's username claim is. + """ + dashboard = _embedded_dashboard() + guest_user_factory(username, _unlisted_resource_ids()) + + assert dashboard.embedded + assert security_manager.has_guest_access(dashboard) is False + with pytest.raises(SupersetSecurityException): + security_manager.raise_for_access(dashboard=dashboard) + + [email protected]("username", USERNAMES, ids=USERNAME_IDS) +def test_dashboard_access_allowed_when_embedded_uuid_in_token( + guest_user_factory: Any, username: str +) -> None: + dashboard = _embedded_dashboard() + guest_user_factory(username, [str(dashboard.embedded[0].uuid)]) + + assert security_manager.has_guest_access(dashboard) is True + security_manager.raise_for_access(dashboard=dashboard) + + [email protected]("username", USERNAMES, ids=USERNAME_IDS) +def test_dashboard_dao_uuid_lookup_denied_when_embedded_uuid_not_in_token( + mocker: MockerFixture, guest_user_factory: Any, username: str +) -> None: + dashboard = _embedded_dashboard() + guest_user_factory(username, _unlisted_resource_ids()) + mocker.patch.object(Dashboard, "get", return_value=dashboard) + + with pytest.raises(DashboardAccessDeniedError): + DashboardDAO.get_by_id_or_slug(str(dashboard.uuid)) + + [email protected]("username", USERNAMES, ids=USERNAME_IDS) +def test_dashboard_dao_uuid_lookup_allowed_when_embedded_uuid_in_token( + mocker: MockerFixture, guest_user_factory: Any, username: str +) -> None: + dashboard = _embedded_dashboard() + guest_user_factory(username, [str(dashboard.embedded[0].uuid)]) + mocker.patch.object(Dashboard, "get", return_value=dashboard) + + assert DashboardDAO.get_by_id_or_slug(str(dashboard.uuid)) is dashboard + + [email protected]("username", USERNAMES, ids=USERNAME_IDS) +def test_dashboard_response_schema_filters_fields_for_any_username( + guest_user_factory: Any, username: str +) -> None: + guest_user_factory(username) + + result = DashboardGetResponseSchema().dump( + { + "id": 1, + "dashboard_title": "Dashboard", + "changed_by_name": "Some User", + "changed_by": {"first_name": "Some", "last_name": "User"}, + "editors": [{"id": 1, "label": "Some User", "type": 1}], + "viewers": [{"id": 2, "label": "Other User", "type": 1}], + } + ) + + assert result["dashboard_title"] == "Dashboard" + for field in ("changed_by_name", "changed_by", "editors", "viewers"): + assert field not in result + + [email protected]("username", USERNAMES, ids=USERNAME_IDS) +def test_error_sanitization_applies_for_any_username( + guest_user_factory: Any, username: str +) -> None: + guest_user_factory(username) + + assert is_sanitization_required() is True diff --git a/tests/unit_tests/thumbnails/guest_digest_test.py b/tests/unit_tests/thumbnails/guest_digest_test.py new file mode 100644 index 00000000000..10e17abeb4e --- /dev/null +++ b/tests/unit_tests/thumbnails/guest_digest_test.py @@ -0,0 +1,131 @@ +# 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. + +""" +Thumbnail digests of embedded guests must reflect the guest's row level rules, +whatever the token's username claim is (including an empty one). + +The guests are built through the request loader from signed tokens; only the +datasource, whose rules are resolved from the guest, is stubbed. +""" + +# pylint: disable=redefined-outer-name + +from typing import Any +from unittest.mock import MagicMock, PropertyMock + +import pytest +from flask import current_app, g, request +from flask_appbuilder.security.sqla.models import Role +from pytest_mock import MockerFixture +from sqlalchemy import text + +from superset import security_manager +from superset.models.dashboard import Dashboard +from superset.models.slice import Slice +from superset.security.guest_token import GuestTokenResourceType, GuestTokenRlsRule +from superset.thumbnails.digest import get_chart_digest, get_dashboard_digest + +USERNAMES = ["embedded_viewer", ""] +USERNAME_IDS = ["non-empty-username", "empty-username"] + +DATASET_ID = 3 + + [email protected](autouse=True) +def embedded_guests(mocker: MockerFixture) -> None: + mocker.patch( + "superset.is_feature_enabled", + side_effect=lambda feature: feature == "EMBEDDED_SUPERSET", + ) + mocker.patch.object(security_manager, "find_role", return_value=Role(name="Public")) + mocker.patch.object(security_manager, "_is_guest_token_revoked", return_value=False) + mocker.patch.object(security_manager, "prefetch_rls_filters", return_value=None) + + [email protected] +def datasource(mocker: MockerFixture) -> MagicMock: + """A datasource that applies the current guest's rules, as a table would.""" + ds = MagicMock(id=DATASET_ID, is_rls_supported=True) + ds.get_sqla_row_level_filters.side_effect = lambda: [ + text(rule["clause"]) for rule in security_manager.get_guest_rls_filters(ds) + ] + mocker.patch.object( + Dashboard, "datasources", new_callable=PropertyMock, return_value={ds} + ) + mocker.patch.object(Slice, "table", new_callable=PropertyMock, return_value=ds) + return ds + + +def _become_guest(username: str, clause: str) -> None: + rls: list[GuestTokenRlsRule] = [{"dataset": str(DATASET_ID), "clause": clause}] + token = security_manager.create_guest_access_token( + user={"username": username}, + resources=[{"type": GuestTokenResourceType.DASHBOARD, "id": "embedded-uuid"}], + rls=rls, + ) + header_name = current_app.config["GUEST_TOKEN_HEADER_NAME"] + with current_app.test_request_context(headers={header_name: token}): + guest_user: Any = security_manager.get_guest_user_from_request(request) + assert guest_user is not None + g.pop("_login_user", None) + g.user = guest_user + + +def _dashboard() -> Dashboard: + return Dashboard( + id=7, + dashboard_title="Embedded dashboard", + slices=[], + position_json="{}", + css="", + json_metadata="{}", + ) + + +def _chart() -> Slice: + return Slice(id=5, slice_name="Chart", params="{}") + + [email protected]("username", USERNAMES, ids=USERNAME_IDS) +def test_dashboard_digest_reflects_guest_rls( + datasource: MagicMock, username: str +) -> None: + _become_guest(username, "tenant = 'A'") + first = get_dashboard_digest(_dashboard()) + again = get_dashboard_digest(_dashboard()) + _become_guest(username, "tenant = 'B'") + second = get_dashboard_digest(_dashboard()) + + assert first is not None + assert first == again + assert second is not None + assert first != second + + [email protected]("username", USERNAMES, ids=USERNAME_IDS) +def test_chart_digest_reflects_guest_rls(datasource: MagicMock, username: str) -> None: + _become_guest(username, "tenant = 'A'") + first = get_chart_digest(_chart()) + again = get_chart_digest(_chart()) + _become_guest(username, "tenant = 'B'") + second = get_chart_digest(_chart()) + + assert first is not None + assert first == again + assert second is not None + assert first != second diff --git a/tests/unit_tests/utils/screenshot_test.py b/tests/unit_tests/utils/screenshot_test.py index 12ba5f64701..42e514673c0 100644 --- a/tests/unit_tests/utils/screenshot_test.py +++ b/tests/unit_tests/utils/screenshot_test.py @@ -730,3 +730,16 @@ class TestScreenshotSubclassesDriverBehavior: assert driver._window == custom_window_size assert chart_screenshot.thumb_size == custom_thumb_size + + +def test_api_request_key_is_separated_by_guest_key_only_when_given() -> None: + screenshot = DashboardScreenshot("http://example.com", "digest") + args = ((1600, 1200), (1600, 1200), "permalink", "dashboard:7") + + without_guest = screenshot.get_api_request_cache_key(*args) + + assert screenshot.get_api_request_cache_key(*args, guest_key=None) == without_guest + assert screenshot.get_api_request_cache_key(*args, guest_key="guest:a") not in { + without_guest, + screenshot.get_api_request_cache_key(*args, guest_key="guest:b"), + }
