aminghadersohi commented on code in PR #36933:
URL: https://github.com/apache/superset/pull/36933#discussion_r2894972810


##########
superset/security/manager.py:
##########
@@ -2810,6 +2821,17 @@ def validate_guest_token_resources(resources: 
GuestTokenResources) -> None:
                     embedded = 
EmbeddedDashboardDAO.find_by_id(str(resource["id"]))
                     if not embedded:
                         raise EmbeddedDashboardNotFoundError()
+            elif resource["type"] == 
GuestTokenResourceType.CHART_PERMALINK.value:
+                # Validate that the chart permalink exists
+                permalink_key = str(resource["id"])
+                try:
+                    permalink_value = 
GetExplorePermalinkCommand(permalink_key).run()
+                    if not permalink_value:
+                        raise EmbeddedChartPermalinkNotFoundError()
+                except EmbeddedChartPermalinkNotFoundError:
+                    raise
+                except (ExplorePermalinkGetFailedError, ValueError) as ex:
+                    raise EmbeddedChartPermalinkNotFoundError() from ex

Review Comment:
   Good point about ChartAccessDeniedError potentially bubbling up through 
GetExplorePermalinkCommand.run(). I'll review the call chain and add it to the 
catch list if it can reach this point. Thanks for the thorough analysis.



##########
embed-demo.html:
##########
@@ -0,0 +1,126 @@
+<!DOCTYPE html>
+<html>
+<head>
+  <title>Superset Embedded Chart Demo</title>
+  <style>
+    body {
+      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 
sans-serif;
+      max-width: 1200px;
+      margin: 0 auto;
+      padding: 40px;
+      background: #f5f5f5;
+    }
+    h1 { color: #333; }
+    .input-section {
+      background: white;
+      border-radius: 8px;
+      padding: 20px;
+      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
+      margin-bottom: 20px;
+    }
+    textarea {
+      width: 100%;
+      height: 150px;
+      font-family: monospace;
+      font-size: 12px;
+      padding: 10px;
+      border: 1px solid #ddd;
+      border-radius: 4px;
+      resize: vertical;
+      box-sizing: border-box;
+    }
+    button {
+      background: #20a7c9;
+      color: white;
+      border: none;
+      padding: 12px 24px;
+      font-size: 16px;
+      border-radius: 4px;
+      cursor: pointer;
+      margin-top: 10px;
+    }
+    button:hover {
+      background: #1a8fa8;
+    }
+    .chart-container {
+      background: white;
+      border-radius: 8px;
+      padding: 20px;
+      box-shadow: 0 2px 8px rgba(0,0,0,0.1);
+      min-height: 450px;
+    }
+    label {
+      font-weight: 600;
+      display: block;
+      margin-bottom: 8px;
+    }
+  </style>
+</head>
+<body>
+  <h1>Superset Embedded Chart Demo</h1>
+
+  <div class="input-section">
+    <label for="iframe-input">Paste iframe_html response here:</label>
+    <textarea id="iframe-input" placeholder="Paste the iframe_html value from 
get_embeddable_chart response..."></textarea>
+    <button onclick="embedChart()">Embed Chart</button>
+  </div>
+
+  <div class="chart-container" id="chart-container">
+    <p style="color: #999; text-align: center; margin-top: 200px;">Chart will 
appear here</p>
+  </div>
+
+  <script>
+    function embedChart() {
+      const input = document.getElementById('iframe-input').value.trim();
+      const container = document.getElementById('chart-container');
+
+      if (!input) {
+        alert('Please paste the iframe_html first');
+        return;
+      }
+
+      // Safely parse input and only allow iframe elements (prevent XSS)
+      const parser = new DOMParser();
+      const doc = parser.parseFromString(input, 'text/html');

Review Comment:
   Thanks for the alert. The embed-demo.html is a developer-facing demo page 
for local testing only — it's not served in production or bundled into the 
application. That said, sanitizing the postMessage data in the demo would be 
good hygiene and I'll add that.



##########
tests/unit_tests/mcp_service/embedded_chart/tool/test_get_embeddable_chart.py:
##########
@@ -0,0 +1,548 @@
+# 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 len(request.allowed_domains) == 2
+        assert "https://example.com"; in request.allowed_domains
+
+    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:
   Exactly right — thanks for verifying the fix.



##########
superset/commands/chart/delete.py:
##########
@@ -68,3 +69,16 @@ 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)
+
+    def validate(self) -> None:
+        pass

Review Comment:
   Great security observation. The embedded chart delete currently relies on 
chart-level ownership checks (the chart owner controls embedded configs), but 
adding an explicit ownership verification in the validate method would be more 
robust defense-in-depth. I'll look into adding that. Thanks for catching this.



##########
superset/security/manager.py:
##########
@@ -2834,6 +2838,17 @@ def validate_guest_token_resources(resources: 
GuestTokenResources) -> None:
                     embedded = 
EmbeddedDashboardDAO.find_by_id(str(resource["id"]))
                     if not embedded:
                         raise EmbeddedDashboardNotFoundError()
+            elif resource["type"] == 
GuestTokenResourceType.CHART_PERMALINK.value:
+                # Validate that the chart permalink exists
+                permalink_key = str(resource["id"])
+                try:
+                    permalink_value = 
GetExplorePermalinkCommand(permalink_key).run()
+                    if not permalink_value:
+                        raise EmbeddedChartPermalinkNotFoundError()
+                except EmbeddedChartPermalinkNotFoundError:
+                    raise
+                except Exception:
+                    raise EmbeddedChartPermalinkNotFoundError()

Review Comment:
   Thanks for confirming. The 'from None' suppression is intentional to avoid 
leaking internal details in tracebacks.



-- 
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]

Reply via email to