aminghadersohi commented on code in PR #36933: URL: https://github.com/apache/superset/pull/36933#discussion_r2891912825
########## superset-frontend/src/pages/EmbeddedChartsList/index.tsx: ########## @@ -0,0 +1,249 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +import { useCallback, useEffect, useMemo, useState } from 'react'; +import { Link } from 'react-router-dom'; +import { SupersetClient } from '@superset-ui/core'; +import { styled, css, t } from '@apache-superset/core/ui'; +import { DeleteModal, Tooltip } from '@superset-ui/core/components'; +import { Icons } from '@superset-ui/core/components/Icons'; +import withToasts from 'src/components/MessageToasts/withToasts'; +import { ListView } from 'src/components'; +import SubMenu, { SubMenuProps } from 'src/features/home/SubMenu'; + +const PAGE_SIZE = 25; + +interface EmbeddedChart { + uuid: string; + chart_id: number; + chart_name: string | null; + allowed_domains: string[]; + changed_on: string | null; +} + +interface EmbeddedChartsListProps { + addDangerToast: (msg: string) => void; + addSuccessToast: (msg: string) => void; +} + +const ActionsWrapper = styled.div` + display: flex; + gap: 8px; +`; + +const ActionButton = styled.button` + ${({ theme }) => css` + background: none; + border: none; + cursor: pointer; + padding: 4px; + color: ${theme.colorTextSecondary}; + &:hover { + color: ${theme.colorPrimary}; + } + `} +`; + +function EmbeddedChartsList({ + addDangerToast, + addSuccessToast, +}: EmbeddedChartsListProps) { + const [embeddedCharts, setEmbeddedCharts] = useState<EmbeddedChart[]>([]); + const [loading, setLoading] = useState(true); + const [chartToDelete, setChartToDelete] = useState<EmbeddedChart | null>( + null, + ); + + const fetchEmbeddedCharts = useCallback(async () => { + setLoading(true); + try { + const response = await SupersetClient.get({ + endpoint: '/api/v1/chart/embedded', + }); + setEmbeddedCharts(response.json.result || []); + } catch (error) { + addDangerToast(t('Error loading embedded charts')); + } finally { + setLoading(false); + } + }, [addDangerToast]); + + useEffect(() => { + fetchEmbeddedCharts(); + }, [fetchEmbeddedCharts]); + + const handleDelete = useCallback( + async (chart: EmbeddedChart) => { + try { + await SupersetClient.delete({ + endpoint: `/api/v1/chart/${chart.chart_id}/embedded`, + }); + addSuccessToast(t('Embedding disabled for %s', chart.chart_name)); + fetchEmbeddedCharts(); + } catch (error) { + addDangerToast(t('Error disabling embedding for %s', chart.chart_name)); + } finally { + setChartToDelete(null); + } + }, + [addDangerToast, addSuccessToast, fetchEmbeddedCharts], + ); + + const copyToClipboard = useCallback( + (text: string) => { + navigator.clipboard.writeText(text).then( + () => addSuccessToast(t('UUID copied to clipboard')), + () => addDangerToast(t('Failed to copy to clipboard')), + ); + }, + [addDangerToast, addSuccessToast], + ); Review Comment: Fixed in ee13c3f. Added `navigator.clipboard?.writeText` guard with fallback error toast for non-secure contexts. ########## superset/commands/chart/delete.py: ########## @@ -68,3 +69,23 @@ def validate(self) -> None: security_manager.raise_for_ownership(model) except SupersetSecurityException as ex: raise ChartForbiddenError() from ex + + +class DeleteEmbeddedChartCommand(BaseCommand): + def __init__(self, chart: Slice): + self._chart = chart + + @transaction(on_error=partial(on_error, reraise=ChartDeleteEmbeddedFailedError)) + def run(self) -> None: + self.validate() + return EmbeddedChartDAO.delete(self._chart.embedded) Review Comment: No change needed. `chart.embedded` is a SQLAlchemy relationship which returns a list (defined as `embedded = relationship("EmbeddedChart", ...)` in `models/slice.py:123`). `BaseDAO.delete()` expects `list[T]` and `chart.embedded` already is a list, so no wrapping is needed. ########## superset/embedded_chart/view.py: ########## @@ -0,0 +1,136 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +import logging +from typing import Callable +from urllib.parse import urlparse + +from flask import abort, current_app, request +from flask_appbuilder import expose +from flask_login import AnonymousUserMixin, login_user + +from superset import event_logger +from superset.daos.key_value import KeyValueDAO +from superset.explore.permalink.schemas import ExplorePermalinkSchema +from superset.key_value.shared_entries import get_permalink_salt +from superset.key_value.types import ( + KeyValueResource, + MarshmallowKeyValueCodec, + SharedKey, +) +from superset.key_value.utils import decode_permalink_id +from superset.superset_typing import FlaskResponse +from superset.utils import json +from superset.views.base import BaseSupersetView, common_bootstrap_payload + +logger = logging.getLogger(__name__) + + +def same_origin(url1: str | None, url2: str | None) -> bool: + """Check if two URLs have the same origin (scheme + netloc).""" + if not url1 or not url2: + return False + parsed1 = urlparse(url1) + parsed2 = urlparse(url2) + # For domain matching, we just check if the host matches + # url2 might just be a domain like "example.com" + if not parsed2.scheme: + # url2 is just a domain, check if it matches url1's netloc + return parsed1.netloc == url2 or parsed1.netloc.endswith(f".{url2}") + return (parsed1.scheme, parsed1.netloc) == (parsed2.scheme, parsed2.netloc) + + +class EmbeddedChartView(BaseSupersetView): + """Server-side rendering for embedded chart pages.""" + + route_base = "/embedded/chart" + + @expose("/") + @event_logger.log_this_with_extra_payload + def embedded_chart( + self, + add_extra_log_payload: Callable[..., None] = lambda **kwargs: None, + ) -> FlaskResponse: + """ + Server side rendering for the embedded chart page. + Expects ?permalink_key=xxx query parameter. + """ + # Get permalink_key from query params + permalink_key = request.args.get("permalink_key") + if not permalink_key: + logger.warning("Missing permalink_key in embedded chart request") + abort(404) + + # Get permalink value to check allowed domains + try: + salt = get_permalink_salt(SharedKey.EXPLORE_PERMALINK_SALT) + codec = MarshmallowKeyValueCodec(ExplorePermalinkSchema()) + key = decode_permalink_id(permalink_key, salt=salt) + permalink_value = KeyValueDAO.get_value( + KeyValueResource.EXPLORE_PERMALINK, + key, + codec, + ) + except (ValueError, KeyError) as ex: + logger.warning("Error fetching permalink for referrer validation: %s", ex) + permalink_value = None + + # Validate request referrer against allowed domains (if configured) + if permalink_value: + state = permalink_value.get("state", {}) + allowed_domains = state.get("allowedDomains", []) + + if allowed_domains: + is_referrer_allowed = False + for domain in allowed_domains: + if same_origin(request.referrer, domain): + is_referrer_allowed = True + break + + if not is_referrer_allowed: + logger.warning( + "Embedded chart referrer not in allowed domains: %s", + request.referrer, + ) + abort(403) + + # Log in as anonymous user for page rendering + # This view needs to be visible to all users, + # and building the page fails if g.user and/or ctx.user aren't present. + login_user(AnonymousUserMixin(), force=True) + Review Comment: Fixed in ee13c3f. Added `if not current_user.is_authenticated:` guard before calling `login_user(AnonymousUserMixin(), force=True)`. This prevents overwriting an existing authenticated session when a logged-in user visits the embedded chart URL directly. ########## superset/security/manager.py: ########## @@ -3049,6 +3071,28 @@ def has_guest_access(self, dashboard: "Dashboard") -> bool: return True return False + def has_guest_chart_permalink_access(self, datasource: Any) -> bool: + """ + Check if a guest user has access to a datasource via a chart permalink resource. + + For embedded charts, the guest token contains chart_permalink resources. + This grants datasource access when the user holds at least one + chart_permalink resource. The embedded chart page constrains the actual + query to the datasource specified in the permalink's formData. + + TODO: For stricter security, resolve each permalink and compare the + datasource in its formData against the requested datasource. This would + prevent a guest user from crafting requests to other datasources. + """ + user = self.get_current_guest_user_if_guest() + if not user or not isinstance(user, GuestUser): + return False + + return any( + r.get("type") == GuestTokenResourceType.CHART_PERMALINK + for r in user.resources + ) + Review Comment: Fixed in ee13c3f. Changed to use `.value` for the comparison: `r.get("type") == GuestTokenResourceType.CHART_PERMALINK.value`. While both work with StrEnum (string equality), using `.value` is more explicit and consistent with the pattern in `api.py:72` and `security/manager.py:2938`. ########## tests/unit_tests/mcp_service/embedded_chart/tool/test_get_embeddable_chart.py: ########## @@ -0,0 +1,550 @@ +# 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. + +""" +Unit tests for MCP get_embeddable_chart tool +""" + +from datetime import datetime, timezone +from unittest.mock import MagicMock, patch + +import pytest + +from superset.mcp_service.chart.schemas import ( + ColumnRef, + FilterConfig, + TableChartConfig, + XYChartConfig, +) +from superset.mcp_service.embedded_chart.schemas import ( + GetEmbeddableChartRequest, + GetEmbeddableChartResponse, +) +from superset.mcp_service.embedded_chart.tool.get_embeddable_chart import ( + _ensure_guest_role_permissions, +) + + +class TestGetEmbeddableChartSchemas: + """Tests for get_embeddable_chart schemas.""" + + def test_request_with_xy_config(self): + """Test request with XY chart config (same as generate_chart).""" + config = XYChartConfig( + chart_type="xy", + x=ColumnRef(name="genre"), + y=[ColumnRef(name="sales", aggregate="SUM")], + kind="bar", + ) + request = GetEmbeddableChartRequest( + datasource_id=22, + config=config, + ) + assert request.datasource_id == 22 + assert request.config.chart_type == "xy" + assert request.config.x.name == "genre" + assert request.config.y[0].aggregate == "SUM" + assert request.config.kind == "bar" + assert request.ttl_minutes == 60 # default + assert request.height == 400 # default + + def test_request_with_table_config(self): + """Test request with table chart config.""" + config = TableChartConfig( + chart_type="table", + columns=[ + ColumnRef(name="genre"), + ColumnRef(name="sales", aggregate="SUM", label="Total Sales"), + ], + ) + request = GetEmbeddableChartRequest( + datasource_id="dataset-uuid-here", + config=config, + ttl_minutes=120, + height=600, + ) + assert request.datasource_id == "dataset-uuid-here" + assert request.config.chart_type == "table" + assert len(request.config.columns) == 2 + assert request.ttl_minutes == 120 + assert request.height == 600 + + def test_request_with_rls_rules(self): + """Test request with row-level security rules.""" + config = XYChartConfig( + chart_type="xy", + x=ColumnRef(name="date"), + y=[ColumnRef(name="count", aggregate="COUNT")], + kind="line", + ) + request = GetEmbeddableChartRequest( + datasource_id=123, + config=config, + rls_rules=[ + {"dataset": 123, "clause": "tenant_id = 42"}, + {"dataset": 123, "clause": "region = 'US'"}, + ], + ) + assert len(request.rls_rules) == 2 + assert request.rls_rules[0]["clause"] == "tenant_id = 42" + + def test_request_with_allowed_domains(self): + """Test request with allowed_domains for iframe security.""" + config = TableChartConfig( + chart_type="table", + columns=[ColumnRef(name="col1")], + ) + request = GetEmbeddableChartRequest( + datasource_id=1, + config=config, + allowed_domains=["https://example.com", "https://app.example.com"], + ) + assert request.allowed_domains == [ + "https://example.com", + "https://app.example.com", + ] + + def test_request_ttl_validation(self): + """Test TTL minutes validation bounds.""" + config = TableChartConfig( + chart_type="table", + columns=[ColumnRef(name="col1")], + ) + # Valid min TTL + request = GetEmbeddableChartRequest( + datasource_id=1, + config=config, + ttl_minutes=1, + ) + assert request.ttl_minutes == 1 + + # Valid max TTL (1 week) + request = GetEmbeddableChartRequest( + datasource_id=1, + config=config, + ttl_minutes=10080, + ) + assert request.ttl_minutes == 10080 + + # Invalid TTL should raise + with pytest.raises(ValueError, match="greater than or equal to 1"): + GetEmbeddableChartRequest( + datasource_id=1, + config=config, + ttl_minutes=0, # below min + ) + + with pytest.raises(ValueError, match="less than or equal to 10080"): + GetEmbeddableChartRequest( + datasource_id=1, + config=config, + ttl_minutes=10081, # above max Review Comment: No change needed. Pydantic v2's `ValidationError` is a subclass of `ValueError` (`issubclass(ValidationError, ValueError)` returns `True`), so `pytest.raises(ValueError)` correctly catches Pydantic validation errors. This is by design in Pydantic v2 for backwards compatibility. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
