codeant-ai-for-open-source[bot] commented on code in PR #40354: URL: https://github.com/apache/superset/pull/40354#discussion_r3326673455
########## superset/mcp_service/role/tool/create_role.py: ########## @@ -0,0 +1,95 @@ +# 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. + +import logging + +from fastmcp import Context +from flask_appbuilder.security.sqla.models import PermissionView +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset import security_manager +from superset.extensions import db, event_logger +from superset.mcp_service.role.schemas import CreateRoleRequest, CreateRoleResponse + +logger = logging.getLogger(__name__) + + +@tool( + tags=["mutate"], + class_permission_name="security", + method_permission_name="write", + annotations=ToolAnnotations( + title="Create a new role", + readOnlyHint=False, + destructiveHint=False, + ), +) +async def create_role(request: CreateRoleRequest, ctx: Context) -> CreateRoleResponse: + """Create a new FAB role, optionally assigning PermissionView IDs. + + Admin-only. Use this when you need to provision a new role in Superset's + role-based access control system. The created role starts with no + permissions unless ``permission_ids`` are supplied. + + Workflow: + 1. Call this tool with a unique role name + 2. Optionally supply ``permission_ids`` to pre-assign permissions + 3. Use the returned ``id`` to reference the role in downstream operations + """ + await ctx.info( + "Creating role: name=%r, permission_ids=%s" + % (request.name, request.permission_ids) + ) + + try: + # Reject creation if role already exists + existing = security_manager.find_role(request.name) + if existing is not None: + await ctx.warning("Role already exists: name=%r" % (request.name,)) + return CreateRoleResponse( + error=f"Role '{request.name}' already exists (id={existing.id})." + ) + + with event_logger.log_context(action="mcp.create_role.create"): + role = security_manager.add_role(request.name) Review Comment: **Suggestion:** The uniqueness check is a TOCTOU race: two concurrent requests with the same role name can both pass `find_role`, and one will fail later at insert time with an unstructured exception instead of the documented structured duplicate-role response. Make creation atomic (or catch DB uniqueness violations explicitly) and return `CreateRoleResponse(error=...)` for that conflict path. [race condition] <details> <summary><b>Severity Level:</b> Major ⚠️</summary> ```mdx - ⚠️ MCP `create_role` tool can return generic errors on conflict. - ⚠️ Concurrent admin role provisioning may intermittently fail unexpectedly. - ⚠️ Violates `CreateRoleRequest.name` documented uniqueness contract. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Start the MCP server so that tools are registered; `init_fastmcp_server()` in `superset/mcp_service/app.py:107-154` imports `create_role` at `superset/mcp_service/app.py:66-69`, which registers the `create_role` tool defined in `superset/mcp_service/role/tool/create_role.py:41-89`. 2. From two MCP clients (or one client issuing concurrent calls), invoke the `create_role` tool with the same `name` value, e.g. `{"name": "MyConcurrentRole"}`, so both requests enter `create_role()` in `superset/mcp_service/role/tool/create_role.py:41-89`. 3. In each request, the function executes the duplicate-name precheck at `create_role.py:60-65`, where `security_manager.find_role(request.name)` returns `None` for both calls because neither has created the role yet, so both skip the structured duplicate-role error path and proceed into the creation block at `create_role.py:67-69`. 4. Both requests call `security_manager.add_role(request.name)` at `create_role.py:68`; one of them eventually hits a database-level uniqueness conflict for the role name (or otherwise violates the "Must be unique" contract documented in `CreateRoleRequest.name` at `superset/mcp_service/role/schemas.py:28-36`), causing an exception during insert/commit that is only handled by the generic `except Exception` block at `create_role.py:91-95`, which logs `ctx.error(...)` and re-raises. The failing caller therefore receives an unstructured MCP/server error rather than a `CreateRoleResponse` with a populated `error` field indicating the duplicate-role condition. ``` </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=f019b141d6d94d8a9645f1990108cf5b&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=f019b141d6d94d8a9645f1990108cf5b&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/role/tool/create_role.py **Line:** 60:68 **Comment:** *Race Condition: The uniqueness check is a TOCTOU race: two concurrent requests with the same role name can both pass `find_role`, and one will fail later at insert time with an unstructured exception instead of the documented structured duplicate-role response. Make creation atomic (or catch DB uniqueness violations explicitly) and return `CreateRoleResponse(error=...)` for that conflict path. 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%2F40354&comment_hash=205ae9f075231e28e7a386d93d50d752029229937f1b0e177ac9f2d525beef59&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40354&comment_hash=205ae9f075231e28e7a386d93d50d752029229937f1b0e177ac9f2d525beef59&reaction=dislike'>👎</a> ########## superset/mcp_service/role/tool/update_role.py: ########## @@ -0,0 +1,105 @@ +# 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. + +import logging + +from fastmcp import Context +from flask_appbuilder.security.sqla.models import PermissionView +from superset_core.mcp.decorators import tool, ToolAnnotations + +from superset import security_manager +from superset.extensions import db, event_logger +from superset.mcp_service.role.schemas import UpdateRoleRequest, UpdateRoleResponse + +logger = logging.getLogger(__name__) + + +@tool( + tags=["mutate"], + class_permission_name="security", + method_permission_name="write", + annotations=ToolAnnotations( + title="Update an existing role", + readOnlyHint=False, + destructiveHint=False, + ), +) +async def update_role(request: UpdateRoleRequest, ctx: Context) -> UpdateRoleResponse: + """Update an existing FAB role's name and/or permission assignments. + + Admin-only. Use this when you need to rename a role or change its + PermissionView assignments. When ``permission_ids`` is supplied it + replaces the full existing permission set — partial updates are not + supported. + + Workflow: + 1. Call with the role ``id`` to update + 2. Supply ``name`` to rename the role (must be unique) + 3. Supply ``permission_ids`` to replace all existing permissions + 4. Omit a field to leave it unchanged + """ + await ctx.info( + "Updating role: id=%s, name=%r, permission_ids=%s" + % (request.id, request.name, request.permission_ids) + ) + + try: + roles = security_manager.find_roles_by_id([request.id]) + if not roles: + await ctx.warning("Role not found: id=%s" % (request.id,)) + return UpdateRoleResponse(error=f"Role with id={request.id} not found.") + + role = roles[0] + + if request.name is not None: + existing = security_manager.find_role(request.name) + if existing is not None and existing.id != role.id: + await ctx.warning("Role name already in use: name=%r" % (request.name,)) + return UpdateRoleResponse( + error=( + f"Role name '{request.name}' is already in use" + f" (id={existing.id})." + ) + ) + role.name = request.name Review Comment: **Suggestion:** This tool allows renaming core built-in roles (including the configured admin role) without any guard. Superset's admin checks are name-based (`AUTH_ROLE_ADMIN`), so renaming that role can immediately break admin detection and effectively lock users out of admin-only behavior. Block renaming of protected/built-in roles (at minimum the configured admin role) and return a validation error. [security] <details> <summary><b>Severity Level:</b> Critical 🚨</summary> ```mdx - ❌ Renaming admin role can cause admins to lose admin status. - ❌ Dashboard access and curation logic may misclassify true admins. - ❌ Ownership checks can incorrectly deny modifications to resources. - ⚠️ Background task visibility may be restricted for former admins. ``` </details> <details> <summary><b>Steps of Reproduction ✅ </b></summary> ```mdx 1. Superset's security manager defines admin detection in `superset/security/manager.py:8-17`, where `is_admin()` returns `True` if `get_conf()["AUTH_ROLE_ADMIN"]` matches any `role.name` in `self.get_user_roles()`, and the default admin role is created as `"Admin"` in `sync_role_definitions()` at `superset/security/manager.py:12-16` (using `self.set_role("Admin", ...)`). 2. Start the MCP server so that the `update_role` tool is registered via `superset/mcp_service/app.py:66-69`, which imports `superset.mcp_service.role.tool` and thus the `update_role` implementation in `superset/mcp_service/role/tool/update_role.py:41-99`. 3. As a current admin user (whose roles include the configured admin role name, typically `"Admin"`), call the `update_role` MCP tool with the `id` of that admin role and a different `name`, e.g. `{"id": <admin_role_id>, "name": "SuperAdmin"}`, so the code in `update_role.py:61-79` loads the role, passes the uniqueness precheck at `update_role.py:69-77`, and then executes `role.name = request.name` at `update_role.py:78` followed by `db.session.commit()` at `update_role.py:95-96`. 4. After the rename commit, the user's roles now include `"SuperAdmin"` instead of the configured admin role name, so `security_manager.is_admin()` at `superset/security/manager.py:8-17` returns `False`; downstream admin-only checks that rely on `is_admin()`, such as dashboard filtering (`superset/dashboards/filters.py:7-9`), resource ownership and access checks (`superset/security/manager.py:3107-3119`, `superset/security/manager.py:3548-3559`), and background task access control (`superset/tasks/filters.py:3-7`), will now treat this user as a non-admin, effectively breaking name-based authorization for the built-in admin role and risking partial or complete loss of admin capabilities. ``` </details> [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=5182934783554ec3b93d6f7d536d3d7c&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=5182934783554ec3b93d6f7d536d3d7c&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/role/tool/update_role.py **Line:** 78:78 **Comment:** *Security: This tool allows renaming core built-in roles (including the configured admin role) without any guard. Superset's admin checks are name-based (`AUTH_ROLE_ADMIN`), so renaming that role can immediately break admin detection and effectively lock users out of admin-only behavior. Block renaming of protected/built-in roles (at minimum the configured admin role) and return a validation error. 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%2F40354&comment_hash=14ae871cc431b6004dc265e09843ce2a6dcf828cf8533a625612da4f5a9f91dc&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40354&comment_hash=14ae871cc431b6004dc265e09843ce2a6dcf828cf8533a625612da4f5a9f91dc&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]
