aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3253725829


##########
superset/mcp_service/composite_token_verifier.py:
##########
@@ -0,0 +1,104 @@
+# 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.
+
+"""
+Composite token verifier for MCP authentication.
+
+Routes Bearer tokens to the appropriate verifier based on prefix:
+- Tokens matching FAB_API_KEY_PREFIXES (e.g. ``sst_``) are passed through
+  to the Flask layer where ``_resolve_user_from_api_key()`` handles
+  actual validation via FAB SecurityManager.
+- All other tokens are delegated to the wrapped JWT verifier (when one is
+  configured); when no JWT verifier is configured, non-API-key tokens are
+  rejected at the transport layer.
+"""
+
+import logging
+
+from fastmcp.server.auth import AccessToken
+from fastmcp.server.auth.providers.jwt import TokenVerifier
+
+logger = logging.getLogger(__name__)
+
+# Namespaced claim that flags an AccessToken as an API-key pass-through.
+# Namespacing avoids collision with custom claims an external IdP might
+# happen to mint on a JWT — a plain ``_api_key_passthrough`` claim could
+# be silently misidentified as a Superset API-key request.
+API_KEY_PASSTHROUGH_CLAIM = "_superset_mcp_api_key_passthrough"
+
+
+class CompositeTokenVerifier(TokenVerifier):
+    """Routes Bearer tokens between API key pass-through and JWT verification.
+
+    API key tokens (identified by prefix) are accepted at the transport layer
+    with a marker claim so that ``_resolve_user_from_jwt_context()`` can
+    detect them and fall through to ``_resolve_user_from_api_key()`` for
+    actual validation.
+
+    Args:
+        jwt_verifier: The wrapped JWT verifier for non-API-key tokens.
+            When ``None``, only API-key tokens are accepted; all other
+            Bearer tokens are rejected at the transport layer (used when
+            ``MCP_AUTH_ENABLED=False`` but ``FAB_API_KEY_ENABLED=True``).
+        api_key_prefixes: List of prefixes that identify API key tokens
+            (e.g. ``["sst_"]``).
+    """
+
+    def __init__(
+        self,
+        jwt_verifier: TokenVerifier | None,
+        api_key_prefixes: list[str],
+    ) -> None:
+        super().__init__(
+            base_url=getattr(jwt_verifier, "base_url", None),
+            required_scopes=getattr(jwt_verifier, "required_scopes", None) or 
[],
+        )
+        self._jwt_verifier = jwt_verifier
+        self._api_key_prefixes = tuple(api_key_prefixes)
+
+    async def verify_token(self, token: str) -> AccessToken | None:
+        """Verify a Bearer token.
+
+        If the token starts with an API key prefix, return a pass-through
+        AccessToken with a ``_api_key_passthrough`` claim. The Flask-layer

Review Comment:
   The docstring in the current code correctly uses 
`_superset_mcp_api_key_passthrough` (matching the `API_KEY_PASSTHROUGH_CLAIM` 
constant) — this was corrected in an earlier commit. The plain 
`_api_key_passthrough` name referenced here was from a draft version.



##########
superset/mcp_service/mcp_config.py:
##########
@@ -335,6 +335,21 @@
 
             auth_provider = JWTVerifier(**common_kwargs)
 
+        # Wrap with CompositeTokenVerifier when API key auth is enabled
+        # so that API key tokens (e.g. sst_...) pass through the transport
+        # layer instead of being rejected by the JWT verifier.
+        if app.config.get("FAB_API_KEY_ENABLED", False):
+            from superset.mcp_service.composite_token_verifier import (
+                CompositeTokenVerifier,
+            )
+

Review Comment:
   This flag is against an older commit. In the current code, the logger call 
at this location (`logger.warning('FAB_API_KEY_PREFIXES must be a string or 
list; using default')`) logs a static string with no format args or sensitive 
data. Should clear on the next CodeQL scan.



##########
superset/security/manager.py:
##########
@@ -1361,6 +1365,15 @@ def create_custom_permissions(self) -> None:
         self.add_permission_view_menu("can_tag", "Chart")
         self.add_permission_view_menu("can_tag", "Dashboard")
 
+        # API Key permissions (FAB's ApiKeyApi blueprint).
+        # Superset uses AppBuilder(update_perms=False) so FAB skips
+        # permission creation during blueprint registration. Create them
+        # explicitly here so that ``superset init`` picks them up and
+        # sync_role_definitions assigns them to the Admin role.
+        if current_app.config.get("FAB_API_KEY_ENABLED", False):
+            for perm in ("can_list", "can_create", "can_get", "can_delete"):
+                self.add_permission_view_menu(perm, "ApiKey")

Review Comment:
   `create_custom_permissions` itself has no new ApiKey logic — the admin-only 
classification happens via the `ADMIN_ONLY_VIEW_MENUS` class attribute. The 
test `test_api_key_view_menu_is_admin_only` in 
`tests/unit_tests/security/test_granular_export_permissions.py` covers this 
with an assertion and a doc comment explaining the guard.



-- 
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]

Reply via email to