aminghadersohi commented on code in PR #40354: URL: https://github.com/apache/superset/pull/40354#discussion_r3328094208
########## 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: Fixed — `IntegrityError` is caught in `update_role` after commit, the session is rolled back, and a second `find_role()` call retrieves the conflicting role to return a structured duplicate-name response. The `_check_rename` helper handles the pre-commit uniqueness check; the `except IntegrityError` block handles the post-commit race. Test `test_update_role_integrity_error_race_condition` verifies rollback is called. ########## 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: Fixed — `update_role` now checks the current role name against `AUTH_ROLE_ADMIN` and `AUTH_ROLE_PUBLIC` config values (via `current_app.config`) before allowing a rename. Attempting to rename either built-in role returns a structured error. Test `test_update_role_blocks_renaming_admin_role` covers this guard. ########## 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=True, + ), +) +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 + + if request.permission_ids is not None: + pvms = ( + db.session.query(PermissionView) + .filter(PermissionView.id.in_(request.permission_ids)) + .all() + ) + found_ids = {pvm.id for pvm in pvms} + missing = set(request.permission_ids) - found_ids + if missing: + await ctx.warning( + "Some permission_ids not found and will be skipped: %s" + % sorted(missing) + ) + role.permissions = pvms + + with event_logger.log_context(action="mcp.update_role.commit"): + db.session.commit() # pylint: disable=consider-using-transaction + + await ctx.info("Role updated: id=%s, name=%r" % (role.id, role.name)) + return UpdateRoleResponse(id=role.id, name=role.name) + + except Exception as exc: + await ctx.error( + "Unexpected error updating role: %s: %s" % (type(exc).__name__, str(exc)) + ) + raise Review Comment: Fixed — added an `except IntegrityError:` block in `update_role` that calls `db.session.rollback()` and returns a structured duplicate-name error, matching the pattern from `create_role`. Test `test_update_role_integrity_error_race_condition` verifies rollback is called and a structured error is returned. -- 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]
