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


##########
docs/docs/configuration/databases.mdx:
##########
@@ -1137,6 +1194,28 @@ More information about PostgreSQL connection options can 
be found in the
 and the
 [PostgreSQL 
docs](https://www.postgresql.org/docs/9.1/libpq-connect.html#LIBPQ-PQCONNECTDBPARAMS).
 
+:::resources
+- [Blog: Data Visualization in PostgreSQL With Apache 
Superset](https://www.tigerdata.com/blog/data-visualization-in-postgresql-with-apache-superset)
+:::
+
+#### QuestDB
+
+[QuestDB](https://questdb.io/) is a high-performance, open-source time-series 
database with SQL support.
+The recommended connector library is the PostgreSQL driver 
[psycopg2](https://www.psycopg.org/docs/),
+as QuestDB supports the PostgreSQL wire protocol.
+
+The connection string is formatted as follows:
+
+```
+postgresql+psycopg2://{username}:{password}@{hostname}:{port}/{database}
+```
+
+The default port for QuestDB's PostgreSQL interface is `8812`.
+
+:::resources
+- [QuestDB Docs: Apache Superset 
Integration](https://questdb.com/docs/third-party-tools/superset/)

Review Comment:
   Correct — the docs file wasn't changed in this PR. Any issues there are 
pre-existing.



##########
superset/embedded_chart/view.py:
##########
@@ -0,0 +1,116 @@
+# 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 Any, Callable, cast
+
+from flask import abort, current_app, request
+from flask_appbuilder import expose
+from flask_login import AnonymousUserMixin, login_user
+from flask_wtf.csrf import same_origin
+
+from superset import event_logger, is_feature_enabled
+from superset.commands.explore.permalink.get import GetExplorePermalinkCommand
+from superset.superset_typing import FlaskResponse
+from superset.utils import json
+from superset.views.base import BaseSupersetView, common_bootstrap_payload
+
+logger = logging.getLogger(__name__)
+
+
+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.
+        """
+        if not is_feature_enabled("EMBEDDABLE_CHARTS_MCP"):
+            abort(404)
+
+        # 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)
+
+        # Fetch permalink to get allowed_domains for referrer validation
+        try:
+            permalink_value = GetExplorePermalinkCommand(permalink_key).run()
+        except Exception:
+            logger.exception("Error fetching permalink for embedded chart")
+            permalink_value = None
+
+        if not permalink_value:
+            logger.warning("Permalink not found for embedded chart: %s", 
permalink_key)
+            abort(404)
+
+        assert permalink_value is not None  # for mypy

Review Comment:
   Thanks for confirming the approach. Using abort(500) instead of assert is 
more appropriate for production error handling.



##########
superset-frontend/webpack.config.js:
##########
@@ -300,6 +300,7 @@ const config = {
     menu: addPreamble('src/views/menu.tsx'),
     spa: addPreamble('/src/views/index.tsx'),
     embedded: addPreamble('/src/embedded/index.tsx'),
+    embeddedChart: addPreamble('/src/embeddedChart/index.tsx'),
   },

Review Comment:
   Thanks for verifying consistency with the other webpack entries.



##########
superset-frontend/src/dashboard/components/EmbeddedChartModal/index.tsx:
##########
@@ -0,0 +1,289 @@
+/**
+ * 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, useState } from 'react';
+import { logging, makeApi, SupersetApiError, t } from '@superset-ui/core';
+import { styled, css, Alert } from '@apache-superset/core/ui';
+import {
+  Button,
+  FormItem,
+  InfoTooltip,
+  Input,
+  Modal,
+  Loading,
+  Form,
+  Space,
+} from '@superset-ui/core/components';
+import { useToasts } from 'src/components/MessageToasts/withToasts';
+import { Typography } from '@superset-ui/core/components/Typography';
+import { ModalTitleWithIcon } from 'src/components/ModalTitleWithIcon';
+
+type Props = {
+  chartId: number;
+  formData: Record<string, unknown>;
+  show: boolean;
+  onHide: () => void;
+};
+
+type EmbeddedChart = {
+  uuid: string;
+  allowed_domains: string[];
+  chart_id: number;
+  changed_on: string;
+};
+
+type EmbeddedApiPayload = { allowed_domains: string[] };
+
+const stringToList = (stringyList: string): string[] =>
+  stringyList.split(/(?:\s|,)+/).filter(x => x);
+
+const ButtonRow = styled.div`
+  display: flex;
+  flex-direction: row;
+  justify-content: flex-end;
+`;
+
+export const ChartEmbedControls = ({ chartId, onHide }: Props) => {
+  const { addInfoToast, addDangerToast } = useToasts();
+  const [ready, setReady] = useState(true);
+  const [loading, setLoading] = useState(false);
+  const [embedded, setEmbedded] = useState<EmbeddedChart | null>(null);
+  const [allowedDomains, setAllowedDomains] = useState<string>('');
+  const [showDeactivateConfirm, setShowDeactivateConfirm] = useState(false);
+
+  const endpoint = `/api/v1/chart/${chartId}/embedded`;
+  const isDirty =
+    !embedded ||
+    stringToList(allowedDomains).join() !== embedded.allowed_domains.join();
+
+  const enableEmbedded = useCallback(() => {
+    setLoading(true);
+    makeApi<EmbeddedApiPayload, { result: EmbeddedChart }>({
+      method: 'POST',
+      endpoint,
+    })({
+      allowed_domains: stringToList(allowedDomains),
+    })
+      .then(
+        ({ result }) => {
+          setEmbedded(result);
+          setAllowedDomains(result.allowed_domains.join(', '));
+          addInfoToast(t('Changes saved.'));
+        },
+        err => {
+          logging.error(err);
+          addDangerToast(
+            t('Sorry, something went wrong. The changes could not be saved.'),
+          );
+        },
+      )
+      .finally(() => {
+        setLoading(false);
+      });
+  }, [endpoint, allowedDomains, addInfoToast, addDangerToast]);
+
+  const disableEmbedded = useCallback(() => {
+    setShowDeactivateConfirm(true);
+  }, []);
+
+  const confirmDeactivate = useCallback(() => {
+    setLoading(true);
+    makeApi<object>({ method: 'DELETE', endpoint })({})
+      .then(
+        () => {
+          setEmbedded(null);
+          setAllowedDomains('');
+          setShowDeactivateConfirm(false);
+          addInfoToast(t('Embedding deactivated.'));
+          onHide();
+        },
+        err => {
+          logging.error(err);
+          addDangerToast(
+            t(
+              'Sorry, something went wrong. Embedding could not be 
deactivated.',
+            ),
+          );
+        },
+      )
+      .finally(() => {
+        setLoading(false);
+      });
+  }, [endpoint, addInfoToast, addDangerToast, onHide]);
+
+  useEffect(() => {
+    setReady(false);
+    makeApi<object, { result: EmbeddedChart }>({
+      method: 'GET',
+      endpoint,
+    })({})
+      .catch(err => {
+        if ((err as SupersetApiError).status === 404) {
+          return { result: null };
+        }
+        addDangerToast(t('Sorry, something went wrong. Please try again.'));
+        throw err;
+      })
+      .then(({ result }) => {
+        setReady(true);
+        setEmbedded(result);
+        setAllowedDomains(result ? result.allowed_domains.join(', ') : '');
+      });

Review Comment:
   Exactly — the .finally() ensures the spinner is dismissed regardless of 
success or failure. Glad the pattern reads well.



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

Review Comment:
   Thanks for the thorough analysis. You've captured the security model well — 
referrer validation is defense-in-depth while the guest token provides the 
primary security boundary.



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