aminghadersohi commented on code in PR #41606: URL: https://github.com/apache/superset/pull/41606#discussion_r3604745515
########## superset/mcp_service/dashboard/tool/manage_dashboard_certification.py: ########## @@ -0,0 +1,154 @@ +# 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 fastmcp import Context +from sqlalchemy.exc import SQLAlchemyError +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset.extensions import db, event_logger +from superset.mcp_service.dashboard.schemas import ( + ManageDashboardCertificationRequest, + ManageDashboardCertificationResponse, +) +from superset.mcp_service.dashboard.tool.governance_utils import ( + dashboard_url, + find_and_authorize_dashboard, +) + +logger: logging.Logger = logging.getLogger(__name__) + + +@tool( + tags=["mutate"], + class_permission_name="Dashboard", + method_permission_name="write", + annotations=ToolAnnotations( + title="Manage dashboard certification", + readOnlyHint=False, + destructiveHint=False, + ), +) +def manage_dashboard_certification( + request: ManageDashboardCertificationRequest, ctx: Context +) -> ManageDashboardCertificationResponse: + """ + Set or clear a dashboard's certification badge. + + ``certified_by`` and ``certification_details`` are independent optional + fields: omit (None) to leave a field unchanged, pass an empty string to + clear it, or pass a value to set it. Certification surfaces as a badge + next to the dashboard title in the UI. + + Example:: + + manage_dashboard_certification(request={ + "identifier": 42, + "certified_by": "Data Platform Team", + "certification_details": "Verified against source-of-truth metrics.", + }) + """ + ctx.info(f"Managing dashboard certification: identifier={request.identifier}") + + dashboard, auth_error = find_and_authorize_dashboard( + request.identifier, ManageDashboardCertificationResponse + ) + if auth_error is not None: + return auth_error + + if request.certified_by is None and request.certification_details is None: + return ManageDashboardCertificationResponse( + certified_by=dashboard.certified_by, + certification_details=dashboard.certification_details, + dashboard_url=dashboard_url(dashboard), + changed_fields=[], + warnings=["No fields provided; dashboard unchanged."], + ) + + changed_fields: list[str] = [] + warnings: list[str] = [] + # Captured before commit so the final response never has to dereference + # `dashboard` post-commit: SQLAlchemy expires ORM attributes on commit, + # and a failed `refresh()` below would otherwise leave a later + # `dashboard.certified_by`/`certification_details` read free to raise an + # unhandled `SQLAlchemyError` from a broken session. + final_certified_by = dashboard.certified_by + final_certification_details = dashboard.certification_details Review Comment: Fixed in cde36518a5: both annotated `str | None`. ########## superset/mcp_service/dashboard/schemas.py: ########## @@ -1083,6 +1083,385 @@ class UpdateDashboardResponse(BaseModel): ) +class ManageDashboardOwnersRequest(BaseModel): + """Request schema for explicit add/remove dashboard owner management. + + Unlike ``update_dashboard``'s dropped ``owners`` field (a full-replacement + list with no safety guard, so an empty or partial list could silently + orphan a dashboard), this tool takes explicit add/remove operations and + rejects any change that would leave the dashboard with zero owners. + + "Owners" here means USER-type entries in the dashboard's Subject-based + ``editors`` list (the ownership model apache/superset#38831 introduced, + replacing the legacy ``owners`` relationship). Any ROLE- or GROUP-type + editors already on the dashboard are left untouched by this tool. + """ + + identifier: int | str = Field( + ..., + description=( + "Dashboard ID (integer), UUID, or slug. Same identifier shape " + "accepted by ``get_dashboard_info``." + ), + ) + add_owner_ids: list[int] = Field( + default_factory=list, + description=( + "User IDs to add as dashboard owners. Discover IDs with ``find_users``." + ), + ) + remove_owner_ids: list[int] = Field( + default_factory=list, + description=( + "User IDs to remove from dashboard owners. Rejected if it would " + "leave the dashboard with zero owners, or if an ID is not " + "currently an owner." + ), + ) + + @field_validator("identifier", mode="before") + @classmethod + def reject_bool_identifier(cls, value: object) -> object: + """bool is a subclass of int, so identifier=true would coerce to + dashboard ID 1 and mutate the wrong dashboard; reject it outright.""" + if isinstance(value, bool): + raise ValueError("identifier must be an integer ID, UUID, or slug string") + return value + + @field_validator("add_owner_ids", "remove_owner_ids", mode="before") + @classmethod + def reject_bool_owner_ids(cls, value: object) -> object: + """bool is a subclass of int, so a `true`/`false` list element would + coerce to owner ID 1/0 and add/remove the wrong owner; reject it.""" + if isinstance(value, list) and any(isinstance(item, bool) for item in value): + raise ValueError("owner ID list items must be integers, not booleans") + return value + + @model_validator(mode="after") + def _validate_operations(self) -> "ManageDashboardOwnersRequest": + if not self.add_owner_ids and not self.remove_owner_ids: + raise ValueError( + "At least one of add_owner_ids or remove_owner_ids is required." + ) + overlap: list[int] = sorted( + set(self.add_owner_ids) & set(self.remove_owner_ids) + ) + if overlap: + raise ValueError( + "User IDs cannot appear in both add_owner_ids and " + f"remove_owner_ids: {overlap}." + ) + return self + + +class DashboardMutationErrorFields(BaseModel): + """Shared ``error``/``permission_denied`` fields for dashboard governance + mutation responses (owners/roles/certification), including the + validator that wraps ``error`` before it is exposed to LLM context. + """ + + error: str | None = Field(None, description="Error message, if operation failed") + permission_denied: bool = Field( + default=False, + description=("True when the user lacks edit rights on the target dashboard."), + ) + + @field_validator("error") + @classmethod + def sanitize_error_for_llm_context(cls, value: str | None) -> str | None: + """Wrap error text before it is exposed to LLM context.""" + if value is None: + return value + return sanitize_for_llm_context(value, field_path=("error",)) + + +class ManageDashboardOwnersResponse(DashboardMutationErrorFields): + """Response schema for ``manage_dashboard_owners``.""" + + owners: list[SubjectInfo] = Field( + default_factory=list, + description=( + "Full list of USER-type editor subjects (dashboard owners) " + "after the operation. Any ROLE/GROUP-type editors on the " + "dashboard are not included here." + ), + ) + dashboard_url: str | None = Field(None, description="URL to view the dashboard") + added_owner_ids: list[int] = Field( + default_factory=list, + description="User IDs actually added as owners by this call.", + ) + removed_owner_ids: list[int] = Field( + default_factory=list, + description="User IDs actually removed from owners by this call.", + ) + warnings: list[str] = Field( + default_factory=list, + description=( + "Non-fatal advisory messages, e.g. that a non-admin caller was " + "automatically re-added as owner after trying to remove " + "themselves." + ), + ) + + @field_validator("owners", mode="after") + @classmethod + def sanitize_owners_for_llm_context( + cls, value: list[SubjectInfo] + ) -> list[SubjectInfo]: + """Wrap owner labels before LLM exposure; owner display names are + user-controlled and render as plain text in this response, so an + unsanitized label could inject content into LLM context (CWE-79 + analog for LLM-facing output). Entries that sanitize to an empty + label are dropped rather than surfaced with a blank identity.""" + sanitized: list[SubjectInfo] = [] + for subject in value: + if subject.label is None: + sanitized.append(subject) + continue + clean_label = sanitize_for_llm_context( + subject.label, field_path=("owners", "label") + ) Review Comment: Fixed in cde36518a5: annotated `str`. ########## superset/mcp_service/dashboard/schemas.py: ########## @@ -1083,6 +1083,385 @@ class UpdateDashboardResponse(BaseModel): ) +class ManageDashboardOwnersRequest(BaseModel): + """Request schema for explicit add/remove dashboard owner management. + + Unlike ``update_dashboard``'s dropped ``owners`` field (a full-replacement + list with no safety guard, so an empty or partial list could silently + orphan a dashboard), this tool takes explicit add/remove operations and + rejects any change that would leave the dashboard with zero owners. + + "Owners" here means USER-type entries in the dashboard's Subject-based + ``editors`` list (the ownership model apache/superset#38831 introduced, + replacing the legacy ``owners`` relationship). Any ROLE- or GROUP-type + editors already on the dashboard are left untouched by this tool. + """ + + identifier: int | str = Field( + ..., + description=( + "Dashboard ID (integer), UUID, or slug. Same identifier shape " + "accepted by ``get_dashboard_info``." + ), + ) + add_owner_ids: list[int] = Field( + default_factory=list, + description=( + "User IDs to add as dashboard owners. Discover IDs with ``find_users``." + ), + ) + remove_owner_ids: list[int] = Field( + default_factory=list, + description=( + "User IDs to remove from dashboard owners. Rejected if it would " + "leave the dashboard with zero owners, or if an ID is not " + "currently an owner." + ), + ) + + @field_validator("identifier", mode="before") + @classmethod + def reject_bool_identifier(cls, value: object) -> object: + """bool is a subclass of int, so identifier=true would coerce to + dashboard ID 1 and mutate the wrong dashboard; reject it outright.""" + if isinstance(value, bool): + raise ValueError("identifier must be an integer ID, UUID, or slug string") + return value + + @field_validator("add_owner_ids", "remove_owner_ids", mode="before") + @classmethod + def reject_bool_owner_ids(cls, value: object) -> object: + """bool is a subclass of int, so a `true`/`false` list element would + coerce to owner ID 1/0 and add/remove the wrong owner; reject it.""" + if isinstance(value, list) and any(isinstance(item, bool) for item in value): + raise ValueError("owner ID list items must be integers, not booleans") + return value + + @model_validator(mode="after") + def _validate_operations(self) -> "ManageDashboardOwnersRequest": + if not self.add_owner_ids and not self.remove_owner_ids: + raise ValueError( + "At least one of add_owner_ids or remove_owner_ids is required." + ) + overlap: list[int] = sorted( + set(self.add_owner_ids) & set(self.remove_owner_ids) + ) + if overlap: + raise ValueError( + "User IDs cannot appear in both add_owner_ids and " + f"remove_owner_ids: {overlap}." + ) + return self + + +class DashboardMutationErrorFields(BaseModel): + """Shared ``error``/``permission_denied`` fields for dashboard governance + mutation responses (owners/roles/certification), including the + validator that wraps ``error`` before it is exposed to LLM context. + """ + + error: str | None = Field(None, description="Error message, if operation failed") + permission_denied: bool = Field( + default=False, + description=("True when the user lacks edit rights on the target dashboard."), + ) + + @field_validator("error") + @classmethod + def sanitize_error_for_llm_context(cls, value: str | None) -> str | None: + """Wrap error text before it is exposed to LLM context.""" + if value is None: + return value + return sanitize_for_llm_context(value, field_path=("error",)) + + +class ManageDashboardOwnersResponse(DashboardMutationErrorFields): + """Response schema for ``manage_dashboard_owners``.""" + + owners: list[SubjectInfo] = Field( + default_factory=list, + description=( + "Full list of USER-type editor subjects (dashboard owners) " + "after the operation. Any ROLE/GROUP-type editors on the " + "dashboard are not included here." + ), + ) + dashboard_url: str | None = Field(None, description="URL to view the dashboard") + added_owner_ids: list[int] = Field( + default_factory=list, + description="User IDs actually added as owners by this call.", + ) + removed_owner_ids: list[int] = Field( + default_factory=list, + description="User IDs actually removed from owners by this call.", + ) + warnings: list[str] = Field( + default_factory=list, + description=( + "Non-fatal advisory messages, e.g. that a non-admin caller was " + "automatically re-added as owner after trying to remove " + "themselves." + ), + ) + + @field_validator("owners", mode="after") + @classmethod + def sanitize_owners_for_llm_context( + cls, value: list[SubjectInfo] + ) -> list[SubjectInfo]: + """Wrap owner labels before LLM exposure; owner display names are + user-controlled and render as plain text in this response, so an + unsanitized label could inject content into LLM context (CWE-79 + analog for LLM-facing output). Entries that sanitize to an empty + label are dropped rather than surfaced with a blank identity.""" + sanitized: list[SubjectInfo] = [] + for subject in value: + if subject.label is None: + sanitized.append(subject) + continue + clean_label = sanitize_for_llm_context( + subject.label, field_path=("owners", "label") + ) + if not clean_label: + continue + sanitized.append(subject.model_copy(update={"label": clean_label})) + return sanitized + + +class ManageDashboardRolesRequest(BaseModel): + """Request schema for explicit add/remove dashboard RBAC role management. + + Unlike ``update_dashboard``'s dropped ``roles`` field (a full-replacement + access-control list), this tool takes explicit add/remove operations. + + "Roles" here means ROLE-type entries in the dashboard's Subject-based + ``viewers`` list (the access model apache/superset#38831 introduced, + replacing the legacy ``roles``/``DASHBOARD_RBAC`` relationship). Any + USER- or GROUP-type viewers already on the dashboard are left untouched + by this tool. + """ + + identifier: int | str = Field( + ..., + description=( + "Dashboard ID (integer), UUID, or slug. Same identifier shape " + "accepted by ``get_dashboard_info``." + ), + ) + add_role_ids: list[int] = Field( + default_factory=list, + description=( + "Role IDs to grant dashboard access to. Discover IDs with ``list_roles``." + ), + ) + remove_role_ids: list[int] = Field( + default_factory=list, + description=( + "Role IDs to revoke dashboard access from. Rejected if an ID is " + "not currently assigned to the dashboard." + ), + ) + + @field_validator("identifier", mode="before") + @classmethod + def reject_bool_identifier(cls, value: object) -> object: + """bool is a subclass of int, so identifier=true would coerce to + dashboard ID 1 and mutate the wrong dashboard; reject it outright.""" + if isinstance(value, bool): + raise ValueError("identifier must be an integer ID, UUID, or slug string") + return value + + @field_validator("add_role_ids", "remove_role_ids", mode="before") + @classmethod + def reject_bool_role_ids(cls, value: object) -> object: + """bool is a subclass of int, so a `true`/`false` list element would + coerce to role ID 1/0 and grant/revoke the wrong role; reject it.""" + if isinstance(value, list) and any(isinstance(item, bool) for item in value): + raise ValueError("role ID list items must be integers, not booleans") + return value + + @model_validator(mode="after") + def _validate_operations(self) -> "ManageDashboardRolesRequest": + if not self.add_role_ids and not self.remove_role_ids: + raise ValueError( + "At least one of add_role_ids or remove_role_ids is required." + ) + overlap: list[int] = sorted(set(self.add_role_ids) & set(self.remove_role_ids)) + if overlap: + raise ValueError( + "Role IDs cannot appear in both add_role_ids and " + f"remove_role_ids: {overlap}." + ) + return self + + +class ManageDashboardRolesResponse(DashboardMutationErrorFields): + """Response schema for ``manage_dashboard_roles``.""" + + roles: list[SubjectInfo] = Field( + default_factory=list, + description=( + "Full list of ROLE-type viewer subjects (dashboard access " + "roles) after the operation. Any USER/GROUP-type viewers on " + "the dashboard are not included here." + ), + ) + dashboard_url: str | None = Field(None, description="URL to view the dashboard") + added_role_ids: list[int] = Field( + default_factory=list, + description="Role IDs actually added by this call.", + ) + removed_role_ids: list[int] = Field( + default_factory=list, + description="Role IDs actually removed by this call.", + ) + viewers_enabled: bool = Field( + default=False, + description=( + "Whether the ENABLE_VIEWERS feature flag is enabled on this " + "instance. When False, dashboard viewers are stored but have no " + "effect on access control — access still follows normal " + "Superset permissions/editorship." + ), + ) + warnings: list[str] = Field( + default_factory=list, description="Non-fatal advisory messages." + ) + + @field_validator("roles", mode="after") + @classmethod + def sanitize_roles_for_llm_context( + cls, value: list[SubjectInfo] + ) -> list[SubjectInfo]: + """Wrap role labels before LLM exposure; role display names are + user-controlled and render as plain text in this response, so an + unsanitized label could inject content into LLM context (CWE-79 + analog for LLM-facing output). Entries that sanitize to an empty + label are dropped rather than surfaced with a blank identity.""" + sanitized: list[SubjectInfo] = [] + for subject in value: + if subject.label is None: + sanitized.append(subject) + continue + clean_label = sanitize_for_llm_context( + subject.label, field_path=("roles", "label") + ) Review Comment: Fixed in cde36518a5: annotated `str`. ########## superset/mcp_service/dashboard/tool/manage_dashboard_roles.py: ########## @@ -0,0 +1,315 @@ +# 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.extensions import db, event_logger +from superset.mcp_service.dashboard.schemas import ( + ManageDashboardRolesRequest, + ManageDashboardRolesResponse, +) +from superset.mcp_service.dashboard.tool.governance_utils import ( + dashboard_url, + find_and_authorize_dashboard, +) +from superset.mcp_service.system.schemas import serialize_subject_object +from superset.subjects.types import SubjectType + +logger: logging.Logger = logging.getLogger(__name__) + + +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, list[int] | None, ManageDashboardRolesResponse | None]: + """Load current viewer roles and apply add/remove operations. + + Returns ``(current_role_ids, new_role_ids, None)`` on success or + ``(None, None, error_response)`` when the initial lazy-load fails or a + removal targets an unassigned role. The pre-call ``current_role_ids`` + is returned so the caller can report true added/removed deltas. + """ + 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, + 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, + 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 current_role_ids, new_role_ids, None + + +def _resolve_role_subjects(new_role_ids: list[int]) -> tuple[list[Any], list[int]]: + """Resolve role IDs to ROLE-type Subjects, one at a time. + + Mirrors the owners tool's ``get_or_create_user_subject`` loop: a role + that exists but has no synced Subject row yet is synced on demand + instead of being misreported as nonexistent. Returns + ``(resolved_subjects, missing_role_ids)`` where the latter contains + only IDs with no matching role at all. + """ + from superset.subjects.utils import get_or_create_role_subject + + resolved_role_subjects: list[Any] = [] + missing_role_ids: list[int] = [] + for role_id in new_role_ids: + subject = get_or_create_role_subject(role_id) + if subject is None: + missing_role_ids.append(role_id) + else: + resolved_role_subjects.append(subject) + return resolved_role_subjects, missing_role_ids + + +@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. A request that has no effective change (e.g. "adding" a + role that is already assigned) returns an empty ``roles`` list rather + than the full current set, so this tool cannot be used as a disguised + directory lookup. + + 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, ManageDashboardRolesResponse + ) + 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." + ) + + current_role_ids, new_role_ids, compute_error = _compute_new_role_ids( + dashboard, request, viewers_enabled + ) + if compute_error is not None: + return compute_error + assert current_role_ids is not None # narrows for mypy + assert new_role_ids is not None # narrows for mypy + + # No-op short-circuit: skip the DB write and, more importantly, the + # full roles list in the response — mirrors manage_dashboard_owners. + # The roles list is only sanctioned as confirmation of an actual change + # (see docstring); returning it for a request that changes nothing + # would let a caller enumerate access roles via a disguised no-op + # (e.g. "add" a role that is already assigned). + if set(new_role_ids) == set(current_role_ids): + ctx.info(f"Dashboard {dashboard.id} roles unchanged; no-op request.") + return ManageDashboardRolesResponse( + dashboard_url=dashboard_url(dashboard), + viewers_enabled=viewers_enabled, + warnings=warnings + + ["No effective change: requested roles already match the current state."], + ) + + try: + with event_logger.log_context(action="mcp.manage_dashboard_roles.apply"): + other_viewers = _other_viewers(dashboard) + + resolved_role_subjects, missing_role_ids = _resolve_role_subjects( + new_role_ids + ) + if missing_role_ids: + return ManageDashboardRolesResponse( + viewers_enabled=viewers_enabled, + error=( + f"One or more role IDs do not exist: " + f"{sorted(missing_role_ids)}. Use list_roles to " + "resolve valid role IDs." + ), + ) Review Comment: Good catch — fixed in cde36518a5. Added `db.session.rollback()` before the early return so any Subject rows `_resolve_role_subjects` already flushed for earlier, valid role IDs in the same request don't linger uncommitted. Applied the identical fix to `manage_dashboard_owners.py`'s analogous `get_or_create_user_subject` loop and `SubjectsNotFoundValidationError` branch, which had the same gap, and added regression tests asserting `db.session.rollback()` is called in both tools' "unknown ID" paths. ########## superset/mcp_service/dashboard/tool/governance_utils.py: ########## @@ -0,0 +1,107 @@ +# 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. + +""" +Shared helpers for the dashboard governance tools +(``manage_dashboard_owners`` / ``manage_dashboard_roles`` / +``manage_dashboard_certification``). + +``update_dashboard`` keeps its own variant of the lookup/authorization +helper because its not-found contract differs — it returns a +``DashboardError`` carrying an ``error_type`` rather than the tool's own +response schema; unifying that shape is left to a follow-up. +""" + +import logging +from typing import Any, TypeVar + +from sqlalchemy.exc import SQLAlchemyError + +from superset.commands.dashboard.exceptions import ( + DashboardAccessDeniedError, + DashboardNotFoundError, +) +from superset.exceptions import SupersetSecurityException +from superset.mcp_service.dashboard.schemas import DashboardMutationErrorFields +from superset.mcp_service.utils.url_utils import get_superset_base_url + +logger: logging.Logger = logging.getLogger(__name__) + +ResponseT = TypeVar("ResponseT", bound=DashboardMutationErrorFields) + + +def find_and_authorize_dashboard( + identifier: int | str, + response_cls: type[ResponseT], +) -> tuple[Any, ResponseT | None]: + """Return (dashboard, None) on success or (None, error_response) on failure. + + ``response_cls`` is the calling tool's response schema; every failure + mode is reported through it so the caller has a single pre-condition + branch. 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 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. + return None, response_cls( + permission_denied=True, + error=( + "You do not have permission to access this dashboard. " + "Ask the user to grant access; do not retry." + ), + ) + except DashboardNotFoundError: + return None, response_cls( + error=f"Dashboard not found: {identifier!r}", + ) + except SQLAlchemyError: + logger.exception("Database error looking up dashboard %r", identifier) + return None, response_cls( + error="Failed to look up dashboard due to a database error.", + ) + + if dashboard is None: + return None, response_cls( + error=f"Dashboard not found: {identifier!r}", + ) + + try: + security_manager.raise_for_editorship(dashboard) + except SupersetSecurityException: + return None, response_cls( + permission_denied=True, + error=( + f"You don't have permission to edit dashboard " + f"'{dashboard.dashboard_title}' (ID: {dashboard.id})." + ), + ) Review Comment: Good catch — fixed in cde36518a5. Added an `except SQLAlchemyError` branch around `raise_for_editorship` that maps to the tool's structured database-error response, mirroring the catch already present around the DAO lookup just above it. Added a regression test (`test_editorship_check_db_fault_returns_database_error`) covering this path. Note `update_dashboard.py`'s own separate copy of this helper has the same pre-existing gap; left that alone as out of scope for this PR. ########## superset/mcp_service/dashboard/tool/manage_dashboard_owners.py: ########## @@ -0,0 +1,354 @@ +# 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.extensions import db, event_logger +from superset.mcp_service.dashboard.schemas import ( + ManageDashboardOwnersRequest, + ManageDashboardOwnersResponse, +) +from superset.mcp_service.dashboard.tool.governance_utils import ( + dashboard_url, + find_and_authorize_dashboard, +) +from superset.mcp_service.system.schemas import serialize_subject_object +from superset.subjects.exceptions import SubjectsNotFoundValidationError +from superset.subjects.types import SubjectType + +logger: logging.Logger = logging.getLogger(__name__) + + +def _owner_user_ids(dashboard: Any) -> list[int]: + """User IDs behind the dashboard's USER-type editor subjects.""" + return [ + subject.user_id + for subject in dashboard.editors + if subject.type == SubjectType.USER + ] + + +def _other_editors(dashboard: Any) -> list[Any]: + """Non-USER-type editors (ROLE/GROUP subjects), preserved untouched.""" + return [ + subject for subject in dashboard.editors if subject.type != SubjectType.USER + ] + + +def _compute_new_owner_ids( + current_owner_ids: list[int], request: ManageDashboardOwnersRequest +) -> tuple[list[int] | None, ManageDashboardOwnersResponse | None]: + """Apply add/remove operations and validate the result. + + Returns ``(new_owner_ids, None)`` on success or ``(None, error_response)`` + when a removal targets a non-owner or the result would be empty. + """ + unknown_removals = sorted(set(request.remove_owner_ids) - set(current_owner_ids)) + if unknown_removals: + return None, ManageDashboardOwnersResponse( + error=( + f"Cannot remove user IDs that are not currently owners: " + f"{unknown_removals}. Current owner IDs: " + f"{sorted(current_owner_ids)}." + ), + ) + + new_owner_ids = [ + owner_id + for owner_id in current_owner_ids + if owner_id not in request.remove_owner_ids + ] + for owner_id in request.add_owner_ids: + if owner_id not in new_owner_ids: + new_owner_ids.append(owner_id) + + if not new_owner_ids: + return None, ManageDashboardOwnersResponse( + error=( + "Cannot remove all owners; a dashboard must have at least " + "one owner. To transfer ownership, add the new owner in the " + "same call as removing the last existing one." + ), + ) + + return new_owner_ids, None + + +def _apply_owner_change( + dashboard: Any, new_owner_ids: list[int] +) -> tuple[list[Any] | None, ManageDashboardOwnersResponse | None]: + """Resolve the new owner user IDs to USER-type Subjects and persist. + + Mutates ``dashboard.editors`` in place on success — replacing the + USER-type entries while preserving any ROLE/GROUP-type editors. Returns + ``(resolved_owner_subjects, None)`` on success — captured before commit + so callers never need to dereference ``dashboard.editors`` post-commit + (SQLAlchemy expires ORM attributes on commit, and a failed + ``refresh()`` would otherwise leave a later ``dashboard.editors`` read + free to raise an unhandled ``SQLAlchemyError`` from a broken session) — + or ``(None, error_response)`` on failure. + """ + from superset.commands.utils import populate_subject_list + from superset.subjects.utils import get_or_create_user_subject + + try: + with event_logger.log_context(action="mcp.manage_dashboard_owners.apply"): + other_editors = _other_editors(dashboard) + + new_subject_ids: list[int] = [] + for user_id in new_owner_ids: + subject = get_or_create_user_subject(user_id) + if subject is None: + return None, ManageDashboardOwnersResponse( + error=( + f"User ID {user_id} does not exist. Use " + "find_users to resolve valid user IDs." + ), + ) + new_subject_ids.append(subject.id) + + try: + resolved_owner_subjects = populate_subject_list( + new_subject_ids, + default_to_user=False, + ensure_no_lockout=True, + field_name="editors", + ) + except SubjectsNotFoundValidationError: + return None, ManageDashboardOwnersResponse( + error=( + "One or more user IDs could not be resolved to " + "owners. Use find_users to resolve valid user IDs." + ), + ) + + dashboard.editors = other_editors + resolved_owner_subjects + db.session.commit() # pylint: disable=consider-using-transaction + try: + db.session.refresh(dashboard) + except SQLAlchemyError: + logger.warning( + "Dashboard %s owners 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 owners update failed: %s", db_err, exc_info=True) + return None, ManageDashboardOwnersResponse( + error="Failed to update dashboard owners due to a database error.", + ) + + return resolved_owner_subjects, None + + +def _build_owner_warnings( + final_owner_ids: set[int], new_owner_ids: list[int] +) -> list[str]: + """Flag when the resolver re-added an ID that was not requested. + + Happens when a non-admin caller tries to remove themselves — + ``populate_subject_list``'s ``ensure_no_lockout`` self-protection + re-adds their USER subject. + """ + auto_added = final_owner_ids - set(new_owner_ids) + if not auto_added: + return [] + return [ + f"User ID(s) {sorted(auto_added)} were automatically re-added as " + "owner(s): non-admin callers cannot remove themselves from the " + "owners list." + ] + + +@tool( + tags=["mutate"], + class_permission_name="Dashboard", + method_permission_name="write", + annotations=ToolAnnotations( + title="Manage dashboard owners", + readOnlyHint=False, + destructiveHint=True, + ), +) +def manage_dashboard_owners( + request: ManageDashboardOwnersRequest, ctx: Context +) -> ManageDashboardOwnersResponse: + """ + Add or remove dashboard owners with explicit, safe operations. + + Owners can edit the dashboard, manage its charts, and delete it. Unlike + ``update_dashboard``'s dropped ``owners`` field, this tool never accepts + a full-replacement list — only ``add_owner_ids``/``remove_owner_ids`` — + and rejects any change that would leave the dashboard with zero owners. + + Owners are the USER-type entries in the dashboard's Subject-based + ``editors`` list. Any ROLE- or GROUP-type editors already on the + dashboard are left untouched. + + A non-admin caller who removes themselves is automatically re-added + (mirrors the same self-protection ``update_dashboard``'s editorship + check relies on) unless an ``EXTRA_EDITORS_RESOLVER`` is configured on + the instance; the response's ``warnings`` reports when this happens. + + Privacy: the returned ``owners`` 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 owns X" for a dashboard the + caller did not ask to modify, and do not call this tool merely to look + up current owners — those remain off-limits per the server instructions. + A request that has no effective change (e.g. "adding" an ID that is + already an owner) returns an empty ``owners`` list rather than the full + current set, so this tool cannot be used as a disguised directory + lookup. + + Example:: + + manage_dashboard_owners(request={ + "identifier": 42, + "add_owner_ids": [7], + "remove_owner_ids": [3], + }) + """ + ctx.info( + f"Managing dashboard owners: identifier={request.identifier} " + f"add={request.add_owner_ids} remove={request.remove_owner_ids}" + ) + + dashboard, auth_error = find_and_authorize_dashboard( + request.identifier, ManageDashboardOwnersResponse + ) + if auth_error is not None: + return auth_error + + try: + current_owner_ids = _owner_user_ids(dashboard) + except SQLAlchemyError as db_err: + logger.error( + "Failed to load owners for dashboard %s: %s", + request.identifier, + db_err, + exc_info=True, + ) + return ManageDashboardOwnersResponse( + error="Failed to load dashboard owners due to a database error.", + ) + + new_owner_ids, compute_error = _compute_new_owner_ids(current_owner_ids, request) + if compute_error is not None: + return compute_error + assert new_owner_ids is not None # narrows for mypy; empty list errors above + + # No-op short-circuit: skip the DB write and, more importantly, the full + # owners list in the response. The owners list is only sanctioned as + # confirmation of an actual change (see docstring); returning it for a + # request that changes nothing would let a caller enumerate owners via + # a disguised no-op (e.g. "add" an ID that is already an owner). + # + # A self-removal-only request from a non-admin is deliberately NOT + # detected here even though ensure_no_lockout will revert it: whether + # the caller is actually re-added depends on resolution-time state + # (admin status, EXTRA_EDITORS_RESOLVER) that populate_subject_list + # owns, and predicting it here would duplicate that logic. That rare + # path is allowed to commit a redundant (state-preserving) write and is + # caught by the post-resolution no-op check further down. + if set(new_owner_ids) == set(current_owner_ids): + ctx.info(f"Dashboard {dashboard.id} owners unchanged; no-op request.") + return ManageDashboardOwnersResponse( + dashboard_url=dashboard_url(dashboard), + warnings=[ + "No effective change: requested owners already match the current state." + ], + ) + + resolved_owner_subjects, apply_error = _apply_owner_change(dashboard, new_owner_ids) + if apply_error is not None: + return apply_error + assert resolved_owner_subjects is not None # narrows for mypy + + final_owner_ids = { + subject.user_id + for subject in resolved_owner_subjects + if subject.type == SubjectType.USER + } Review Comment: Good catch — fixed in cde36518a5. `_apply_owner_change` now captures `final_owner_ids` (a plain `set[int]`) and the serialized `owners_response` list *before* `db.session.commit()`, and returns those primitives instead of the ORM `Subject` list — mirroring the pattern `manage_dashboard_roles.py` already used for its `final_role_ids`/`roles_response`. The caller no longer dereferences any Subject attributes after the commit. -- 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]
