codeant-ai-for-open-source[bot] commented on code in PR #41606: URL: https://github.com/apache/superset/pull/41606#discussion_r3555309291
########## superset/mcp_service/dashboard/tool/manage_dashboard_roles.py: ########## @@ -0,0 +1,238 @@ +# 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. + +""" +Manage dashboard access roles FastMCP tool + +Adds/removes DASHBOARD_RBAC access roles via explicit operations. Companion +to ``manage_dashboard_owners`` — dashboard roles are dropped from the +generic ``update_dashboard`` tool because a full-replacement access-control +list silently widens or narrows who can see a dashboard. +""" + +import logging +from typing import Any + +from fastmcp import Context +from sqlalchemy.exc import SQLAlchemyError +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset.commands.dashboard.exceptions import DashboardNotFoundError +from superset.commands.exceptions import RolesNotFoundValidationError +from superset.exceptions import SupersetSecurityException +from superset.extensions import db, event_logger +from superset.mcp_service.dashboard.schemas import ( + ManageDashboardRolesRequest, + ManageDashboardRolesResponse, + serialize_role_object, +) +from superset.mcp_service.utils.url_utils import get_superset_base_url + +logger = logging.getLogger(__name__) + + +def _find_and_authorize_dashboard( + identifier: int | str, +) -> tuple[Any, ManageDashboardRolesResponse | None]: + """Return (dashboard, None) on success or (None, error_response) on failure. + + Mirrors the helper in ``update_dashboard``: avoids ImportError before + Flask app initialisation by co-locating the imports it needs with the + call site rather than importing them at module load time. + """ + from superset import security_manager + from superset.daos.dashboard import DashboardDAO + + try: + dashboard = DashboardDAO.get_by_id_or_slug(identifier) + except (DashboardNotFoundError, SQLAlchemyError): + return None, ManageDashboardRolesResponse( + error=f"Dashboard not found: {identifier!r}", + ) + + if dashboard is None: + return None, ManageDashboardRolesResponse( + error=f"Dashboard not found: {identifier!r}", + ) + + try: + security_manager.raise_for_ownership(dashboard) + except SupersetSecurityException: + return None, ManageDashboardRolesResponse( + permission_denied=True, + error=( + f"You don't have permission to edit dashboard " + f"'{dashboard.dashboard_title}' (ID: {dashboard.id})." + ), + ) + + return dashboard, None + + +def _dashboard_url(dashboard: Any) -> str: + """Build the user-facing dashboard URL, preferring slug over id.""" + return ( + f"{get_superset_base_url()}/superset/dashboard/" + f"{dashboard.slug or dashboard.id}/" + ) + + +@tool( + tags=["mutate"], + class_permission_name="Dashboard", + method_permission_name="write", + annotations=ToolAnnotations( + title="Manage dashboard access roles", + readOnlyHint=False, + destructiveHint=True, + ), +) +def manage_dashboard_roles( + request: ManageDashboardRolesRequest, ctx: Context +) -> ManageDashboardRolesResponse: + """ + Add or remove dashboard RBAC access roles with explicit operations. + + Dashboard roles (DASHBOARD_RBAC) restrict who can view a dashboard to + members of the listed roles, on top of normal Superset permissions. An + empty roles list means "no role restriction" — the dashboard is visible + per standard permissions instead. This only takes effect when the + ``DASHBOARD_RBAC`` feature flag is enabled; the response's + ``dashboard_rbac_enabled`` field reports whether it is, and ``warnings`` + notes when a change was applied but has no live effect. + + Unlike ``update_dashboard``'s dropped ``roles`` field, this tool never + accepts a full-replacement list — only + ``add_role_ids``/``remove_role_ids``. + + Privacy: the returned ``roles`` list is sanctioned only as confirmation + of the add/remove operation the caller explicitly requested on this + dashboard. Do not use it to answer "who can access X" for a dashboard + the caller did not ask to modify, and do not call this tool merely to + look up current roles — those remain off-limits per the server + instructions. + + Example:: + + manage_dashboard_roles(request={ + "identifier": 42, + "add_role_ids": [5], + }) + """ + from superset import is_feature_enabled + + ctx.info( + f"Managing dashboard roles: identifier={request.identifier} " + f"add={request.add_role_ids} remove={request.remove_role_ids}" + ) + + dashboard, auth_error = _find_and_authorize_dashboard(request.identifier) + if auth_error is not None: + return auth_error + + dashboard_rbac_enabled = is_feature_enabled("DASHBOARD_RBAC") + warnings: list[str] = [] + if not dashboard_rbac_enabled: + warnings.append( + "The DASHBOARD_RBAC feature flag is disabled on this instance; " + "dashboard roles will be stored but have no effect on access " + "control until it is enabled." + ) + + current_role_ids = [role.id for role in dashboard.roles] Review Comment: **Suggestion:** Loading `dashboard.roles` happens before the SQLAlchemy error-handling block, so a lazy-load/database failure here will bubble up as an unhandled exception instead of returning the tool’s structured database error response. Move this read inside the guarded try/except path and return a `ManageDashboardRolesResponse` error on failure. [possible bug] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx ❌ manage_dashboard_roles MCP tool can crash on database errors. ⚠️ Caller misses structured error message describing database failure. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Start the Superset MCP service where manage_dashboard_roles is listed as an available tool in superset/mcp_service/app.py:127-140 under "Dashboard Management". 2. Configure the environment so that loading the dashboard.roles relationship will raise a SQLAlchemyError (for example, by pointing Superset’s SQLAlchemy engine at an unreachable database or otherwise inducing a database-layer failure for role queries). 3. Call manage_dashboard_roles with any valid ManageDashboardRolesRequest (identifier, add_role_ids and/or remove_role_ids as defined in superset/mcp_service/dashboard/schemas.py:23-35) so execution reaches current_role_ids = [role.id for role in dashboard.roles] at superset/mcp_service/dashboard/tool/manage_dashboard_roles.py:156. 4. When dashboard.roles is evaluated, a SQLAlchemyError is raised during lazy-loading of the relationship before the guarded try/except SQLAlchemyError block at lines 178-218; because the exception occurs outside that block, it propagates as an unhandled error, crashing the MCP tool call instead of returning a structured ManageDashboardRolesResponse with dashboard_rbac_enabled and error="Failed to update dashboard roles due to a database error.". ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=c9fd223c6b3f4e0b91b214b23421d605&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) [](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=c9fd223c6b3f4e0b91b214b23421d605&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/manage_dashboard_roles.py **Line:** 156:156 **Comment:** *Possible Bug: Loading `dashboard.roles` happens before the SQLAlchemy error-handling block, so a lazy-load/database failure here will bubble up as an unhandled exception instead of returning the tool’s structured database error response. Move this read inside the guarded try/except path and return a `ManageDashboardRolesResponse` error on failure. 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%2F41606&comment_hash=4d49fc8cb0affa74cda87ef1db6e0966e9536e3aa147e8d9d705cd675e3a6ab5&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41606&comment_hash=4d49fc8cb0affa74cda87ef1db6e0966e9536e3aa147e8d9d705cd675e3a6ab5&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]
