codeant-ai-for-open-source[bot] commented on code in PR #41606:
URL: https://github.com/apache/superset/pull/41606#discussion_r3588448945
##########
superset/mcp_service/dashboard/schemas.py:
##########
@@ -1062,6 +1062,358 @@ 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
+
+ @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."
+ ),
+ )
Review Comment:
**Suggestion:** `add_role_ids`/`remove_role_ids` also accept `List[int]`
without a bool guard, so boolean payload values are coerced to role IDs (`true`
→ `1`) and can grant/revoke access for unintended roles. Enforce strict integer
validation for these arrays. [type error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
❌ Role-based dashboard access can change due to boolean IDs.
⚠️ Access control automation may misgrant or revoke role visibility.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. The `manage_dashboard_roles` MCP tool defined in
`superset/mcp_service/dashboard/tool/manage_dashboard_roles.py:199-260`
consumes
`ManageDashboardRolesRequest` from
`superset/mcp_service/dashboard/schemas.py:202-257`,
where `add_role_ids` and `remove_role_ids` are declared as `List[int]` at
lines 1222-1233
without additional element validation.
2. A caller issues a request like `{"identifier": 42, "add_role_ids":
[true]}`; Pydantic
constructs `ManageDashboardRolesRequest`, coercing the boolean `true` to
integer `1`
because the field type is `List[int]` and there is no `mode="before"`
validator on these
arrays; thus `request.add_role_ids` becomes `[1]`.
3. In `manage_dashboard_roles()` at
`superset/mcp_service/dashboard/tool/manage_dashboard_roles.py:199-260`, the
function logs
the request and calls `_compute_new_role_ids(dashboard, request,
viewers_enabled)` at
lines 255-257; `_compute_new_role_ids()`
(`manage_dashboard_roles.py:134-187`) reads
current viewer roles, then applies `request.add_role_ids` /
`request.remove_role_ids` to
compute `new_role_ids`, so the coerced ID `1` is treated as a legitimate
role ID and will
be persisted to the dashboard’s Subject-based viewers list.
4. Similarly, if a caller sends `{"identifier": 42, "remove_role_ids":
[false]}`, Pydantic
coerces `false` to `0`; `_compute_new_role_ids()` uses
`request.remove_role_ids` in
set-based difference operations at lines 162-185, and any role with ID 0
present in
`current_role_ids` will be revoked unintentionally, resulting in unintended
changes to
role-based dashboard access driven solely by boolean payload values.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=eeec748821154061a0130e920a380835&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=eeec748821154061a0130e920a380835&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/schemas.py
**Line:** 1222:1233
**Comment:**
*Type Error: `add_role_ids`/`remove_role_ids` also accept `List[int]`
without a bool guard, so boolean payload values are coerced to role IDs (`true`
→ `1`) and can grant/revoke access for unintended roles. Enforce strict integer
validation for these arrays.
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=51311679e6b5e0af5743b0578131bae1143d9d1a2cd03c300da5dda5b6e90469&reaction=like'>👍</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41606&comment_hash=51311679e6b5e0af5743b0578131bae1143d9d1a2cd03c300da5dda5b6e90469&reaction=dislike'>👎</a>
##########
superset/mcp_service/dashboard/schemas.py:
##########
@@ -1062,6 +1062,358 @@ 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."
+ ),
+ )
Review Comment:
**Suggestion:** `add_owner_ids`/`remove_owner_ids` use `List[int]` without
rejecting booleans, so values like `true`/`false` are coerced to `1`/`0` and
can unintentionally add or remove the wrong owners. Validate list elements as
non-bool integers (e.g., strict ints) before processing. [type error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
❌ Owner changes may target wrong users from boolean payloads.
⚠️ Governance automation risks unintended owner addition or removal.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. The `manage_dashboard_owners` MCP tool is defined at
`superset/mcp_service/dashboard/tool/manage_dashboard_owners.py:275-395` and
uses
`ManageDashboardOwnersRequest` from
`superset/mcp_service/dashboard/schemas.py:66-125`,
where `add_owner_ids` and `remove_owner_ids` are declared as `List[int]` at
lines
1086-1099.
2. A caller invokes `manage_dashboard_owners` with a JSON body such as
`{"identifier": 42,
"add_owner_ids": [true]}`, sending a boolean list element; Pydantic builds
`ManageDashboardOwnersRequest`, coercing `true` to integer `1` for the
`List[int]` fields
because there is no per-element bool guard, so `request.add_owner_ids`
becomes `[1]`.
3. Inside `manage_dashboard_owners()` (`manage_dashboard_owners.py:275-338`),
`_compute_new_owner_ids()` at `manage_dashboard_owners.py:136-172` processes
`request.add_owner_ids` and `request.remove_owner_ids`, producing
`new_owner_ids` that now
include the coerced ID `1`; `_apply_owner_change()` at
`manage_dashboard_owners.py:175-243` then iterates `new_owner_ids`, calling
`get_or_create_user_subject(user_id)` and `populate_subject_list(...)`,
which will resolve
and persist ownership for user ID 1 based on the mis-specified boolean
rather than an
explicitly chosen numeric ID.
4. Similarly, a payload like `{"identifier": 42, "remove_owner_ids":
[false]}` is
accepted, with `false` coerced to `0`; `_compute_new_owner_ids()` uses this
`0` in its
set-based removal logic at lines 144-162, so if a user with ID 0 exists or
equals an owner
in `current_owner_ids`, that owner can be removed unintentionally due to the
boolean-to-int coercion.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=7ba42dfef9cb4b8ba4f904efbd3ae780&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=7ba42dfef9cb4b8ba4f904efbd3ae780&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/schemas.py
**Line:** 1086:1099
**Comment:**
*Type Error: `add_owner_ids`/`remove_owner_ids` use `List[int]` without
rejecting booleans, so values like `true`/`false` are coerced to `1`/`0` and
can unintentionally add or remove the wrong owners. Validate list elements as
non-bool integers (e.g., strict ints) before processing.
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=e058d7cb2a7b1d1a4c8fcbd42f279e5f93d52e4e073ff97c1893d4c17a1955af&reaction=like'>👍</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41606&comment_hash=e058d7cb2a7b1d1a4c8fcbd42f279e5f93d52e4e073ff97c1893d4c17a1955af&reaction=dislike'>👎</a>
##########
superset/mcp_service/dashboard/tool/manage_dashboard_owners.py:
##########
@@ -0,0 +1,395 @@
+# 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 (
+ DashboardAccessDeniedError,
+ 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.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 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, ManageDashboardOwnersResponse(
+ 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, ManageDashboardOwnersResponse(
+ error=f"Dashboard not found: {identifier!r}",
+ )
+ except SQLAlchemyError:
+ logger.exception("Database error looking up dashboard %r", identifier)
+ return None, ManageDashboardOwnersResponse(
+ error="Failed to look up dashboard due to a database error.",
+ )
+
+ 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()}/dashboard/{dashboard.slug or
dashboard.id}/"
+
+
+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]
+) -> 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
+ an error response on failure, or ``None`` on success.
+ """
+ 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 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 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 ManageDashboardOwnersResponse(
+ error="Failed to update dashboard owners due to a database error.",
+ )
+
+ return 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)
+ 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).
+ 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."
+ ],
+ )
+
+ if (apply_error := _apply_owner_change(dashboard, new_owner_ids)) is not
None:
+ return apply_error
+
+ final_owner_ids = set(_owner_user_ids(dashboard))
+ warnings = _build_owner_warnings(final_owner_ids, new_owner_ids)
+
+ # True deltas against the PRE-call state — not just membership in the
+ # request — so a redundant add/remove (already-satisfied, or reverted by
+ # ensure_no_lockout self-protection) is never reported or disclosed as a
+ # change.
+ added_owner_ids = sorted(
+ (final_owner_ids & set(request.add_owner_ids)) - set(current_owner_ids)
+ )
+ removed_owner_ids = sorted(
+ (set(request.remove_owner_ids) & set(current_owner_ids)) -
final_owner_ids
+ )
Review Comment:
**Suggestion:** After committing, the code reads owners again and serializes
`dashboard.editors` without any `SQLAlchemyError` handling. If a post-commit
lazy-load/read fails, the tool raises an unhandled exception and loses the
structured response path. Wrap these post-commit reads in the same DB-error
handling pattern used earlier in the function. [possible bug]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
❌ Post-update owner reads can crash governance MCP tool.
⚠️ Callers lose structured error messages on DB failures.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. The `manage_dashboard_owners` FastMCP tool in
`superset/mcp_service/dashboard/tool/manage_dashboard_owners.py:275-395`
processes
requests to change owners, first loading current owners via
`_owner_user_ids()` inside a
`try`/`except SQLAlchemyError` block at lines 322-333 and then persisting
changes via
`_apply_owner_change()` at lines 175-243.
2. `_apply_owner_change()` uses `db.session.commit()` and
`db.session.refresh(dashboard)`
at lines 218-221, catching `SQLAlchemyError` from `refresh` and logging a
warning but
otherwise continuing; in the presence of a transient database issue or broken
relationship, subsequent lazy-loads of `dashboard.editors` can raise
`SQLAlchemyError` as
well when accessed.
3. After `_apply_owner_change()` returns successfully,
`manage_dashboard_owners()`
continues at
`superset/mcp_service/dashboard/tool/manage_dashboard_owners.py:357-369`,
calling `final_owner_ids = set(_owner_user_ids(dashboard))` (line 357) and
later iterating
over `dashboard.editors` in the list comprehension that builds the `owners`
field (lines
385-390), but these post-commit reads are not wrapped in any `try`/`except
SQLAlchemyError`.
4. If a database error occurs during these post-commit reads (for example, a
failure when
lazily loading `dashboard.editors` after the commit),
`_owner_user_ids(dashboard)` or the
owners list comprehension will raise `SQLAlchemyError` that bubbles out of
`manage_dashboard_owners()` without being converted to a
`ManageDashboardOwnersResponse`,
causing the tool to crash and depriving callers of the structured error
message pattern
used earlier in the function for database failures.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=48f6150e7d604a9db94de8618a45e488&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=48f6150e7d604a9db94de8618a45e488&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:** 357:369
**Comment:**
*Possible Bug: After committing, the code reads owners again and
serializes `dashboard.editors` without any `SQLAlchemyError` handling. If a
post-commit lazy-load/read fails, the tool raises an unhandled exception and
loses the structured response path. Wrap these post-commit reads in the same
DB-error handling pattern used earlier in the function.
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=b81a2a234c61a605b3cc5f90eb5cac47e62bd8d027e39068aad003287f77540e&reaction=like'>👍</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41606&comment_hash=b81a2a234c61a605b3cc5f90eb5cac47e62bd8d027e39068aad003287f77540e&reaction=dislike'>👎</a>
##########
superset/mcp_service/dashboard/schemas.py:
##########
@@ -1062,6 +1062,358 @@ 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
+
+ @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
+
+ @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")
+ )
+ if not clean_label:
+ continue
+ sanitized.append(subject.model_copy(update={"label": clean_label}))
+ return sanitized
+
+
+class ManageDashboardCertificationRequest(BaseModel):
+ """Request schema for setting or clearing dashboard certification.
+
+ ``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 — mirrors the ``slug``/``css``
+ clear-with-empty-string convention on ``update_dashboard``.
+ """
+
+ identifier: int | str = Field(
+ ...,
+ description=(
+ "Dashboard ID (integer), UUID, or slug. Same identifier shape "
+ "accepted by ``get_dashboard_info``."
+ ),
+ )
Review Comment:
**Suggestion:** `ManageDashboardCertificationRequest` accepts `identifier:
int | str` but does not reject booleans, so `identifier=true` is coerced to `1`
and can mutate the wrong dashboard. Add the same pre-validation used by the
owners/roles requests (or use a strict integer type) so boolean inputs are
rejected before lookup. [type error]
<details>
<summary><b>Severity Level:</b> Major ⚠️</summary>
```mdx
❌ Certification changes may affect unintended dashboard when identifier
boolean.
⚠️ Mis-targeted updates confuse MCP callers and governance workflows.
```
</details>
<details>
<summary><b>Steps of Reproduction ✅ </b></summary>
```mdx
1. The MCP FastMCP server registers the `manage_dashboard_certification`
tool defined in
`superset/mcp_service/dashboard/tool/manage_dashboard_certification.py:119-200`,
which
takes a `ManageDashboardCertificationRequest` from
`superset/mcp_service/dashboard/schemas.py:317-387` as its request model.
2. A caller invokes `manage_dashboard_certification` with a JSON body where
`"identifier":
true` (boolean), relying on the documented `identifier: int | str` field at
`superset/mcp_service/dashboard/schemas.py:1325-1331` to accept dashboard
identifiers.
3. Because `ManageDashboardCertificationRequest` lacks the
`reject_bool_identifier`
validator that exists on `ManageDashboardOwnersRequest.identifier`
(`schemas.py:102-109`)
and `ManageDashboardRolesRequest.identifier` (`schemas.py:236-243`),
Pydantic accepts the
boolean and coerces it to integer `1` for the `int | str` field, so
`request.identifier`
becomes `1`.
4. In `manage_dashboard_certification()` at
`superset/mcp_service/dashboard/tool/manage_dashboard_certification.py:140-167`,
the code
passes this coerced `identifier=1` into `_find_and_authorize_dashboard()`
(`manage_dashboard_certification.py:49-102`), which calls
`DashboardDAO.get_by_id_or_slug(identifier)` and then updates
`dashboard.certified_by` /
`dashboard.certification_details` and commits at lines 156-168, causing
certification
changes to be applied to the dashboard with ID 1 rather than the caller’s
intended target
when `identifier=true` was supplied.
```
</details>
[](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=6966eb3fa8934e6d975381c772d07c59&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=6966eb3fa8934e6d975381c772d07c59&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/schemas.py
**Line:** 1325:1331
**Comment:**
*Type Error: `ManageDashboardCertificationRequest` accepts `identifier:
int | str` but does not reject booleans, so `identifier=true` is coerced to `1`
and can mutate the wrong dashboard. Add the same pre-validation used by the
owners/roles requests (or use a strict integer type) so boolean inputs are
rejected before lookup.
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=0f634121c59bf8a1097b285cfe1fbb02b9f4bf157ff8af4bf5bbf5d33e3c69c9&reaction=like'>👍</a>
| <a
href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F41606&comment_hash=0f634121c59bf8a1097b285cfe1fbb02b9f4bf157ff8af4bf5bbf5d33e3c69c9&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]