codeant-ai-for-open-source[bot] commented on code in PR #41606: URL: https://github.com/apache/superset/pull/41606#discussion_r3556167622
########## superset/mcp_service/dashboard/tool/manage_dashboard_owners.py: ########## @@ -0,0 +1,378 @@ +# 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 owners FastMCP tool + +Adds/removes dashboard owners via explicit operations, guarding against the +"empty owners" footgun that the generic ``update_dashboard`` tool +deliberately does not expose (a full-replacement ``owners``/``editors`` list +has no "keep >=1 owner" guard of its own — ``populate_subject_list``'s +``ensure_no_lockout`` only re-adds the CALLER, it does not prevent an admin +from emptying the list outright). + +"Owners" are modeled as USER-type entries in the dashboard's Subject-based +``editors`` list (apache/superset#38831 replaced the legacy ``owners`` +relationship with a unified Subject model covering User/Role/Group). Any +ROLE- or GROUP-type editors already on the dashboard are preserved +untouched by this tool. +""" + +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.exceptions import SupersetSecurityException +from superset.extensions import db, event_logger +from superset.mcp_service.dashboard.schemas import ( + ManageDashboardOwnersRequest, + ManageDashboardOwnersResponse, +) +from superset.mcp_service.system.schemas import serialize_subject_object +from superset.mcp_service.utils.url_utils import get_superset_base_url +from superset.subjects.exceptions import SubjectsNotFoundValidationError +from superset.subjects.types import SubjectType + +logger = logging.getLogger(__name__) + + +def _find_and_authorize_dashboard( + identifier: int | str, +) -> tuple[Any, ManageDashboardOwnersResponse | 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, ManageDashboardOwnersResponse( + error=f"Dashboard not found: {identifier!r}", + ) + + if dashboard is None: + return None, ManageDashboardOwnersResponse( + error=f"Dashboard not found: {identifier!r}", + ) + + try: + security_manager.raise_for_editorship(dashboard) + except SupersetSecurityException: + return None, ManageDashboardOwnersResponse( + 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}/" + ) Review Comment: **Suggestion:** The dashboard URL builder uses a hardcoded `/superset/dashboard/` prefix instead of matching the rest of the MCP dashboard tools. This can return malformed links in proxied/path-prefixed installs when the configured base URL already contains `/superset`. [api mismatch] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ Owners management tool returns malformed dashboard URLs. - ⚠️ Downstream MCP clients navigate to incorrect dashboard pages. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Set WEBDRIVER_BASEURL_USER_FRIENDLY to "https://example.com/superset" so get_superset_base_url() returns a value that already includes the application path (superset/mcp_service/utils/url_utils.py:42-55). 2. Start the MCP service so manage_dashboard_owners is available (superset/mcp_service/dashboard/tool/manage_dashboard_owners.py:248-260) and ensure there is a dashboard the caller can edit (checked by _find_and_authorize_dashboard at lines 57-92). 3. Call manage_dashboard_owners with any valid ManageDashboardOwnersRequest; after applying owner changes, the tool builds the response dashboard_url via _dashboard_url() at superset/mcp_service/dashboard/tool/manage_dashboard_owners.py:95-100, formatting f"{get_superset_base_url()}/superset/dashboard/{dashboard.slug or dashboard.id}/". 4. Compare this URL to those produced by other dashboard tools like update_dashboard._build_dashboard_url() (superset/mcp_service/dashboard/tool/update_dashboard.py:48-50) and dashboard serializers (superset/mcp_service/dashboard/schemas.py:74-80), and observe that manage_dashboard_owners returns URLs of the form "https://example.com/superset/superset/dashboard/..." instead of "https://example.com/superset/dashboard/...", confirming a double-prefix bug. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=03605171bffd434eb6a32497fb6c3d12&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=03605171bffd434eb6a32497fb6c3d12&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_owners.py **Line:** 97:100 **Comment:** *Api Mismatch: The dashboard URL builder uses a hardcoded `/superset/dashboard/` prefix instead of matching the rest of the MCP dashboard tools. This can return malformed links in proxied/path-prefixed installs when the configured base URL already contains `/superset`. 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=52d1c7e55302ca0a0bc23c055111d14a75e29ec34430e461f312519540c3fa02&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41606&comment_hash=52d1c7e55302ca0a0bc23c055111d14a75e29ec34430e461f312519540c3fa02&reaction=dislike'>👎</a> ########## superset/mcp_service/dashboard/tool/manage_dashboard_roles.py: ########## @@ -0,0 +1,299 @@ +# 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 role-based dashboard access via explicit operations. Companion +to ``manage_dashboard_owners`` — dashboard access 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. + +"Roles" are modeled as ROLE-type entries in the dashboard's Subject-based +``viewers`` list (apache/superset#38831 replaced the legacy +``roles``/``DASHBOARD_RBAC`` relationship with a unified Subject model +covering User/Role/Group, gated by the ``ENABLE_VIEWERS`` feature flag +instead of ``DASHBOARD_RBAC``). Any USER- or GROUP-type viewers already on +the dashboard are preserved untouched by this tool. +""" + +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.exceptions import SupersetSecurityException +from superset.extensions import db, event_logger +from superset.mcp_service.dashboard.schemas import ( + ManageDashboardRolesRequest, + ManageDashboardRolesResponse, +) +from superset.mcp_service.system.schemas import serialize_subject_object +from superset.mcp_service.utils.url_utils import get_superset_base_url +from superset.subjects.types import SubjectType + +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_editorship(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}/" + ) Review Comment: **Suggestion:** The URL helper hardcodes `/superset/dashboard/`, which can double-prefix the path and return unusable links in common reverse-proxy setups. Use the same `/dashboard/{slug_or_id}/` pattern used by sibling dashboard tools. [api mismatch] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ Roles management tool returns double-prefixed dashboard URLs. - ⚠️ LLM workflows using links break in path-prefixed installs. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Configure WEBDRIVER_BASEURL_USER_FRIENDLY with a path-prefixed value such as "https://example.com/superset"; get_superset_base_url() then returns this base URL (superset/mcp_service/utils/url_utils.py:42-55). 2. Start Superset’s MCP service and ensure manage_dashboard_roles is registered (superset/mcp_service/dashboard/tool/manage_dashboard_roles.py:163-175). 3. Invoke manage_dashboard_roles with a valid ManageDashboardRolesRequest; after authorization in _find_and_authorize_dashboard() (lines 55-90), the tool constructs dashboard_url using _dashboard_url() at lines 93-98, which formats f"{get_superset_base_url()}/superset/dashboard/{dashboard.slug or dashboard.id}/". 4. Inspect the response and see dashboard_url like "https://example.com/superset/superset/dashboard/{slug_or_id}/", while other MCP dashboard helpers (e.g. update_dashboard._build_dashboard_url at superset/mcp_service/dashboard/tool/update_dashboard.py:48-50 and serialize_dashboard_object at superset/mcp_service/dashboard/schemas.py:71-81) consistently build "https://example.com/superset/dashboard/{slug_or_id}/", demonstrating a double-prefixed path. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=82effc584773486aa1d17e69075592d8&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=82effc584773486aa1d17e69075592d8&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:** 95:98 **Comment:** *Api Mismatch: The URL helper hardcodes `/superset/dashboard/`, which can double-prefix the path and return unusable links in common reverse-proxy setups. Use the same `/dashboard/{slug_or_id}/` pattern used by sibling dashboard tools. 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=2c1e12c7257268741205ec8f1de887635917ebff05178ffa2b11c9cd8bc51d8e&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41606&comment_hash=2c1e12c7257268741205ec8f1de887635917ebff05178ffa2b11c9cd8bc51d8e&reaction=dislike'>👎</a> ########## superset/mcp_service/dashboard/tool/manage_dashboard_roles.py: ########## @@ -0,0 +1,299 @@ +# 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 role-based dashboard access via explicit operations. Companion +to ``manage_dashboard_owners`` — dashboard access 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. + +"Roles" are modeled as ROLE-type entries in the dashboard's Subject-based +``viewers`` list (apache/superset#38831 replaced the legacy +``roles``/``DASHBOARD_RBAC`` relationship with a unified Subject model +covering User/Role/Group, gated by the ``ENABLE_VIEWERS`` feature flag +instead of ``DASHBOARD_RBAC``). Any USER- or GROUP-type viewers already on +the dashboard are preserved untouched by this tool. +""" + +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.exceptions import SupersetSecurityException +from superset.extensions import db, event_logger +from superset.mcp_service.dashboard.schemas import ( + ManageDashboardRolesRequest, + ManageDashboardRolesResponse, +) +from superset.mcp_service.system.schemas import serialize_subject_object +from superset.mcp_service.utils.url_utils import get_superset_base_url +from superset.subjects.types import SubjectType + +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_editorship(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}/" + ) + + +def _viewer_role_ids(dashboard: Any) -> list[int]: + """Role IDs behind the dashboard's ROLE-type viewer subjects.""" + return [ + subject.role_id + for subject in dashboard.viewers + if subject.type == SubjectType.ROLE + ] + + +def _other_viewers(dashboard: Any) -> list[Any]: + """Non-ROLE-type viewers (USER/GROUP subjects), preserved untouched.""" + return [ + subject for subject in dashboard.viewers if subject.type != SubjectType.ROLE + ] + + +def _compute_new_role_ids( + dashboard: Any, request: ManageDashboardRolesRequest, viewers_enabled: bool +) -> tuple[list[int] | None, ManageDashboardRolesResponse | None]: + """Load current viewer roles and apply add/remove operations. + + Returns ``(new_role_ids, None)`` on success or ``(None, error_response)`` + when the initial lazy-load fails or a removal targets an unassigned + role. + """ + try: + current_role_ids = _viewer_role_ids(dashboard) + except SQLAlchemyError as db_err: + logger.error( + "Failed to load roles for dashboard %s: %s", + request.identifier, + db_err, + exc_info=True, + ) + return None, ManageDashboardRolesResponse( + viewers_enabled=viewers_enabled, + error="Failed to load dashboard roles due to a database error.", + ) + + unknown_removals = sorted(set(request.remove_role_ids) - set(current_role_ids)) + if unknown_removals: + return None, ManageDashboardRolesResponse( + viewers_enabled=viewers_enabled, + error=( + f"Cannot remove role IDs that are not currently assigned: " + f"{unknown_removals}. Current role IDs: " + f"{sorted(current_role_ids)}." + ), + ) + + new_role_ids = [ + role_id + for role_id in current_role_ids + if role_id not in request.remove_role_ids + ] + for role_id in request.add_role_ids: + if role_id not in new_role_ids: + new_role_ids.append(role_id) + + return new_role_ids, None + + +@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 access roles with explicit operations. + + Dashboard access roles 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 ``ENABLE_VIEWERS`` + feature flag is enabled; the response's ``viewers_enabled`` field + reports whether it is, and ``warnings`` notes when a change was applied + but has no live effect. + + Roles are the ROLE-type entries in the dashboard's Subject-based + ``viewers`` list. Any USER- or GROUP-type viewers already on the + dashboard are left untouched. + + 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 + + viewers_enabled = is_feature_enabled("ENABLE_VIEWERS") + warnings: list[str] = [] + if not viewers_enabled: + warnings.append( + "The ENABLE_VIEWERS feature flag is disabled on this instance; " + "dashboard viewers will be stored but have no effect on access " + "control until it is enabled." + ) + + new_role_ids, compute_error = _compute_new_role_ids( + dashboard, request, viewers_enabled + ) + if compute_error is not None: + return compute_error + assert new_role_ids is not None # narrows for mypy + + try: + with event_logger.log_context(action="mcp.manage_dashboard_roles.apply"): + from superset.subjects.utils import subjects_from_roles + + other_viewers = _other_viewers(dashboard) + resolved_role_subjects = subjects_from_roles(new_role_ids) + resolved_role_ids = {subject.role_id for subject in resolved_role_subjects} + missing_role_ids = sorted(set(new_role_ids) - resolved_role_ids) + if missing_role_ids: + return ManageDashboardRolesResponse( + viewers_enabled=viewers_enabled, + error=( + f"One or more role IDs do not exist: " + f"{missing_role_ids}. Use list_roles to resolve " + "valid role IDs." + ), + ) + + dashboard.viewers = other_viewers + resolved_role_subjects + db.session.commit() # pylint: disable=consider-using-transaction + try: + db.session.refresh(dashboard) + except SQLAlchemyError: + logger.warning( + "Dashboard %s roles updated but refresh failed; " + "continuing with current values", + dashboard.id, + exc_info=True, + ) + + except SQLAlchemyError as db_err: + try: + db.session.rollback() # pylint: disable=consider-using-transaction + except SQLAlchemyError: + logger.warning( + "Database rollback failed during error handling", + exc_info=True, + ) + logger.error("Dashboard roles update failed: %s", db_err, exc_info=True) + return ManageDashboardRolesResponse( + viewers_enabled=viewers_enabled, + error="Failed to update dashboard roles due to a database error.", + ) + + final_role_ids = set(_viewer_role_ids(dashboard)) + ctx.info(f"Dashboard {dashboard.id} roles updated: {sorted(final_role_ids)}") + + return ManageDashboardRolesResponse( + roles=[ + info + for subject in dashboard.viewers + if subject.type == SubjectType.ROLE + and (info := serialize_subject_object(subject)) is not None + ], + dashboard_url=_dashboard_url(dashboard), + added_role_ids=sorted(final_role_ids & set(request.add_role_ids)), Review Comment: **Suggestion:** `added_role_ids` is computed from final membership intersected with requested adds, not from a pre/post delta. If a requested role was already assigned before the call, it is incorrectly reported as “actually added,” which breaks the response contract and can mislead downstream automation. Compute additions against the pre-call role set. [logic error] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ⚠️ Response misreports already-assigned roles as newly added. - ⚠️ Automation may misbehave based on incorrect added_role_ids. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. On a dashboard that already has a viewer role R assigned (so _viewer_role_ids() returns a list containing R; superset/mcp_service/dashboard/tool/manage_dashboard_roles.py:101-107), call manage_dashboard_roles with request.add_role_ids set to [R] and request.remove_role_ids empty, exercising manage_dashboard_roles() at lines 173-208. 2. Inside _compute_new_role_ids() (lines 117-160), current_role_ids includes R, unknown_removals is empty, and new_role_ids is computed to include R as well, so no actual change in viewer roles occurs. 3. After subjects_from_roles() resolves the same role subjects and dashboard.viewers is reassigned, manage_dashboard_roles() computes final_role_ids as the set of ROLE-type viewer IDs, which still contains R (lines 236-281). 4. The response is then constructed at lines 283-299 with added_role_ids=sorted(final_role_ids & set(request.add_role_ids)), which evaluates to [R], causing the tool to report R as “added” even though it was already present before the call, potentially misleading downstream automation that interprets added_role_ids as the set of newly granted roles. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=db251b08ba9f4813b5ad496f3454d47d&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=db251b08ba9f4813b5ad496f3454d47d&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:** 291:291 **Comment:** *Logic Error: `added_role_ids` is computed from final membership intersected with requested adds, not from a pre/post delta. If a requested role was already assigned before the call, it is incorrectly reported as “actually added,” which breaks the response contract and can mislead downstream automation. Compute additions against the pre-call role set. 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=09c0efd71f4e57402e9a3478c80b24017e67c8ac6f918d916ac98ba845c7dadf&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41606&comment_hash=09c0efd71f4e57402e9a3478c80b24017e67c8ac6f918d916ac98ba845c7dadf&reaction=dislike'>👎</a> ########## superset/mcp_service/dashboard/tool/manage_dashboard_certification.py: ########## @@ -0,0 +1,189 @@ +# 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 certification FastMCP tool + +Sets or clears the ``certified_by`` / ``certification_details`` badge +fields. Split out from the generic ``update_dashboard`` tool because +certification is a distinct governance concern from layout/theme/metadata +edits. +""" + +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.exceptions import SupersetSecurityException +from superset.extensions import db, event_logger +from superset.mcp_service.dashboard.schemas import ( + ManageDashboardCertificationRequest, + ManageDashboardCertificationResponse, +) +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, ManageDashboardCertificationResponse | 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, ManageDashboardCertificationResponse( + error=f"Dashboard not found: {identifier!r}", + ) + + if dashboard is None: + return None, ManageDashboardCertificationResponse( + error=f"Dashboard not found: {identifier!r}", + ) + + try: + security_manager.raise_for_editorship(dashboard) + except SupersetSecurityException: + return None, ManageDashboardCertificationResponse( + 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}/" + ) Review Comment: **Suggestion:** The dashboard URL builder hardcodes an extra `/superset` path segment. In deployments where `WEBDRIVER_BASEURL_USER_FRIENDLY` already includes the app root (for example `https://host/superset`), this produces broken links like `/superset/superset/dashboard/...`. Build URLs the same way as the other dashboard tools by appending only `/dashboard/...` to the configured base URL. [api mismatch] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ❌ Certification tool returns broken dashboard URLs in responses. - ⚠️ MCP agents may follow invalid URLs during workflows. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Configure Superset so WEBDRIVER_BASEURL_USER_FRIENDLY is set to a path-prefixed URL like "https://example.com/superset", which get_superset_base_url() returns unchanged (superset/mcp_service/utils/url_utils.py:42-55). 2. Start Superset and the MCP service so the manage_dashboard_certification FastMCP tool is registered (superset/mcp_service/dashboard/tool/manage_dashboard_certification.py:92-104). 3. Invoke manage_dashboard_certification with a valid dashboard identifier via MCP, causing it to call _dashboard_url() at superset/mcp_service/dashboard/tool/manage_dashboard_certification.py:84-89 to build dashboard_url using f"{get_superset_base_url()}/superset/dashboard/{dashboard.slug or dashboard.id}/". 4. Observe that the response’s dashboard_url field is "https://example.com/superset/superset/dashboard/{slug_or_id}/", while other dashboard tooling builds "https://example.com/superset/dashboard/{slug_or_id}/" by either concatenating base_url and dashboard.url (superset/mcp_service/dashboard/schemas.py:2-6) or using f"{get_superset_base_url()}/dashboard/{slug_or_id}/" (superset/mcp_service/dashboard/tool/update_dashboard.py:48-50), confirming a double "/superset" segment. ``` </details> [](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=d8fdaa50362d4b90b5cfb9c880cb1c50&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=d8fdaa50362d4b90b5cfb9c880cb1c50&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_certification.py **Line:** 86:89 **Comment:** *Api Mismatch: The dashboard URL builder hardcodes an extra `/superset` path segment. In deployments where `WEBDRIVER_BASEURL_USER_FRIENDLY` already includes the app root (for example `https://host/superset`), this produces broken links like `/superset/superset/dashboard/...`. Build URLs the same way as the other dashboard tools by appending only `/dashboard/...` to the configured base URL. 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=abc325986c854532951339af1cc2dda13ab7b3e9a44f2ff367d13863e34ebf68&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41606&comment_hash=abc325986c854532951339af1cc2dda13ab7b3e9a44f2ff367d13863e34ebf68&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]
