bito-code-review[bot] commented on code in PR #36933:
URL: https://github.com/apache/superset/pull/36933#discussion_r2891600171


##########
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:
   <!-- Bito Reply -->
   The fix in commit a8b866e changes the exception handling in 
`validate_guest_token_resources` to use `from None`, suppressing the exception 
chain to avoid leaking internal error details in tracebacks. This improves 
security by not exposing underlying errors.
   
   **superset/security/manager.py**
   ```
   except (ExplorePermalinkGetFailedError, ValueError) as ex:
                       raise EmbeddedChartPermalinkNotFoundError() from ex
   ```
   
   **superset/security/manager.py**
   ```
   except (ValueError, KeyError, AttributeError):
                       raise EmbeddedChartPermalinkNotFoundError() from None
   ```



##########
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:
   <!-- Bito Reply -->
   Yes, the pull request does not include any changes to 
docs/docs/configuration/databases.mdx, so any issues in that documentation file 
are pre-existing and not introduced by this PR.



##########
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:
   <!-- Bito Reply -->
   You're right—the code in view.py now uses `if permalink_value is None: 
abort(500)` instead of an assert statement for better production error 
handling. The `login_user(AnonymousUserMixin(), force=True)` is indeed a 
Flask-Login API call to log in an anonymous user for page rendering, not an 
assertion.



##########
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:
   <!-- Bito Reply -->
   The PR adds the embeddedChart entry as 
`addPreamble('src/embeddedChart/index.tsx')` without a leading slash, 
consistent with the other entries (menu, spa, embedded) in the webpack config.



##########
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:
   <!-- Bito Reply -->
   This change adds a `.finally()` block to ensure the `ready` state is set to 
`true` after the initial fetch, regardless of success or failure. Combined with 
setting `ready` to `false` at the start of the effect, it displays the loading 
spinner during the API call.
   
   **superset-frontend/src/dashboard/components/EmbeddedChartModal/index.tsx**
   ```
   .then(({ result }) => {
           setReady(true);
           setEmbedded(result);
           setAllowedDomains(result ? result.allowed_domains.join(', ') : '');
         })
         .finally(() => setReady(true));
   ```



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