codeant-ai-for-open-source[bot] commented on code in PR #41472:
URL: https://github.com/apache/superset/pull/41472#discussion_r3556085737


##########
superset/mcp_service/dashboard/tool/delete_dashboard.py:
##########
@@ -0,0 +1,235 @@
+# 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.
+
+"""
+MCP tool: delete_dashboard
+"""
+
+import logging
+from typing import TYPE_CHECKING
+
+from fastmcp import Context
+from sqlalchemy.exc import SQLAlchemyError
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset import is_feature_enabled
+from superset.commands.dashboard.exceptions import (
+    DashboardAccessDeniedError,
+    DashboardDeleteFailedReportsExistError,
+    DashboardForbiddenError,
+    DashboardNotFoundError,
+)
+from superset.commands.exceptions import CommandException
+from superset.extensions import event_logger
+from superset.mcp_service.dashboard.schemas import (
+    DeleteDashboardRequest,
+    DeleteDashboardResponse,
+)
+from superset.mcp_service.utils import (
+    escape_llm_context_delimiters,
+    sanitize_for_llm_context,
+)
+
+if TYPE_CHECKING:
+    from superset.models.dashboard import Dashboard
+
+logger = logging.getLogger(__name__)
+
+
+def _find_dashboard_by_identifier(identifier: int | str) -> "Dashboard | None":
+    """Resolve a dashboard by numeric ID, UUID string, or slug. Returns 
None."""
+    from superset.daos.dashboard import DashboardDAO
+
+    if isinstance(identifier, int) or (
+        isinstance(identifier, str) and identifier.isdigit()
+    ):
+        return DashboardDAO.find_by_id(int(identifier))
+    # Try UUID, then fall back to slug.
+    dashboard = DashboardDAO.find_by_id(identifier, id_column="uuid")
+    if dashboard:
+        return dashboard
+    try:
+        return DashboardDAO.get_by_id_or_slug(identifier)
+    except DashboardNotFoundError:
+        return None
+
+
+def _rollback() -> None:
+    """Best-effort session rollback so a failed delete cannot poison the
+    request's transaction; rollback failures are logged, not raised."""
+    from superset import db
+
+    try:
+        db.session.rollback()  # pylint: disable=consider-using-transaction
+    except SQLAlchemyError:
+        logger.warning(
+            "Database rollback failed during delete_dashboard error handling"
+        )
+
+
+def _routes_to_soft_delete() -> bool:
+    """Mirror the ``BaseDAO.delete`` routing predicate so the response can
+    report whether the row was trashed (restorable) or permanently removed."""
+    from superset.models.dashboard import Dashboard
+    from superset.models.helpers import SoftDeleteMixin
+
+    return issubclass(Dashboard, SoftDeleteMixin) and 
is_feature_enabled("SOFT_DELETE")
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="Dashboard",
+    annotations=ToolAnnotations(
+        title="Delete dashboard",
+        readOnlyHint=False,
+        destructiveHint=True,
+    ),
+)
+async def delete_dashboard(
+    request: DeleteDashboardRequest, ctx: Context
+) -> DeleteDashboardResponse:
+    """Delete a dashboard.
+
+    Identify the dashboard by numeric ID, UUID string, or slug. When the
+    ``SOFT_DELETE`` feature flag is enabled the dashboard is moved to trash and
+    can be restored by an owner or Admin; otherwise the delete is permanent and
+    cannot be undone. The ``soft_deleted`` response field reports which
+    happened. It removes the dashboard container only — the charts on it are
+    NOT deleted. The caller must be an editor of the dashboard (owners and
+    Admins qualify); dashboards with attached alerts/reports cannot be
+    deleted until those are removed.
+
+    Example:
+    ```json
+    {"identifier": 42}
+    ```
+
+    Returns success with the deleted dashboard's id/title, or an error. When 
the
+    caller lacks permission, ``permission_denied`` is true — do not retry; ask
+    the user.
+    """
+    await ctx.info("Deleting dashboard: identifier=%s" % (request.identifier,))
+
+    try:
+        dashboard = _find_dashboard_by_identifier(request.identifier)
+    except DashboardAccessDeniedError:
+        # get_by_id_or_slug re-checks view access and raises access-denied for
+        # dashboards the caller cannot see; surface it as the structured
+        # permission_denied response instead of an unhandled error.
+        await ctx.warning("Access denied resolving dashboard identifier for 
delete")
+        return DeleteDashboardResponse(
+            success=False,
+            permission_denied=True,
+            error=(
+                "You do not have permission to access this dashboard. "
+                "Ask the user to delete it or grant access; do not retry."
+            ),
+            error_type="Forbidden",
+        )
+    except SQLAlchemyError:
+        _rollback()
+        logger.exception("Dashboard lookup failed during delete_dashboard")
+        return DeleteDashboardResponse(
+            success=False,
+            error="Dashboard lookup failed due to a database error.",
+            error_type="LookupFailed",
+        )
+    if not dashboard:
+        safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+        msg = (
+            f"No dashboard found with identifier: {safe_id}. "
+            "Use list_dashboards to get valid dashboard IDs."
+        )
+        return DeleteDashboardResponse(success=False, error=msg, 
error_type="NotFound")
+
+    dashboard_id = dashboard.id
+    # Dashboard titles are user-controlled; wrap before composing responses.
+    dashboard_name = sanitize_for_llm_context(
+        dashboard.dashboard_title, field_path=("dashboard_title",)
+    )
+
+    # The try/except sits inside log_context so failed attempts (forbidden,
+    # reports-exist, db errors) are recorded in the audit log too — the
+    # context manager does not log when an exception propagates through it.
+    with event_logger.log_context(action="mcp.delete_dashboard"):
+        try:
+            from superset.commands.dashboard.delete import 
DeleteDashboardCommand
+
+            DeleteDashboardCommand([dashboard_id]).run()
+
+            soft_deleted = _routes_to_soft_delete()
+            if soft_deleted:
+                message = (
+                    f"Moved dashboard '{dashboard_name}' (id={dashboard_id}) 
to "
+                    "trash; it can be restored by an owner or Admin. Its 
charts "
+                    "were not deleted."
+                )
+            else:
+                message = (
+                    f"Permanently deleted dashboard '{dashboard_name}' "
+                    f"(id={dashboard_id}). Its charts were not deleted."
+                )
+            return DeleteDashboardResponse(
+                success=True,
+                deleted_id=dashboard_id,
+                deleted_name=dashboard_name,
+                soft_deleted=soft_deleted,
+                message=message,
+            )
+        except DashboardForbiddenError:
+            await ctx.warning(
+                "Permission denied deleting dashboard id=%s" % (dashboard_id,)
+            )
+            return DeleteDashboardResponse(
+                success=False,
+                permission_denied=True,
+                error=(
+                    f"You do not have permission to delete dashboard "
+                    f"'{dashboard_name}' (id={dashboard_id}). Ask the user to "
+                    "delete it or grant access; do not retry."
+                ),
+                error_type="Forbidden",
+            )
+        except DashboardDeleteFailedReportsExistError as ex:
+            _rollback()
+            return DeleteDashboardResponse(
+                success=False,
+                error=(
+                    f"Dashboard '{dashboard_name}' (id={dashboard_id}) cannot 
be "
+                    f"deleted: {ex}. Remove the associated alerts/reports 
first."
+                ),
+                error_type="ReportsExist",
+            )
+        except DashboardNotFoundError:
+            msg = f"Dashboard id={dashboard_id} no longer exists."
+            return DeleteDashboardResponse(
+                success=False, error=msg, error_type="NotFound"
+            )
+        except (CommandException, SQLAlchemyError, ValueError) as ex:
+            _rollback()
+            await ctx.error("Dashboard delete failed: %s: %s" % 
(type(ex).__name__, ex))
+            # Raw SQLAlchemy text can leak SQL or connection details; command
+            # and validation messages are user-facing by design.
+            if isinstance(ex, SQLAlchemyError):
+                client_error = "Dashboard delete failed due to a database 
error."
+            else:
+                client_error = f"Dashboard delete failed: {ex}"

Review Comment:
   **Suggestion:** The fallback error path returns `f"Dashboard delete failed: 
{ex}"` directly, which can surface unsanitized, user-influenced command 
messages to the model. This creates an injection surface in error responses; 
sanitize or wrap the exception text before returning it. [security]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ LLM receives unsanitized dashboard-delete error messages.
   - ⚠️ Potential prompt-injection via command/validation error text.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Start the MCP server (superset/mcp_service/app.py:926), ensuring the 
delete_dashboard
   tool from superset/mcp_service/dashboard/tool/delete_dashboard.py is loaded 
and advertised
   in get_default_instructions (app.py:127-139).
   
   2. Trigger a dashboard delete failure where DeleteDashboardCommand or the 
surrounding
   logic raises a CommandException or ValueError with a message that may include
   user-influenced data (delete_dashboard catches these at lines 222-223).
   
   3. In superset/mcp_service/dashboard/tool/delete_dashboard.py:227-230, the 
generic
   exception handler sets client_error = f"Dashboard delete failed: {ex}" for 
non-SQLAlchemy
   errors, directly interpolating the exception string into 
DeleteDashboardResponse.error
   without passing it through sanitize_for_llm_context.
   
   4. DeleteDashboardResponse in superset/mcp_service/dashboard/schemas.py:7-23 
defines error
   as a plain str with no validator, so this unsanitized error string is 
emitted in MCP tool
   responses and fed into the LLM context, allowing any user-influenced command 
or validation
   message content carried by ex to flow through the error channel unwrapped.
   ```
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=5847de1aad654406a09c7ed7726e73fc&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=5847de1aad654406a09c7ed7726e73fc&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/dashboard/tool/delete_dashboard.py
   **Line:** 227:230
   **Comment:**
        *Security: The fallback error path returns `f"Dashboard delete failed: 
{ex}"` directly, which can surface unsanitized, user-influenced command 
messages to the model. This creates an injection surface in error responses; 
sanitize or wrap the exception text before returning it.
   
   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.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41472&comment_hash=1132bc38ca6f131a322bde2b76cac5c4cfd4f2ed93362392ffe74d7c01835649&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41472&comment_hash=1132bc38ca6f131a322bde2b76cac5c4cfd4f2ed93362392ffe74d7c01835649&reaction=dislike'>👎</a>



##########
superset/mcp_service/chart/tool/delete_chart.py:
##########
@@ -0,0 +1,186 @@
+# 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.
+
+"""
+MCP tool: delete_chart
+"""
+
+import logging
+
+from fastmcp import Context
+from sqlalchemy.exc import SQLAlchemyError
+from superset_core.mcp.decorators import tool, ToolAnnotations
+
+from superset import is_feature_enabled
+from superset.commands.chart.exceptions import (
+    ChartDeleteFailedReportsExistError,
+    ChartForbiddenError,
+    ChartNotFoundError,
+)
+from superset.commands.exceptions import CommandException
+from superset.extensions import event_logger
+from superset.mcp_service.chart.chart_helpers import find_chart_by_identifier
+from superset.mcp_service.chart.schemas import (
+    DeleteChartRequest,
+    DeleteChartResponse,
+)
+from superset.mcp_service.utils import (
+    escape_llm_context_delimiters,
+    sanitize_for_llm_context,
+)
+
+logger = logging.getLogger(__name__)
+
+
+def _rollback() -> None:
+    """Best-effort session rollback so a failed delete cannot poison the
+    request's transaction; rollback failures are logged, not raised."""
+    from superset import db
+
+    try:
+        db.session.rollback()  # pylint: disable=consider-using-transaction
+    except SQLAlchemyError:
+        logger.warning("Database rollback failed during delete_chart error 
handling")
+
+
+def _routes_to_soft_delete() -> bool:
+    """Mirror the ``BaseDAO.delete`` routing predicate so the response can
+    report whether the row was trashed (restorable) or permanently removed."""
+    from superset.models.helpers import SoftDeleteMixin
+    from superset.models.slice import Slice
+
+    return issubclass(Slice, SoftDeleteMixin) and 
is_feature_enabled("SOFT_DELETE")
+
+
+@tool(
+    tags=["mutate"],
+    class_permission_name="Chart",
+    annotations=ToolAnnotations(
+        title="Delete chart",
+        readOnlyHint=False,
+        destructiveHint=True,
+    ),
+)
+async def delete_chart(
+    request: DeleteChartRequest, ctx: Context
+) -> DeleteChartResponse:
+    """Delete a saved chart.
+
+    Identify the chart by numeric ID or UUID string (NOT chart name). When the
+    ``SOFT_DELETE`` feature flag is enabled the chart is moved to trash and can
+    be restored by an owner or Admin; otherwise the delete is permanent and
+    cannot be undone. The ``soft_deleted`` response field reports which
+    happened. The caller must be an editor of the chart (owners and Admins
+    qualify); charts with attached alerts/reports cannot be deleted until
+    those are removed.
+
+    Example:
+    ```json
+    {"identifier": 123}
+    ```
+
+    Returns success with the deleted chart's id/name, or an error. When the
+    caller lacks permission, ``permission_denied`` is true — do not retry; ask
+    the user.
+    """
+    await ctx.info("Deleting chart: identifier=%s" % (request.identifier,))
+
+    try:
+        chart = find_chart_by_identifier(request.identifier)
+    except SQLAlchemyError:
+        _rollback()
+        logger.exception("Chart lookup failed during delete_chart")
+        return DeleteChartResponse(
+            success=False,
+            error="Chart lookup failed due to a database error.",
+            error_type="LookupFailed",
+        )
+    if not chart:
+        safe_id = escape_llm_context_delimiters(str(request.identifier)[:200])
+        msg = (
+            f"No chart found with identifier: {safe_id}. "
+            "Use list_charts to get valid chart IDs."
+        )
+        return DeleteChartResponse(success=False, error=msg, 
error_type="NotFound")
+
+    chart_id = chart.id
+    # Chart names are user-controlled; wrap before composing response text.
+    chart_name = sanitize_for_llm_context(chart.slice_name, 
field_path=("slice_name",))
+
+    # The try/except sits inside log_context so failed attempts (forbidden,
+    # reports-exist, db errors) are recorded in the audit log too — the
+    # context manager does not log when an exception propagates through it.
+    with event_logger.log_context(action="mcp.delete_chart"):
+        try:
+            from superset.commands.chart.delete import DeleteChartCommand
+
+            DeleteChartCommand([chart_id]).run()
+
+            soft_deleted = _routes_to_soft_delete()
+            if soft_deleted:
+                message = (
+                    f"Moved chart '{chart_name}' (id={chart_id}) to trash. "
+                    "It can be restored by an owner or Admin."
+                )
+            else:
+                message = f"Permanently deleted chart '{chart_name}' 
(id={chart_id})."
+            return DeleteChartResponse(
+                success=True,
+                deleted_id=chart_id,
+                deleted_name=chart_name,
+                soft_deleted=soft_deleted,
+                message=message,
+            )
+        except ChartForbiddenError:
+            await ctx.warning("Permission denied deleting chart id=%s" % 
(chart_id,))
+            return DeleteChartResponse(
+                success=False,
+                permission_denied=True,
+                error=(
+                    f"You do not have permission to delete chart 
'{chart_name}' "
+                    f"(id={chart_id}). Ask the user to delete it or grant "
+                    "access; do not retry."
+                ),
+                error_type="Forbidden",
+            )
+        except ChartDeleteFailedReportsExistError as ex:
+            _rollback()
+            return DeleteChartResponse(
+                success=False,
+                error=(
+                    f"Chart '{chart_name}' (id={chart_id}) cannot be deleted: "
+                    f"{ex}. Remove the associated alerts/reports first."
+                ),
+                error_type="ReportsExist",
+            )
+        except ChartNotFoundError:
+            msg = f"Chart id={chart_id} no longer exists."
+            return DeleteChartResponse(success=False, error=msg, 
error_type="NotFound")
+        except (CommandException, SQLAlchemyError, ValueError) as ex:
+            _rollback()
+            await ctx.error("Chart delete failed: %s: %s" % 
(type(ex).__name__, ex))
+            # Raw SQLAlchemy text can leak SQL or connection details; command
+            # and validation messages are user-facing by design.
+            if isinstance(ex, SQLAlchemyError):
+                client_error = "Chart delete failed due to a database error."
+            else:
+                client_error = f"Chart delete failed: {ex}"

Review Comment:
   **Suggestion:** The generic exception handler returns `f"Chart delete 
failed: {ex}"` without sanitizing exception text, which can leak 
attacker-controlled command message content into the model context. Sanitize or 
delimit exception strings before including them in `error` responses. [security]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ⚠️ LLM receives unsanitized chart-delete error messages.
   - ⚠️ Potential prompt-injection via command/validation messages.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Start the MCP server (superset/mcp_service/app.py:926) so the 
delete_chart tool is
   available, as listed in get_default_instructions at 
superset/mcp_service/app.py:175-185.
   
   2. Trigger a chart delete failure where DeleteChartCommand or the 
surrounding logic raises
   a CommandException or ValueError carrying a message derived from user input 
(delete_chart
   catches these at superset/mcp_service/chart/tool/delete_chart.py:173-174).
   
   3. In superset/mcp_service/chart/tool/delete_chart.py:178-181, the generic 
exception
   handler sets client_error = f"Chart delete failed: {ex}" for non-SQLAlchemy 
errors,
   directly interpolating the exception string into the 
DeleteChartResponse.error field
   without using sanitize_for_llm_context.
   
   4. DeleteChartResponse in superset/mcp_service/chart/schemas.py:11-27 
defines error as a
   plain str with no field_validator, so this unsanitized error string is 
serialized into MCP
   tool output and passed to the LLM context, allowing any user-influenced 
exception message
   content to flow through the error channel unwrapped.
   ```
   </details>
   
   [![Fix in 
Cursor](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-cursor-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=139a4fb6b30440b88c55e37c596b4d7b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
 [![Fix in VSCode 
Claude](https://new-codeant-butcket.s3.us-west-1.amazonaws.com/badges/fix-in-vscode-claude-flat.svg)](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=139a4fb6b30440b88c55e37c596b4d7b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/mcp_service/chart/tool/delete_chart.py
   **Line:** 178:181
   **Comment:**
        *Security: The generic exception handler returns `f"Chart delete 
failed: {ex}"` without sanitizing exception text, which can leak 
attacker-controlled command message content into the model context. Sanitize or 
delimit exception strings before including them in `error` responses.
   
   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.
   Once fix is implemented, also check other comments on the same PR, and ask 
user if the user wants to fix the rest of the comments as well. if said yes, 
then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41472&comment_hash=bc8e6c02069eda5484b2f8d3023c07eb4ea4af0fbdb3abbb99d99e049edbcc3f&reaction=like'>👍</a>
 | <a 
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41472&comment_hash=bc8e6c02069eda5484b2f8d3023c07eb4ea4af0fbdb3abbb99d99e049edbcc3f&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]

Reply via email to