You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ga...@apache.org on 2026/07/09 17:58:10 UTC
(superset) branch master updated: feat(mcp): scope embedded-guest data reads to the token's dashboards (#41753)
This is an automated email from the ASF dual-hosted git repository.
gabotorresruiz pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new 1fd43ffe52c feat(mcp): scope embedded-guest data reads to the token's dashboards (#41753)
1fd43ffe52c is described below
commit 1fd43ffe52c8ba01ae4246c0f94f95913e481787
Author: Gabriel Torres Ruiz <ga...@gmail.com>
AuthorDate: Thu Jul 9 14:58:01 2026 -0300
feat(mcp): scope embedded-guest data reads to the token's dashboards (#41753)
---
superset/charts/filters.py | 11 +-
superset/mcp_service/CLAUDE.md | 11 +-
superset/mcp_service/SECURITY.md | 8 +-
superset/mcp_service/auth.py | 110 +++++++++----
superset/mcp_service/chart/tool/get_chart_data.py | 62 ++++---
superset/mcp_service/chart/tool/get_chart_info.py | 9 +-
.../mcp_service/chart/tool/get_chart_preview.py | 19 ++-
superset/mcp_service/chart/tool/get_chart_sql.py | 10 ++
superset/mcp_service/guest_scope.py | 72 ++++++++
superset/mcp_service/mcp_config.py | 24 ++-
superset/mcp_service/privacy.py | 5 +
.../mcp_service/rls/tool/get_rls_filter_info.py | 10 ++
superset/mcp_service/rls/tool/list_rls_filters.py | 10 ++
superset/security/manager.py | 4 +
superset/utils/filters.py | 53 +++++-
tests/unit_tests/charts/test_filters.py | 180 ++++++++++++++++++++
.../mcp_service/chart/tool/test_get_chart_data.py | 31 +++-
.../mcp_service/chart/tool/test_get_chart_info.py | 19 +++
.../chart/tool/test_get_chart_preview.py | 36 +++-
.../mcp_service/chart/tool/test_get_chart_sql.py | 18 ++
.../mcp_service/chart/tool/test_list_charts.py | 1 +
.../mcp_service/rls/tool/test_rls_tools.py | 28 ++++
.../system/tool/test_get_current_user.py | 1 +
tests/unit_tests/mcp_service/test_guest_scope.py | 121 ++++++++++++++
.../mcp_service/test_guest_token_auth.py | 182 ++++++++++++++++++---
tests/unit_tests/mcp_service/test_privacy.py | 45 +++++
tests/unit_tests/security/manager_test.py | 37 +++++
tests/unit_tests/utils/filters_test.py | 119 +++++++++++++-
28 files changed, 1136 insertions(+), 100 deletions(-)
diff --git a/superset/charts/filters.py b/superset/charts/filters.py
index a56f6fb2cac..86217086600 100644
--- a/superset/charts/filters.py
+++ b/superset/charts/filters.py
@@ -34,7 +34,10 @@ from superset.subjects.filters import (
from superset.subjects.models import chart_editors
from superset.tags.filters import BaseTagIdFilter, BaseTagNameFilter
from superset.utils.core import get_user_id
-from superset.utils.filters import get_dataset_access_filters
+from superset.utils.filters import (
+ get_dataset_access_filters,
+ guest_embedded_dashboard_filter,
+)
from superset.views.base import BaseFilter
from superset.views.base_api import BaseFavoriteFilter
from superset.views.filters import BaseDeletedStateFilter
@@ -108,6 +111,12 @@ class ChartCertifiedFilter(BaseFilter): # pylint: disable=too-few-public-method
class ChartFilter(BaseFilter): # pylint: disable=too-few-public-methods
def apply(self, query: Query, value: Any) -> Query:
+ # Embedded guests are scoped to their token's dashboards first. A guest
+ # is never entitled to all charts, regardless of what its role grants,
+ # and an empty token scope denies all charts (a deny-all clause).
+ if (guest_dashboards := guest_embedded_dashboard_filter()) is not None:
+ return query.filter(self.model.dashboards.any(guest_dashboards))
+
if security_manager.can_access_all_datasources():
return query
diff --git a/superset/mcp_service/CLAUDE.md b/superset/mcp_service/CLAUDE.md
index a7c70a38d41..a6edd0aa900 100644
--- a/superset/mcp_service/CLAUDE.md
+++ b/superset/mcp_service/CLAUDE.md
@@ -462,7 +462,16 @@ MCP_RBAC_ENABLED = True # Enable permission checking (default: True)
# Embedded guest auth (opt-in; requires the EMBEDDED_SUPERSET feature flag).
# Reuses core GUEST_TOKEN_JWT_* config — no MCP-specific guest secret/audience.
MCP_EMBEDDED_GUEST_AUTH_ENABLED = False
-MCP_GUEST_DENIED_TOOLS = {"find_users", "get_instance_info"} # tools guests cannot call
+# Default-deny: the ONLY tools a guest may call (everything else is denied).
+MCP_GUEST_ALLOWED_TOOLS = {
+ "get_dashboard_info", "get_dashboard_layout", "list_dashboards",
+ "list_charts", "get_chart_info", "get_chart_data", "get_chart_preview",
+}
+# Principal-agnostic extension point: given the current user, return an allow-list
+# (only these tools are callable) or None if unrestricted. Defaults to restricting
+# embedded guests to MCP_GUEST_ALLOWED_TOOLS; override to add other restricted
+# principals without touching the enforcement path.
+MCP_RESTRICTED_TOOL_POLICY = None # Callable[[user], frozenset[str] | None]
# Response Caching (optional, uses in-memory store by default; Redis when MCP_STORE_CONFIG enabled)
diff --git a/superset/mcp_service/SECURITY.md b/superset/mcp_service/SECURITY.md
index 26390418aa5..26c9ed421a3 100644
--- a/superset/mcp_service/SECURITY.md
+++ b/superset/mcp_service/SECURITY.md
@@ -239,9 +239,11 @@ MCP_EMBEDDED_GUEST_AUTH_ENABLED = True # opt-in for the MCP transport (de
source, so a guest is never downgraded to API-key / `MCP_DEV_USERNAME` / `g.user`.
- Data access is scoped by core's existing `raise_for_access` (dataset allowlist,
dashboard access, RLS) — guests only reach their token's resources.
-- Sensitive enumeration tools are denied to guests via `MCP_GUEST_DENIED_TOOLS`
- (default `{"find_users", "get_instance_info"}`), enforced at both tool listing
- and call time regardless of `MCP_RBAC_ENABLED`.
+- Guests are default-deny: they may call only the tools in `MCP_GUEST_ALLOWED_TOOLS`
+ (dashboard and chart read tools, scoped to the token's dashboards), enforced at
+ both tool listing and call time regardless of `MCP_RBAC_ENABLED`. Every other
+ tool (mutating, data-model, SQL, RLS, user/role/tag/task/annotation/report/query)
+ is denied by default.
**Deployment requirements**
diff --git a/superset/mcp_service/auth.py b/superset/mcp_service/auth.py
index a04e2213e56..d6167dbee50 100644
--- a/superset/mcp_service/auth.py
+++ b/superset/mcp_service/auth.py
@@ -236,32 +236,80 @@ def _log_scope_denial(
)
-# Guest deny-list default (when MCP_GUEST_DENIED_TOOLS is unset); blocks tools
-# with no RBAC class that would otherwise fall open. Sync with mcp_config.py.
-_DEFAULT_GUEST_DENIED_TOOLS: frozenset[str] = frozenset(
- {"find_users", "get_instance_info"}
+# Default-deny allow-list for embedded guests: a guest may call only these tools,
+# regardless of MCP_RBAC_ENABLED or how the guest role (PUBLIC_ROLE_LIKE) is
+# configured. Everything else is denied, including newly added tools until listed
+# here. Sync with mcp_config.py.
+_DEFAULT_GUEST_ALLOWED_TOOLS: frozenset[str] = frozenset(
+ {
+ # Dashboard structure, scoped to the token's embedded dashboards.
+ "get_dashboard_info",
+ "get_dashboard_layout",
+ "list_dashboards",
+ # Chart read + data, scoped by ChartFilter; data-model fields redacted.
+ "list_charts",
+ "get_chart_info",
+ "get_chart_data",
+ "get_chart_preview",
+ }
)
-def _tool_denied_for_guest(func: Callable[..., Any]) -> bool:
- """True when the current user is a guest and ``func`` is on the guest
- deny-list — barring enumeration tools (user listing, instance metadata) that
- may declare no RBAC class. ``isinstance`` (not ``is_guest_user``) keeps this
- cheap and off the feature-flag path."""
- if not isinstance(getattr(g, "user", None), GuestUser):
- return False
- denied = current_app.config.get("MCP_GUEST_DENIED_TOOLS")
- # A str would make ``in`` do substring matching and corrupt the decision;
- # require a real collection, else fall back to the default.
- if not isinstance(denied, (set, frozenset, list, tuple)):
- if denied is not None:
+def _guest_allowed_tools() -> frozenset[str]:
+ """The tool allow-list for embedded guests (``MCP_GUEST_ALLOWED_TOOLS`` or the
+ default). A str config is rejected — it would make ``in`` do substring
+ matching — and falls back to the safe default."""
+ allowed = current_app.config.get("MCP_GUEST_ALLOWED_TOOLS")
+ if not isinstance(allowed, (set, frozenset, list, tuple)):
+ if allowed is not None:
logger.warning(
- "MCP_GUEST_DENIED_TOOLS must be a set/list of tool names, got %s; "
- "using the default deny-list",
- type(denied).__name__,
+ "MCP_GUEST_ALLOWED_TOOLS must be a set/list of tool names, got %s; "
+ "using the default allow-list",
+ type(allowed).__name__,
)
- denied = _DEFAULT_GUEST_DENIED_TOOLS
- return getattr(func, "__name__", None) in denied
+ return _DEFAULT_GUEST_ALLOWED_TOOLS
+ return frozenset(allowed)
+
+
+def _default_restricted_tool_policy(user: Any) -> frozenset[str] | None:
+ """Map a principal to its MCP tool allow-list, or None when the principal is
+ not allow-list-restricted (RBAC governs instead). Embedded guests are the
+ built-in restricted principal; override ``MCP_RESTRICTED_TOOL_POLICY`` to add
+ others (e.g. a future embedded principal type)."""
+ if isinstance(user, GuestUser):
+ return _guest_allowed_tools()
+ return None
+
+
+def _tool_denied_for_principal(func: Callable[..., Any]) -> bool:
+ """True when the current principal is allow-list-restricted and ``func`` is
+ not on its allow-list. Default-deny for restricted principals (embedded guests
+ by default), holds even with MCP_RBAC_ENABLED off; unrestricted principals are
+ governed by RBAC and never blocked here."""
+ policy = (
+ current_app.config.get("MCP_RESTRICTED_TOOL_POLICY")
+ or _default_restricted_tool_policy
+ )
+ if not callable(policy):
+ # A misconfigured (non-callable) policy must not crash every tool call:
+ # fall back to the built-in default, same as MCP_GUEST_ALLOWED_TOOLS.
+ logger.warning(
+ "MCP_RESTRICTED_TOOL_POLICY is not callable (%s); using the default policy",
+ type(policy).__name__,
+ )
+ policy = _default_restricted_tool_policy
+ allowed = policy(getattr(g, "user", None))
+ if allowed is None:
+ return False
+ if not isinstance(allowed, (set, frozenset, list, tuple)):
+ # A misbehaving custom policy must not open the surface: fail closed.
+ logger.warning(
+ "MCP_RESTRICTED_TOOL_POLICY returned %s, expected a set/list or None; "
+ "denying all tools for this principal",
+ type(allowed).__name__,
+ )
+ return True
+ return getattr(func, "__name__", None) not in allowed
def check_tool_permission( # noqa: C901
@@ -285,18 +333,18 @@ def check_tool_permission( # noqa: C901
True if user has permission or no permission is required.
"""
try:
- # Embedded guests are barred from sensitive enumeration tools regardless
- # of RBAC config (the deny-list is a guest restriction, not a FAB
- # permission, so it must hold even when MCP_RBAC_ENABLED is False).
- if _tool_denied_for_guest(func):
+ # Restricted principals (embedded guests by default) are default-deny:
+ # only allow-listed tools pass, enforced regardless of RBAC config (holds
+ # even when MCP_RBAC_ENABLED is False).
+ if _tool_denied_for_principal(func):
if log_denial:
logger.warning(
- "Tool %s denied for embedded guest (MCP_GUEST_DENIED_TOOLS)",
+ "Tool %s denied for restricted principal (not allow-listed)",
func.__name__,
)
else:
logger.debug(
- "Tool %s hidden for embedded guest (MCP_GUEST_DENIED_TOOLS)",
+ "Tool %s hidden for restricted principal (not allow-listed)",
func.__name__,
)
return False
@@ -402,10 +450,10 @@ def is_tool_visible_to_current_user(tool: Any) -> bool:
if tool_func is None:
return True
- # Hide guest-denied tools from tools/list regardless of RBAC config
- # (enforced again at call time in check_tool_permission, including for
- # permission-less tools).
- if _tool_denied_for_guest(tool_func):
+ # Hide non-allow-listed tools from restricted principals in tools/list
+ # regardless of RBAC config (enforced again at call time in
+ # check_tool_permission, including for permission-less tools).
+ if _tool_denied_for_principal(tool_func):
return False
if not current_app.config.get("MCP_RBAC_ENABLED", True):
diff --git a/superset/mcp_service/chart/tool/get_chart_data.py b/superset/mcp_service/chart/tool/get_chart_data.py
index 9c3b74b01a7..97588b00bd0 100644
--- a/superset/mcp_service/chart/tool/get_chart_data.py
+++ b/superset/mcp_service/chart/tool/get_chart_data.py
@@ -35,6 +35,7 @@ if TYPE_CHECKING:
from superset.commands.exceptions import CommandException
from superset.exceptions import OAuth2Error, OAuth2RedirectError, SupersetException
from superset.extensions import event_logger
+from superset.mcp_service import guest_scope
from superset.mcp_service.chart.chart_helpers import (
build_query_context_from_form_data,
build_query_dicts_from_form_data,
@@ -106,6 +107,16 @@ _VIZ_CATEGORY: dict[str, str] = {
_MAX_RECOMMENDATIONS = 4
+def _coerce_row_limit(value: Any, default: int) -> int:
+ """Coerce a row_limit (which may arrive as a str from chart.params) to int,
+ falling back to ``default`` when it is missing or non-numeric — downstream
+ apply_max_row_limit compares it against an int."""
+ try:
+ return int(value)
+ except (TypeError, ValueError):
+ return default
+
+
def _recommend_visualizations(
viz_type: str,
columns: list[DataColumn],
@@ -363,6 +374,9 @@ async def get_chart_data( # noqa: C901
subqueryload(Slice.table).subqueryload(SqlaTable.metrics),
]
+ # Guest-scoped by ChartFilter; guest_dashboard_id authorizes the data
+ # query (None for non-guests).
+ guest_dashboard_id: int | None = None
with event_logger.log_context(action="mcp.get_chart_data.chart_lookup"):
await ctx.debug("Looking up chart: identifier=%s" % (request.identifier,))
if request.identifier is None:
@@ -373,6 +387,8 @@ async def get_chart_data( # noqa: C901
chart = find_chart_by_identifier(
request.identifier, query_options=chart_query_options
)
+ if chart is not None:
+ guest_dashboard_id = guest_scope.guest_dashboard_id(chart)
if not chart:
await ctx.warning("Chart not found: identifier=%s" % (request.identifier,))
@@ -395,21 +411,23 @@ async def get_chart_data( # noqa: C901
)
logger.info("Getting data for chart %s: %s", chart.id, chart.slice_name)
- # Validate the chart's dataset is accessible before retrieving data
- validation_result = validate_chart_dataset(chart, check_access=True)
- if not validation_result.is_valid:
- await ctx.warning(
- "Chart found but dataset is not accessible: %s"
- % (validation_result.error,)
- )
- return ChartError(
- error=validation_result.error
- or "Chart's dataset is not accessible. Dataset may have been deleted.",
- error_type="DatasetNotAccessible",
- )
- # Log any warnings (e.g., virtual dataset warnings)
- for warning in validation_result.warnings:
- await ctx.warning("Dataset warning: %s" % (warning,))
+ # Skip the dataset RBAC pre-check for guests (see guest_scope.is_guest_read).
+ if not guest_scope.is_guest_read():
+ validation_result = validate_chart_dataset(chart, check_access=True)
+ if not validation_result.is_valid:
+ await ctx.warning(
+ "Chart found but dataset is not accessible: %s"
+ % (validation_result.error,)
+ )
+ return ChartError(
+ error=validation_result.error
+ or "Chart's dataset is not accessible. "
+ "Dataset may have been deleted.",
+ error_type="DatasetNotAccessible",
+ )
+ # Log any warnings (e.g., virtual dataset warnings)
+ for warning in validation_result.warnings:
+ await ctx.warning("Dataset warning: %s" % (warning,))
start_time = time.time()
@@ -508,10 +526,11 @@ async def get_chart_data( # noqa: C901
from superset.common.query_context_factory import QueryContextFactory
factory = QueryContextFactory()
- row_limit = (
- request.limit
- or form_data.get("row_limit")
- or current_app.config["ROW_LIMIT"]
+ # row_limit from chart.params may be a str; coerce for
+ # apply_max_row_limit's int comparison.
+ row_limit = _coerce_row_limit(
+ request.limit or form_data.get("row_limit"),
+ current_app.config["ROW_LIMIT"],
)
# Handle different chart types that have different form_data
@@ -604,6 +623,11 @@ async def get_chart_data( # noqa: C901
)
)
+ # For an embedded guest, attach the dashboard context so
+ # raise_for_access authorizes the data query.
+ if guest_dashboard_id is not None:
+ guest_scope.authorize_query(query_context, guest_dashboard_id, chart)
+
# Execute the query
with event_logger.log_context(action="mcp.get_chart_data.query_execution"):
command = ChartDataCommand(query_context)
diff --git a/superset/mcp_service/chart/tool/get_chart_info.py b/superset/mcp_service/chart/tool/get_chart_info.py
index 82c49f6399d..7e09984424f 100644
--- a/superset/mcp_service/chart/tool/get_chart_info.py
+++ b/superset/mcp_service/chart/tool/get_chart_info.py
@@ -106,9 +106,13 @@ async def _validate_chart_dataset_access(
Logs any non-fatal warnings (e.g., virtual dataset warnings) via ctx.
"""
from superset.daos.chart import ChartDAO
+ from superset.mcp_service import guest_scope
if not result.id:
return None
+ # Guests read via the dashboard context, not dataset RBAC; skip the perm-check.
+ if guest_scope.is_guest_read():
+ return None
chart = ChartDAO.find_by_id(result.id)
if not chart:
return None
@@ -314,6 +318,8 @@ async def get_chart_info(
]
with event_logger.log_context(action="mcp.get_chart_info.lookup"):
+ # Resolution is guest-scoped by ChartFilter; the dataset perm-check below
+ # skips guests internally.
tool = ModelGetInfoCore(
dao_class=ChartDAO,
output_schema=ChartInfo,
@@ -323,7 +329,6 @@ async def get_chart_info(
logger=logger,
query_options=eager_options,
)
-
result = tool.run_tool(request.identifier)
if isinstance(result, ChartInfo):
@@ -346,7 +351,7 @@ async def get_chart_info(
"is_unsaved_state=%s" % (result.slice_name, result.is_unsaved_state)
)
- # Validate the chart's dataset is accessible
+ # Validate the chart's dataset is accessible (skips guests internally).
dataset_error = await _validate_chart_dataset_access(result, ctx)
if dataset_error is not None:
return dataset_error
diff --git a/superset/mcp_service/chart/tool/get_chart_preview.py b/superset/mcp_service/chart/tool/get_chart_preview.py
index 107cc9440c3..dea381c8d0f 100644
--- a/superset/mcp_service/chart/tool/get_chart_preview.py
+++ b/superset/mcp_service/chart/tool/get_chart_preview.py
@@ -243,6 +243,14 @@ class PreviewFormatStrategy:
"""Generate preview in the specific format."""
raise NotImplementedError
+ def _authorize_guest_query(self, query_context: Any) -> None:
+ """For a guest, attach the dashboard context so raise_for_access
+ authorizes the preview query."""
+ from superset.mcp_service import guest_scope
+
+ if (dashboard_id := guest_scope.guest_dashboard_id(self.chart)) is not None:
+ guest_scope.authorize_query(query_context, dashboard_id, self.chart)
+
class URLPreviewStrategy(PreviewFormatStrategy):
"""Generate URL-based preview with explore link."""
@@ -292,6 +300,7 @@ class ASCIIPreviewStrategy(PreviewFormatStrategy):
force=False,
)
+ self._authorize_guest_query(query_context)
command = ChartDataCommand(query_context)
command.validate()
result = command.run()
@@ -353,6 +362,7 @@ class TablePreviewStrategy(PreviewFormatStrategy):
force=False,
)
+ self._authorize_guest_query(query_context)
command = ChartDataCommand(query_context)
command.validate()
result = command.run()
@@ -444,6 +454,7 @@ class VegaLitePreviewStrategy(PreviewFormatStrategy):
)
# Execute the query
+ self._authorize_guest_query(query_context)
command = ChartDataCommand(query_context)
command.validate()
result = command.run()
@@ -1243,9 +1254,11 @@ async def _get_chart_preview_internal( # noqa: C901
logger.info("Generating preview for chart %s", getattr(chart, "id", "NO_ID"))
logger.info("Chart datasource_id: %s", getattr(chart, "datasource_id", "NONE"))
- # Validate the chart's dataset is accessible before generating preview
- # Skip validation for transient charts (no ID) - different data sources
- if getattr(chart, "id", None) is not None:
+ # Skip the dataset pre-check for transient charts (no ID) and for guests
+ # (authorized via the dashboard context, not dataset RBAC).
+ from superset.mcp_service import guest_scope
+
+ if getattr(chart, "id", None) is not None and not guest_scope.is_guest_read():
validation_result = validate_chart_dataset(chart, check_access=True)
if not validation_result.is_valid:
await ctx.warning(
diff --git a/superset/mcp_service/chart/tool/get_chart_sql.py b/superset/mcp_service/chart/tool/get_chart_sql.py
index 8555bfc56d1..c53af04d745 100644
--- a/superset/mcp_service/chart/tool/get_chart_sql.py
+++ b/superset/mcp_service/chart/tool/get_chart_sql.py
@@ -386,6 +386,16 @@ async def _handle_chart_sql_request(
request: GetChartSqlRequest, ctx: Context
) -> ChartSql | ChartError:
"""Core logic for get_chart_sql, extracted for complexity."""
+ from superset import security_manager
+
+ # A chart's SQL exposes tables/columns/joins; deny guests (like get_dataset_info)
+ # explicitly so it holds even with MCP_RBAC_ENABLED off.
+ if security_manager.is_guest_user():
+ return ChartError(
+ error="Chart SQL is not available to embedded guests.",
+ error_type="Forbidden",
+ )
+
# Handle unsaved chart (form_data_key only, no identifier)
if not request.identifier and request.form_data_key:
return await _handle_unsaved_chart_sql(request.form_data_key, ctx)
diff --git a/superset/mcp_service/guest_scope.py b/superset/mcp_service/guest_scope.py
new file mode 100644
index 00000000000..41ae8ad554e
--- /dev/null
+++ b/superset/mcp_service/guest_scope.py
@@ -0,0 +1,72 @@
+# 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.
+
+"""Embedded-guest data-query authorization for MCP chart tools.
+
+Chart *resolution* is scoped for guests by the core ``ChartFilter`` (mirroring
+``DashboardAccessFilter``). This module handles the remaining MCP-layer concern:
+attaching the embedded dashboard context to a chart's data query so the existing
+guest ``raise_for_access`` branch authorizes it, exactly as the embedded
+dashboard frontend does.
+"""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+
+def is_guest_read() -> bool:
+ """True when the current MCP read is an embedded guest's, so the chart tools
+ skip the dataset RBAC pre-check: a guest reads via the dashboard context, not
+ dataset RBAC, and ``raise_for_access`` remains the real gate."""
+ from superset import security_manager
+
+ return security_manager.is_guest_user()
+
+
+def guest_dashboard_id(chart: Any) -> int | None:
+ """Id of a guest-accessible dashboard containing ``chart``, else None (also
+ the "is embedded-guest read" signal: None for non-guests)."""
+ from superset import security_manager
+
+ if not security_manager.is_guest_user():
+ return None
+ for dashboard in getattr(chart, "dashboards", None) or []:
+ if security_manager.has_guest_access(dashboard):
+ return dashboard.id
+ return None
+
+
+def authorize_query(query_context: Any, dashboard_id: int, chart: Any) -> None:
+ """Attach the embedded dashboard context so the guest ``raise_for_access``
+ branch authorizes the query, and pin ``slice_`` (when unset) so the guest
+ payload tamper-guard compares the request against this chart."""
+ if getattr(query_context, "slice_", None) is None:
+ query_context.slice_ = chart
+
+ form_data = getattr(query_context, "form_data", None)
+ if isinstance(form_data, dict):
+ form_data["dashboardId"] = dashboard_id
+ form_data["slice_id"] = chart.id
+ return
+ try:
+ query_context.form_data = {"dashboardId": dashboard_id, "slice_id": chart.id}
+ except (AttributeError, TypeError):
+ logger.warning("Could not attach embedded dashboard context to query_context")
diff --git a/superset/mcp_service/mcp_config.py b/superset/mcp_service/mcp_config.py
index 2dc0fe5a6a8..734255ff49f 100644
--- a/superset/mcp_service/mcp_config.py
+++ b/superset/mcp_service/mcp_config.py
@@ -154,9 +154,25 @@ MCP_API_KEY_CREATE_URL = "/profile/"
# GUEST_TOKEN_JWT_* config. See SECURITY.md "Embedded Guest Authentication".
MCP_EMBEDDED_GUEST_AUTH_ENABLED: bool = False
-# Tools a guest may never call (enforced at tools/list and call time, regardless
-# of RBAC). Sync with _DEFAULT_GUEST_DENIED_TOOLS in auth.py.
-MCP_GUEST_DENIED_TOOLS: set[str] = {"find_users", "get_instance_info"}
+# The only tools an embedded guest may call (default-deny, regardless of RBAC).
+# Guest data is further scoped to the token's dashboards by the chart/dashboard
+# filters and redacted by the data-model privacy gate. Sync with
+# _DEFAULT_GUEST_ALLOWED_TOOLS in auth.py.
+MCP_GUEST_ALLOWED_TOOLS: set[str] = {
+ "get_dashboard_info",
+ "get_dashboard_layout",
+ "list_dashboards",
+ "list_charts",
+ "get_chart_info",
+ "get_chart_data",
+ "get_chart_preview",
+}
+
+# Hook to restrict which MCP tools a principal may call, independent of RBAC.
+# Given the current user, return an allow-list (only these tools are callable) or
+# None if the principal is not restricted. Defaults to restricting embedded guests
+# to MCP_GUEST_ALLOWED_TOOLS; set a callable to add other restricted principals.
+MCP_RESTRICTED_TOOL_POLICY: Callable[[Any], frozenset[str] | None] | None = None
# Session configuration for local development
@@ -672,7 +688,7 @@ def get_mcp_config(app_config: dict[str, Any] | None = None) -> dict[str, Any]:
"MCP_DISABLED_CHART_PLUGINS": MCP_DISABLED_CHART_PLUGINS,
"MCP_CHART_PLUGIN_ENABLED_FUNC": MCP_CHART_PLUGIN_ENABLED_FUNC,
"MCP_EMBEDDED_GUEST_AUTH_ENABLED": MCP_EMBEDDED_GUEST_AUTH_ENABLED,
- "MCP_GUEST_DENIED_TOOLS": set(MCP_GUEST_DENIED_TOOLS),
+ "MCP_GUEST_ALLOWED_TOOLS": set(MCP_GUEST_ALLOWED_TOOLS),
**MCP_SESSION_CONFIG,
**MCP_CSRF_CONFIG,
}
diff --git a/superset/mcp_service/privacy.py b/superset/mcp_service/privacy.py
index a741d9743f4..a007772ad69 100644
--- a/superset/mcp_service/privacy.py
+++ b/superset/mcp_service/privacy.py
@@ -128,6 +128,11 @@ def user_can_view_data_model_metadata() -> bool:
try:
from superset import security_manager
+ # Deny guests unconditionally: a PUBLIC_ROLE_LIKE=Gamma guest carries
+ # can_get_drill_info on Dataset, which would otherwise pass the check below.
+ if security_manager.is_guest_user():
+ return False
+
return any(
security_manager.can_access(permission_name, "Dataset")
for permission_name in (
diff --git a/superset/mcp_service/rls/tool/get_rls_filter_info.py b/superset/mcp_service/rls/tool/get_rls_filter_info.py
index 2d226a7ef77..86a6ee718f7 100644
--- a/superset/mcp_service/rls/tool/get_rls_filter_info.py
+++ b/superset/mcp_service/rls/tool/get_rls_filter_info.py
@@ -59,6 +59,16 @@ async def get_rls_filter_info(
{"identifier": 1}
```
"""
+ from superset import security_manager
+
+ # An RLS clause exposes tables/columns and roles; deny guests explicitly so
+ # it holds even with MCP_RBAC_ENABLED off.
+ if security_manager.is_guest_user():
+ return RlsFilterError(
+ error="RLS filters are not available to embedded guests.",
+ error_type="Forbidden",
+ )
+
await ctx.info(
"Retrieving RLS filter information: identifier=%s" % (request.identifier,)
)
diff --git a/superset/mcp_service/rls/tool/list_rls_filters.py b/superset/mcp_service/rls/tool/list_rls_filters.py
index 9b1922d873b..0dd972994f7 100644
--- a/superset/mcp_service/rls/tool/list_rls_filters.py
+++ b/superset/mcp_service/rls/tool/list_rls_filters.py
@@ -65,6 +65,16 @@ async def list_rls_filters(
if ctx is None:
raise RuntimeError("FastMCP context is required for list_rls_filters")
+ from superset import security_manager
+
+ # An RLS clause exposes tables/columns and roles; deny guests explicitly so
+ # it holds even with MCP_RBAC_ENABLED off.
+ if security_manager.is_guest_user():
+ return RlsFilterError(
+ error="RLS filters are not available to embedded guests.",
+ error_type="Forbidden",
+ )
+
request = request or _DEFAULT_LIST_RLS_FILTERS_REQUEST.model_copy(deep=True)
await ctx.info(
diff --git a/superset/security/manager.py b/superset/security/manager.py
index 585899812c7..4a54fea00ab 100644
--- a/superset/security/manager.py
+++ b/superset/security/manager.py
@@ -4409,6 +4409,10 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods
embedded = EmbeddedDashboardDAO.find_by_id(str(resource["id"]))
if not embedded:
raise EmbeddedDashboardNotFoundError()
+ elif not dashboard.embedded:
+ # A raw dashboard id must still reference an embedded dashboard;
+ # otherwise a guest token could be scoped to a non-embedded one.
+ raise EmbeddedDashboardNotFoundError()
def create_guest_access_token(
self,
diff --git a/superset/utils/filters.py b/superset/utils/filters.py
index 8c4a079949b..6f164dcb420 100644
--- a/superset/utils/filters.py
+++ b/superset/utils/filters.py
@@ -14,11 +14,11 @@
# KIND, either express or implied. See the License for the
# specific language governing permissions and limitations
# under the License.
-from typing import Any
+from typing import Any, Optional
from flask_appbuilder import Model
-from sqlalchemy import or_
-from sqlalchemy.sql.elements import BooleanClauseList
+from sqlalchemy import and_, false, or_
+from sqlalchemy.sql.elements import BooleanClauseList, ColumnElement
def get_dataset_access_filters(
@@ -41,3 +41,50 @@ def get_dataset_access_filters(
base_model.schema_perm.in_(schema_perms),
*args,
)
+
+
+def guest_embedded_dashboard_filter() -> Optional[ColumnElement[bool]]:
+ """SQLAlchemy condition scoping charts to the dashboards embedded via the
+ current guest token, or None when the user is not an embedded guest.
+
+ For an embedded guest the result is never None: a token with no dashboard
+ resources returns a deny-all clause so the chart filter fails closed instead
+ of falling back to the ordinary role-based access path.
+
+ Mirrors how DashboardAccessFilter scopes dashboards.
+ """
+ # pylint: disable=import-outside-toplevel
+ from superset import is_feature_enabled, security_manager
+ from superset.models.dashboard import Dashboard, is_uuid
+ from superset.models.embedded_dashboard import EmbeddedDashboard
+ from superset.security.guest_token import GuestTokenResourceType
+
+ if not is_feature_enabled("EMBEDDED_SUPERSET"):
+ return None
+ guest = security_manager.get_current_guest_user_if_guest()
+ if guest is None:
+ return None
+ # The user is an embedded guest from here: scope to the token's dashboards
+ # and never widen back to role-based access. No dashboards means deny all.
+ ids: list[Any] = [
+ r["id"]
+ for r in guest.resources
+ if r["type"] == GuestTokenResourceType.DASHBOARD.value
+ ]
+ if not ids:
+ return false()
+ # TODO (embedded): only use the uuid filter once uuids are rolled out
+ # A guest token may mix uuid and int dashboard ids during the uuid rollout.
+ # Route each id kind to its own column and OR them — a plain int sent to the
+ # uuid-typed column would raise a bind/type error.
+ uuid_ids = [id_ for id_ in ids if is_uuid(id_)]
+ int_ids = [id_ for id_ in ids if not is_uuid(id_)]
+ conditions: list[Any] = []
+ if uuid_ids:
+ conditions.append(Dashboard.embedded.any(EmbeddedDashboard.uuid.in_(uuid_ids)))
+ if int_ids:
+ # Int ids must resolve to an embedded dashboard too (mirrors the uuid
+ # branch and has_guest_access); a guest is only ever scoped to embedded
+ # dashboards, never a plain internal id.
+ conditions.append(and_(Dashboard.id.in_(int_ids), Dashboard.embedded.any()))
+ return or_(*conditions) if conditions else false()
diff --git a/tests/unit_tests/charts/test_filters.py b/tests/unit_tests/charts/test_filters.py
new file mode 100644
index 00000000000..aa688a99b41
--- /dev/null
+++ b/tests/unit_tests/charts/test_filters.py
@@ -0,0 +1,180 @@
+# 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.
+
+"""Tests for the ``ChartFilter`` embedded-guest scoping branch."""
+
+from typing import Any
+from unittest.mock import MagicMock
+
+import pytest
+from pytest_mock import MockerFixture
+from sqlalchemy import create_engine
+
+
+def test_chart_filter_scopes_guest_to_token_dashboards(mocker: MockerFixture) -> None:
+ """A guest's chart list is scoped to the dashboards in its token."""
+ from superset.charts.filters import ChartFilter
+ from superset.extensions import security_manager
+ from superset.models.dashboard import Dashboard
+ from superset.models.slice import Slice
+
+ mocker.patch.object(
+ security_manager, "can_access_all_datasources", return_value=False
+ )
+ mocker.patch(
+ "superset.charts.filters.guest_embedded_dashboard_filter",
+ return_value=Dashboard.id.in_([1, 2]),
+ )
+
+ captured: dict[str, Any] = {}
+ query: MagicMock = MagicMock()
+
+ def _capture_filter(clause: object) -> MagicMock:
+ captured["clause"] = clause
+ return query
+
+ query.filter.side_effect = _capture_filter
+
+ filt: ChartFilter = ChartFilter.__new__(ChartFilter)
+ filt.model = Slice
+ result = filt.apply(query, None)
+
+ assert result is query
+ query.filter.assert_called_once()
+ # Guest branch returns early: it must NOT take the datasource-access join path.
+ query.join.assert_not_called()
+
+ compiled: str = str(
+ captured["clause"].compile(
+ create_engine("sqlite://"), compile_kwargs={"literal_binds": True}
+ )
+ )
+ assert "EXISTS" in compiled # scoped via the m2m dashboards relationship
+ assert "IN (1, 2)" in compiled
+
+
+def test_chart_filter_non_guest_skips_guest_branch(mocker: MockerFixture) -> None:
+ """With no embedded guest, ChartFilter does not take the guest branch (it
+ proceeds to the normal viewer-access path instead of filtering on dashboards)."""
+ from superset.charts.filters import ChartFilter
+ from superset.extensions import security_manager
+ from superset.models.slice import Slice
+
+ mocker.patch.object(
+ security_manager, "can_access_all_datasources", return_value=False
+ )
+ guest_filter: MagicMock = mocker.patch(
+ "superset.charts.filters.guest_embedded_dashboard_filter", return_value=None
+ )
+ # Stop apply right after the guest check — reaching the viewer-access path
+ # proves the guest branch was skipped.
+ sentinel: RuntimeError = RuntimeError("reached viewer-access path")
+ mocker.patch.object(ChartFilter, "_apply_viewers", side_effect=sentinel)
+ query: MagicMock = MagicMock()
+
+ filt: ChartFilter = ChartFilter.__new__(ChartFilter)
+ filt.model = Slice
+
+ with pytest.raises(RuntimeError, match="viewer-access path"):
+ filt.apply(query, None)
+
+ guest_filter.assert_called_once()
+ query.filter.assert_not_called() # guest branch (query.filter) was NOT taken
+
+
+def test_chart_filter_admin_bypasses_all_scoping(mocker: MockerFixture) -> None:
+ """A non-guest who can access all datasources gets the query back untouched.
+
+ The guest scope check runs first but returns None for a non-guest, so the
+ all-datasources bypass still applies.
+ """
+ from superset.charts.filters import ChartFilter
+ from superset.extensions import security_manager
+ from superset.models.slice import Slice
+
+ mocker.patch.object(
+ security_manager, "can_access_all_datasources", return_value=True
+ )
+ guest_filter: MagicMock = mocker.patch(
+ "superset.charts.filters.guest_embedded_dashboard_filter", return_value=None
+ )
+
+ query: MagicMock = MagicMock()
+ filt: ChartFilter = ChartFilter.__new__(ChartFilter)
+ filt.model = Slice
+
+ assert filt.apply(query, None) is query
+ query.filter.assert_not_called()
+ guest_filter.assert_called_once()
+
+
+def test_chart_filter_guest_scoped_even_with_all_datasource_access(
+ mocker: MockerFixture,
+) -> None:
+ """A guest is scoped to its token's dashboards even when its role can access
+ all datasources: the guest branch runs before the all-datasources bypass."""
+ from superset.charts.filters import ChartFilter
+ from superset.extensions import security_manager
+ from superset.models.dashboard import Dashboard
+ from superset.models.slice import Slice
+
+ can_access = mocker.patch.object(
+ security_manager, "can_access_all_datasources", return_value=True
+ )
+ mocker.patch(
+ "superset.charts.filters.guest_embedded_dashboard_filter",
+ return_value=Dashboard.id.in_([1, 2]),
+ )
+ query: MagicMock = MagicMock()
+ query.filter.return_value = query
+ filt: ChartFilter = ChartFilter.__new__(ChartFilter)
+ filt.model = Slice
+
+ assert filt.apply(query, None) is query
+ # Scoped via the guest branch — NOT returned untouched by the all-access path.
+ query.filter.assert_called_once()
+ can_access.assert_not_called()
+
+
+def test_chart_filter_guest_no_resources_denied(mocker: MockerFixture) -> None:
+ """A guest whose token has no dashboards is denied all charts: the filter
+ returns a deny-all clause (not None), so apply scopes rather than falling
+ through to role-based access."""
+ from sqlalchemy import false
+
+ from superset.charts.filters import ChartFilter
+ from superset.extensions import security_manager
+ from superset.models.slice import Slice
+
+ mocker.patch.object(
+ security_manager, "can_access_all_datasources", return_value=False
+ )
+ mocker.patch(
+ "superset.charts.filters.guest_embedded_dashboard_filter",
+ return_value=false(),
+ )
+ viewers = mocker.patch.object(
+ ChartFilter, "_apply_viewers", side_effect=AssertionError("role path")
+ )
+ query: MagicMock = MagicMock()
+ query.filter.return_value = query
+ filt: ChartFilter = ChartFilter.__new__(ChartFilter)
+ filt.model = Slice
+
+ assert filt.apply(query, None) is query
+ query.filter.assert_called_once() # scoped (to nothing), not role-based
+ viewers.assert_not_called()
diff --git a/tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py b/tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py
index 2f46fbd5c57..4f4f1e062f2 100644
--- a/tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py
+++ b/tests/unit_tests/mcp_service/chart/tool/test_get_chart_data.py
@@ -33,6 +33,7 @@ from superset.mcp_service.chart.schemas import (
PerformanceMetadata,
)
from superset.mcp_service.chart.tool.get_chart_data import (
+ _coerce_row_limit,
_GENERIC_TYPE_MAP,
_MAX_RECOMMENDATIONS,
_query_from_form_data,
@@ -1262,9 +1263,10 @@ class TestChartLookupEagerLoading:
)
assert len(query_options) == 1
load_path = _extract_metrics_load_path(query_options[0])
- assert load_path == ["table", "metrics"], (
- f"Expected subqueryload chain 'table' -> 'metrics', got {load_path}"
- )
+ assert load_path == [
+ "table",
+ "metrics",
+ ], f"Expected subqueryload chain 'table' -> 'metrics', got {load_path}"
@pytest.mark.asyncio
async def test_uuid_lookup_passes_metrics_eager_load(self, mcp_server, mock_auth):
@@ -1293,9 +1295,10 @@ class TestChartLookupEagerLoading:
"UUID chart lookup must pass query_options for eager-loading."
)
load_path = _extract_metrics_load_path(query_options[0])
- assert load_path == ["table", "metrics"], (
- f"Expected subqueryload chain 'table' -> 'metrics', got {load_path}"
- )
+ assert load_path == [
+ "table",
+ "metrics",
+ ], f"Expected subqueryload chain 'table' -> 'metrics', got {load_path}"
@pytest.mark.asyncio
async def test_json_format_also_eager_loads_metrics(self, mcp_server, mock_auth):
@@ -1452,3 +1455,19 @@ def test_bool_isinstance_check_before_int():
elif all(isinstance(v, (int, float)) for v in sample_values):
data_type = "numeric"
assert data_type == "boolean"
+
+
+@pytest.mark.parametrize(
+ "value,default,expected",
+ [
+ (100, 500, 100), # int passthrough
+ ("250", 500, 250), # numeric string from chart.params
+ (None, 500, 500), # missing -> default
+ ("", 500, 500), # empty string -> default
+ ("abc", 500, 500), # non-numeric -> default
+ (0, 500, 0), # explicit zero preserved
+ ],
+)
+def test_coerce_row_limit(value: Any, default: int, expected: int) -> None:
+ """_coerce_row_limit tolerates str/None row_limits from chart.params."""
+ assert _coerce_row_limit(value, default) == expected
diff --git a/tests/unit_tests/mcp_service/chart/tool/test_get_chart_info.py b/tests/unit_tests/mcp_service/chart/tool/test_get_chart_info.py
index e90eb6641b9..c6d8648ac56 100644
--- a/tests/unit_tests/mcp_service/chart/tool/test_get_chart_info.py
+++ b/tests/unit_tests/mcp_service/chart/tool/test_get_chart_info.py
@@ -608,3 +608,22 @@ def test_apply_unsaved_state_override_updates_display_name_for_new_viz_type() ->
assert result.viz_type == "pie"
assert result.chart_type_display_name == "Pie Chart"
+
+
+@pytest.mark.asyncio
+async def test_validate_dataset_access_skips_perm_check_for_guest() -> None:
+ """A guest reads via the dashboard context, so the dataset perm-check (and
+ its validate_chart_dataset call) is skipped without returning an error."""
+ result = MagicMock()
+ result.id = 123
+
+ with (
+ patch("superset.mcp_service.guest_scope.is_guest_read", return_value=True),
+ patch.object(get_chart_info_module, "validate_chart_dataset") as mock_validate,
+ ):
+ outcome = await get_chart_info_module._validate_chart_dataset_access(
+ result, MagicMock()
+ )
+
+ assert outcome is None
+ mock_validate.assert_not_called()
diff --git a/tests/unit_tests/mcp_service/chart/tool/test_get_chart_preview.py b/tests/unit_tests/mcp_service/chart/tool/test_get_chart_preview.py
index 385d05b1a36..a2b793d81ef 100644
--- a/tests/unit_tests/mcp_service/chart/tool/test_get_chart_preview.py
+++ b/tests/unit_tests/mcp_service/chart/tool/test_get_chart_preview.py
@@ -22,7 +22,7 @@ Unit tests for get_chart_preview MCP tool
import importlib
from types import SimpleNamespace
from typing import Any
-from unittest.mock import MagicMock
+from unittest.mock import MagicMock, patch
import pytest
@@ -43,6 +43,7 @@ from superset.mcp_service.chart.tool.get_chart_preview import (
_build_query_metrics,
_sanitize_chart_preview_for_llm_context,
ASCIIPreviewStrategy,
+ PreviewFormatStrategy,
TablePreviewStrategy,
)
from superset.mcp_service.utils import sanitize_for_llm_context
@@ -1252,3 +1253,36 @@ class TestDetachedInstanceError:
data = json.loads(response.content[0].text)
assert data["error_type"] == "InternalError"
assert "session" in data["error"].lower() or "retry" in data["error"].lower()
+
+
+def _guest_strategy() -> PreviewFormatStrategy:
+ chart = MagicMock()
+ return PreviewFormatStrategy(chart, GetChartPreviewRequest(identifier=1))
+
+
+def test_authorize_guest_query_attaches_dashboard_context() -> None:
+ """For a guest, the preview query is pinned to the token's dashboard so
+ raise_for_access can authorize it."""
+ strategy = _guest_strategy()
+ query_context = MagicMock()
+
+ with (
+ patch("superset.mcp_service.guest_scope.guest_dashboard_id", return_value=6),
+ patch("superset.mcp_service.guest_scope.authorize_query") as mock_authorize,
+ ):
+ strategy._authorize_guest_query(query_context)
+
+ mock_authorize.assert_called_once_with(query_context, 6, strategy.chart)
+
+
+def test_authorize_guest_query_noop_for_non_guest() -> None:
+ """A non-guest has no dashboard id, so nothing is attached."""
+ strategy = _guest_strategy()
+
+ with (
+ patch("superset.mcp_service.guest_scope.guest_dashboard_id", return_value=None),
+ patch("superset.mcp_service.guest_scope.authorize_query") as mock_authorize,
+ ):
+ strategy._authorize_guest_query(MagicMock())
+
+ mock_authorize.assert_not_called()
diff --git a/tests/unit_tests/mcp_service/chart/tool/test_get_chart_sql.py b/tests/unit_tests/mcp_service/chart/tool/test_get_chart_sql.py
index 2ae4903378c..41c6de2a44d 100644
--- a/tests/unit_tests/mcp_service/chart/tool/test_get_chart_sql.py
+++ b/tests/unit_tests/mcp_service/chart/tool/test_get_chart_sql.py
@@ -1032,6 +1032,24 @@ class TestGetChartSqlTool:
assert data["error_type"] == "NotFound"
assert "999" in data["error"]
+ @pytest.mark.asyncio
+ async def test_guest_denied(self, mcp_server):
+ """An embedded guest is denied chart SQL (data-model metadata), even with
+ RBAC off — chart SQL exposes tables/columns/joins, like get_dataset_info."""
+ from fastmcp import Client
+
+ from superset.extensions import security_manager
+
+ with patch.object(security_manager, "is_guest_user", return_value=True):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "get_chart_sql", {"request": {"identifier": 123}}
+ )
+
+ data = result.structured_content.get("result", result.structured_content)
+ assert data["error_type"] == "Forbidden"
+ assert "guest" in data["error"].lower()
+
@patch.object(_get_chart_sql_mod, "_sql_from_form_data")
@patch.object(_get_chart_sql_mod, "_sql_from_saved_query_context")
@patch.object(_get_chart_sql_mod, "_resolve_effective_form_data")
diff --git a/tests/unit_tests/mcp_service/chart/tool/test_list_charts.py b/tests/unit_tests/mcp_service/chart/tool/test_list_charts.py
index b6622ec33a3..4face4607af 100644
--- a/tests/unit_tests/mcp_service/chart/tool/test_list_charts.py
+++ b/tests/unit_tests/mcp_service/chart/tool/test_list_charts.py
@@ -307,6 +307,7 @@ class TestChartDataModelMetadataPrivacy:
def test_user_can_view_data_model_metadata_uses_dataset_permission(self):
with patch("superset.security_manager", new_callable=Mock) as security_manager:
+ security_manager.is_guest_user.return_value = False
security_manager.can_access.side_effect = [False, True, False]
assert user_can_view_data_model_metadata() is True
diff --git a/tests/unit_tests/mcp_service/rls/tool/test_rls_tools.py b/tests/unit_tests/mcp_service/rls/tool/test_rls_tools.py
index 83272fa7c56..eac79a6ba9e 100644
--- a/tests/unit_tests/mcp_service/rls/tool/test_rls_tools.py
+++ b/tests/unit_tests/mcp_service/rls/tool/test_rls_tools.py
@@ -244,3 +244,31 @@ async def test_list_rls_filters_subjects_only_select_columns(mock_list, mcp_serv
item = data["rls_filters"][0]
assert "subjects" in item
assert item["subjects"][0]["label"] == "Alpha"
+
+
+@pytest.mark.asyncio
+async def test_list_rls_filters_guest_denied(mcp_server):
+ """An embedded guest is denied listing RLS filters, even with RBAC off."""
+ from superset.extensions import security_manager
+
+ with patch.object(security_manager, "is_guest_user", return_value=True):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool("list_rls_filters", {})
+ data = json.loads(result.content[0].text)
+ assert data["error_type"] == "Forbidden"
+ assert "guest" in data["error"].lower()
+
+
+@pytest.mark.asyncio
+async def test_get_rls_filter_info_guest_denied(mcp_server):
+ """An embedded guest is denied RLS filter details, even with RBAC off."""
+ from superset.extensions import security_manager
+
+ with patch.object(security_manager, "is_guest_user", return_value=True):
+ async with Client(mcp_server) as client:
+ result = await client.call_tool(
+ "get_rls_filter_info", {"request": {"identifier": 1}}
+ )
+ data = json.loads(result.content[0].text)
+ assert data["error_type"] == "Forbidden"
+ assert "guest" in data["error"].lower()
diff --git a/tests/unit_tests/mcp_service/system/tool/test_get_current_user.py b/tests/unit_tests/mcp_service/system/tool/test_get_current_user.py
index f07f4d628f2..fd9acad2abc 100644
--- a/tests/unit_tests/mcp_service/system/tool/test_get_current_user.py
+++ b/tests/unit_tests/mcp_service/system/tool/test_get_current_user.py
@@ -182,6 +182,7 @@ def test_user_can_view_data_model_metadata_requires_stronger_dataset_permission(
app_context,
):
with patch("superset.security_manager", new_callable=Mock) as mock_security_manager:
+ mock_security_manager.is_guest_user.return_value = False
mock_security_manager.can_access.side_effect = (
lambda permission_name, view_name: permission_name == "can_read"
)
diff --git a/tests/unit_tests/mcp_service/test_guest_scope.py b/tests/unit_tests/mcp_service/test_guest_scope.py
new file mode 100644
index 00000000000..554adbec6ba
--- /dev/null
+++ b/tests/unit_tests/mcp_service/test_guest_scope.py
@@ -0,0 +1,121 @@
+# 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.
+
+"""Tests for the embedded-guest data-query authorization helpers."""
+
+from types import SimpleNamespace
+from typing import Any
+
+from pytest_mock import MockerFixture
+
+from superset.extensions import security_manager
+from superset.mcp_service import guest_scope
+
+
+def test_is_guest_read_true_for_guest(mocker: MockerFixture) -> None:
+ """The skip predicate is True for an embedded guest."""
+ mocker.patch.object(security_manager, "is_guest_user", return_value=True)
+ assert guest_scope.is_guest_read() is True
+
+
+def test_is_guest_read_false_for_non_guest(mocker: MockerFixture) -> None:
+ """The skip predicate is False for a regular user."""
+ mocker.patch.object(security_manager, "is_guest_user", return_value=False)
+ assert guest_scope.is_guest_read() is False
+
+
+def test_guest_dashboard_id_non_guest_short_circuits(mocker: MockerFixture) -> None:
+ """Non-guests return None without ever inspecting the chart's dashboards."""
+ mocker.patch.object(security_manager, "is_guest_user", return_value=False)
+ has_access = mocker.patch.object(security_manager, "has_guest_access")
+
+ chart = SimpleNamespace(dashboards=[SimpleNamespace(id=7)])
+
+ assert guest_scope.guest_dashboard_id(chart) is None
+ has_access.assert_not_called()
+
+
+def test_guest_dashboard_id_returns_accessible_dashboard(
+ mocker: MockerFixture,
+) -> None:
+ """A guest gets the id of the first dashboard it may access."""
+
+ def _has_access(dashboard: Any) -> bool:
+ return bool(dashboard.id == 7)
+
+ mocker.patch.object(security_manager, "is_guest_user", return_value=True)
+ mocker.patch.object(security_manager, "has_guest_access", side_effect=_has_access)
+
+ chart = SimpleNamespace(dashboards=[SimpleNamespace(id=5), SimpleNamespace(id=7)])
+
+ assert guest_scope.guest_dashboard_id(chart) == 7
+
+
+def test_guest_dashboard_id_out_of_scope_returns_none(mocker: MockerFixture) -> None:
+ """A guest with no access to any of the chart's dashboards gets None."""
+ mocker.patch.object(security_manager, "is_guest_user", return_value=True)
+ mocker.patch.object(security_manager, "has_guest_access", return_value=False)
+
+ chart = SimpleNamespace(dashboards=[SimpleNamespace(id=5)])
+
+ assert guest_scope.guest_dashboard_id(chart) is None
+
+
+def test_guest_dashboard_id_chart_without_dashboards(mocker: MockerFixture) -> None:
+ """A chart with no dashboards (e.g. transient) yields None for a guest."""
+ mocker.patch.object(security_manager, "is_guest_user", return_value=True)
+
+ assert guest_scope.guest_dashboard_id(SimpleNamespace(dashboards=None)) is None
+
+
+def test_authorize_query_merges_into_dict_form_data() -> None:
+ """dashboardId/slice_id are added without dropping existing form_data."""
+ query_context = SimpleNamespace(slice_=object(), form_data={"existing": 1})
+ chart = SimpleNamespace(id=42)
+
+ guest_scope.authorize_query(query_context, 7, chart)
+
+ assert query_context.form_data == {"existing": 1, "dashboardId": 7, "slice_id": 42}
+
+
+def test_authorize_query_pins_slice_when_unset() -> None:
+ """slice_ is pinned to the resolved chart so the tamper-guard can compare."""
+ query_context = SimpleNamespace(slice_=None, form_data={})
+ chart = SimpleNamespace(id=42)
+
+ guest_scope.authorize_query(query_context, 7, chart)
+
+ assert query_context.slice_ is chart
+
+
+def test_authorize_query_keeps_existing_slice() -> None:
+ """An already-resolved slice_ is not overwritten."""
+ existing = object()
+ query_context = SimpleNamespace(slice_=existing, form_data={})
+
+ guest_scope.authorize_query(query_context, 7, SimpleNamespace(id=42))
+
+ assert query_context.slice_ is existing
+
+
+def test_authorize_query_replaces_non_dict_form_data() -> None:
+ """When form_data is not a dict, it is set to a fresh context dict."""
+ query_context = SimpleNamespace(slice_=object(), form_data=None)
+
+ guest_scope.authorize_query(query_context, 7, SimpleNamespace(id=42))
+
+ assert query_context.form_data == {"dashboardId": 7, "slice_id": 42}
diff --git a/tests/unit_tests/mcp_service/test_guest_token_auth.py b/tests/unit_tests/mcp_service/test_guest_token_auth.py
index d2c02d5dd2c..5bf8d4441e5 100644
--- a/tests/unit_tests/mcp_service/test_guest_token_auth.py
+++ b/tests/unit_tests/mcp_service/test_guest_token_auth.py
@@ -39,8 +39,9 @@ from flask import g
from superset.app import SupersetApp
from superset.constants import CHANGE_ME_GUEST_TOKEN_JWT_SECRET
from superset.mcp_service.auth import (
+ _DEFAULT_GUEST_ALLOWED_TOOLS,
_resolve_user_from_jwt_context,
- _tool_denied_for_guest,
+ _tool_denied_for_principal,
check_tool_permission,
CLASS_PERMISSION_ATTR,
is_tool_visible_to_current_user,
@@ -316,21 +317,85 @@ def _make_guest_user() -> GuestUser:
)
-def test_tool_denied_for_guest_helper(app: SupersetApp) -> None:
+def test_tool_denied_for_principal_helper(app: SupersetApp) -> None:
denied = MagicMock()
- denied.__name__ = "find_users"
+ denied.__name__ = "find_users" # not on the allow-list
allowed = MagicMock()
- allowed.__name__ = "list_charts"
+ allowed.__name__ = "list_charts" # on the allow-list
with app.app_context():
- # Non-guest: deny-list never applies.
+ # Non-guest: the guest allow-list never applies.
g.user = MagicMock(spec=[])
- assert _tool_denied_for_guest(denied) is False
+ assert _tool_denied_for_principal(denied) is False
+
+ # Guest: only allow-listed tools pass; everything else is denied.
+ g.user = _make_guest_user()
+ assert _tool_denied_for_principal(denied) is True
+ assert _tool_denied_for_principal(allowed) is False
+
+
+def test_default_allow_list_matches_config() -> None:
+ """The auth.py default and the mcp_config.py default must stay in sync."""
+ from superset.mcp_service.mcp_config import MCP_GUEST_ALLOWED_TOOLS
+
+ assert set(_DEFAULT_GUEST_ALLOWED_TOOLS) == set(MCP_GUEST_ALLOWED_TOOLS)
+
+
+@pytest.mark.parametrize("tool_name", sorted(_DEFAULT_GUEST_ALLOWED_TOOLS))
+def test_allow_listed_tools_permitted_for_guest(
+ app: SupersetApp, tool_name: str
+) -> None:
+ """Every tool on the default allow-list is reachable by a guest."""
+ func = MagicMock()
+ func.__name__ = tool_name
+
+ with app.app_context():
+ g.user = _make_guest_user()
+ assert _tool_denied_for_principal(func) is False
+
+
+@pytest.mark.parametrize(
+ "tool_name",
+ [
+ # user-directory / security-config
+ "find_users",
+ "get_user_info",
+ "list_users",
+ "get_role_info",
+ "list_roles",
+ "get_instance_info",
+ # data-model internals
+ "get_dataset_info",
+ "list_datasets",
+ "query_dataset",
+ "get_database_info",
+ "get_chart_sql",
+ "list_rls_filters",
+ # newly-covered enumeration tools (tags/tasks/annotations/reports/queries)
+ "list_tags",
+ "list_tasks",
+ "list_annotation_layers",
+ "list_reports",
+ "list_queries",
+ "list_saved_queries",
+ # mutating tools
+ "execute_sql",
+ "create_dataset",
+ "update_dashboard",
+ "generate_chart",
+ ],
+)
+def test_non_allow_listed_tools_denied_to_guest(
+ app: SupersetApp, tool_name: str
+) -> None:
+ """Default-deny: any tool not on the allow-list is blocked for a guest,
+ regardless of its RBAC class (holds with RBAC off)."""
+ func = MagicMock()
+ func.__name__ = tool_name
- # Guest: denied tool blocked, non-denied tool allowed.
+ with app.app_context():
g.user = _make_guest_user()
- assert _tool_denied_for_guest(denied) is True
- assert _tool_denied_for_guest(allowed) is False
+ assert _tool_denied_for_principal(func) is True
def test_guest_denied_tool_blocked_at_call_time(app: SupersetApp) -> None:
@@ -354,8 +419,8 @@ def test_guest_denied_tool_hidden_from_listing(app: SupersetApp) -> None:
def test_guest_allowed_tool_permitted_with_rbac(app: SupersetApp) -> None:
- """A guest passes the deny-list and is granted a non-denied tool through the
- full RBAC chain (deny-list runs, RBAC grants, scopes allow)."""
+ """A guest passes the allow-list and is granted an allow-listed tool through
+ the full RBAC chain (allow-list runs, RBAC grants, scopes allow)."""
func = MagicMock()
func.__name__ = "list_charts"
setattr(func, CLASS_PERMISSION_ATTR, "Chart")
@@ -372,33 +437,100 @@ def test_guest_allowed_tool_permitted_with_rbac(app: SupersetApp) -> None:
assert check_tool_permission(func) is True
-def test_denylist_string_misconfig_falls_back_to_default(app: SupersetApp) -> None:
- """A misconfigured string deny-list must not cause substring matching; the
- type guard falls back to the safe default set."""
+def test_allowlist_string_misconfig_falls_back_to_default(app: SupersetApp) -> None:
+ """A misconfigured string allow-list must not cause substring matching; the
+ type guard falls back to the safe default set (fail-closed)."""
func = MagicMock()
- func.__name__ = "find_user" # substring of "find_users"
+ func.__name__ = "chart" # substring of allow-list entries like "get_chart_info"
with app.app_context():
with patch.dict(
- app.config, {"MCP_GUEST_DENIED_TOOLS": "find_users,get_instance_info"}
+ app.config, {"MCP_GUEST_ALLOWED_TOOLS": "get_chart_info,list_charts"}
):
g.user = _make_guest_user()
- # Naive `in` on the string would wrongly match "find_user"; the guard
- # falls back to the default set, so "find_user" is allowed...
- assert _tool_denied_for_guest(func) is False
- # ...while a genuinely-denied tool is still blocked via the default.
- func.__name__ = "find_users"
- assert _tool_denied_for_guest(func) is True
+ # Naive substring `in` would wrongly ALLOW "chart"; the guard falls
+ # back to the default set, where "chart" is absent, so it is denied.
+ assert _tool_denied_for_principal(func) is True
+ # A genuinely allow-listed tool is still permitted via the default.
+ func.__name__ = "get_chart_info"
+ assert _tool_denied_for_principal(func) is False
+
+
+def test_guest_allowed_tools_operator_override(app: SupersetApp) -> None:
+ """An operator can widen the guest allow-list via config."""
+ func = MagicMock()
+ func.__name__ = "get_dataset_info" # not on the default allow-list
+
+ with app.app_context():
+ g.user = _make_guest_user()
+ assert _tool_denied_for_principal(func) is True
+ with patch.dict(app.config, {"MCP_GUEST_ALLOWED_TOOLS": {"get_dataset_info"}}):
+ assert _tool_denied_for_principal(func) is False
+
+
+def test_restricted_tool_policy_hook_restricts_non_guest(app: SupersetApp) -> None:
+ """A custom MCP_RESTRICTED_TOOL_POLICY can restrict a non-guest principal,
+ proving the allow-list layer is principal-agnostic (guests are just the
+ default). The policy returns an allow-list; non-listed tools are denied."""
+ allowed = MagicMock()
+ allowed.__name__ = "list_charts"
+ denied = MagicMock()
+ denied.__name__ = "execute_sql"
+
+ def policy(user: Any) -> frozenset[str] | None:
+ return frozenset({"list_charts"})
+
+ with app.app_context():
+ with patch.dict(app.config, {"MCP_RESTRICTED_TOOL_POLICY": policy}):
+ g.user = MagicMock(spec=[]) # an ordinary (non-guest) principal
+ assert _tool_denied_for_principal(allowed) is False
+ assert _tool_denied_for_principal(denied) is True
+
+
+def test_restricted_tool_policy_hook_none_means_unrestricted(app: SupersetApp) -> None:
+ """A policy returning None leaves the principal governed by RBAC (not blocked
+ by the allow-list layer)."""
+ func = MagicMock()
+ func.__name__ = "execute_sql"
+
+ def policy(user: Any) -> frozenset[str] | None:
+ return None
+
+ with app.app_context():
+ with patch.dict(app.config, {"MCP_RESTRICTED_TOOL_POLICY": policy}):
+ g.user = _make_guest_user()
+ assert _tool_denied_for_principal(func) is False
+
+
+def test_restricted_tool_policy_hook_bad_return_fails_closed(app: SupersetApp) -> None:
+ """A misbehaving policy that returns a non-collection denies all tools."""
+ func = MagicMock()
+ func.__name__ = "get_chart_info"
+
+ def policy(user: Any) -> frozenset[str] | None:
+ return "list_charts" # type: ignore[return-value]
+
+ with app.app_context():
+ with patch.dict(app.config, {"MCP_RESTRICTED_TOOL_POLICY": policy}):
+ g.user = _make_guest_user()
+ assert _tool_denied_for_principal(func) is True
-def test_guest_denied_tools_operator_override(app: SupersetApp) -> None:
+def test_restricted_tool_policy_hook_non_callable_uses_default(
+ app: SupersetApp,
+) -> None:
+ """A non-callable policy (a set is the natural mistake, since
+ MCP_GUEST_ALLOWED_TOOLS is a set) does not crash every call: it falls back to
+ the built-in default, so a guest stays default-denied for non-allow-listed
+ tools."""
func = MagicMock()
func.__name__ = "execute_sql"
with app.app_context():
- with patch.dict(app.config, {"MCP_GUEST_DENIED_TOOLS": {"execute_sql"}}):
+ with patch.dict(app.config, {"MCP_RESTRICTED_TOOL_POLICY": {"list_charts"}}):
g.user = _make_guest_user()
- assert _tool_denied_for_guest(func) is True
+ # No TypeError, and the guest is still restricted (execute_sql denied).
+ assert _tool_denied_for_principal(func) is True
# -- Hardening: expiry, forgery, and the resolution gate --
diff --git a/tests/unit_tests/mcp_service/test_privacy.py b/tests/unit_tests/mcp_service/test_privacy.py
index 803ccb36d9c..3b6b99f0b27 100644
--- a/tests/unit_tests/mcp_service/test_privacy.py
+++ b/tests/unit_tests/mcp_service/test_privacy.py
@@ -17,6 +17,8 @@
"""Tests for MCP privacy helpers."""
+from unittest.mock import patch
+
import pytest
from superset.mcp_service.chart.schemas import ChartInfo
@@ -26,10 +28,53 @@ from superset.mcp_service.dataset.schemas import DatasetInfo
from superset.mcp_service.privacy import (
is_data_model_metadata_error,
redact_chart_data_model_fields,
+ user_can_view_data_model_metadata,
)
from superset.mcp_service.report.schemas import ReportInfo
+def test_user_can_view_data_model_metadata_denies_guest() -> None:
+ """A guest is denied even when the (Gamma-like) role would pass can_access.
+
+ A PUBLIC_ROLE_LIKE=Gamma guest carries can_get_drill_info on Dataset, so the
+ permission check alone returns True; the guest short-circuit must override it.
+ """
+ from superset.extensions import security_manager
+
+ with (
+ patch.object(security_manager, "is_guest_user", return_value=True),
+ patch.object(security_manager, "can_access", return_value=True) as can_access,
+ ):
+ assert user_can_view_data_model_metadata() is False
+ can_access.assert_not_called()
+
+
+def test_user_can_view_data_model_metadata_allows_privileged_non_guest() -> None:
+ """A non-guest with a metadata permission still passes."""
+ from superset.extensions import security_manager
+
+ with (
+ patch.object(security_manager, "is_guest_user", return_value=False),
+ patch.object(
+ security_manager,
+ "can_access",
+ side_effect=lambda perm, _: perm == "can_write",
+ ),
+ ):
+ assert user_can_view_data_model_metadata() is True
+
+
+def test_user_can_view_data_model_metadata_denies_unprivileged_non_guest() -> None:
+ """A non-guest without drill/create/write on Dataset is denied."""
+ from superset.extensions import security_manager
+
+ with (
+ patch.object(security_manager, "is_guest_user", return_value=False),
+ patch.object(security_manager, "can_access", return_value=False),
+ ):
+ assert user_can_view_data_model_metadata() is False
+
+
def test_is_data_model_metadata_error_accepts_missing_privacy_scope() -> None:
assert (
is_data_model_metadata_error(
diff --git a/tests/unit_tests/security/manager_test.py b/tests/unit_tests/security/manager_test.py
index ced9bfa4ecb..564e2597c7a 100644
--- a/tests/unit_tests/security/manager_test.py
+++ b/tests/unit_tests/security/manager_test.py
@@ -2898,3 +2898,40 @@ def test_query_context_modified_orderby_non_bool_direction_blocked(
query_context.queries = []
assert query_context_modified(query_context)
+
+
+def test_validate_guest_token_resources_rejects_non_embedded_int_id(
+ app_context: None, mocker: MockerFixture
+) -> None:
+ """A raw int dashboard id must reference an embedded dashboard, else a guest
+ token could be scoped to a non-embedded dashboard."""
+ from superset.commands.dashboard.embedded.exceptions import (
+ EmbeddedDashboardNotFoundError,
+ )
+ from superset.security.guest_token import GuestTokenResourceType
+
+ sm = SupersetSecurityManager(appbuilder)
+ non_embedded = MagicMock()
+ non_embedded.embedded = [] # not embedded
+ mocker.patch("superset.models.dashboard.Dashboard.get", return_value=non_embedded)
+
+ with pytest.raises(EmbeddedDashboardNotFoundError):
+ sm.validate_guest_token_resources(
+ [{"type": GuestTokenResourceType.DASHBOARD, "id": 5}]
+ )
+
+
+def test_validate_guest_token_resources_accepts_embedded_int_id(
+ app_context: None, mocker: MockerFixture
+) -> None:
+ """A raw int id for an embedded dashboard is accepted."""
+ from superset.security.guest_token import GuestTokenResourceType
+
+ sm = SupersetSecurityManager(appbuilder)
+ embedded_dash = MagicMock()
+ embedded_dash.embedded = [MagicMock()] # embedded
+ mocker.patch("superset.models.dashboard.Dashboard.get", return_value=embedded_dash)
+
+ sm.validate_guest_token_resources(
+ [{"type": GuestTokenResourceType.DASHBOARD, "id": 5}]
+ )
diff --git a/tests/unit_tests/utils/filters_test.py b/tests/unit_tests/utils/filters_test.py
index b41774bb2e4..4bfa803641c 100644
--- a/tests/unit_tests/utils/filters_test.py
+++ b/tests/unit_tests/utils/filters_test.py
@@ -15,10 +15,16 @@
# specific language governing permissions and limitations
# under the License.
+from types import SimpleNamespace
+
from pytest_mock import MockerFixture
from sqlalchemy import create_engine
-from superset.utils.filters import get_dataset_access_filters
+from superset.extensions import security_manager
+from superset.utils.filters import (
+ get_dataset_access_filters,
+ guest_embedded_dashboard_filter,
+)
def test_get_dataset_access_filters(mocker: MockerFixture) -> None:
@@ -52,3 +58,114 @@ def test_get_dataset_access_filters(mocker: MockerFixture) -> None:
"OR tables.catalog_perm IN ('[db].[catalog2]') OR "
"tables.schema_perm IN ('[db].[catalog1].[schema2]')"
)
+
+
+def _guest_with_dashboards(*ids: object) -> SimpleNamespace:
+ """A guest user whose token grants the given dashboard resources."""
+ return SimpleNamespace(resources=[{"type": "dashboard", "id": i} for i in ids])
+
+
+def test_guest_embedded_dashboard_filter_disabled_returns_none(
+ mocker: MockerFixture,
+) -> None:
+ """No filter when the EMBEDDED_SUPERSET feature flag is off."""
+ mocker.patch("superset.is_feature_enabled", return_value=False)
+ assert guest_embedded_dashboard_filter() is None
+
+
+def test_guest_embedded_dashboard_filter_non_guest_returns_none(
+ mocker: MockerFixture,
+) -> None:
+ """No filter when the current user is not an embedded guest."""
+ mocker.patch("superset.is_feature_enabled", return_value=True)
+ mocker.patch.object(
+ security_manager, "get_current_guest_user_if_guest", return_value=None
+ )
+ assert guest_embedded_dashboard_filter() is None
+
+
+def test_guest_embedded_dashboard_filter_no_dashboard_resources(
+ mocker: MockerFixture,
+) -> None:
+ """A guest with no dashboard resources is denied all charts (fail closed),
+ not left to fall back to the role-based access path (which None would do)."""
+ from sqlalchemy.sql.elements import False_
+
+ mocker.patch("superset.is_feature_enabled", return_value=True)
+ guest = SimpleNamespace(resources=[{"type": "dataset", "id": 1}])
+ mocker.patch.object(
+ security_manager, "get_current_guest_user_if_guest", return_value=guest
+ )
+ clause = guest_embedded_dashboard_filter()
+ assert clause is not None
+ assert isinstance(clause, False_)
+
+
+def test_guest_embedded_dashboard_filter_uuid_resources(
+ mocker: MockerFixture,
+) -> None:
+ """UUID resources scope via the embedded-dashboard relationship."""
+ mocker.patch("superset.is_feature_enabled", return_value=True)
+ uuid = "51e44e1c-ffd1-425d-8993-919177955270"
+ mocker.patch.object(
+ security_manager,
+ "get_current_guest_user_if_guest",
+ return_value=_guest_with_dashboards(uuid),
+ )
+
+ # Compiled without literal_binds: the uuid column is BINARY(16), so assert on
+ # structure (an EXISTS against embedded_dashboards.uuid) rather than the value.
+ clause = guest_embedded_dashboard_filter()
+ assert clause is not None
+ compiled = str(clause.compile(create_engine("sqlite://")))
+ assert "EXISTS" in compiled
+ assert "embedded_dashboards" in compiled
+ assert "uuid" in compiled
+
+
+def test_guest_embedded_dashboard_filter_int_resources(
+ mocker: MockerFixture,
+) -> None:
+ """Integer resources scope by dashboard id AND require the dashboard to be
+ embedded (a guest is never scoped to a plain non-embedded internal id)."""
+ mocker.patch("superset.is_feature_enabled", return_value=True)
+ mocker.patch.object(
+ security_manager,
+ "get_current_guest_user_if_guest",
+ return_value=_guest_with_dashboards(5, 7),
+ )
+
+ clause = guest_embedded_dashboard_filter()
+ assert clause is not None
+ compiled = str(
+ clause.compile(
+ create_engine("sqlite://"), compile_kwargs={"literal_binds": True}
+ )
+ )
+ assert "dashboards.id IN (5, 7)" in compiled
+ # The int-id branch also requires an embedded config (mirrors the uuid branch
+ # and has_guest_access), so a non-embedded dashboard id cannot match.
+ assert "embedded_dashboards" in compiled
+
+
+def test_guest_embedded_dashboard_filter_mixed_uuid_and_int_ids(
+ mocker: MockerFixture,
+) -> None:
+ """A token mixing uuid and int ids ORs a uuid-column and an id-column filter
+ (routing a plain int through the uuid-typed column would raise a bind error)."""
+ mocker.patch("superset.is_feature_enabled", return_value=True)
+ uuid = "51e44e1c-ffd1-425d-8993-919177955270"
+ mocker.patch.object(
+ security_manager,
+ "get_current_guest_user_if_guest",
+ return_value=_guest_with_dashboards(uuid, 7),
+ )
+
+ clause = guest_embedded_dashboard_filter()
+ assert clause is not None
+ # uuid column is BINARY(16), so compile without literal_binds and assert
+ # structure: an EXISTS on embedded_dashboards OR a dashboards.id filter.
+ compiled = str(clause.compile(create_engine("sqlite://")))
+ assert "embedded_dashboards" in compiled
+ assert "dashboards.id IN" in compiled
+ assert " OR " in compiled