Copilot commented on code in PR #40354: URL: https://github.com/apache/superset/pull/40354#discussion_r3285753332
########## superset/mcp_service/role/tool/create_role.py: ########## @@ -0,0 +1,97 @@ +# 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 superset_core.mcp.decorators import tool, ToolAnnotations + +from superset.extensions import 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: + from flask_appbuilder.security.sqla.models import PermissionView + + from superset import security_manager + from superset.extensions import db + + # 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: Role creation is only committed when `permission_ids` is non-empty. If `security_manager.add_role()` doesn't commit (it often requires an explicit `db.session.commit()` in Superset code), the new role can be rolled back when the Flask app context tears down, yet the tool returns success. Commit the session after `add_role()` (or wrap creation + permission assignment in a single transaction/commit) so `create_role` reliably persists the role even when no permissions are provided. ########## superset/mcp_service/role/schemas.py: ########## @@ -0,0 +1,46 @@ +# 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. + +"""Pydantic schemas for role-related MCP tools.""" + +from __future__ import annotations + +from pydantic import BaseModel, ConfigDict, Field + + +class CreateRoleRequest(BaseModel): + model_config = ConfigDict(populate_by_name=True) + + name: str = Field(..., description="Name for the new role. Must be unique.") + permission_ids: list[int] = Field( + default_factory=list, + description=( + "Optional list of PermissionView IDs to assign to the role. " + "These correspond to FAB permission-view-menu pairs " Review Comment: `CreateRoleRequest.name` has no validation/sanitization (e.g. empty/whitespace-only names, or names longer than the DB column). The underlying FAB `ab_role.name` is `String(64), unique=True, nullable=False`, so invalid input can raise DB errors and create inconsistent behavior. Consider stripping whitespace and enforcing `min_length=1`, `max_length=64`, and using the existing `sanitize_user_input()` helper to defensively sanitize the role name before persistence. ########## superset/mcp_service/role/tool/create_role.py: ########## @@ -0,0 +1,97 @@ +# 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 superset_core.mcp.decorators import tool, ToolAnnotations + +from superset.extensions import 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. + Review Comment: New MCP mutation tool `create_role` and its request/response schemas aren’t covered by unit tests. Other MCP tools (e.g. `create_virtual_dataset`) have schema validation tests + tool behavior tests (success, duplicate, permission assignment, permission denied), and adding similar tests here would prevent regressions in RBAC gating and DB behavior. ########## superset/mcp_service/role/tool/create_role.py: ########## @@ -0,0 +1,97 @@ +# 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 superset_core.mcp.decorators import tool, ToolAnnotations + +from superset.extensions import 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: + from flask_appbuilder.security.sqla.models import PermissionView + + from superset import security_manager + from superset.extensions import db + + # 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: There’s a race between `find_role()` and `add_role()` when two requests try to create the same role concurrently. Since `ab_role.name` is unique, the second request can hit an `IntegrityError` and bubble up as a 500, rather than returning the intended structured "already exists" response. Catch `IntegrityError`, roll back the session, re-query the role by name, and return the duplicate-role error message consistently. -- 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]
