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


##########
superset/models/embedded_chart.py:
##########
@@ -0,0 +1,58 @@
+# 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 uuid
+
+from flask_appbuilder import Model
+from sqlalchemy import Column, ForeignKey, Integer, Text
+from sqlalchemy.orm import relationship
+from sqlalchemy_utils import UUIDType
+
+from superset.models.helpers import AuditMixinNullable
+
+
+class EmbeddedChart(Model, AuditMixinNullable):
+    """
+    A configuration of embedding for a chart.
+
+    References the chart (slice), and contains a config for embedding that 
chart.
+
+    This data model allows multiple configurations for a given chart,
+    but at this time the API only allows setting one.
+    """
+
+    __tablename__ = "embedded_charts"
+
+    uuid = Column(UUIDType(binary=True), default=uuid.uuid4, primary_key=True)
+    allow_domain_list = Column(Text)  # reference the `allowed_domains` 
property instead
+    chart_id = Column(
+        Integer,
+        ForeignKey("slices.id", ondelete="CASCADE"),
+        nullable=False,
+    )
+    chart = relationship(
+        "Slice",
+        back_populates="embedded",
+        foreign_keys=[chart_id],
+    )
+
+    @property
+    def allowed_domains(self) -> list[str]:
+        """
+        A list of domains which are allowed to embed the chart.
+        An empty list means any domain can embed.
+        """
+        return self.allow_domain_list.split(",") if self.allow_domain_list 
else []

Review Comment:
   Thanks for confirming the domain parsing fix.



##########
superset/embedded_chart/exceptions.py:
##########
@@ -0,0 +1,35 @@
+# 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.
+from superset.exceptions import SupersetException
+
+
+class EmbeddedChartPermalinkNotFoundError(SupersetException):
+    """Raised when an embedded chart permalink is not found or has expired."""
+
+    message = "The embedded chart permalink could not be found or has expired."

Review Comment:
   Thanks for verifying the i18n support and HTTP status code mappings.



##########
superset/views/embedded_charts.py:
##########
@@ -0,0 +1,34 @@
+# 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.
+from flask_appbuilder import expose, has_access
+
+from superset.constants import MODEL_VIEW_RW_METHOD_PERMISSION_MAP
+from superset.superset_typing import FlaskResponse
+from superset.views.base import BaseSupersetView
+
+
+class EmbeddedChartsView(BaseSupersetView):
+    """View for managing embedded charts list."""
+
+    route_base = "/embeddedcharts"
+    class_permission_name = "Chart"
+    method_permission_name = MODEL_VIEW_RW_METHOD_PERMISSION_MAP
+
+    @expose("/list/")
+    @has_access
+    def list(self) -> FlaskResponse:
+        return super().render_app_template()

Review Comment:
   Great clarification — you're right that EmbeddedChartsView (the admin list) 
and EmbeddedChartView (the iframe page) serve different purposes and use 
different entry points. Thanks for the thorough analysis.



##########
superset-frontend/src/explore/components/EmbedCodeContent.tsx:
##########
@@ -57,43 +61,73 @@ const EmbedCodeContent: FC<EmbedCodeContentProps> = ({
     }
   }, []);
 
-  const updateUrl = useCallback(() => {
-    setUrl('');
-    if (!formData?.datasource) return;
-    getChartPermalink(formData as { datasource: string })
-      .then(result => {
-        if (result?.url) {
-          setUrl(result.url);
-          setErrorMessage('');
-        }
-      })
-      .catch(() => {
-        setErrorMessage(t('Error'));
-        addDangerToast?.(t('Sorry, something went wrong. Try again later.'));
+  const generateEmbedCode = useCallback(async () => {
+    if (!formData) return;
+
+    setLoading(true);
+    setErrorMessage('');
+
+    try {
+      const createEmbeddedChart = makeApi<
+        {
+          form_data: LatestQueryFormData;
+          allowed_domains: string[];
+          ttl_minutes: number;
+        },
+        EmbedData
+      >({
+        method: 'POST',
+        endpoint: '/api/v1/embedded_chart/',
       });
-  }, [addDangerToast, formData]);
+
+      const response = await createEmbeddedChart({
+        form_data: formData,
+        allowed_domains: [],
+        ttl_minutes: 60,
+      });
+
+      setEmbedData(response);
+    } catch {
+      setErrorMessage(t('Error generating embed code'));
+      addDangerToast?.(t('Sorry, something went wrong. Try again later.'));
+    } finally {
+      setLoading(false);
+    }
+  }, [formData, addDangerToast]);
 
   useEffect(() => {
-    updateUrl();
-  }, []);
+    generateEmbedCode();
+  }, [generateEmbedCode]);
 
   const html = useMemo(() => {
-    if (!url) return '';
-    const srcLink = `${url}?${URL_PARAMS.standalone.name}=1&height=${height}`;
-    return (
-      '<iframe\n' +
-      `  width="${width}"\n` +
-      `  height="${height}"\n` +
-      '  seamless\n' +
-      '  frameBorder="0"\n' +
-      '  scrolling="no"\n' +
-      `  src="${srcLink}"\n` +
-      '>\n' +
-      '</iframe>'
+    if (!embedData?.iframe_url || !embedData?.guest_token) return '';
+
+    const { origin } = new URL(embedData.iframe_url);
+
+    return `<!-- Superset Embedded Chart -->
+<iframe
+  id="superset-chart"
+  src="${embedData.iframe_url}"
+  width="${width}"
+  height="${height}"
+  frameborder="0"
+  data-guest-token="${embedData.guest_token}"
+  sandbox="allow-scripts allow-same-origin allow-popups"
+></iframe>
+<script>
+  document.getElementById('superset-chart').onload = function() {
+    this.contentWindow.postMessage(
+      { type: '__embedded_comms__', guestToken: '${embedData.guest_token}' },
+      '${origin}'
     );
-  }, [height, url, width]);
+  };
+</script>`;

Review Comment:
   Good point about the hard-coded iframe id causing issues when embedding 
multiple charts on the same page. Using a unique id per chart (e.g., based on 
the permalink key) would be the right fix. I'll update the embed code 
generation to use unique identifiers. Thanks for the catch.



##########
superset/embedded_chart/view.py:
##########
@@ -0,0 +1,137 @@
+# 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, current_user, 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

Review Comment:
   Good observation. You're right that decode_permalink_id could raise 
exceptions beyond ValueError or KeyError for malformed input. I'll broaden the 
exception handling in that specific code path to catch any decoding failures 
gracefully instead of letting them bubble up as 500 errors. Thanks for the 
review.



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