codeant-ai-for-open-source[bot] commented on code in PR #36933:
URL: https://github.com/apache/superset/pull/36933#discussion_r2894550959
##########
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:
**Suggestion:** The embed HTML hard-codes the iframe id as `superset-chart`
and uses `document.getElementById` to attach the onload handler, so if a page
embeds more than one chart, all iframes will share the same id and only the
first iframe will receive the guest token message, causing other embedded
charts on the same page to fail to authenticate and render correctly. [logic
error]
<details>
<summary><b>Severity Level:</b> Critical 🚨</summary>
```mdx
- ❌ Multiple embedded charts on same page fail authentication.
- ⚠️ Only one chart per page reliably supports guest tokens.
```
</details>
```suggestion
return `<!-- Superset Embedded Chart -->
<iframe
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>
(function() {
var script = document.currentScript;
var iframe = script && script.previousElementSibling;
if (!iframe || iframe.tagName !== 'IFRAME') {
return;
}
iframe.onload = function() {
this.contentWindow.postMessage(
{ type: '__embedded_comms__', guestToken:
'${embedData.guest_token}' },
'${origin}'
);
};
})();
</script>`;
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. In the Superset UI, open a chart's Share → Embed flow which renders
`EmbedCodeContent`
in `superset-frontend/src/explore/components/EmbedCodeContent.tsx:41-211`
and generates
the HTML string in the `useMemo` block at lines 102-124.
2. Copy the generated embed HTML for Chart A (includes `<iframe
id="superset-chart">` and
the inline `<script>` calling `document.getElementById('superset-chart')`).
3. Repeat for Chart B, then place both embed snippets sequentially into the
same external
HTML page so the DOM contains two `<iframe id="superset-chart">` elements
(duplicate IDs)
and two identical inline scripts.
4. Load that HTML page in a browser: each script executes
`document.getElementById('superset-chart')` (line 114) which always returns
the first
iframe in DOM order, so only the first iframe receives the `postMessage`
with a guest
token; the second chart never gets its token and fails to
authenticate/render.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset-frontend/src/explore/components/EmbedCodeContent.tsx
**Line:** 107:124
**Comment:**
*Logic Error: The embed HTML hard-codes the iframe id as
`superset-chart` and uses `document.getElementById` to attach the onload
handler, so if a page embeds more than one chart, all iframes will share the
same id and only the first iframe will receive the guest token message, causing
other embedded charts on the same page to fail to authenticate and render
correctly.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36933&comment_hash=6b0404bd5fbc9233b1bf14dd0fe95c2b4bad605120e9bd217d2ad08f19199a22&reaction=like'>👍</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36933&comment_hash=6b0404bd5fbc9233b1bf14dd0fe95c2b4bad605120e9bd217d2ad08f19199a22&reaction=dislike'>👎</a>
##########
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:
**Suggestion:** In the embedded chart view, a malformed `permalink_key`
query parameter can cause `decode_permalink_id` or the codec to raise an
exception that is not a `ValueError` or `KeyError`, leading to an unhandled
exception and a 500 error during referrer validation; broadening the exception
handler to catch all exceptions ensures such bad keys are handled gracefully
and simply skip referrer-based checks as intended. [logic error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
- ❌ Embedded chart iframe requests return 500 for bad keys.
- ⚠️ Error handling inconsistent with missing permalink_key behavior.
- ⚠️ Logs lack clear differentiation of invalid share links.
```
</details>
```suggestion
# 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 Exception as ex: # pylint: disable=broad-except
logger.warning("Error fetching permalink for referrer
validation: %s", ex)
permalink_value = None
```
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. Run the Superset web server including `EmbeddedChartView` defined in
`superset/embedded_chart/view.py` (route_base `/embedded/chart`, method
`embedded_chart`
at approx. lines 61–88).
2. Send an HTTP GET request to `/embedded/chart/?permalink_key=abc` where
`abc` is a
malformed key that cannot be decoded by `hashids` (e.g., `curl
http://localhost:8088/embedded/chart/?permalink_key=abc`).
3. The request enters `EmbeddedChartView.embedded_chart`
(`superset/embedded_chart/view.py:61`), reaches the block starting at line
77, and calls
`decode_permalink_id(permalink_key, salt=salt)` from
`superset/key_value/utils.py:63`.
4. In `decode_permalink_id`, `hashids.Hashids.decode("abc")` returns an
empty list,
causing `KeyValueParseKeyError(_("Invalid permalink key"))` to be raised at
`superset/key_value/utils.py:67`; this exception is *not* a `ValueError` or
`KeyError`, so
it bypasses the current `except (ValueError, KeyError)` in
`EmbeddedChartView.embedded_chart` and propagates to Flask, resulting in an
uncaught
exception and an HTTP 500 response instead of gracefully skipping referrer
validation and
rendering or rejecting the request.
```
</details>
<details>
<summary><b>Prompt for AI Agent 🤖 </b></summary>
```mdx
This is a comment left during a code review.
**Path:** superset/embedded_chart/view.py
**Line:** 77:89
**Comment:**
*Logic Error: In the embedded chart view, a malformed `permalink_key`
query parameter can cause `decode_permalink_id` or the codec to raise an
exception that is not a `ValueError` or `KeyError`, leading to an unhandled
exception and a 500 error during referrer validation; broadening the exception
handler to catch all exceptions ensures such bad keys are handled gracefully
and simply skip referrer-based checks as intended.
Validate the correctness of the flagged issue. If correct, How can I resolve
this? If you propose a fix, implement it and please make it concise.
```
</details>
<a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36933&comment_hash=069b454cd9f4f3a365e31128ff51dd0fde2c1c4deeec059ebda0bd0683f32e56&reaction=like'>👍</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F36933&comment_hash=069b454cd9f4f3a365e31128ff51dd0fde2c1c4deeec059ebda0bd0683f32e56&reaction=dislike'>👎</a>
--
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]