You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "aminghadersohi (via GitHub)" <gi...@apache.org> on 2026/04/23 23:53:16 UTC
[PR] fix(mcp): create ApiKey permissions on init and support API keys with JWT auth [superset]
aminghadersohi opened a new pull request, #39604:
URL: https://github.com/apache/superset/pull/39604
### SUMMARY
Two fixes for MCP API key authentication that were discovered while testing #39437:
**1. `superset init` now creates ApiKey FAB permissions**
When `FAB_API_KEY_ENABLED=True`, the `/api/v1/security/api_keys/` endpoints returned 403 because the required FAB permissions (`can_list`, `can_create`, `can_get`, `can_delete` on `ApiKey`) were never created. Superset uses `AppBuilder(update_perms=False)`, so FAB skips permission creation during blueprint registration. The fix adds ApiKey permissions to `create_custom_permissions()` in the SecurityManager, which is called by `sync_role_definitions()` during `superset init`.
**2. CompositeTokenVerifier allows API key tokens to coexist with JWT auth**
When `MCP_AUTH_ENABLED=True`, the `JWTVerifier` at the FastMCP transport layer rejected all non-JWT Bearer tokens (including `sst_...` API keys) before they could reach the Flask-level `_resolve_user_from_api_key()` handler. The new `CompositeTokenVerifier` wraps the JWT verifier and detects API key prefixes — matching tokens pass through with a marker claim so the existing auth priority chain handles validation.
**Changes:**
- `superset/security/manager.py`: Add ApiKey permissions to `create_custom_permissions()` when `FAB_API_KEY_ENABLED=True`
- `superset/mcp_service/composite_token_verifier.py`: New `CompositeTokenVerifier` that routes tokens by prefix
- `superset/mcp_service/mcp_config.py`: Wrap JWT verifier with `CompositeTokenVerifier` when API keys enabled
- `superset/mcp_service/auth.py`: Detect `_api_key_passthrough` claim in `_resolve_user_from_jwt_context()` and fall through to API key auth
### BEFORE/AFTER SCREENSHOTS OR ANIMATED GIF
N/A — auth infrastructure changes with no UI impact.
### TESTING INSTRUCTIONS
1. Set `FAB_API_KEY_ENABLED = True` and `FEATURE_FLAGS = {"FAB_API_KEY_ENABLED": True}` in `superset_config.py`
2. Run `superset init` — should create ApiKey permissions (verify: Admin role now has `can_list`, `can_create`, `can_get`, `can_delete` on `ApiKey`)
3. Navigate to `/profile/` — API Keys section should load without errors
4. Create an API key via the UI
5. Test with MCP (even with `MCP_AUTH_ENABLED=True`):
```bash
curl -s -X POST http://localhost:5008/mcp \
-H "Authorization: Bearer sst_<your-key>" \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"call_tool","arguments":{"name":"get_instance_info","arguments":{}}}}'
```
6. Run tests: `pytest tests/unit_tests/mcp_service/test_auth_api_key.py tests/unit_tests/mcp_service/test_composite_token_verifier.py -v`
### ADDITIONAL INFORMATION
- [ ] Has associated issue:
- [x] Required feature flags: `FAB_API_KEY_ENABLED`
- [ ] Changes UI
- [ ] Includes DB Migration
- [ ] Introduces new feature or API
- [ ] Removes existing feature or API
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): create ApiKey permissions on init and support API keys with JWT auth [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4309254242
<!-- Bito Reply -->
The CodeQL alert indicates logging of sensitive data (password), but the code logs API key prefixes (e.g., ["sst_"]), which are configuration values, not actual passwords or secrets. This seems like a false positive. The info-level log aids debugging API key authentication setup.
**superset/mcp_service/mcp_config.py**
```
logger.info("API key auth enabled for MCP (prefixes: %s)", api_key_prefixes)
```
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3253538908
##########
superset/mcp_service/mcp_config.py:
##########
@@ -284,56 +287,88 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
- else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception: # noqa: BLE001 — JWT lib raises many types; broad catch intentional
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ api_key_prefixes = app.config.get("FAB_API_KEY_PREFIXES", ["sst_"])
+ logger.info("API key auth enabled for MCP")
+ return CompositeTokenVerifier(
+ jwt_verifier=jwt_verifier,
+ api_key_prefixes=api_key_prefixes,
+ )
Review Comment:
Verified in code: `mcp_config.py` now type-narrows `raw_prefixes: str | Sequence[str]` and handles the string case explicitly. Commit: https://github.com/aminghadersohi/superset/commit/a1c99167a2 and https://github.com/aminghadersohi/superset/commit/75af98f7d1
##########
superset/mcp_service/composite_token_verifier.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.
+
+"""
+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)
+
Review Comment:
Verified in code: `CompositeTokenVerifier.__init__` now filters with `isinstance(p, str) and p.strip()`, logs a warning with the count of invalid entries, and stores only valid prefixes. Commit: https://github.com/aminghadersohi/superset/commit/d19470f60c
##########
superset/mcp_service/mcp_config.py:
##########
@@ -291,56 +294,94 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception: # noqa: BLE001 — JWT lib raises many types; broad catch intentional
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ raw_prefixes = app.config.get("FAB_API_KEY_PREFIXES", ["sst_"])
+ # Normalize: a plain string (e.g. "sst_") would iterate as characters;
+ # wrap it in a list so CompositeTokenVerifier receives a proper sequence.
+ if isinstance(raw_prefixes, str):
+ api_key_prefixes = [raw_prefixes]
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ api_key_prefixes = list(raw_prefixes)
Review Comment:
Fixed: `raw_prefixes` is now annotated as `str | Sequence[str]` so mypy narrows it correctly in both branches — `list[str] = [raw_prefixes]` in the string case and `list(raw_prefixes)` (which mypy infers as `list[str]`) in the else branch. Passes `pre-commit run mypy`. Commit: https://github.com/aminghadersohi/superset/commit/75af98f7d1
##########
superset/mcp_service/mcp_config.py:
##########
@@ -20,12 +20,15 @@
import secrets
from typing import Any, Dict, Optional
+from fastmcp.server.auth.providers.jwt import JWTVerifier
Review Comment:
To confirm: `mcp_config.py` is only ever imported from MCP-specific code paths that are themselves lazy-loaded (e.g. `core_mcp_injection.py` wraps all mcp imports in functions). Non-MCP deployments never touch this module. If you'd prefer an explicit guard (`try/except ImportError`) let me know and I'll add it.
##########
superset/mcp_service/mcp_config.py:
##########
@@ -291,56 +294,94 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception: # noqa: BLE001 — JWT lib raises many types; broad catch intentional
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
Review Comment:
Verified: `except (ValueError, JoseError)` is in the code. Checked fastmcp source — `JWTVerifier.__init__` only raises `ValueError` (config validation only, no network I/O at construction). `JoseError` is added for forward-compatibility. Removed the `# noqa: BLE001` comment. Commit: https://github.com/aminghadersohi/superset/commit/75af98f7d1
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3244925526
##########
tests/unit_tests/mcp_service/test_composite_token_verifier.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.
+
+"""Tests for CompositeTokenVerifier."""
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from fastmcp.server.auth import AccessToken
+
+from superset.mcp_service.composite_token_verifier import CompositeTokenVerifier
+
+
+@pytest.fixture
+def mock_jwt_verifier():
+ verifier = MagicMock()
+ verifier.required_scopes = []
+ verifier.verify_token = AsyncMock()
+ return verifier
+
+
+@pytest.fixture
+def composite_verifier(mock_jwt_verifier):
Review Comment:
Addressed.
##########
tests/unit_tests/mcp_service/test_composite_token_verifier.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.
+
+"""Tests for CompositeTokenVerifier."""
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from fastmcp.server.auth import AccessToken
+
+from superset.mcp_service.composite_token_verifier import CompositeTokenVerifier
+
+
+@pytest.fixture
+def mock_jwt_verifier():
+ verifier = MagicMock()
+ verifier.required_scopes = []
+ verifier.verify_token = AsyncMock()
+ return verifier
+
+
+@pytest.fixture
+def composite_verifier(mock_jwt_verifier):
+ return CompositeTokenVerifier(
+ jwt_verifier=mock_jwt_verifier,
+ api_key_prefixes=["sst_", "pat_"],
+ )
+
+
+@pytest.mark.asyncio
+async def test_api_key_token_returns_passthrough(composite_verifier) -> None:
+ """Tokens matching an API key prefix return a pass-through AccessToken."""
+ api_key = "sst_abc123secret" # noqa: S105
+ result = await composite_verifier.verify_token(api_key)
+
+ assert result is not None
+ assert result.token == api_key
+ assert result.client_id == "api_key"
+ assert result.claims.get("_api_key_passthrough") is True
+
+
+@pytest.mark.asyncio
+async def test_second_prefix_matches(composite_verifier) -> None:
+ """All configured prefixes are checked, not just the first."""
+ result = await composite_verifier.verify_token("pat_mytoken")
+
+ assert result is not None
+ assert result.claims.get("_api_key_passthrough") is True
+
+
+@pytest.mark.asyncio
+async def test_jwt_token_delegates_to_wrapped_verifier(
+ composite_verifier, mock_jwt_verifier
+) -> None:
+ """Non-API-key tokens are delegated to the wrapped JWT verifier."""
+ jwt_token = "eyJhbGciOiJSUzI1NiJ9.jwt_payload" # noqa: S105
+ jwt_result = AccessToken(
+ token=jwt_token,
+ client_id="oauth_client",
+ scopes=["read"],
+ claims={"sub": "user1"},
+ )
+ mock_jwt_verifier.verify_token.return_value = jwt_result
+
+ result = await composite_verifier.verify_token("eyJhbGciOiJSUzI1NiJ9.jwt_payload")
+
+ assert result is jwt_result
+ mock_jwt_verifier.verify_token.assert_awaited_once_with(
+ "eyJhbGciOiJSUzI1NiJ9.jwt_payload"
+ )
+
+
+@pytest.mark.asyncio
+async def test_invalid_jwt_returns_none(composite_verifier, mock_jwt_verifier) -> None:
+ """When the JWT verifier rejects a token, None is returned."""
+ mock_jwt_verifier.verify_token.return_value = None
+
+ result = await composite_verifier.verify_token("not_a_valid_token")
+
+ assert result is None
+ mock_jwt_verifier.verify_token.assert_awaited_once()
+
+
+@pytest.mark.asyncio
+async def test_api_key_does_not_call_jwt_verifier(
+ composite_verifier, mock_jwt_verifier
+) -> None:
Review Comment:
Addressed.
##########
superset/security/manager.py:
##########
@@ -1361,6 +1361,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:
Addressed.
##########
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:
Addressed.
##########
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:
Addressed.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4458400945
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3329454504
##########
superset/mcp_service/mcp_config.py:
##########
@@ -284,56 +287,88 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
- else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception:
Review Comment:
Fixed in a subsequent commit. The bare `except Exception:` was replaced with `except (ValueError, JoseError):` — the two concrete error types that `_build_jwt_verifier` can raise. The non-iterable-prefix guard uses `except TypeError:`. No unexpected exceptions will be silently swallowed.
##########
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:
The behavior was refactored in subsequent commits. Rather than registering ApiKey permissions in `create_custom_permissions()`, `ApiKey` is now unconditionally included in `ADMIN_ONLY_VIEW_MENUS`. The regression test `test_api_key_view_menu_is_admin_only()` in `tests/unit_tests/security/test_granular_export_permissions.py` asserts this entry stays there and prevents the access-control hole from being silently re-opened.
##########
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:
Fixed. The `verify_token` docstring now references the namespaced `API_KEY_PASSTHROUGH_CLAIM` constant (`_superset_mcp_api_key_passthrough`) instead of the old `_api_key_passthrough` name.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3342389305
##########
tests/unit_tests/mcp_service/test_mcp_server.py:
##########
@@ -158,3 +158,26 @@ def test_create_event_store_returns_none_when_redis_store_fails():
result = create_event_store(config)
assert result is None
+
+
+def test_create_auth_provider_uses_default_factory_for_mcp_api_key_only() -> None:
+ """MCP_API_KEY_ENABLED=True should install auth even when FAB API keys are off."""
+ from superset.mcp_service.server import _create_auth_provider
+
+ flask_app = MagicMock()
+ flask_app.config.get.side_effect = lambda key, default=None: {
+ "MCP_AUTH_FACTORY": None,
+ "MCP_AUTH_ENABLED": False,
+ "MCP_API_KEY_ENABLED": True,
+ "FAB_API_KEY_ENABLED": False,
+ }.get(key, default)
+ auth_provider = MagicMock()
+
+ with patch(
+ "superset.mcp_service.mcp_config.create_default_mcp_auth_factory",
+ return_value=auth_provider,
+ ) as create_default_mcp_auth_factory:
+ result = _create_auth_provider(flask_app)
+
+ assert result is auth_provider
+ create_default_mcp_auth_factory.assert_called_once_with(flask_app)
Review Comment:
<!-- Bito Reply -->
The added tests in `test_mcp_config.py` correctly address the concern by directly invoking `_build_composite_verifier` with the specified inputs (string, list, and `None`). This ensures the string-normalization logic is now covered, resolving the identified gap in test coverage.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4616403543
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3357277884
##########
tests/unit_tests/mcp_service/test_mcp_config.py:
##########
@@ -224,3 +224,133 @@ def test_get_mcp_config_respects_app_config_override() -> None:
custom = {"execute_sql", "health_check"}
config = get_mcp_config({"MCP_DISABLED_TOOLS": custom})
assert config["MCP_DISABLED_TOOLS"] == custom
+
+
+def test_build_composite_verifier_string_prefix():
+ """A plain-string FAB_API_KEY_PREFIXES is wrapped into a single-element list."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ "sst_" if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_",)
+
+
+def test_build_composite_verifier_list_prefix():
+ """A list FAB_API_KEY_PREFIXES is passed through as-is."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ ["sst_", "api_"] if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_", "api_")
+
+
+def test_build_composite_verifier_invalid_prefix_falls_back_to_default():
+ """A non-iterable FAB_API_KEY_PREFIXES (e.g. None) falls back to ['sst_']."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ None if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_",)
+
+
+# -- get_mcp_api_key_enabled --
+
+
+def test_get_mcp_api_key_enabled_explicit_true():
+ """MCP_API_KEY_ENABLED=True returns True regardless of FAB setting."""
+ from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ True if key == "MCP_API_KEY_ENABLED" else default
+ )
+
+ assert get_mcp_api_key_enabled(mock_app) is True
Review Comment:
Added in 65bfa38be6: `test_get_mcp_api_key_enabled_fab_fallback_logs_startup_warning` calls `get_mcp_api_key_enabled(mock_app, startup_warning=True)` with `FAB_API_KEY_ENABLED=True` (and `MCP_API_KEY_ENABLED` unset), patches `superset.mcp_service.mcp_config.logger`, and asserts `logger.warning` was called once (plus the return value is `True`).
##########
tests/unit_tests/mcp_service/test_mcp_config.py:
##########
@@ -224,3 +224,133 @@ def test_get_mcp_config_respects_app_config_override() -> None:
custom = {"execute_sql", "health_check"}
config = get_mcp_config({"MCP_DISABLED_TOOLS": custom})
assert config["MCP_DISABLED_TOOLS"] == custom
+
+
+def test_build_composite_verifier_string_prefix():
+ """A plain-string FAB_API_KEY_PREFIXES is wrapped into a single-element list."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ "sst_" if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_",)
+
+
+def test_build_composite_verifier_list_prefix():
+ """A list FAB_API_KEY_PREFIXES is passed through as-is."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ ["sst_", "api_"] if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_", "api_")
+
+
+def test_build_composite_verifier_invalid_prefix_falls_back_to_default():
+ """A non-iterable FAB_API_KEY_PREFIXES (e.g. None) falls back to ['sst_']."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ None if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_",)
+
+
+# -- get_mcp_api_key_enabled --
+
+
+def test_get_mcp_api_key_enabled_explicit_true():
+ """MCP_API_KEY_ENABLED=True returns True regardless of FAB setting."""
+ from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ True if key == "MCP_API_KEY_ENABLED" else default
+ )
+
+ assert get_mcp_api_key_enabled(mock_app) is True
+
+
+def test_get_mcp_api_key_enabled_explicit_false():
+ """MCP_API_KEY_ENABLED=False returns False even when FAB setting is True."""
+ from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ False if key == "MCP_API_KEY_ENABLED" else True
+ )
+
+ assert get_mcp_api_key_enabled(mock_app) is False
+
+
+def test_get_mcp_api_key_enabled_falls_back_to_fab():
+ """When MCP_API_KEY_ENABLED is not set, falls back to FAB_API_KEY_ENABLED."""
+ from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ None
+ if key == "MCP_API_KEY_ENABLED"
+ else (True if key == "FAB_API_KEY_ENABLED" else default)
+ )
+
+ assert get_mcp_api_key_enabled(mock_app) is True
+
+
+def test_get_mcp_api_key_enabled_both_absent_returns_false():
+ """When neither setting is configured, returns False."""
+ from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
+
+ mock_app = MagicMock()
+ mock_app.config.get.return_value = None
+
+ assert get_mcp_api_key_enabled(mock_app) is False
+
+
+# -- create_default_mcp_auth_factory --
+
+
+def test_create_default_mcp_auth_factory_returns_none_when_disabled():
+ """Returns None when neither MCP_AUTH_ENABLED nor API key auth is on."""
+ from superset.mcp_service.mcp_config import create_default_mcp_auth_factory
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ False
+ if key in ("MCP_AUTH_ENABLED", "MCP_API_KEY_ENABLED", "FAB_API_KEY_ENABLED")
+ else default
+ )
+
+ result = create_default_mcp_auth_factory(mock_app)
+
+ assert result is None
+
+
+def test_create_default_mcp_auth_factory_api_key_only():
+ """Returns a CompositeTokenVerifier when only API key auth is enabled."""
+ from superset.mcp_service.composite_token_verifier import CompositeTokenVerifier
+ from superset.mcp_service.mcp_config import create_default_mcp_auth_factory
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: {
+ "MCP_AUTH_ENABLED": False,
+ "MCP_API_KEY_ENABLED": True,
+ "FAB_API_KEY_PREFIXES": ["sst_"],
+ "MCP_REQUIRED_SCOPES": [],
+ }.get(key, default)
+
+ result = create_default_mcp_auth_factory(mock_app)
+
+ assert isinstance(result, CompositeTokenVerifier)
Review Comment:
Added in 65bfa38be6: three tests covering the JWT branches of `create_default_mcp_auth_factory` — `test_create_default_mcp_auth_factory_jwt_with_keys` (JWT enabled with a secret, API key off → returns the built verifier), `test_create_default_mcp_auth_factory_jwt_enabled_without_keys_returns_none` (JWT enabled, no keys/secret, no API-key fallback → `None`, warning logged), and `test_create_default_mcp_auth_factory_jwt_build_failure_returns_none` (`_build_jwt_verifier` raises `ValueError`, no API-key fallback → `None`, error logged).
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3253523228
##########
superset/mcp_service/mcp_config.py:
##########
@@ -20,12 +20,15 @@
import secrets
from typing import Any, Dict, Optional
+from fastmcp.server.auth.providers.jwt import JWTVerifier
Review Comment:
`mcp_config.py` is only ever imported via MCP-specific code paths (e.g. `core_mcp_injection.py` guards all mcp imports inside lazy functions). So `fastmcp` is effectively a conditional dependency — it is required when MCP is used but does not affect non-MCP deployments.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3242877389
##########
superset/mcp_service/composite_token_verifier.py:
##########
@@ -0,0 +1,113 @@
+# 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
+ valid: list[str] = [
+ p for p in api_key_prefixes if isinstance(p, str) and p.strip()
+ ]
+ invalid = [p for p in api_key_prefixes if p not in valid]
+ if invalid:
+ logger.warning(
+ "FAB_API_KEY_PREFIXES contains invalid entries (ignored): %r", invalid
Review Comment:
## CodeQL / Clear-text logging of sensitive information
This expression logs [sensitive data (password)](1) as clear text.
This expression logs [sensitive data (password)](2) as clear text.
This expression logs [sensitive data (password)](2) as clear text.
[Show more details](https://github.com/apache/superset/security/code-scanning/2284)
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3305650861
##########
superset/mcp_service/mcp_config.py:
##########
@@ -284,56 +287,88 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
- else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception:
Review Comment:
<!-- Bito Reply -->
The suggestion in the PR comment recommends replacing a bare `Exception` catch with specific exception types (`ValueError`, `KeyError`, `RuntimeError`) to avoid catching unintended errors. This is a valid and recommended practice in Python for error handling, as it increases code clarity and prevents masking unrelated issues. The suggestion is appropriate and should be applied if it aligns with the intended error-handling logic.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4625224093
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4555961096
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4523644813
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3350595652
##########
superset/mcp_service/mcp_config.py:
##########
@@ -303,57 +314,142 @@
}
+def get_mcp_api_key_enabled(app: Flask, *, startup_warning: bool = False) -> bool:
+ """Return whether API key auth is enabled for the MCP transport.
+
+ Prefers ``MCP_API_KEY_ENABLED`` when explicitly set; falls back to
+ ``FAB_API_KEY_ENABLED``. When ``startup_warning=True`` and the value
+ is inherited from ``FAB_API_KEY_ENABLED``, logs a warning so operators
+ know a FAB config change now also affects the MCP transport.
+ """
+ if (mcp_setting := app.config.get("MCP_API_KEY_ENABLED", None)) is not None:
+ return bool(mcp_setting)
+ fab_enabled = bool(app.config.get("FAB_API_KEY_ENABLED", False))
+ if startup_warning and fab_enabled:
+ logger.warning(
+ "MCP API key auth is enabled via FAB_API_KEY_ENABLED=True. "
+ "Set MCP_API_KEY_ENABLED=True to silence this warning or "
+ "MCP_API_KEY_ENABLED=False to disable API keys on the MCP "
+ "transport without affecting the FAB REST API."
+ )
+ return fab_enabled
+
+
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``MCP_API_KEY_ENABLED=True`` (or ``FAB_API_KEY_ENABLED=True``
+ as a fallback) — API-key-only verifier that rejects all non-API-key
+ Bearer tokens at the transport.
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ ``MCP_API_KEY_ENABLED=None`` (default) defers to ``FAB_API_KEY_ENABLED``
+ and logs a startup warning when that setting is True, so operators are
+ aware that a FAB config change now also affects the MCP transport.
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = get_mcp_api_key_enabled(app, startup_warning=True)
+
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
- else:
- # MCPJWTVerifier: minimal logging + browser-friendly error page.
- from superset.mcp_service.jwt_verifier import MCPJWTVerifier
-
- auth_provider = MCPJWTVerifier(**common_kwargs)
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except (ValueError, JoseError):
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ return _build_composite_verifier(app, jwt_verifier)
+
+ return jwt_verifier
+
+
+def _build_composite_verifier(app: Flask, jwt_verifier: Any) -> CompositeTokenVerifier:
+ """Build a CompositeTokenVerifier with API key prefixes from config."""
+ if required_scopes := app.config.get("MCP_REQUIRED_SCOPES", []):
+ logger.debug(
+ "MCP_REQUIRED_SCOPES is configured but API key tokens bypass "
+ "scope enforcement. API key holders gain access regardless of "
+ "MCP_REQUIRED_SCOPES=%r.",
+ required_scopes,
+ )
+ raw_prefixes: str | Sequence[str] = app.config.get("FAB_API_KEY_PREFIXES", ["sst_"])
+ # Normalize: a plain string (e.g. "sst_") would iterate as characters;
+ # wrap it in a list so CompositeTokenVerifier receives a proper sequence.
+ # Guard against non-iterable config values (e.g. None, integers) that
+ # would raise TypeError and cause _create_auth_provider to fail open.
+ if isinstance(raw_prefixes, str):
+ api_key_prefixes: list[str] = [raw_prefixes]
+ else:
+ try:
+ api_key_prefixes = list(raw_prefixes)
+ except TypeError:
+ logger.warning(
+ "FAB_API_KEY_PREFIXES must be a string or list; using default"
+ )
+ api_key_prefixes = ["sst_"]
+ logger.info("API key auth enabled for MCP")
+ return CompositeTokenVerifier(
+ jwt_verifier=jwt_verifier,
+ api_key_prefixes=api_key_prefixes,
+ app=app,
+ )
+
+
+def _build_jwt_verifier(
+ app: Flask,
+ jwks_uri: Optional[str],
+ public_key: Optional[str],
+ secret: Optional[str],
+) -> JWTVerifier:
+ """Construct the JWT verifier from configured keys/secret."""
+ debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+
+ common_kwargs: Dict[str, Any] = {
+ "issuer": app.config.get("MCP_JWT_ISSUER"),
+ "audience": app.config.get("MCP_JWT_AUDIENCE"),
+ "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
+ }
- return auth_provider
- except Exception:
- # Do not log the exception — it may contain the HS256 secret
- # from common_kwargs["public_key"]
- logger.error("Failed to create MCP auth provider")
- return None
+ # For HS256 (symmetric), use the secret as the public_key parameter
+ if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
+ common_kwargs["public_key"] = secret
+ common_kwargs["algorithm"] = "HS256"
+ else:
+ # For RS256 (asymmetric), use public key or JWKS
+ common_kwargs["jwks_uri"] = jwks_uri
+ common_kwargs["public_key"] = public_key
+ common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
+
+ if debug_errors:
+ # DetailedJWTVerifier: detailed server-side logging of JWT
+ # validation failures. HTTP responses are always generic per
+ # RFC 6750 Section 3.1.
+ return DetailedJWTVerifier(**common_kwargs)
+
+ # MCPJWTVerifier: minimal logging + browser-friendly error page.
+ return MCPJWTVerifier(**common_kwargs)
Review Comment:
<!-- Bito Reply -->
The reviewer's suggestion to add unit tests for `_build_jwt_verifier` is a valid point regarding test coverage for new helper functions. However, as you noted, the function is a thin wrapper around an external library's constructor, and its behavior is already exercised end-to-end by the existing `test_mcp_server.py` test suite. Given that the current integration tests cover the factory invocation and the resulting verifier, adding unit tests for this specific wrapper would indeed introduce fragility by requiring mocks of library internals. You may choose to acknowledge the reviewer's concern while explaining that the existing integration coverage is sufficient for this specific case.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): create ApiKey permissions on init and support API keys with JWT auth [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4381227923
## Review: `CompositeTokenVerifier` scope handling
Two findings from digging into the FastMCP internals:
### 🔴 Bug: pass-through tokens will 403 when `MCP_JWT_REQUIRED_SCOPES` is set
There are two independent scope enforcement layers in FastMCP:
1. **Inside `verify_token()`** — `JWTVerifier.load_access_token()` (`providers/jwt.py:463-473`) checks `required_scopes` before returning. The composite bypasses this for API key tokens — fine.
2. **Transport middleware** — `RequireAuthMiddleware.__call__()` (`bearer_auth.py:78-96`) independently checks each required scope against `AuthCredentials(auth_info.scopes)`. The pass-through `AccessToken` has `scopes=[]`, so this check **will 403 every API key request** when `MCP_JWT_REQUIRED_SCOPES` is non-empty.
Fix: populate `scopes` from `self.required_scopes` on the pass-through token so the middleware is satisfied while `_api_key_passthrough` still tells `_resolve_user_from_jwt_context` to defer:
```python
# composite_token_verifier.py
return AccessToken(
token=token,
client_id="api_key",
scopes=list(self.required_scopes), # satisfy RequireAuthMiddleware
claims={"_api_key_passthrough": True},
)
```
### 🟡 Minor: `_api_key_passthrough` claim name collision
A JWT issued by an external IdP that happens to include `{"_api_key_passthrough": true}` as a custom claim would be silently misidentified in `_resolve_user_from_jwt_context` and cause auth failure. Not an auth bypass, but a subtle footgun. Consider a namespaced sentinel like `_superset_mcp_api_key_passthrough` or keying off `client_id == "api_key"` instead.
---
(`base_url=None` on `super().__init__()` for HS256 verifiers is fine — silently accepted, only suppresses RFC 9728 metadata routes which aren't needed here.)
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3243625916
##########
tests/unit_tests/mcp_service/test_auth_api_key.py:
##########
@@ -54,100 +84,110 @@ def _disable_api_keys(app):
app.config["MCP_DEV_USERNAME"] = old_dev
+@contextmanager
+def _mock_sm_ctx(app: SupersetApp, mock_sm: MagicMock):
+ """Push an app context with g.user cleared and appbuilder.sm mocked.
+
+ Defaults find_user_with_relationships to None so JWT/dev-user lookups
+ that hit the SM (via load_user_with_relationships) behave as "user not
+ found" without a real DB, matching the pre-refactor db.session behavior.
+ Tests that need a specific return value should set it on mock_sm directly.
+ """
+ mock_sm.find_user_with_relationships.return_value = None
Review Comment:
_mock_sm_ctx unconditionally accesses mock_sm.find_user_with_relationships, but tests later pass MagicMock(spec=[]), which will raise AttributeError on that access. Also, load_user_with_relationships() now delegates to the global superset.security_manager.find_user_with_relationships (not app.appbuilder.sm), so setting this on appbuilder.sm is ineffective. Remove this line or guard it (e.g., only set it when the attribute exists), and if you need to avoid DB lookups in these tests, patch superset.security_manager.find_user_with_relationships or superset.mcp_service.auth.load_user_with_relationships instead.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3210862950
##########
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 verify_token() docstring still says the pass-through AccessToken contains a ``_api_key_passthrough`` claim, but the implementation uses the namespaced `API_KEY_PASSTHROUGH_CLAIM` ("_superset_mcp_api_key_passthrough"). Update the docstring to avoid confusing readers and to match the new collision-safe claim name.
##########
tests/unit_tests/mcp_service/test_auth_api_key.py:
##########
@@ -158,89 +195,154 @@ def test_g_user_fallback_when_no_jwt_or_api_key(app, mock_user) -> None:
assert result.username == "api_key_user"
-# -- FAB version without extract_api_key_from_request --
+# -- FAB version without validate_api_key --
@pytest.mark.usefixtures("_enable_api_keys")
-def test_fab_without_extract_method_skips_gracefully(app) -> None:
- """If FAB SecurityManager lacks extract_api_key_from_request,
- API key auth should be skipped with a debug log, not crash."""
+def test_fab_without_validate_method_raises(app: SupersetApp) -> None:
+ """If FAB SecurityManager lacks validate_api_key, should raise
+ PermissionError about unavailable validation."""
mock_sm = MagicMock(spec=[]) # empty spec = no attributes
- with app.test_request_context():
+ with app.app_context():
g.user = None
app.appbuilder = MagicMock()
app.appbuilder.sm = mock_sm
- with pytest.raises(ValueError, match="No authenticated user found"):
- get_user_from_request()
+ with _patch_access_token(_passthrough_access_token("sst_abc123")):
+ with pytest.raises(
+ PermissionError, match="API key validation is not available"
+ ):
+ get_user_from_request()
-# -- FAB version without validate_api_key --
+# -- Relationship reload fallback --
@pytest.mark.usefixtures("_enable_api_keys")
-def test_fab_without_validate_method_raises(app) -> None:
- """If FAB has extract_api_key_from_request but not validate_api_key,
- should raise PermissionError about unavailable validation."""
- mock_sm = MagicMock(spec=["extract_api_key_from_request"])
- mock_sm.extract_api_key_from_request.return_value = "sst_abc123"
+def test_relationship_reload_failure_returns_original_user(
+ app: SupersetApp, mock_user: MagicMock
+) -> None:
+ """If load_user_with_relationships fails, the original user from
+ validate_api_key should be returned as fallback."""
+ mock_sm = MagicMock()
+ mock_sm.validate_api_key.return_value = mock_user
- with app.test_request_context(headers={"Authorization": "Bearer sst_abc123"}):
+ with app.app_context():
g.user = None
app.appbuilder = MagicMock()
app.appbuilder.sm = mock_sm
- with pytest.raises(
- PermissionError, match="API key validation is not available"
+ with (
+ _patch_access_token(_passthrough_access_token("sst_abc123")),
+ patch(
+ "superset.mcp_service.auth.load_user_with_relationships",
+ return_value=None,
+ ),
):
- get_user_from_request()
+ result = get_user_from_request()
+
+ assert result is mock_user
-# -- Relationship reload fallback --
+# -- AccessToken without passthrough claim (plain JWT) -> skip API key auth --
@pytest.mark.usefixtures("_enable_api_keys")
-def test_relationship_reload_failure_returns_original_user(app, mock_user) -> None:
- """If load_user_with_relationships fails, the original user from
- validate_api_key should be returned as fallback."""
+def test_jwt_access_token_skips_api_key_auth(app: SupersetApp) -> None:
+ """When the AccessToken is a plain JWT (no ``_api_key_passthrough`` claim),
+ API key auth is skipped — the JWT was already validated by the JWT
+ verifier and resolved in _resolve_user_from_jwt_context."""
Review Comment:
This test docstring refers to the legacy ``_api_key_passthrough`` claim name, but the implementation now uses the namespaced `API_KEY_PASSTHROUGH_CLAIM` ("_superset_mcp_api_key_passthrough"). Update the wording so the test documentation matches the behavior being asserted elsewhere in this file.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3237086757
##########
tests/unit_tests/mcp_service/test_auth_api_key.py:
##########
@@ -158,89 +195,154 @@ def test_g_user_fallback_when_no_jwt_or_api_key(app, mock_user) -> None:
assert result.username == "api_key_user"
-# -- FAB version without extract_api_key_from_request --
+# -- FAB version without validate_api_key --
@pytest.mark.usefixtures("_enable_api_keys")
-def test_fab_without_extract_method_skips_gracefully(app) -> None:
- """If FAB SecurityManager lacks extract_api_key_from_request,
- API key auth should be skipped with a debug log, not crash."""
+def test_fab_without_validate_method_raises(app: SupersetApp) -> None:
+ """If FAB SecurityManager lacks validate_api_key, should raise
+ PermissionError about unavailable validation."""
mock_sm = MagicMock(spec=[]) # empty spec = no attributes
- with app.test_request_context():
+ with app.app_context():
g.user = None
app.appbuilder = MagicMock()
app.appbuilder.sm = mock_sm
Review Comment:
Addressed. — agor claude on Amin's behalf
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3212048211
##########
superset/mcp_service/mcp_config.py:
##########
@@ -284,56 +287,88 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
- else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception:
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Blind exception catch without specificity</b></div>
<div id="fix">
Replace bare `Exception` with specific exception types (e.g., `ValueError`, `KeyError`, `RuntimeError`) to avoid catching unexpected errors.
</div>
<details>
<summary>
<b>Code suggestion</b>
</summary>
<blockquote>Check the AI-generated fix before applying</blockquote>
<div id="code">
````suggestion
except (ValueError, KeyError, RuntimeError):
````
</div>
</details>
</div>
<small><i>Code Review Run #df6cf1</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
tests/unit_tests/mcp_service/test_auth_api_key.py:
##########
@@ -158,89 +195,154 @@ def test_g_user_fallback_when_no_jwt_or_api_key(app, mock_user) -> None:
assert result.username == "api_key_user"
-# -- FAB version without extract_api_key_from_request --
+# -- FAB version without validate_api_key --
@pytest.mark.usefixtures("_enable_api_keys")
-def test_fab_without_extract_method_skips_gracefully(app) -> None:
- """If FAB SecurityManager lacks extract_api_key_from_request,
- API key auth should be skipped with a debug log, not crash."""
+def test_fab_without_validate_method_raises(app: SupersetApp) -> None:
+ """If FAB SecurityManager lacks validate_api_key, should raise
+ PermissionError about unavailable validation."""
mock_sm = MagicMock(spec=[]) # empty spec = no attributes
- with app.test_request_context():
+ with app.app_context():
g.user = None
app.appbuilder = MagicMock()
app.appbuilder.sm = mock_sm
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Duplicated test setup code</b></div>
<div id="fix">
The setup code for mocking app context, g.user, appbuilder, and sm is duplicated across multiple test functions (test_fab_without_validate_method_raises, test_relationship_reload_failure_returns_original_user, test_jwt_access_token_skips_api_key_auth, test_unnamespaced_passthrough_claim_does_not_trigger_api_key_path). This creates maintenance risk if the setup needs to change. Consider extracting this into a pytest fixture or a helper function to improve maintainability.
</div>
</div>
<small><i>Code Review Run #df6cf1</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3244924722
##########
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:
Addressed.
##########
tests/unit_tests/mcp_service/test_auth_api_key.py:
##########
@@ -220,3 +223,74 @@ def test_relationship_reload_failure_returns_original_user(app, mock_user) -> No
result = get_user_from_request()
assert result is mock_user
+
+
+# -- Bearer token present but not matching API key prefix --
+
+
+@pytest.mark.usefixtures("_enable_api_keys")
+def test_non_matching_bearer_token_skips_api_key_auth(app) -> None:
Review Comment:
Addressed.
##########
tests/unit_tests/mcp_service/test_auth_api_key.py:
##########
@@ -220,3 +223,74 @@ def test_relationship_reload_failure_returns_original_user(app, mock_user) -> No
result = get_user_from_request()
assert result is mock_user
+
+
+# -- Bearer token present but not matching API key prefix --
+
+
+@pytest.mark.usefixtures("_enable_api_keys")
+def test_non_matching_bearer_token_skips_api_key_auth(app) -> None:
+ """When a Bearer token is present but does not match FAB_API_KEY_PREFIXES
+ (e.g., a JWT token), extract_api_key_from_request returns None and API key
+ auth is skipped, falling through to the next auth method."""
+ mock_sm = MagicMock()
+ mock_sm.extract_api_key_from_request.return_value = None
+
+ with app.test_request_context(
+ headers={"Authorization": "Bearer eyJhbGciOiJIUzI1NiJ9.not-an-api-key"}
+ ):
+ g.user = None
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm = mock_sm
+
+ with pytest.raises(ValueError, match="No authenticated user found"):
+ get_user_from_request()
+
+ # extract was called but returned None, so validate should NOT be called
+ mock_sm.extract_api_key_from_request.assert_called_once()
+ mock_sm.validate_api_key.assert_not_called()
+
+
+# -- API key pass-through from CompositeTokenVerifier --
+
+
+def test_jwt_context_with_api_key_passthrough_returns_none(app) -> None:
Review Comment:
Addressed.
##########
tests/unit_tests/mcp_service/test_auth_api_key.py:
##########
@@ -220,3 +223,74 @@ def test_relationship_reload_failure_returns_original_user(app, mock_user) -> No
result = get_user_from_request()
assert result is mock_user
+
+
+# -- Bearer token present but not matching API key prefix --
+
+
+@pytest.mark.usefixtures("_enable_api_keys")
+def test_non_matching_bearer_token_skips_api_key_auth(app) -> None:
+ """When a Bearer token is present but does not match FAB_API_KEY_PREFIXES
+ (e.g., a JWT token), extract_api_key_from_request returns None and API key
+ auth is skipped, falling through to the next auth method."""
+ mock_sm = MagicMock()
+ mock_sm.extract_api_key_from_request.return_value = None
+
+ with app.test_request_context(
+ headers={"Authorization": "Bearer eyJhbGciOiJIUzI1NiJ9.not-an-api-key"}
+ ):
+ g.user = None
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm = mock_sm
+
+ with pytest.raises(ValueError, match="No authenticated user found"):
+ get_user_from_request()
+
+ # extract was called but returned None, so validate should NOT be called
+ mock_sm.extract_api_key_from_request.assert_called_once()
+ mock_sm.validate_api_key.assert_not_called()
+
+
+# -- API key pass-through from CompositeTokenVerifier --
+
+
+def test_jwt_context_with_api_key_passthrough_returns_none(app) -> None:
+ """When CompositeTokenVerifier passes through an API key token,
+ _resolve_user_from_jwt_context should detect the _api_key_passthrough
+ claim and return None so get_user_from_request falls through to
+ _resolve_user_from_api_key."""
+ mock_access_token = MagicMock()
+ mock_access_token.claims = {"_api_key_passthrough": True}
+
+ with patch(
+ "fastmcp.server.dependencies.get_access_token",
+ return_value=mock_access_token,
+ ):
+ result = _resolve_user_from_jwt_context(app)
+
+ assert result is None
+
+
+# -- SecurityManager method name regression test --
+
+
+def test_security_manager_has_expected_api_key_methods(app) -> None:
Review Comment:
Addressed.
##########
tests/unit_tests/mcp_service/test_composite_token_verifier.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.
+
+"""Tests for CompositeTokenVerifier."""
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from fastmcp.server.auth import AccessToken
+
+from superset.mcp_service.composite_token_verifier import CompositeTokenVerifier
+
+
+@pytest.fixture
+def mock_jwt_verifier():
Review Comment:
Addressed.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3253539033
##########
superset/mcp_service/mcp_config.py:
##########
@@ -20,12 +20,15 @@
import secrets
from typing import Any, Dict, Optional
+from fastmcp.server.auth.providers.jwt import JWTVerifier
Review Comment:
To confirm: `mcp_config.py` is only ever imported from MCP-specific code paths that are themselves lazy-loaded (e.g. `core_mcp_injection.py` wraps all mcp imports in functions). Non-MCP deployments never touch this module. If you'd prefer an explicit guard (`try/except ImportError`) let me know and I'll add it.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): create ApiKey permissions on init and support API keys with JWT auth [superset]
Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3134630262
##########
tests/unit_tests/mcp_service/test_auth_api_key.py:
##########
@@ -220,3 +223,74 @@ def test_relationship_reload_failure_returns_original_user(app, mock_user) -> No
result = get_user_from_request()
assert result is mock_user
+
+
+# -- Bearer token present but not matching API key prefix --
+
+
+@pytest.mark.usefixtures("_enable_api_keys")
+def test_non_matching_bearer_token_skips_api_key_auth(app) -> None:
Review Comment:
**Suggestion:** Add an explicit type annotation for the test fixture parameter so the new function has full parameter and return typing. [custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
The function is newly added and its `app` parameter is unannotated, so it does not meet the stated rule requiring explicit type hints for all parameters on new function definitions.
</details>
[Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20tests%2Funit_tests%2Fmcp_service%2Ftest_auth_api_key.py%0A%2A%2ALine%3A%2A%2A%20232%3A232%0A%2A%2AComment%3A%2A%2A%0A%09%2ACustom%20Rule%3A%20Add%20an%20explicit%20type%20annotation%20for%20the%20test%20fixture%20parameter%20so%20the%20new%20function%20has%20full%20parameter%20and%20return%20typing.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%20a%20minimal%20fix%0A)
| [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20tests%2Funit_tests%2Fmcp_service%2Ftest_auth_api_key.py%0A%2A%2ALine%3A%2A%2A%20232%3A232%0A%2A%2AComment%3A%2A%2A%0A%09%2ACustom%20Rule%3A%20Add%20an%20explicit%20type%20annotation%20for%20the%20test%20fixture%20parameter%20so%20the%20new%20function%20has%20full%20parameter%20and%20return%20typing.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%20a%20mi
nimal%20fix%0A)
*(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:** tests/unit_tests/mcp_service/test_auth_api_key.py
**Line:** 232:232
**Comment:**
*Custom Rule: Add an explicit type annotation for the test fixture parameter so the new function has full parameter and return typing.
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%2F39604&comment_hash=88f6ba982b2f3aab641967944bf6f70479f3b4fc23ea14deed14326e810d6124&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39604&comment_hash=88f6ba982b2f3aab641967944bf6f70479f3b4fc23ea14deed14326e810d6124&reaction=dislike'>👎</a>
##########
tests/unit_tests/mcp_service/test_auth_api_key.py:
##########
@@ -220,3 +223,74 @@ def test_relationship_reload_failure_returns_original_user(app, mock_user) -> No
result = get_user_from_request()
assert result is mock_user
+
+
+# -- Bearer token present but not matching API key prefix --
+
+
+@pytest.mark.usefixtures("_enable_api_keys")
+def test_non_matching_bearer_token_skips_api_key_auth(app) -> None:
+ """When a Bearer token is present but does not match FAB_API_KEY_PREFIXES
+ (e.g., a JWT token), extract_api_key_from_request returns None and API key
+ auth is skipped, falling through to the next auth method."""
+ mock_sm = MagicMock()
+ mock_sm.extract_api_key_from_request.return_value = None
+
+ with app.test_request_context(
+ headers={"Authorization": "Bearer eyJhbGciOiJIUzI1NiJ9.not-an-api-key"}
+ ):
+ g.user = None
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm = mock_sm
+
+ with pytest.raises(ValueError, match="No authenticated user found"):
+ get_user_from_request()
+
+ # extract was called but returned None, so validate should NOT be called
+ mock_sm.extract_api_key_from_request.assert_called_once()
+ mock_sm.validate_api_key.assert_not_called()
+
+
+# -- API key pass-through from CompositeTokenVerifier --
+
+
+def test_jwt_context_with_api_key_passthrough_returns_none(app) -> None:
Review Comment:
**Suggestion:** Annotate the function argument with its concrete type to satisfy the requirement that new function signatures are fully typed. [custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
This is a newly introduced function and the `app` parameter has no type annotation, which matches the custom rule violation described by the suggestion.
</details>
[Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20tests%2Funit_tests%2Fmcp_service%2Ftest_auth_api_key.py%0A%2A%2ALine%3A%2A%2A%20257%3A257%0A%2A%2AComment%3A%2A%2A%0A%09%2ACustom%20Rule%3A%20Annotate%20the%20function%20argument%20with%20its%20concrete%20type%20to%20satisfy%20the%20requirement%20that%20new%20function%20signatures%20are%20fully%20typed.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%20a%20minimal%20fix
%0A) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20tests%2Funit_tests%2Fmcp_service%2Ftest_auth_api_key.py%0A%2A%2ALine%3A%2A%2A%20257%3A257%0A%2A%2AComment%3A%2A%2A%0A%09%2ACustom%20Rule%3A%20Annotate%20the%20function%20argument%20with%20its%20concrete%20type%20to%20satisfy%20the%20requirement%20that%20new%20function%20signatures%20are%20fully%20typed.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%
20a%20minimal%20fix%0A)
*(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:** tests/unit_tests/mcp_service/test_auth_api_key.py
**Line:** 257:257
**Comment:**
*Custom Rule: Annotate the function argument with its concrete type to satisfy the requirement that new function signatures are fully typed.
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%2F39604&comment_hash=0c7316385dd69bb08394f63d190985b48eecaa5bb889d277cee6783a00549f3e&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39604&comment_hash=0c7316385dd69bb08394f63d190985b48eecaa5bb889d277cee6783a00549f3e&reaction=dislike'>👎</a>
##########
tests/unit_tests/mcp_service/test_composite_token_verifier.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.
+
+"""Tests for CompositeTokenVerifier."""
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from fastmcp.server.auth import AccessToken
+
+from superset.mcp_service.composite_token_verifier import CompositeTokenVerifier
+
+
+@pytest.fixture
+def mock_jwt_verifier():
+ verifier = MagicMock()
+ verifier.required_scopes = []
+ verifier.verify_token = AsyncMock()
+ return verifier
+
+
+@pytest.fixture
+def composite_verifier(mock_jwt_verifier):
+ return CompositeTokenVerifier(
+ jwt_verifier=mock_jwt_verifier,
+ api_key_prefixes=["sst_", "pat_"],
+ )
+
+
+@pytest.mark.asyncio
+async def test_api_key_token_returns_passthrough(composite_verifier) -> None:
+ """Tokens matching an API key prefix return a pass-through AccessToken."""
+ api_key = "sst_abc123secret" # noqa: S105
+ result = await composite_verifier.verify_token(api_key)
+
+ assert result is not None
+ assert result.token == api_key
+ assert result.client_id == "api_key"
+ assert result.claims.get("_api_key_passthrough") is True
+
+
+@pytest.mark.asyncio
+async def test_second_prefix_matches(composite_verifier) -> None:
+ """All configured prefixes are checked, not just the first."""
+ result = await composite_verifier.verify_token("pat_mytoken")
+
+ assert result is not None
+ assert result.claims.get("_api_key_passthrough") is True
+
+
+@pytest.mark.asyncio
+async def test_jwt_token_delegates_to_wrapped_verifier(
+ composite_verifier, mock_jwt_verifier
+) -> None:
+ """Non-API-key tokens are delegated to the wrapped JWT verifier."""
+ jwt_token = "eyJhbGciOiJSUzI1NiJ9.jwt_payload" # noqa: S105
+ jwt_result = AccessToken(
+ token=jwt_token,
+ client_id="oauth_client",
+ scopes=["read"],
+ claims={"sub": "user1"},
+ )
+ mock_jwt_verifier.verify_token.return_value = jwt_result
+
+ result = await composite_verifier.verify_token("eyJhbGciOiJSUzI1NiJ9.jwt_payload")
+
+ assert result is jwt_result
+ mock_jwt_verifier.verify_token.assert_awaited_once_with(
+ "eyJhbGciOiJSUzI1NiJ9.jwt_payload"
+ )
+
+
+@pytest.mark.asyncio
+async def test_invalid_jwt_returns_none(composite_verifier, mock_jwt_verifier) -> None:
+ """When the JWT verifier rejects a token, None is returned."""
+ mock_jwt_verifier.verify_token.return_value = None
+
+ result = await composite_verifier.verify_token("not_a_valid_token")
+
+ assert result is None
+ mock_jwt_verifier.verify_token.assert_awaited_once()
+
+
+@pytest.mark.asyncio
+async def test_api_key_does_not_call_jwt_verifier(
+ composite_verifier, mock_jwt_verifier
+) -> None:
Review Comment:
**Suggestion:** Add explicit type annotations for all fixture-injected parameters in these new async test functions so each new function has fully typed inputs. [custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
Each of the new async test functions has fixture parameters without type annotations, so the suggestion accurately identifies an actual typing omission.
</details>
[Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20tests%2Funit_tests%2Fmcp_service%2Ftest_composite_token_verifier.py%0A%2A%2ALine%3A%2A%2A%2045%3A101%0A%2A%2AComment%3A%2A%2A%0A%09%2ACustom%20Rule%3A%20Add%20explicit%20type%20annotations%20for%20all%20fixture-injected%20parameters%20in%20these%20new%20async%20test%20functions%20so%20each%20new%20function%20has%20fully%20typed%20inputs.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20
and%20implement%20a%20minimal%20fix%0A) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20tests%2Funit_tests%2Fmcp_service%2Ftest_composite_token_verifier.py%0A%2A%2ALine%3A%2A%2A%2045%3A101%0A%2A%2AComment%3A%2A%2A%0A%09%2ACustom%20Rule%3A%20Add%20explicit%20type%20annotations%20for%20all%20fixture-injected%20parameters%20in%20these%20new%20async%20test%20functions%20so%20each%20new%20function%20has%20fully%20typed%20inputs.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20
all%20the%20comments%20validate%20the%20correctness%20and%20implement%20a%20minimal%20fix%0A)
*(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:** tests/unit_tests/mcp_service/test_composite_token_verifier.py
**Line:** 45:101
**Comment:**
*Custom Rule: Add explicit type annotations for all fixture-injected parameters in these new async test functions so each new function has fully typed inputs.
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%2F39604&comment_hash=8b5d9e6db2ef04502ca54323841084007ad014cac6e7073438d0eea478f044a7&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39604&comment_hash=8b5d9e6db2ef04502ca54323841084007ad014cac6e7073438d0eea478f044a7&reaction=dislike'>👎</a>
##########
tests/unit_tests/mcp_service/test_composite_token_verifier.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.
+
+"""Tests for CompositeTokenVerifier."""
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from fastmcp.server.auth import AccessToken
+
+from superset.mcp_service.composite_token_verifier import CompositeTokenVerifier
+
+
+@pytest.fixture
+def mock_jwt_verifier():
Review Comment:
**Suggestion:** Add an explicit return type annotation to this fixture so the new function definition is fully typed. [custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
The fixture is a new function definition and it has no return type annotation. This matches the suggested rule violation.
</details>
[Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20tests%2Funit_tests%2Fmcp_service%2Ftest_composite_token_verifier.py%0A%2A%2ALine%3A%2A%2A%2029%3A29%0A%2A%2AComment%3A%2A%2A%0A%09%2ACustom%20Rule%3A%20Add%20an%20explicit%20return%20type%20annotation%20to%20this%20fixture%20so%20the%20new%20function%20definition%20is%20fully%20typed.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%20a%20minimal%20fix%0A) | [Fix in VSCo
de Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20tests%2Funit_tests%2Fmcp_service%2Ftest_composite_token_verifier.py%0A%2A%2ALine%3A%2A%2A%2029%3A29%0A%2A%2AComment%3A%2A%2A%0A%09%2ACustom%20Rule%3A%20Add%20an%20explicit%20return%20type%20annotation%20to%20this%20fixture%20so%20the%20new%20function%20definition%20is%20fully%20typed.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%20a%20minimal%20fix%0A)
*(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:** tests/unit_tests/mcp_service/test_composite_token_verifier.py
**Line:** 29:29
**Comment:**
*Custom Rule: Add an explicit return type annotation to this fixture so the new function definition is fully typed.
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%2F39604&comment_hash=0c01e2591bd42d0b9d3a27bd04189febf989c73d92f85d258a82b48a78194ada&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39604&comment_hash=0c01e2591bd42d0b9d3a27bd04189febf989c73d92f85d258a82b48a78194ada&reaction=dislike'>👎</a>
##########
tests/unit_tests/mcp_service/test_auth_api_key.py:
##########
@@ -220,3 +223,74 @@ def test_relationship_reload_failure_returns_original_user(app, mock_user) -> No
result = get_user_from_request()
assert result is mock_user
+
+
+# -- Bearer token present but not matching API key prefix --
+
+
+@pytest.mark.usefixtures("_enable_api_keys")
+def test_non_matching_bearer_token_skips_api_key_auth(app) -> None:
+ """When a Bearer token is present but does not match FAB_API_KEY_PREFIXES
+ (e.g., a JWT token), extract_api_key_from_request returns None and API key
+ auth is skipped, falling through to the next auth method."""
+ mock_sm = MagicMock()
+ mock_sm.extract_api_key_from_request.return_value = None
+
+ with app.test_request_context(
+ headers={"Authorization": "Bearer eyJhbGciOiJIUzI1NiJ9.not-an-api-key"}
+ ):
+ g.user = None
+ app.appbuilder = MagicMock()
+ app.appbuilder.sm = mock_sm
+
+ with pytest.raises(ValueError, match="No authenticated user found"):
+ get_user_from_request()
+
+ # extract was called but returned None, so validate should NOT be called
+ mock_sm.extract_api_key_from_request.assert_called_once()
+ mock_sm.validate_api_key.assert_not_called()
+
+
+# -- API key pass-through from CompositeTokenVerifier --
+
+
+def test_jwt_context_with_api_key_passthrough_returns_none(app) -> None:
+ """When CompositeTokenVerifier passes through an API key token,
+ _resolve_user_from_jwt_context should detect the _api_key_passthrough
+ claim and return None so get_user_from_request falls through to
+ _resolve_user_from_api_key."""
+ mock_access_token = MagicMock()
+ mock_access_token.claims = {"_api_key_passthrough": True}
+
+ with patch(
+ "fastmcp.server.dependencies.get_access_token",
+ return_value=mock_access_token,
+ ):
+ result = _resolve_user_from_jwt_context(app)
+
+ assert result is None
+
+
+# -- SecurityManager method name regression test --
+
+
+def test_security_manager_has_expected_api_key_methods(app) -> None:
Review Comment:
**Suggestion:** Add a type hint to the function parameter so this new test definition includes explicit typing for both inputs and output. [custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
The function signature is missing a type annotation for the `app` parameter. Since the suggestion targets explicit typing for new function parameters, the violation is real.
</details>
[Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20tests%2Funit_tests%2Fmcp_service%2Ftest_auth_api_key.py%0A%2A%2ALine%3A%2A%2A%20277%3A277%0A%2A%2AComment%3A%2A%2A%0A%09%2ACustom%20Rule%3A%20Add%20a%20type%20hint%20to%20the%20function%20parameter%20so%20this%20new%20test%20definition%20includes%20explicit%20typing%20for%20both%20inputs%20and%20output.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%20a%20minimal%20fix
%0A) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20tests%2Funit_tests%2Fmcp_service%2Ftest_auth_api_key.py%0A%2A%2ALine%3A%2A%2A%20277%3A277%0A%2A%2AComment%3A%2A%2A%0A%09%2ACustom%20Rule%3A%20Add%20a%20type%20hint%20to%20the%20function%20parameter%20so%20this%20new%20test%20definition%20includes%20explicit%20typing%20for%20both%20inputs%20and%20output.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%
20a%20minimal%20fix%0A)
*(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:** tests/unit_tests/mcp_service/test_auth_api_key.py
**Line:** 277:277
**Comment:**
*Custom Rule: Add a type hint to the function parameter so this new test definition includes explicit typing for both inputs and output.
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%2F39604&comment_hash=2e5d13010470d4a24da30a19b6977ab38ffe9e826eb5f3b8a38ce00224c8bb3c&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39604&comment_hash=2e5d13010470d4a24da30a19b6977ab38ffe9e826eb5f3b8a38ce00224c8bb3c&reaction=dislike'>👎</a>
##########
tests/unit_tests/mcp_service/test_composite_token_verifier.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.
+
+"""Tests for CompositeTokenVerifier."""
+
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from fastmcp.server.auth import AccessToken
+
+from superset.mcp_service.composite_token_verifier import CompositeTokenVerifier
+
+
+@pytest.fixture
+def mock_jwt_verifier():
+ verifier = MagicMock()
+ verifier.required_scopes = []
+ verifier.verify_token = AsyncMock()
+ return verifier
+
+
+@pytest.fixture
+def composite_verifier(mock_jwt_verifier):
Review Comment:
**Suggestion:** Add explicit type annotations for the fixture parameter and return type in this fixture definition. [custom_rule]
**Severity Level:** Minor ⚠️
<details>
<summary><b>Why it matters? 🤔 </b></summary>
The fixture parameter is untyped and the function has no return annotation, so this is a genuine violation of the typing requirement described by the suggestion.
</details>
[Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20tests%2Funit_tests%2Fmcp_service%2Ftest_composite_token_verifier.py%0A%2A%2ALine%3A%2A%2A%2037%3A37%0A%2A%2AComment%3A%2A%2A%0A%09%2ACustom%20Rule%3A%20Add%20explicit%20type%20annotations%20for%20the%20fixture%20parameter%20and%20return%20type%20in%20this%20fixture%20definition.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%20a%20minimal%20fix%0A) | [Fix in VSCode Cla
ude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt=This%20is%20a%20comment%20left%20during%20a%20code%20review.%0A%0A%2A%2APath%3A%2A%2A%20tests%2Funit_tests%2Fmcp_service%2Ftest_composite_token_verifier.py%0A%2A%2ALine%3A%2A%2A%2037%3A37%0A%2A%2AComment%3A%2A%2A%0A%09%2ACustom%20Rule%3A%20Add%20explicit%20type%20annotations%20for%20the%20fixture%20parameter%20and%20return%20type%20in%20this%20fixture%20definition.%0A%0AValidate%20the%20correctness%20of%20the%20flagged%20issue.%20If%20correct%2C%20How%20can%20I%20resolve%20this%3F%20If%20you%20propose%20a%20fix%2C%20implement%20it%20and%20please%20make%20it%20concise.%0AOnce%20fix%20is%20implemented%2C%20also%20check%20other%20comments%20on%20the%20same%20PR%2C%20and%20ask%20user%20if%20the%20user%20wants%20to%20fix%20the%20rest%20of%20the%20comments%20as%20well.%20if%20said%20yes%2C%20then%20fetch%20all%20the%20comments%20validate%20the%20correctness%20and%20implement%20a%20minimal%20fix%0A)
*(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:** tests/unit_tests/mcp_service/test_composite_token_verifier.py
**Line:** 37:37
**Comment:**
*Custom Rule: Add explicit type annotations for the fixture parameter and return type in this fixture definition.
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%2F39604&comment_hash=df50f9146e6d1734fb29a66df32e0eefa6bdf65cc03cd8892c3c8baebc64df6c&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F39604&comment_hash=df50f9146e6d1734fb29a66df32e0eefa6bdf65cc03cd8892c3c8baebc64df6c&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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): create ApiKey permissions on init and support API keys with JWT auth [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4309510637
Addressed all review comments in the latest commit:
**CodeQL (clear-text logging):** False positive — the log line logs `FAB_API_KEY_PREFIXES` (e.g. `["sst_"]`), which are configuration values/prefixes, not actual API keys or passwords. No sensitive data is exposed.
**codeant-ai (type annotations):** Added explicit type annotations to all new test function parameters and fixture return types across both test files. Fixtures now have return type annotations (`-> MagicMock`, `-> CompositeTokenVerifier`) and test functions annotate their fixture parameters (`app: SupersetApp`, `composite_verifier: CompositeTokenVerifier`, `mock_jwt_verifier: MagicMock`).
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): create ApiKey permissions on init and support API keys with JWT auth [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4309731203
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3244926569
##########
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:
Addressed.
##########
superset/mcp_service/mcp_config.py:
##########
@@ -284,56 +287,88 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
- else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception:
Review Comment:
Addressed.
##########
superset/mcp_service/auth.py:
##########
@@ -218,6 +220,25 @@
if access_token is None:
return None
+ # API key pass-through: CompositeTokenVerifier accepted this token
+ # at the transport layer but defers actual validation to
+ # _resolve_user_from_api_key() (priority 2 in get_user_from_request).
+ # Require client_id=="api_key" (set by CompositeTokenVerifier) in addition
+ # to the claim so that an external IdP JWT that happens to include the
+ # claim name is not misclassified as an API-key pass-through.
+ claims = getattr(access_token, "claims", None)
+ if isinstance(claims, dict) and claims.get(API_KEY_PASSTHROUGH_CLAIM):
+ if getattr(access_token, "client_id", None) == "api_key":
+ logger.debug(
+ "API key pass-through token detected, deferring to API key auth"
+ )
+ return None
+ logger.debug(
+ "Ignoring %s claim on non-API-key token (client_id=%r); processing as JWT",
+ API_KEY_PASSTHROUGH_CLAIM,
Review Comment:
Addressed.
##########
superset/mcp_service/mcp_config.py:
##########
@@ -284,56 +287,88 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
- else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception: # noqa: BLE001 — JWT lib raises many types; broad catch intentional
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ api_key_prefixes = app.config.get("FAB_API_KEY_PREFIXES", ["sst_"])
+ logger.info("API key auth enabled for MCP")
+ return CompositeTokenVerifier(
+ jwt_verifier=jwt_verifier,
+ api_key_prefixes=api_key_prefixes,
+ )
Review Comment:
Addressed.
##########
superset/mcp_service/composite_token_verifier.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.
+
+"""
+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)
+
Review Comment:
Addressed.
##########
superset/mcp_service/composite_token_verifier.py:
##########
@@ -0,0 +1,113 @@
+# 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
+ valid: list[str] = [
+ p for p in api_key_prefixes if isinstance(p, str) and p.strip()
+ ]
+ invalid = [p for p in api_key_prefixes if p not in valid]
+ if invalid:
+ logger.warning(
+ "FAB_API_KEY_PREFIXES contains invalid entries (ignored): %r", invalid
Review Comment:
Addressed.
##########
tests/unit_tests/mcp_service/test_auth_api_key.py:
##########
@@ -54,100 +84,110 @@ def _disable_api_keys(app):
app.config["MCP_DEV_USERNAME"] = old_dev
+@contextmanager
+def _mock_sm_ctx(app: SupersetApp, mock_sm: MagicMock):
+ """Push an app context with g.user cleared and appbuilder.sm mocked.
+
+ Defaults find_user_with_relationships to None so JWT/dev-user lookups
+ that hit the SM (via load_user_with_relationships) behave as "user not
+ found" without a real DB, matching the pre-refactor db.session behavior.
+ Tests that need a specific return value should set it on mock_sm directly.
+ """
+ mock_sm.find_user_with_relationships.return_value = None
Review Comment:
Addressed.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "dpgaspar (via GitHub)" <gi...@apache.org>.
dpgaspar commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3247557060
##########
superset/mcp_service/auth.py:
##########
@@ -218,6 +198,24 @@ def _resolve_user_from_jwt_context(app: Any) -> User | None:
if access_token is None:
return None
+ # API key pass-through: CompositeTokenVerifier accepted this token
+ # at the transport layer but defers actual validation to
+ # _resolve_user_from_api_key() (priority 2 in get_user_from_request).
+ # Require client_id=="api_key" (set by CompositeTokenVerifier) in addition
+ # to the claim so that an external IdP JWT that happens to include the
+ # claim name is not misclassified as an API-key pass-through.
+ claims = getattr(access_token, "claims", None)
+ if isinstance(claims, dict) and claims.get(API_KEY_PASSTHROUGH_CLAIM):
+ if getattr(access_token, "client_id", None) == "api_key":
+ logger.debug(
+ "API key pass-through token detected, deferring to API key auth"
+ )
+ return None
+ logger.debug(
+ "API key passthrough claim present but client_id is not 'api_key';"
+ " processing as JWT"
+ )
+
# Use configurable resolver or default
from superset.mcp_service.mcp_config import default_user_resolver
Review Comment:
nit: can this be imported at the module level?
##########
superset/mcp_service/auth.py:
##########
@@ -148,45 +149,24 @@ def check_tool_permission(func: Callable[..., Any]) -> bool:
def load_user_with_relationships(
username: str | None = None, email: str | None = None
) -> User | None:
- """
- Load a user with all relationships needed for permission checks.
-
- This function eagerly loads User.roles, User.groups, and Group.roles
- to prevent detached instance errors when the session is closed/rolled back.
+ """Load a user with roles and group roles eagerly loaded.
- IMPORTANT: Always use this function instead of security_manager.find_user()
- when loading users for MCP tool execution. The find_user() method doesn't
- eagerly load Group.roles, causing "detached instance" errors when permission
- checks access group.roles after the session is rolled back.
-
- Args:
- username: The username to look up (optional if email provided)
- email: The email to look up (optional if username provided)
-
- Returns:
- User object with relationships loaded, or None if not found
+ Delegates to :meth:`SupersetSecurityManager.find_user_with_relationships`,
+ which mirrors FAB's ``find_user`` (including ``auth_username_ci`` and
+ ``MultipleResultsFound`` handling) while adding eager loading of
+ ``User.roles`` and ``User.groups.roles`` to prevent detached-instance
+ errors when the SQLAlchemy session is closed or rolled back after the
+ lookup — as happens in MCP tool-execution contexts.
Raises:
ValueError: If neither username nor email is provided
"""
if not username and not email:
raise ValueError("Either username or email must be provided")
- from sqlalchemy.orm import joinedload
+ from superset import security_manager
Review Comment:
nit: Can we import the security_manager at the module level? we can access it also with `current_app.appbuilder.sm`
##########
superset/mcp_service/mcp_config.py:
##########
@@ -20,12 +20,15 @@
import secrets
from typing import Any, Dict, Optional
+from fastmcp.server.auth.providers.jwt import JWTVerifier
Review Comment:
Will this import make `fastmcp` a required dependency?
##########
superset/mcp_service/auth.py:
##########
@@ -131,8 +133,7 @@ def check_tool_permission(func: Callable[..., Any]) -> bool:
if not has_permission:
logger.warning(
- "Permission denied for user %s: %s on %s (tool: %s)",
- g.user.username,
+ "Permission denied: %s on %s (tool: %s)",
Review Comment:
Why is the current user being removed from the log, it's super useful for debugging or security audits
##########
superset/mcp_service/mcp_config.py:
##########
@@ -291,56 +294,94 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception: # noqa: BLE001 — JWT lib raises many types; broad catch intentional
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ raw_prefixes = app.config.get("FAB_API_KEY_PREFIXES", ["sst_"])
+ # Normalize: a plain string (e.g. "sst_") would iterate as characters;
+ # wrap it in a list so CompositeTokenVerifier receives a proper sequence.
+ if isinstance(raw_prefixes, str):
+ api_key_prefixes = [raw_prefixes]
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ api_key_prefixes = list(raw_prefixes)
+ logger.info("API key auth enabled for MCP")
+ return CompositeTokenVerifier(
+ jwt_verifier=jwt_verifier,
+ api_key_prefixes=api_key_prefixes,
+ )
- auth_provider = JWTVerifier(**common_kwargs)
+ return jwt_verifier
- return auth_provider
- except Exception:
- # Do not log the exception — it may contain the HS256 secret
- # from common_kwargs["public_key"]
- logger.error("Failed to create MCP auth provider")
- return None
+
+def _build_jwt_verifier(
+ app: Flask,
+ jwks_uri: Optional[str],
+ public_key: Optional[str],
+ secret: Optional[str],
+) -> Any:
Review Comment:
nit: can we declare the return type as `JWTVerifier`
##########
superset/mcp_service/mcp_config.py:
##########
@@ -291,56 +294,94 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception: # noqa: BLE001 — JWT lib raises many types; broad catch intentional
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
Review Comment:
nit: FastMCP's JWTVerifier uses authlib under the hood, and authlib has a clean exception hierarchy:
JoseError (base)
├── BadSignatureError
├── DecodeError
├── ExpiredTokenError
└── ...
The JWTVerifier.__init__() constructor can realistically raise:
- JoseError (and subclasses) — key parsing, JOSE protocol issues
- ValueError — invalid configuration (bad algorithm, malformed URIs, etc.)
Superset's own DetailedJWTVerifier already imports JoseError as the base class in superset/mcp_service/jwt_verifier.py:37:
``` python
from authlib.jose.errors import (
BadSignatureError,
DecodeError,
ExpiredTokenError,
JoseError, # <-- base exception, already used in this codebase
)
```
So the catch should be:
``` python
except (ValueError, JoseError):
logger.error("Failed to create MCP JWT verifier")
if not api_key_enabled:
return None
```
The comment "JWT lib raises many types; broad catch intentional" isn't accurate — authlib has JoseError as a proper parent class specifically for this purpose. A bare except Exception swallows things
like TypeError, ImportError, or MemoryError that should propagate.
##########
superset/security/manager.py:
##########
@@ -3164,6 +3169,60 @@ def get_user_by_username(self, username: str) -> Optional[User]:
.one_or_none()
)
+ def find_user_with_relationships(
+ self,
+ username: Optional[str] = None,
+ email: Optional[str] = None,
+ ) -> Optional[User]:
+ """Find a user with roles and group roles eagerly loaded.
+
+ Mirrors FAB's ``SecurityManager.find_user``
+ (including ``auth_username_ci`` case-insensitive handling and
+ ``MultipleResultsFound`` guard) and additionally eager-loads
+ ``User.roles`` and ``User.groups.roles`` to prevent detached-instance
+ errors when the SQLAlchemy session is closed or rolled back after the
+ lookup — as happens in MCP tool-execution contexts.
+ """
+ eager = [
+ joinedload(self.user_model.roles),
+ joinedload(self.user_model.groups).joinedload(self.group_model.roles),
+ ]
+ if username:
+ try:
+ if self.auth_username_ci:
+ from sqlalchemy import func as sa_func
Review Comment:
nit: Let's move this import to the module level
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4468625558
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4582096812
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4605550790
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4607454856
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3350594605
##########
superset/mcp_service/mcp_config.py:
##########
@@ -303,57 +314,142 @@
}
+def get_mcp_api_key_enabled(app: Flask, *, startup_warning: bool = False) -> bool:
+ """Return whether API key auth is enabled for the MCP transport.
+
+ Prefers ``MCP_API_KEY_ENABLED`` when explicitly set; falls back to
+ ``FAB_API_KEY_ENABLED``. When ``startup_warning=True`` and the value
+ is inherited from ``FAB_API_KEY_ENABLED``, logs a warning so operators
+ know a FAB config change now also affects the MCP transport.
+ """
+ if (mcp_setting := app.config.get("MCP_API_KEY_ENABLED", None)) is not None:
+ return bool(mcp_setting)
+ fab_enabled = bool(app.config.get("FAB_API_KEY_ENABLED", False))
+ if startup_warning and fab_enabled:
+ logger.warning(
+ "MCP API key auth is enabled via FAB_API_KEY_ENABLED=True. "
+ "Set MCP_API_KEY_ENABLED=True to silence this warning or "
+ "MCP_API_KEY_ENABLED=False to disable API keys on the MCP "
+ "transport without affecting the FAB REST API."
+ )
+ return fab_enabled
Review Comment:
<!-- Bito Reply -->
The addition of four dedicated unit tests in `test_mcp_config.py` effectively addresses the reviewer's concern regarding the lack of test coverage for the `get_mcp_api_key_enabled` function. These tests cover the required scenarios: explicit overrides, the fallback to `FAB_API_KEY_ENABLED`, and the default behavior when both are absent.
##########
superset/mcp_service/mcp_config.py:
##########
@@ -303,57 +314,142 @@
}
+def get_mcp_api_key_enabled(app: Flask, *, startup_warning: bool = False) -> bool:
+ """Return whether API key auth is enabled for the MCP transport.
+
+ Prefers ``MCP_API_KEY_ENABLED`` when explicitly set; falls back to
+ ``FAB_API_KEY_ENABLED``. When ``startup_warning=True`` and the value
+ is inherited from ``FAB_API_KEY_ENABLED``, logs a warning so operators
+ know a FAB config change now also affects the MCP transport.
+ """
+ if (mcp_setting := app.config.get("MCP_API_KEY_ENABLED", None)) is not None:
+ return bool(mcp_setting)
+ fab_enabled = bool(app.config.get("FAB_API_KEY_ENABLED", False))
+ if startup_warning and fab_enabled:
+ logger.warning(
+ "MCP API key auth is enabled via FAB_API_KEY_ENABLED=True. "
+ "Set MCP_API_KEY_ENABLED=True to silence this warning or "
+ "MCP_API_KEY_ENABLED=False to disable API keys on the MCP "
+ "transport without affecting the FAB REST API."
+ )
+ return fab_enabled
+
+
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``MCP_API_KEY_ENABLED=True`` (or ``FAB_API_KEY_ENABLED=True``
+ as a fallback) — API-key-only verifier that rejects all non-API-key
+ Bearer tokens at the transport.
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ ``MCP_API_KEY_ENABLED=None`` (default) defers to ``FAB_API_KEY_ENABLED``
+ and logs a startup warning when that setting is True, so operators are
+ aware that a FAB config change now also affects the MCP transport.
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = get_mcp_api_key_enabled(app, startup_warning=True)
+
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
- else:
- # MCPJWTVerifier: minimal logging + browser-friendly error page.
- from superset.mcp_service.jwt_verifier import MCPJWTVerifier
-
- auth_provider = MCPJWTVerifier(**common_kwargs)
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except (ValueError, JoseError):
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ return _build_composite_verifier(app, jwt_verifier)
+
+ return jwt_verifier
Review Comment:
<!-- Bito Reply -->
The reviewer has identified that the refactored `create_default_mcp_auth_factory` function lacks direct unit tests, despite handling multiple authentication modes (JWT, API-key, and composite). The reviewer suggests that comprehensive unit tests covering success paths, error scenarios, and edge cases should be added to comply with project standards for new features.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3350594350
##########
superset/mcp_service/mcp_config.py:
##########
@@ -303,57 +314,142 @@
}
+def get_mcp_api_key_enabled(app: Flask, *, startup_warning: bool = False) -> bool:
+ """Return whether API key auth is enabled for the MCP transport.
+
+ Prefers ``MCP_API_KEY_ENABLED`` when explicitly set; falls back to
+ ``FAB_API_KEY_ENABLED``. When ``startup_warning=True`` and the value
+ is inherited from ``FAB_API_KEY_ENABLED``, logs a warning so operators
+ know a FAB config change now also affects the MCP transport.
+ """
+ if (mcp_setting := app.config.get("MCP_API_KEY_ENABLED", None)) is not None:
+ return bool(mcp_setting)
+ fab_enabled = bool(app.config.get("FAB_API_KEY_ENABLED", False))
+ if startup_warning and fab_enabled:
+ logger.warning(
+ "MCP API key auth is enabled via FAB_API_KEY_ENABLED=True. "
+ "Set MCP_API_KEY_ENABLED=True to silence this warning or "
+ "MCP_API_KEY_ENABLED=False to disable API keys on the MCP "
+ "transport without affecting the FAB REST API."
+ )
+ return fab_enabled
+
+
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``MCP_API_KEY_ENABLED=True`` (or ``FAB_API_KEY_ENABLED=True``
+ as a fallback) — API-key-only verifier that rejects all non-API-key
+ Bearer tokens at the transport.
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ ``MCP_API_KEY_ENABLED=None`` (default) defers to ``FAB_API_KEY_ENABLED``
+ and logs a startup warning when that setting is True, so operators are
+ aware that a FAB config change now also affects the MCP transport.
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = get_mcp_api_key_enabled(app, startup_warning=True)
+
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
- else:
- # MCPJWTVerifier: minimal logging + browser-friendly error page.
- from superset.mcp_service.jwt_verifier import MCPJWTVerifier
-
- auth_provider = MCPJWTVerifier(**common_kwargs)
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except (ValueError, JoseError):
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ return _build_composite_verifier(app, jwt_verifier)
+
+ return jwt_verifier
+
+
+def _build_composite_verifier(app: Flask, jwt_verifier: Any) -> CompositeTokenVerifier:
+ """Build a CompositeTokenVerifier with API key prefixes from config."""
+ if required_scopes := app.config.get("MCP_REQUIRED_SCOPES", []):
+ logger.debug(
+ "MCP_REQUIRED_SCOPES is configured but API key tokens bypass "
+ "scope enforcement. API key holders gain access regardless of "
+ "MCP_REQUIRED_SCOPES=%r.",
+ required_scopes,
+ )
+ raw_prefixes: str | Sequence[str] = app.config.get("FAB_API_KEY_PREFIXES", ["sst_"])
+ # Normalize: a plain string (e.g. "sst_") would iterate as characters;
+ # wrap it in a list so CompositeTokenVerifier receives a proper sequence.
+ # Guard against non-iterable config values (e.g. None, integers) that
+ # would raise TypeError and cause _create_auth_provider to fail open.
+ if isinstance(raw_prefixes, str):
+ api_key_prefixes: list[str] = [raw_prefixes]
+ else:
+ try:
+ api_key_prefixes = list(raw_prefixes)
+ except TypeError:
+ logger.warning(
+ "FAB_API_KEY_PREFIXES must be a string or list; using default"
+ )
+ api_key_prefixes = ["sst_"]
+ logger.info("API key auth enabled for MCP")
+ return CompositeTokenVerifier(
+ jwt_verifier=jwt_verifier,
+ api_key_prefixes=api_key_prefixes,
+ app=app,
+ )
+
+
+def _build_jwt_verifier(
+ app: Flask,
+ jwks_uri: Optional[str],
+ public_key: Optional[str],
+ secret: Optional[str],
+) -> JWTVerifier:
+ """Construct the JWT verifier from configured keys/secret."""
+ debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+
+ common_kwargs: Dict[str, Any] = {
+ "issuer": app.config.get("MCP_JWT_ISSUER"),
+ "audience": app.config.get("MCP_JWT_AUDIENCE"),
+ "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
+ }
- return auth_provider
- except Exception:
- # Do not log the exception — it may contain the HS256 secret
- # from common_kwargs["public_key"]
- logger.error("Failed to create MCP auth provider")
- return None
+ # For HS256 (symmetric), use the secret as the public_key parameter
+ if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
+ common_kwargs["public_key"] = secret
+ common_kwargs["algorithm"] = "HS256"
+ else:
+ # For RS256 (asymmetric), use public key or JWKS
+ common_kwargs["jwks_uri"] = jwks_uri
+ common_kwargs["public_key"] = public_key
+ common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
+
+ if debug_errors:
+ # DetailedJWTVerifier: detailed server-side logging of JWT
+ # validation failures. HTTP responses are always generic per
+ # RFC 6750 Section 3.1.
+ return DetailedJWTVerifier(**common_kwargs)
+
+ # MCPJWTVerifier: minimal logging + browser-friendly error page.
+ return MCPJWTVerifier(**common_kwargs)
Review Comment:
`_build_jwt_verifier` is a thin wrapper around FastMCP's `JWTVerifier` constructor — adding unit tests would require mocking external library internals, which is fragile. The function is exercised end-to-end by the JWT path in `create_default_mcp_auth_factory`, which is already covered in `test_mcp_server.py` (the `test_init_fastmcp_server_applies_auth_to_global_instance` test verifies `create_default_mcp_auth_factory` is invoked and returns the right factory).
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3253725583
##########
superset/security/manager.py:
##########
@@ -1361,6 +1361,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:
Addressed in commit `8a9d51173c` — the 3 failing tests now patch `superset.mcp_service.auth.security_manager` (where the binding lives after the module-level import) instead of `superset.security_manager`. Same fix applied to the 4th similar test for consistency.
##########
superset/security/manager.py:
##########
@@ -1361,6 +1361,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:
The `"ApiKey"` entry is unconditional but harmless when `FAB_API_KEY_ENABLED=False` — no PVMs exist under that view menu when the feature is off, so `_is_admin_only_pvm` never fires. When enabled, FAB registers the `ApiKeyApi` blueprint and its PVMs; the static entry correctly classifies them admin-only without any runtime config lookup. Making it conditional would require either mutating the class-level set at init time or overriding `_is_admin_only_pvm`, both of which add complexity without a safety benefit. Happy to switch to a conditional approach if you still prefer it.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): create ApiKey permissions on init and support API keys with JWT auth [superset]
Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4309282150
### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
| Name | Link |
|:-:|------------------------|
|<span aria-hidden="true">🔨</span> Latest commit | d7b92b10ac06e213c638d2cb8c43201356b9f9ad |
|<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/69eab0ed83d3b20008a7816c |
|<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-39604--superset-docs-preview.netlify.app](https://deploy-preview-39604--superset-docs-preview.netlify.app) |
|<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br /><br /><br />_Use your smartphone camera to open QR code link._</details> |
---
<!-- [superset-docs-preview Preview](https://deploy-preview-39604--superset-docs-preview.netlify.app) -->
_To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3326416306
##########
superset/mcp_service/auth.py:
##########
@@ -305,47 +304,78 @@ def _resolve_user_from_jwt_context(app: Any) -> User | None:
if not user:
# Fail closed: JWT says this user should exist but they don't.
# Do NOT fall through to MCP_DEV_USERNAME or stale g.user.
+ # Avoid echoing the JWT-extracted username in the exception message
+ # (CodeQL py/clear-text-logging-sensitive-data).
+ logger.debug("JWT-authenticated user not found in database (identity from JWT)")
raise ValueError(
- f"JWT authenticated user '{username}' not found in Superset database. "
- f"Ensure the user exists before granting MCP access."
+ "JWT authenticated user not found in Superset database. "
+ "Ensure the user exists before granting MCP access."
)
return user
+def _redact_access_token(access_token: Any) -> None:
+ """Redact the raw token value after validation so it does not persist."""
+ try:
+ object.__setattr__(access_token, "token", "")
+ except (AttributeError, TypeError):
+ pass # immutable AccessToken; LoggingMiddleware handles sanitization
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Missing security test coverage</b></div>
<div id="fix">
The new `_redact_access_token` function redacts the raw API key after validation to prevent token persistence. However, `test_valid_api_key_returns_user` (line 114-130 in test_auth_api_key.py) verifies `validate_api_key` is called with the correct token but does NOT assert that the token is redacted afterward. A test should verify the redaction occurs, ensuring the security measure actually works and guards against future regressions.
</div>
</div>
<small><i>Code Review Run #e16d04</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3329454675
##########
superset/mcp_service/auth.py:
##########
@@ -218,6 +220,25 @@
if access_token is None:
return None
+ # API key pass-through: CompositeTokenVerifier accepted this token
+ # at the transport layer but defers actual validation to
+ # _resolve_user_from_api_key() (priority 2 in get_user_from_request).
+ # Require client_id=="api_key" (set by CompositeTokenVerifier) in addition
+ # to the claim so that an external IdP JWT that happens to include the
+ # claim name is not misclassified as an API-key pass-through.
+ claims = getattr(access_token, "claims", None)
+ if isinstance(claims, dict) and claims.get(API_KEY_PASSTHROUGH_CLAIM):
+ if getattr(access_token, "client_id", None) == "api_key":
+ logger.debug(
+ "API key pass-through token detected, deferring to API key auth"
+ )
+ return None
+ logger.debug(
+ "Ignoring %s claim on non-API-key token (client_id=%r); processing as JWT",
+ API_KEY_PASSTHROUGH_CLAIM,
Review Comment:
Fixed in a subsequent commit. The debug log that included `client_id=%r` was removed. The current code logs a static string (`"API key passthrough claim present but client_id is not 'api_key'; processing as JWT"`) without interpolating the sensitive `client_id` value. This alert was filed against an earlier commit and no longer applies to the current code.
##########
superset/mcp_service/mcp_config.py:
##########
@@ -284,56 +287,88 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
- else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception: # noqa: BLE001 — JWT lib raises many types; broad catch intentional
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ api_key_prefixes = app.config.get("FAB_API_KEY_PREFIXES", ["sst_"])
+ logger.info("API key auth enabled for MCP")
+ return CompositeTokenVerifier(
+ jwt_verifier=jwt_verifier,
+ api_key_prefixes=api_key_prefixes,
+ )
Review Comment:
Added in a subsequent commit. `_build_composite_verifier` now: (1) coerces a bare string to a single-element list, (2) catches `TypeError` for non-iterable values and falls back to `["sst_"]` with a warning. `CompositeTokenVerifier.__init__` additionally filters the list to non-empty, non-whitespace strings and warns on discarded entries. Tests for empty-string, whitespace-only, non-string, and all-invalid-prefix cases live in `test_composite_token_verifier.py`.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3329455048
##########
tests/unit_tests/mcp_service/test_auth_api_key.py:
##########
@@ -54,100 +84,110 @@ def _disable_api_keys(app):
app.config["MCP_DEV_USERNAME"] = old_dev
+@contextmanager
+def _mock_sm_ctx(app: SupersetApp, mock_sm: MagicMock):
+ """Push an app context with g.user cleared and appbuilder.sm mocked.
+
+ Defaults find_user_with_relationships to None so JWT/dev-user lookups
+ that hit the SM (via load_user_with_relationships) behave as "user not
+ found" without a real DB, matching the pre-refactor db.session behavior.
+ Tests that need a specific return value should set it on mock_sm directly.
+ """
+ mock_sm.find_user_with_relationships.return_value = None
Review Comment:
Fixed in a subsequent commit. `_mock_sm_ctx` no longer accesses `mock_sm.find_user_with_relationships` unconditionally, so passing `MagicMock(spec=[])` is safe. Tests that need `load_user_with_relationships` to return `None` now patch `superset.mcp_service.auth.load_user_with_relationships` directly (via `_patch_load_user_not_found()`), which matches the actual delegation path through the global `security_manager` — not `app.appbuilder.sm`.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3290464377
##########
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:
The approach changed in a subsequent commit (fix(security): drop redundant explicit ApiKey perm creation) — `create_custom_permissions()` was not modified. Only `ADMIN_ONLY_VIEW_MENUS` was updated (adding `"ApiKey"` to the static set). No new behavior was added to `create_custom_permissions()`, so no new test is needed for that function. The existing `ADMIN_ONLY_VIEW_MENUS` coverage in the RBAC tests exercises the gating logic.
##########
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 was updated in a prior commit — it now reads `_superset_mcp_api_key_passthrough` (the namespaced constant `API_KEY_PASSTHROUGH_CLAIM`). See composite_token_verifier.py line 90.
##########
superset/mcp_service/mcp_config.py:
##########
@@ -284,56 +287,88 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
- else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception:
Review Comment:
The bare `Exception` was replaced with specific types in an earlier commit: `except (ValueError, JoseError)` for the JWT verifier construction block, and `except TypeError` for the prefix normalization block.
##########
superset/mcp_service/auth.py:
##########
@@ -218,6 +220,25 @@
if access_token is None:
return None
+ # API key pass-through: CompositeTokenVerifier accepted this token
+ # at the transport layer but defers actual validation to
+ # _resolve_user_from_api_key() (priority 2 in get_user_from_request).
+ # Require client_id=="api_key" (set by CompositeTokenVerifier) in addition
+ # to the claim so that an external IdP JWT that happens to include the
+ # claim name is not misclassified as an API-key pass-through.
+ claims = getattr(access_token, "claims", None)
+ if isinstance(claims, dict) and claims.get(API_KEY_PASSTHROUGH_CLAIM):
+ if getattr(access_token, "client_id", None) == "api_key":
+ logger.debug(
+ "API key pass-through token detected, deferring to API key auth"
+ )
+ return None
+ logger.debug(
+ "Ignoring %s claim on non-API-key token (client_id=%r); processing as JWT",
+ API_KEY_PASSTHROUGH_CLAIM,
Review Comment:
Addressed in the latest commit (fix(mcp): remove exc_info=True from tool-visibility debug log). The `exc_info=True` in the tool-visibility except block was the flagged path — it could include full tracebacks with sensitive local variables. Removed; the log message alone is sufficient.
##########
superset/mcp_service/mcp_config.py:
##########
@@ -284,56 +287,88 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
- else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception: # noqa: BLE001 — JWT lib raises many types; broad catch intentional
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ api_key_prefixes = app.config.get("FAB_API_KEY_PREFIXES", ["sst_"])
+ logger.info("API key auth enabled for MCP")
+ return CompositeTokenVerifier(
+ jwt_verifier=jwt_verifier,
+ api_key_prefixes=api_key_prefixes,
+ )
Review Comment:
Validation was added in a prior commit. `mcp_config.py` now normalizes `FAB_API_KEY_PREFIXES`: a plain string is wrapped in a list, non-iterable values fall back to the default with a warning (`except TypeError`), and empty/non-string entries are filtered out inside `CompositeTokenVerifier.__init__`.
##########
superset/mcp_service/composite_token_verifier.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.
+
+"""
+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)
+
Review Comment:
Validation is in `__init__`: non-string and empty/whitespace entries are filtered via `[p for p in api_key_prefixes if isinstance(p, str) and p.strip()]`, invalid entries are logged (count only, not values) as a warning, and the clean list is stored as `self._api_key_prefixes`.
##########
superset/mcp_service/composite_token_verifier.py:
##########
@@ -0,0 +1,113 @@
+# 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
+ valid: list[str] = [
+ p for p in api_key_prefixes if isinstance(p, str) and p.strip()
+ ]
+ invalid = [p for p in api_key_prefixes if p not in valid]
+ if invalid:
+ logger.warning(
+ "FAB_API_KEY_PREFIXES contains invalid entries (ignored): %r", invalid
Review Comment:
This is a CodeQL false positive — `len(invalid)` logs only the integer count of invalid entries, not the values themselves. The actual prefix strings are never logged. The surrounding comment at line 76-77 documents this explicitly.
##########
tests/unit_tests/mcp_service/test_auth_api_key.py:
##########
@@ -54,100 +84,110 @@ def _disable_api_keys(app):
app.config["MCP_DEV_USERNAME"] = old_dev
+@contextmanager
+def _mock_sm_ctx(app: SupersetApp, mock_sm: MagicMock):
+ """Push an app context with g.user cleared and appbuilder.sm mocked.
+
+ Defaults find_user_with_relationships to None so JWT/dev-user lookups
+ that hit the SM (via load_user_with_relationships) behave as "user not
+ found" without a real DB, matching the pre-refactor db.session behavior.
+ Tests that need a specific return value should set it on mock_sm directly.
+ """
+ mock_sm.find_user_with_relationships.return_value = None
Review Comment:
`_mock_sm_ctx` no longer accesses `find_user_with_relationships` — it only sets `app.appbuilder.sm = mock_sm`. The MagicMock(spec=[]) test (test_fab_without_validate_method_raises) relies on `hasattr(sm, "validate_api_key")` returning `False` for a spec-empty mock, which is correct. Tests that need `load_user_with_relationships` to return specific values patch it directly via `patch("superset.mcp_service.auth.load_user_with_relationships", ...)` as described in the `_patch_load_user_not_found()` helper.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3253523056
##########
superset/mcp_service/auth.py:
##########
@@ -131,8 +133,7 @@ def check_tool_permission(func: Callable[..., Any]) -> bool:
if not has_permission:
logger.warning(
- "Permission denied for user %s: %s on %s (tool: %s)",
- g.user.username,
+ "Permission denied: %s on %s (tool: %s)",
Review Comment:
Good catch — logging `g.user.id` (the integer primary key) instead of `g.user.username`. The username attribute triggers CodeQL `py/clear-text-logging-sensitive-data`, but the integer user ID gives the same audit-trail value (correlatable against the DB) without the flag.
##########
superset/mcp_service/auth.py:
##########
@@ -148,45 +149,24 @@ def check_tool_permission(func: Callable[..., Any]) -> bool:
def load_user_with_relationships(
username: str | None = None, email: str | None = None
) -> User | None:
- """
- Load a user with all relationships needed for permission checks.
-
- This function eagerly loads User.roles, User.groups, and Group.roles
- to prevent detached instance errors when the session is closed/rolled back.
+ """Load a user with roles and group roles eagerly loaded.
- IMPORTANT: Always use this function instead of security_manager.find_user()
- when loading users for MCP tool execution. The find_user() method doesn't
- eagerly load Group.roles, causing "detached instance" errors when permission
- checks access group.roles after the session is rolled back.
-
- Args:
- username: The username to look up (optional if email provided)
- email: The email to look up (optional if username provided)
-
- Returns:
- User object with relationships loaded, or None if not found
+ Delegates to :meth:`SupersetSecurityManager.find_user_with_relationships`,
+ which mirrors FAB's ``find_user`` (including ``auth_username_ci`` and
+ ``MultipleResultsFound`` handling) while adding eager loading of
+ ``User.roles`` and ``User.groups.roles`` to prevent detached-instance
+ errors when the SQLAlchemy session is closed or rolled back after the
+ lookup — as happens in MCP tool-execution contexts.
Raises:
ValueError: If neither username nor email is provided
"""
if not username and not email:
raise ValueError("Either username or email must be provided")
- from sqlalchemy.orm import joinedload
+ from superset import security_manager
Review Comment:
Done — moved to module level: `from superset import security_manager`. Removed all three deferred inline imports.
##########
superset/mcp_service/auth.py:
##########
@@ -218,6 +198,24 @@ def _resolve_user_from_jwt_context(app: Any) -> User | None:
if access_token is None:
return None
+ # API key pass-through: CompositeTokenVerifier accepted this token
+ # at the transport layer but defers actual validation to
+ # _resolve_user_from_api_key() (priority 2 in get_user_from_request).
+ # Require client_id=="api_key" (set by CompositeTokenVerifier) in addition
+ # to the claim so that an external IdP JWT that happens to include the
+ # claim name is not misclassified as an API-key pass-through.
+ claims = getattr(access_token, "claims", None)
+ if isinstance(claims, dict) and claims.get(API_KEY_PASSTHROUGH_CLAIM):
+ if getattr(access_token, "client_id", None) == "api_key":
+ logger.debug(
+ "API key pass-through token detected, deferring to API key auth"
+ )
+ return None
+ logger.debug(
+ "API key passthrough claim present but client_id is not 'api_key';"
+ " processing as JWT"
+ )
+
# Use configurable resolver or default
from superset.mcp_service.mcp_config import default_user_resolver
Review Comment:
Done — moved to module level. No circular import: `mcp_config.py` does not import from `auth.py`.
##########
superset/mcp_service/mcp_config.py:
##########
@@ -291,56 +294,94 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception: # noqa: BLE001 — JWT lib raises many types; broad catch intentional
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ raw_prefixes = app.config.get("FAB_API_KEY_PREFIXES", ["sst_"])
+ # Normalize: a plain string (e.g. "sst_") would iterate as characters;
+ # wrap it in a list so CompositeTokenVerifier receives a proper sequence.
+ if isinstance(raw_prefixes, str):
+ api_key_prefixes = [raw_prefixes]
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ api_key_prefixes = list(raw_prefixes)
+ logger.info("API key auth enabled for MCP")
+ return CompositeTokenVerifier(
+ jwt_verifier=jwt_verifier,
+ api_key_prefixes=api_key_prefixes,
+ )
- auth_provider = JWTVerifier(**common_kwargs)
+ return jwt_verifier
- return auth_provider
- except Exception:
- # Do not log the exception — it may contain the HS256 secret
- # from common_kwargs["public_key"]
- logger.error("Failed to create MCP auth provider")
- return None
+
+def _build_jwt_verifier(
+ app: Flask,
+ jwks_uri: Optional[str],
+ public_key: Optional[str],
+ secret: Optional[str],
+) -> Any:
Review Comment:
Done — `_build_jwt_verifier` now returns `-> JWTVerifier`. `DetailedJWTVerifier` is a subclass so the return type is correct.
##########
superset/security/manager.py:
##########
@@ -3164,6 +3169,60 @@ def get_user_by_username(self, username: str) -> Optional[User]:
.one_or_none()
)
+ def find_user_with_relationships(
+ self,
+ username: Optional[str] = None,
+ email: Optional[str] = None,
+ ) -> Optional[User]:
+ """Find a user with roles and group roles eagerly loaded.
+
+ Mirrors FAB's ``SecurityManager.find_user``
+ (including ``auth_username_ci`` case-insensitive handling and
+ ``MultipleResultsFound`` guard) and additionally eager-loads
+ ``User.roles`` and ``User.groups.roles`` to prevent detached-instance
+ errors when the SQLAlchemy session is closed or rolled back after the
+ lookup — as happens in MCP tool-execution contexts.
+ """
+ eager = [
+ joinedload(self.user_model.roles),
+ joinedload(self.user_model.groups).joinedload(self.group_model.roles),
+ ]
+ if username:
+ try:
+ if self.auth_username_ci:
+ from sqlalchemy import func as sa_func
Review Comment:
Done — added `func as sa_func` to the module-level `from sqlalchemy import ...` line and removed the inline import.
##########
superset/mcp_service/mcp_config.py:
##########
@@ -20,12 +20,15 @@
import secrets
from typing import Any, Dict, Optional
+from fastmcp.server.auth.providers.jwt import JWTVerifier
Review Comment:
`mcp_config.py` is only ever imported via MCP-specific code paths (e.g. `core_mcp_injection.py` guards all mcp imports inside lazy functions). So `fastmcp` is effectively a conditional dependency — it is required when MCP is used but does not affect non-MCP deployments. Happy to guard with `try/except ImportError` if you'd prefer explicit over implicit.
##########
superset/mcp_service/mcp_config.py:
##########
@@ -291,56 +294,94 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception: # noqa: BLE001 — JWT lib raises many types; broad catch intentional
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
Review Comment:
Done — replaced `except Exception` with `except (ValueError, JoseError)`. Confirmed via fastmcp source that `JWTVerifier.__init__` only raises `ValueError` (config validation, no network I/O at construction). `JoseError` added for forward-compatibility with authlib token errors. Removed the misleading `# noqa: BLE001` comment.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3337417383
##########
tests/unit_tests/mcp_service/test_mcp_server.py:
##########
@@ -158,3 +158,26 @@ def test_create_event_store_returns_none_when_redis_store_fails():
result = create_event_store(config)
assert result is None
+
+
+def test_create_auth_provider_uses_default_factory_for_mcp_api_key_only() -> None:
+ """MCP_API_KEY_ENABLED=True should install auth even when FAB API keys are off."""
+ from superset.mcp_service.server import _create_auth_provider
+
+ flask_app = MagicMock()
+ flask_app.config.get.side_effect = lambda key, default=None: {
+ "MCP_AUTH_FACTORY": None,
+ "MCP_AUTH_ENABLED": False,
+ "MCP_API_KEY_ENABLED": True,
+ "FAB_API_KEY_ENABLED": False,
+ }.get(key, default)
+ auth_provider = MagicMock()
+
+ with patch(
+ "superset.mcp_service.mcp_config.create_default_mcp_auth_factory",
+ return_value=auth_provider,
+ ) as create_default_mcp_auth_factory:
+ result = _create_auth_provider(flask_app)
+
+ assert result is auth_provider
+ create_default_mcp_auth_factory.assert_called_once_with(flask_app)
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Missing test coverage for key logic</b></div>
<div id="fix">
The new test correctly verifies `create_default_mcp_auth_factory` is called when `MCP_API_KEY_ENABLED=True`, but it mocks this factory so `_build_composite_verifier` (lines 402-411 in mcp_config.py) is never exercised. The string-normalization logic that wraps `FAB_API_KEY_PREFIXES` strings into lists is untested. Consider adding tests in `test_mcp_config.py` that directly invoke `_build_composite_verifier` with various `FAB_API_KEY_PREFIXES` configs (string `'sst_'`, list `['sst_']`, and invalid values like `None` that trigger the TypeError guard).
</div>
</div>
<small><i>Code Review Run #68148e</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4449086594
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3344864773
##########
superset/mcp_service/mcp_config.py:
##########
@@ -303,57 +314,142 @@
}
+def get_mcp_api_key_enabled(app: Flask, *, startup_warning: bool = False) -> bool:
+ """Return whether API key auth is enabled for the MCP transport.
+
+ Prefers ``MCP_API_KEY_ENABLED`` when explicitly set; falls back to
+ ``FAB_API_KEY_ENABLED``. When ``startup_warning=True`` and the value
+ is inherited from ``FAB_API_KEY_ENABLED``, logs a warning so operators
+ know a FAB config change now also affects the MCP transport.
+ """
+ if (mcp_setting := app.config.get("MCP_API_KEY_ENABLED", None)) is not None:
+ return bool(mcp_setting)
+ fab_enabled = bool(app.config.get("FAB_API_KEY_ENABLED", False))
+ if startup_warning and fab_enabled:
+ logger.warning(
+ "MCP API key auth is enabled via FAB_API_KEY_ENABLED=True. "
+ "Set MCP_API_KEY_ENABLED=True to silence this warning or "
+ "MCP_API_KEY_ENABLED=False to disable API keys on the MCP "
+ "transport without affecting the FAB REST API."
+ )
+ return fab_enabled
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Missing unit tests for API key check</b></div>
<div id="fix">
`get_mcp_api_key_enabled` is a new public function that determines API key auth mode with fallback logic, but has no dedicated unit tests. Per BITO.md rule [11730], this new feature needs test coverage.
</div>
</div>
<small><i>Code Review Run #fa7b4d</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
superset/mcp_service/mcp_config.py:
##########
@@ -303,57 +314,142 @@
}
+def get_mcp_api_key_enabled(app: Flask, *, startup_warning: bool = False) -> bool:
+ """Return whether API key auth is enabled for the MCP transport.
+
+ Prefers ``MCP_API_KEY_ENABLED`` when explicitly set; falls back to
+ ``FAB_API_KEY_ENABLED``. When ``startup_warning=True`` and the value
+ is inherited from ``FAB_API_KEY_ENABLED``, logs a warning so operators
+ know a FAB config change now also affects the MCP transport.
+ """
+ if (mcp_setting := app.config.get("MCP_API_KEY_ENABLED", None)) is not None:
+ return bool(mcp_setting)
+ fab_enabled = bool(app.config.get("FAB_API_KEY_ENABLED", False))
+ if startup_warning and fab_enabled:
+ logger.warning(
+ "MCP API key auth is enabled via FAB_API_KEY_ENABLED=True. "
+ "Set MCP_API_KEY_ENABLED=True to silence this warning or "
+ "MCP_API_KEY_ENABLED=False to disable API keys on the MCP "
+ "transport without affecting the FAB REST API."
+ )
+ return fab_enabled
+
+
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``MCP_API_KEY_ENABLED=True`` (or ``FAB_API_KEY_ENABLED=True``
+ as a fallback) — API-key-only verifier that rejects all non-API-key
+ Bearer tokens at the transport.
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ ``MCP_API_KEY_ENABLED=None`` (default) defers to ``FAB_API_KEY_ENABLED``
+ and logs a startup warning when that setting is True, so operators are
+ aware that a FAB config change now also affects the MCP transport.
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = get_mcp_api_key_enabled(app, startup_warning=True)
+
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
- else:
- # MCPJWTVerifier: minimal logging + browser-friendly error page.
- from superset.mcp_service.jwt_verifier import MCPJWTVerifier
-
- auth_provider = MCPJWTVerifier(**common_kwargs)
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except (ValueError, JoseError):
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ return _build_composite_verifier(app, jwt_verifier)
+
+ return jwt_verifier
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Missing unit tests for auth factory</b></div>
<div id="fix">
The refactored `create_default_mcp_auth_factory` handles multiple auth modes (JWT, API-key, composite) but has no direct unit tests. Only an indirect integration test exists in `test_mcp_server.py`. Per BITO.md rule [11730], new features should have comprehensive unit tests covering success paths, error scenarios, and edge cases.
</div>
</div>
<small><i>Code Review Run #fa7b4d</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
superset/mcp_service/mcp_config.py:
##########
@@ -303,57 +314,142 @@
}
+def get_mcp_api_key_enabled(app: Flask, *, startup_warning: bool = False) -> bool:
+ """Return whether API key auth is enabled for the MCP transport.
+
+ Prefers ``MCP_API_KEY_ENABLED`` when explicitly set; falls back to
+ ``FAB_API_KEY_ENABLED``. When ``startup_warning=True`` and the value
+ is inherited from ``FAB_API_KEY_ENABLED``, logs a warning so operators
+ know a FAB config change now also affects the MCP transport.
+ """
+ if (mcp_setting := app.config.get("MCP_API_KEY_ENABLED", None)) is not None:
+ return bool(mcp_setting)
+ fab_enabled = bool(app.config.get("FAB_API_KEY_ENABLED", False))
+ if startup_warning and fab_enabled:
+ logger.warning(
+ "MCP API key auth is enabled via FAB_API_KEY_ENABLED=True. "
+ "Set MCP_API_KEY_ENABLED=True to silence this warning or "
+ "MCP_API_KEY_ENABLED=False to disable API keys on the MCP "
+ "transport without affecting the FAB REST API."
+ )
+ return fab_enabled
+
+
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``MCP_API_KEY_ENABLED=True`` (or ``FAB_API_KEY_ENABLED=True``
+ as a fallback) — API-key-only verifier that rejects all non-API-key
+ Bearer tokens at the transport.
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ ``MCP_API_KEY_ENABLED=None`` (default) defers to ``FAB_API_KEY_ENABLED``
+ and logs a startup warning when that setting is True, so operators are
+ aware that a FAB config change now also affects the MCP transport.
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = get_mcp_api_key_enabled(app, startup_warning=True)
+
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
- else:
- # MCPJWTVerifier: minimal logging + browser-friendly error page.
- from superset.mcp_service.jwt_verifier import MCPJWTVerifier
-
- auth_provider = MCPJWTVerifier(**common_kwargs)
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except (ValueError, JoseError):
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ return _build_composite_verifier(app, jwt_verifier)
+
+ return jwt_verifier
+
+
+def _build_composite_verifier(app: Flask, jwt_verifier: Any) -> CompositeTokenVerifier:
+ """Build a CompositeTokenVerifier with API key prefixes from config."""
+ if required_scopes := app.config.get("MCP_REQUIRED_SCOPES", []):
+ logger.debug(
+ "MCP_REQUIRED_SCOPES is configured but API key tokens bypass "
+ "scope enforcement. API key holders gain access regardless of "
+ "MCP_REQUIRED_SCOPES=%r.",
+ required_scopes,
+ )
+ raw_prefixes: str | Sequence[str] = app.config.get("FAB_API_KEY_PREFIXES", ["sst_"])
+ # Normalize: a plain string (e.g. "sst_") would iterate as characters;
+ # wrap it in a list so CompositeTokenVerifier receives a proper sequence.
+ # Guard against non-iterable config values (e.g. None, integers) that
+ # would raise TypeError and cause _create_auth_provider to fail open.
+ if isinstance(raw_prefixes, str):
+ api_key_prefixes: list[str] = [raw_prefixes]
+ else:
+ try:
+ api_key_prefixes = list(raw_prefixes)
+ except TypeError:
+ logger.warning(
+ "FAB_API_KEY_PREFIXES must be a string or list; using default"
+ )
+ api_key_prefixes = ["sst_"]
+ logger.info("API key auth enabled for MCP")
+ return CompositeTokenVerifier(
+ jwt_verifier=jwt_verifier,
+ api_key_prefixes=api_key_prefixes,
+ app=app,
+ )
+
+
+def _build_jwt_verifier(
+ app: Flask,
+ jwks_uri: Optional[str],
+ public_key: Optional[str],
+ secret: Optional[str],
+) -> JWTVerifier:
+ """Construct the JWT verifier from configured keys/secret."""
+ debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+
+ common_kwargs: Dict[str, Any] = {
+ "issuer": app.config.get("MCP_JWT_ISSUER"),
+ "audience": app.config.get("MCP_JWT_AUDIENCE"),
+ "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
+ }
- return auth_provider
- except Exception:
- # Do not log the exception — it may contain the HS256 secret
- # from common_kwargs["public_key"]
- logger.error("Failed to create MCP auth provider")
- return None
+ # For HS256 (symmetric), use the secret as the public_key parameter
+ if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
+ common_kwargs["public_key"] = secret
+ common_kwargs["algorithm"] = "HS256"
+ else:
+ # For RS256 (asymmetric), use public key or JWKS
+ common_kwargs["jwks_uri"] = jwks_uri
+ common_kwargs["public_key"] = public_key
+ common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
+
+ if debug_errors:
+ # DetailedJWTVerifier: detailed server-side logging of JWT
+ # validation failures. HTTP responses are always generic per
+ # RFC 6750 Section 3.1.
+ return DetailedJWTVerifier(**common_kwargs)
+
+ # MCPJWTVerifier: minimal logging + browser-friendly error page.
+ return MCPJWTVerifier(**common_kwargs)
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Missing unit tests for JWT verifier builder</b></div>
<div id="fix">
`_build_jwt_verifier` constructs JWT verifier objects with different algorithms and debug settings but lacks unit tests. Per BITO.md rule [11730], this refactored helper needs test coverage.
</div>
</div>
<small><i>Code Review Run #fa7b4d</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3358319542
##########
superset/mcp_service/composite_token_verifier.py:
##########
@@ -0,0 +1,199 @@
+# 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 validated against
+ the FAB database at the transport layer. Invalid keys are rejected before
+ any MCP method (tools/list, resources/list, tool calls) is reached.
+- 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 asyncio
+import logging
+from typing import Any
+
+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 token.
+# 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"
+
+# Claim that carries the FAB-validated username after transport-layer
+# API key validation. When present, ``_resolve_user_from_api_key`` skips
+# the second DB call and loads the user directly by username.
+API_KEY_VALIDATED_USERNAME_CLAIM = "_superset_mcp_validated_username"
+
+
+class CompositeTokenVerifier(TokenVerifier):
+ """Routes Bearer tokens between API key validation and JWT verification.
+
+ API key tokens (identified by prefix) are validated against the FAB
+ database at the transport layer so that invalid keys are rejected before
+ any MCP method (tools/list, resources/list, tool calls) is reached.
+
+ 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_"]``).
+ app: Flask application instance used to push an app context for
+ FAB SecurityManager access during token validation. When
+ ``None``, prefix matching is used without DB validation
+ (backward-compatible / test mode).
+ """
+
+ def __init__(
+ self,
+ jwt_verifier: TokenVerifier | None,
+ api_key_prefixes: list[str],
+ app: Any = None,
+ ) -> 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._app = app
+ if app is None:
+ logger.warning(
+ "CompositeTokenVerifier created without a Flask app; API keys "
+ "will not be validated at the transport layer. Invalid keys are "
+ "rejected later at the Flask layer instead. Pass app=<flask_app> "
+ "to enable transport-layer rejection."
+ )
+ valid: list[str] = []
+ invalid_count = 0
+ for prefix in api_key_prefixes:
+ if isinstance(prefix, str) and (normalized := prefix.strip()):
+ valid.append(normalized)
+ else:
+ invalid_count += 1
+ if invalid_count:
+ # Log count only — actual values may be config secrets
+ # (CodeQL py/clear-text-logging-sensitive-data).
+ logger.warning(
+ "FAB_API_KEY_PREFIXES has %d invalid entries (empty/non-string)"
+ " — ignored",
+ invalid_count,
+ )
+ self._api_key_prefixes = tuple(valid)
+
+ def _validate_api_key_sync(self, token: str) -> str | None:
+ """Validate an API key against FAB and return the owner's username.
+
+ Runs synchronously inside a thread executor. Pushes a fresh Flask
+ app context so that FAB's SecurityManager can access the database.
+
+ Returns the username on success, or ``None`` if the key is invalid,
+ FAB does not support ``validate_api_key``, or an unexpected error
+ occurs (fail closed).
+ """
+ if self._app is None:
+ return None
+ try:
+ with self._app.app_context():
+ sm = self._app.appbuilder.sm
+ if not hasattr(sm, "validate_api_key"):
+ logger.warning(
+ "FAB SecurityManager does not support validate_api_key; "
+ "rejecting API key token at transport"
+ )
+ return None
+ user = sm.validate_api_key(token)
+ username = user.username if user else None
+ # Unbind the local reference so this frame no longer points at
+ # the raw token (defense-in-depth). Python does not zero the
+ # underlying string memory on rebind.
+ token = "" # noqa: S105
+ return username
+ except Exception: # noqa: BLE001 — catch-all: DB errors, FAB internals, etc.
+ logger.warning(
+ "API key transport validation failed unexpectedly; rejecting token",
+ exc_info=True,
+ )
+ return None
+
+ async def verify_token(self, token: str) -> AccessToken | None:
+ """Verify a Bearer token.
+
+ For API key tokens (prefix match):
+ - When a Flask app is configured, validates the key against FAB at
+ the transport layer and rejects invalid keys with a transport-level
+ 401 before any MCP method is reached.
+ - When no app is configured (test/compat mode), falls back to prefix-
+ only acceptance and defers DB validation to the Flask layer.
+
+ For all other tokens, delegates to the wrapped JWT verifier when one
+ is configured; rejects if no JWT verifier is configured.
+ """
+ if any(token.startswith(prefix) for prefix in self._api_key_prefixes):
+ if self._app is not None:
+ loop = asyncio.get_running_loop()
+ username = await loop.run_in_executor(
+ None, self._validate_api_key_sync, token
+ )
+ if username is None:
+ logger.debug(
+ "API key rejected at transport layer (invalid or expired)"
+ )
+ return None
+ logger.debug(
+ "API key validated at transport layer for user=%s", username
+ )
+ return AccessToken(
+ token=token,
+ client_id="api_key",
+ scopes=list(self.required_scopes or []),
+ claims={
+ API_KEY_PASSTHROUGH_CLAIM: True,
+ API_KEY_VALIDATED_USERNAME_CLAIM: username,
+ },
+ )
+
+ # No app configured: fall back to prefix-only pass-through so
+ # ``_resolve_user_from_api_key`` handles DB validation.
+ # NOTE: ``MCP_REQUIRED_SCOPES`` is intentionally not enforced for
+ # API-key auth — FAB API keys do not carry scopes. Authorization is
+ # enforced downstream via ``check_tool_permission`` (RBAC).
+ logger.debug("API key token detected (prefix match), passing through")
+ return AccessToken(
+ token=token,
+ client_id="api_key",
+ scopes=list(self.required_scopes or []),
+ claims={API_KEY_PASSTHROUGH_CLAIM: True},
+ )
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>API key not redacted in no-app path</b></div>
<div id="fix">
In the no-app pass-through branch, after constructing the `AccessToken`, call the existing `_redact_access_token(access_token)` helper before returning it so that the raw API key is not retained in memory.
</div>
</div>
<small><i>Code Review Run #f58b7f</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
superset/mcp_service/server.py:
##########
@@ -679,7 +681,11 @@ def _create_auth_provider(flask_app: Any) -> Any | None:
except Exception:
# Do not log the exception — it may contain secrets
logger.error("Failed to create auth provider from MCP_AUTH_FACTORY")
- elif flask_app.config.get("MCP_AUTH_ENABLED", False):
+ elif (
+ flask_app.config.get("MCP_AUTH_ENABLED", False)
+ or flask_app.config.get("MCP_API_KEY_ENABLED", False)
+ or flask_app.config.get("FAB_API_KEY_ENABLED", False)
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Missing unit test coverage</b></div>
<div id="fix">
The new `FAB_API_KEY_ENABLED` condition (line 687) lacks a dedicated unit test. The existing test only covers `MCP_API_KEY_ENABLED=True`. Per the MCP service testing standard, all new code paths need unit tests. Add a test verifying `_create_auth_provider` triggers the default factory when only `FAB_API_KEY_ENABLED=True`.
</div>
</div>
<small><i>Code Review Run #f58b7f</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3357279421
##########
tests/unit_tests/mcp_service/test_mcp_config.py:
##########
@@ -224,3 +224,133 @@ def test_get_mcp_config_respects_app_config_override() -> None:
custom = {"execute_sql", "health_check"}
config = get_mcp_config({"MCP_DISABLED_TOOLS": custom})
assert config["MCP_DISABLED_TOOLS"] == custom
+
+
+def test_build_composite_verifier_string_prefix():
+ """A plain-string FAB_API_KEY_PREFIXES is wrapped into a single-element list."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ "sst_" if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_",)
+
+
+def test_build_composite_verifier_list_prefix():
+ """A list FAB_API_KEY_PREFIXES is passed through as-is."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ ["sst_", "api_"] if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_", "api_")
+
+
+def test_build_composite_verifier_invalid_prefix_falls_back_to_default():
+ """A non-iterable FAB_API_KEY_PREFIXES (e.g. None) falls back to ['sst_']."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ None if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_",)
+
+
+# -- get_mcp_api_key_enabled --
+
+
+def test_get_mcp_api_key_enabled_explicit_true():
+ """MCP_API_KEY_ENABLED=True returns True regardless of FAB setting."""
+ from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ True if key == "MCP_API_KEY_ENABLED" else default
+ )
+
+ assert get_mcp_api_key_enabled(mock_app) is True
Review Comment:
<!-- Bito Reply -->
The suggestion is valid and appropriate. It addresses the need to verify that the `startup_warning` parameter correctly triggers the expected logging behavior when `FAB_API_KEY_ENABLED` is set to `True`.
**tests/unit_tests/mcp_service/test_mcp_config.py**
```
def test_get_mcp_api_key_enabled_fab_fallback_logs_startup_warning():
from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
from unittest.mock import MagicMock, patch
mock_app = MagicMock()
mock_app.config.get.side_effect = lambda key, default=None: (
True if key == "FAB_API_KEY_ENABLED" else default
)
with patch("superset.mcp_service.mcp_config.logger") as mock_logger:
assert get_mcp_api_key_enabled(mock_app, startup_warning=True) is True
mock_logger.warning.assert_called_once()
```
##########
tests/unit_tests/mcp_service/test_mcp_config.py:
##########
@@ -224,3 +224,133 @@ def test_get_mcp_config_respects_app_config_override() -> None:
custom = {"execute_sql", "health_check"}
config = get_mcp_config({"MCP_DISABLED_TOOLS": custom})
assert config["MCP_DISABLED_TOOLS"] == custom
+
+
+def test_build_composite_verifier_string_prefix():
+ """A plain-string FAB_API_KEY_PREFIXES is wrapped into a single-element list."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ "sst_" if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_",)
+
+
+def test_build_composite_verifier_list_prefix():
+ """A list FAB_API_KEY_PREFIXES is passed through as-is."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ ["sst_", "api_"] if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_", "api_")
+
+
+def test_build_composite_verifier_invalid_prefix_falls_back_to_default():
+ """A non-iterable FAB_API_KEY_PREFIXES (e.g. None) falls back to ['sst_']."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ None if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_",)
+
+
+# -- get_mcp_api_key_enabled --
+
+
+def test_get_mcp_api_key_enabled_explicit_true():
+ """MCP_API_KEY_ENABLED=True returns True regardless of FAB setting."""
+ from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ True if key == "MCP_API_KEY_ENABLED" else default
+ )
+
+ assert get_mcp_api_key_enabled(mock_app) is True
+
+
+def test_get_mcp_api_key_enabled_explicit_false():
+ """MCP_API_KEY_ENABLED=False returns False even when FAB setting is True."""
+ from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ False if key == "MCP_API_KEY_ENABLED" else True
+ )
+
+ assert get_mcp_api_key_enabled(mock_app) is False
+
+
+def test_get_mcp_api_key_enabled_falls_back_to_fab():
+ """When MCP_API_KEY_ENABLED is not set, falls back to FAB_API_KEY_ENABLED."""
+ from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ None
+ if key == "MCP_API_KEY_ENABLED"
+ else (True if key == "FAB_API_KEY_ENABLED" else default)
+ )
+
+ assert get_mcp_api_key_enabled(mock_app) is True
+
+
+def test_get_mcp_api_key_enabled_both_absent_returns_false():
+ """When neither setting is configured, returns False."""
+ from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
+
+ mock_app = MagicMock()
+ mock_app.config.get.return_value = None
+
+ assert get_mcp_api_key_enabled(mock_app) is False
+
+
+# -- create_default_mcp_auth_factory --
+
+
+def test_create_default_mcp_auth_factory_returns_none_when_disabled():
+ """Returns None when neither MCP_AUTH_ENABLED nor API key auth is on."""
+ from superset.mcp_service.mcp_config import create_default_mcp_auth_factory
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ False
+ if key in ("MCP_AUTH_ENABLED", "MCP_API_KEY_ENABLED", "FAB_API_KEY_ENABLED")
+ else default
+ )
+
+ result = create_default_mcp_auth_factory(mock_app)
+
+ assert result is None
+
+
+def test_create_default_mcp_auth_factory_api_key_only():
+ """Returns a CompositeTokenVerifier when only API key auth is enabled."""
+ from superset.mcp_service.composite_token_verifier import CompositeTokenVerifier
+ from superset.mcp_service.mcp_config import create_default_mcp_auth_factory
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: {
+ "MCP_AUTH_ENABLED": False,
+ "MCP_API_KEY_ENABLED": True,
+ "FAB_API_KEY_PREFIXES": ["sst_"],
+ "MCP_REQUIRED_SCOPES": [],
+ }.get(key, default)
+
+ result = create_default_mcp_auth_factory(mock_app)
+
+ assert isinstance(result, CompositeTokenVerifier)
Review Comment:
<!-- Bito Reply -->
The pull request includes three new tests in `tests/unit_tests/mcp_service/test_mcp_config.py` that cover JWT-related branches of `create_default_mcp_auth_factory`. These tests address the following scenarios:
* **JWT enabled with keys:** Verifies that the factory returns the built verifier when JWT is enabled with a secret and API key authentication is disabled.
* **JWT enabled without keys:** Verifies that the factory returns `None` and logs a warning when JWT is enabled but no keys/secret are provided and there is no API-key fallback.
* **JWT build failure:** Verifies that the factory returns `None` and logs an error when `_build_jwt_verifier` raises a `ValueError` and there is no API-key fallback.
These additions improve the test coverage for the authentication factory's configuration logic.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4505111518
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4568854687
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4596788230
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3329454612
##########
superset/mcp_service/mcp_config.py:
##########
@@ -284,56 +287,88 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
- else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception:
Review Comment:
<!-- Bito Reply -->
The suggestion in the PR comment recommends replacing a bare `Exception` catch with specific exception types (`ValueError`, `KeyError`, `RuntimeError`) to avoid catching unintended errors. This is a valid and recommended practice in Python for error handling, as it increases code clarity and prevents masking unrelated issues. The suggestion is appropriate and should be applied if it aligns with the intended error-handling logic.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): create ApiKey permissions on init and support API keys with JWT auth [superset]
Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4309267833
## [Codecov](https://app.codecov.io/gh/apache/superset/pull/39604?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
:x: Patch coverage is `0%` with `30 lines` in your changes missing coverage. Please review.
:white_check_mark: Project coverage is 55.33%. Comparing base ([`4bdc8d4`](https://app.codecov.io/gh/apache/superset/commit/4bdc8d4c68102eccc1c3ffeeaa442d896b1f7a31?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`d7b92b1`](https://app.codecov.io/gh/apache/superset/commit/d7b92b10ac06e213c638d2cb8c43201356b9f9ad?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
:warning: Report is 102 commits behind head on master.
| [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/39604?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
|---|---|---|
| [superset/mcp\_service/composite\_token\_verifier.py](https://app.codecov.io/gh/apache/superset/pull/39604?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fcomposite_token_verifier.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvY29tcG9zaXRlX3Rva2VuX3ZlcmlmaWVyLnB5) | 0.00% | [14 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/39604?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [superset/mcp\_service/mcp\_config.py](https://app.codecov.io/gh/apache/superset/pull/39604?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fmcp_config.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvbWNwX2NvbmZpZy5weQ==) | 0.00% | [7 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/39604?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [superset/mcp\_service/auth.py](https://app.codecov.io/gh/apache/superset/pull/39604?src=pr&el=tree&filepath=superset%2Fmcp_service%2Fauth.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvbWNwX3NlcnZpY2UvYXV0aC5weQ==) | 0.00% | [6 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/39604?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
| [superset/security/manager.py](https://app.codecov.io/gh/apache/superset/pull/39604?src=pr&el=tree&filepath=superset%2Fsecurity%2Fmanager.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvc2VjdXJpdHkvbWFuYWdlci5weQ==) | 0.00% | [3 Missing :warning: ](https://app.codecov.io/gh/apache/superset/pull/39604?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
<details><summary>Additional details and impacted files</summary>
```diff
@@ Coverage Diff @@
## master #39604 +/- ##
==========================================
- Coverage 64.49% 55.33% -9.17%
==========================================
Files 2557 2564 +7
Lines 133097 133424 +327
Branches 30910 30971 +61
==========================================
- Hits 85846 73824 -12022
- Misses 45761 58948 +13187
+ Partials 1490 652 -838
```
| [Flag](https://app.codecov.io/gh/apache/superset/pull/39604/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
|---|---|---|
| [hive](https://app.codecov.io/gh/apache/superset/pull/39604/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [mysql](https://app.codecov.io/gh/apache/superset/pull/39604/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [postgres](https://app.codecov.io/gh/apache/superset/pull/39604/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [presto](https://app.codecov.io/gh/apache/superset/pull/39604/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `41.58% <0.00%> (-0.08%)` | :arrow_down: |
| [python](https://app.codecov.io/gh/apache/superset/pull/39604/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `41.58% <0.00%> (-20.58%)` | :arrow_down: |
| [sqlite](https://app.codecov.io/gh/apache/superset/pull/39604/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
| [unit](https://app.codecov.io/gh/apache/superset/pull/39604/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
</details>
[:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/superset/pull/39604?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
:loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
<details><summary> :rocket: New features to boost your workflow: </summary>
- :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
- :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): create ApiKey permissions on init and support API keys with JWT auth [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4310648462
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3237570512
##########
superset/mcp_service/auth.py:
##########
@@ -218,6 +220,25 @@
if access_token is None:
return None
+ # API key pass-through: CompositeTokenVerifier accepted this token
+ # at the transport layer but defers actual validation to
+ # _resolve_user_from_api_key() (priority 2 in get_user_from_request).
+ # Require client_id=="api_key" (set by CompositeTokenVerifier) in addition
+ # to the claim so that an external IdP JWT that happens to include the
+ # claim name is not misclassified as an API-key pass-through.
+ claims = getattr(access_token, "claims", None)
+ if isinstance(claims, dict) and claims.get(API_KEY_PASSTHROUGH_CLAIM):
+ if getattr(access_token, "client_id", None) == "api_key":
+ logger.debug(
+ "API key pass-through token detected, deferring to API key auth"
+ )
+ return None
+ logger.debug(
+ "Ignoring %s claim on non-API-key token (client_id=%r); processing as JWT",
+ API_KEY_PASSTHROUGH_CLAIM,
Review Comment:
## CodeQL / Clear-text logging of sensitive information
This expression logs [sensitive data (password)](1) as clear text.
This expression logs [sensitive data (password)](2) as clear text.
[Show more details](https://github.com/apache/superset/security/code-scanning/2283)
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3237598198
##########
superset/mcp_service/mcp_config.py:
##########
@@ -284,56 +287,88 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
- else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception: # noqa: BLE001 — JWT lib raises many types; broad catch intentional
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ api_key_prefixes = app.config.get("FAB_API_KEY_PREFIXES", ["sst_"])
+ logger.info("API key auth enabled for MCP")
+ return CompositeTokenVerifier(
+ jwt_verifier=jwt_verifier,
+ api_key_prefixes=api_key_prefixes,
+ )
Review Comment:
`FAB_API_KEY_PREFIXES` is read from config as `Any` and passed straight into `CompositeTokenVerifier`. If a user misconfigures this (e.g. sets a string or includes empty/whitespace prefixes), `token.startswith(prefix)` can misclassify tokens (or match everything), causing unexpected auth failures/DoS. Consider normalizing/validating here (coerce to a list of non-empty strings; otherwise fall back to the default and log a warning).
##########
superset/mcp_service/composite_token_verifier.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.
+
+"""
+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)
+
Review Comment:
`api_key_prefixes` is converted to a tuple and then used in `startswith` checks without any validation. If the list contains `""`/whitespace or non-strings, every token can match or matching can behave unexpectedly. Recommend filtering/validating prefixes in `__init__` (non-empty `str` only) and raising or warning on invalid config to avoid misclassification/DoS.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3244996744
##########
superset/security/manager.py:
##########
@@ -3164,6 +3169,60 @@ def get_user_by_username(self, username: str) -> Optional[User]:
.one_or_none()
)
+ def find_user_with_relationships(
+ self,
+ username: Optional[str] = None,
+ email: Optional[str] = None,
+ ) -> Optional[User]:
+ """Find a user with roles and group roles eagerly loaded.
+
+ Mirrors FAB's ``SecurityManager.find_user``
+ (including ``auth_username_ci`` case-insensitive handling and
+ ``MultipleResultsFound`` guard) and additionally eager-loads
+ ``User.roles`` and ``User.groups.roles`` to prevent detached-instance
+ errors when the SQLAlchemy session is closed or rolled back after the
+ lookup — as happens in MCP tool-execution contexts.
+ """
+ eager = [
+ joinedload(self.user_model.roles),
+ joinedload(self.user_model.groups).joinedload("roles"),
Review Comment:
In find_user_with_relationships(), the eager-load option uses a string-based loader path: joinedload(self.user_model.groups).joinedload("roles"). Elsewhere in Superset, joinedload() is consistently called with class-bound relationship attributes (not strings), which avoids typos and keeps the code forward-compatible with SQLAlchemy’s deprecations around string-based relationship names. Consider switching this to use the Group model’s roles attribute (e.g., via self.group_model.roles) instead of the string literal.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3253726181
##########
superset/mcp_service/auth.py:
##########
@@ -218,6 +220,25 @@
if access_token is None:
return None
+ # API key pass-through: CompositeTokenVerifier accepted this token
+ # at the transport layer but defers actual validation to
+ # _resolve_user_from_api_key() (priority 2 in get_user_from_request).
+ # Require client_id=="api_key" (set by CompositeTokenVerifier) in addition
+ # to the claim so that an external IdP JWT that happens to include the
+ # claim name is not misclassified as an API-key pass-through.
+ claims = getattr(access_token, "claims", None)
+ if isinstance(claims, dict) and claims.get(API_KEY_PASSTHROUGH_CLAIM):
+ if getattr(access_token, "client_id", None) == "api_key":
+ logger.debug(
+ "API key pass-through token detected, deferring to API key auth"
+ )
+ return None
+ logger.debug(
+ "Ignoring %s claim on non-API-key token (client_id=%r); processing as JWT",
+ API_KEY_PASSTHROUGH_CLAIM,
Review Comment:
This flag is against an older commit. In the current code at this location, `logger.debug('JWT-authenticated user not found in database (identity from JWT)')` logs a static string with no sensitive variables in format args. Addressed in commit `bf6136d0c8`.
##########
superset/mcp_service/composite_token_verifier.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.
+
+"""
+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)
+
Review Comment:
`CompositeTokenVerifier.__init__` already filters: `valid = [p for p in api_key_prefixes if isinstance(p, str) and p.strip()]`. Non-string or empty entries are silently dropped (count-only warning to avoid logging actual prefix values per CodeQL `py/clear-text-logging-sensitive-data`).
##########
superset/mcp_service/mcp_config.py:
##########
@@ -284,56 +287,88 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
- else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception: # noqa: BLE001 — JWT lib raises many types; broad catch intentional
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ api_key_prefixes = app.config.get("FAB_API_KEY_PREFIXES", ["sst_"])
+ logger.info("API key auth enabled for MCP")
+ return CompositeTokenVerifier(
+ jwt_verifier=jwt_verifier,
+ api_key_prefixes=api_key_prefixes,
+ )
Review Comment:
Addressed in commit `2a34d01ebb`: added a `try/except TypeError` around `list(raw_prefixes)` so non-iterable values (e.g. `None`, integers) fall back to `["sst_"]` with a warning instead of raising and causing `_create_auth_provider` to fail open.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): create ApiKey permissions on init and support API keys with JWT auth [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4309230215
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3232014743
##########
tests/unit_tests/mcp_service/test_auth_api_key.py:
##########
@@ -158,89 +195,154 @@ def test_g_user_fallback_when_no_jwt_or_api_key(app, mock_user) -> None:
assert result.username == "api_key_user"
-# -- FAB version without extract_api_key_from_request --
+# -- FAB version without validate_api_key --
@pytest.mark.usefixtures("_enable_api_keys")
-def test_fab_without_extract_method_skips_gracefully(app) -> None:
- """If FAB SecurityManager lacks extract_api_key_from_request,
- API key auth should be skipped with a debug log, not crash."""
+def test_fab_without_validate_method_raises(app: SupersetApp) -> None:
+ """If FAB SecurityManager lacks validate_api_key, should raise
+ PermissionError about unavailable validation."""
mock_sm = MagicMock(spec=[]) # empty spec = no attributes
- with app.test_request_context():
+ with app.app_context():
g.user = None
app.appbuilder = MagicMock()
app.appbuilder.sm = mock_sm
- with pytest.raises(ValueError, match="No authenticated user found"):
- get_user_from_request()
+ with _patch_access_token(_passthrough_access_token("sst_abc123")):
+ with pytest.raises(
+ PermissionError, match="API key validation is not available"
+ ):
+ get_user_from_request()
-# -- FAB version without validate_api_key --
+# -- Relationship reload fallback --
@pytest.mark.usefixtures("_enable_api_keys")
-def test_fab_without_validate_method_raises(app) -> None:
- """If FAB has extract_api_key_from_request but not validate_api_key,
- should raise PermissionError about unavailable validation."""
- mock_sm = MagicMock(spec=["extract_api_key_from_request"])
- mock_sm.extract_api_key_from_request.return_value = "sst_abc123"
+def test_relationship_reload_failure_returns_original_user(
+ app: SupersetApp, mock_user: MagicMock
+) -> None:
+ """If load_user_with_relationships fails, the original user from
+ validate_api_key should be returned as fallback."""
+ mock_sm = MagicMock()
+ mock_sm.validate_api_key.return_value = mock_user
- with app.test_request_context(headers={"Authorization": "Bearer sst_abc123"}):
+ with app.app_context():
g.user = None
app.appbuilder = MagicMock()
app.appbuilder.sm = mock_sm
- with pytest.raises(
- PermissionError, match="API key validation is not available"
+ with (
+ _patch_access_token(_passthrough_access_token("sst_abc123")),
+ patch(
+ "superset.mcp_service.auth.load_user_with_relationships",
+ return_value=None,
+ ),
):
- get_user_from_request()
+ result = get_user_from_request()
+
+ assert result is mock_user
-# -- Relationship reload fallback --
+# -- AccessToken without passthrough claim (plain JWT) -> skip API key auth --
@pytest.mark.usefixtures("_enable_api_keys")
-def test_relationship_reload_failure_returns_original_user(app, mock_user) -> None:
- """If load_user_with_relationships fails, the original user from
- validate_api_key should be returned as fallback."""
+def test_jwt_access_token_skips_api_key_auth(app: SupersetApp) -> None:
+ """When the AccessToken is a plain JWT (no ``_api_key_passthrough`` claim),
+ API key auth is skipped — the JWT was already validated by the JWT
+ verifier and resolved in _resolve_user_from_jwt_context."""
Review Comment:
Addressed. — agor claude on Amin's behalf
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4566624844
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3290466293
##########
superset/mcp_service/mcp_config.py:
##########
@@ -284,56 +287,88 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
- else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception:
Review Comment:
<!-- Bito Reply -->
The suggestion in the PR comment recommends replacing a bare `Exception` catch with specific exception types (`ValueError`, `KeyError`, `RuntimeError`) to avoid catching unintended errors. This is a valid and recommended practice in Python for error handling, as it increases code clarity and prevents masking unrelated issues. The suggestion is appropriate and should be applied if it aligns with the intended error-handling logic.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3351737006
##########
tests/unit_tests/mcp_service/test_mcp_config.py:
##########
@@ -224,3 +224,133 @@ def test_get_mcp_config_respects_app_config_override() -> None:
custom = {"execute_sql", "health_check"}
config = get_mcp_config({"MCP_DISABLED_TOOLS": custom})
assert config["MCP_DISABLED_TOOLS"] == custom
+
+
+def test_build_composite_verifier_string_prefix():
+ """A plain-string FAB_API_KEY_PREFIXES is wrapped into a single-element list."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ "sst_" if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_",)
+
+
+def test_build_composite_verifier_list_prefix():
+ """A list FAB_API_KEY_PREFIXES is passed through as-is."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ ["sst_", "api_"] if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_", "api_")
+
+
+def test_build_composite_verifier_invalid_prefix_falls_back_to_default():
+ """A non-iterable FAB_API_KEY_PREFIXES (e.g. None) falls back to ['sst_']."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ None if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_",)
+
+
+# -- get_mcp_api_key_enabled --
+
+
+def test_get_mcp_api_key_enabled_explicit_true():
+ """MCP_API_KEY_ENABLED=True returns True regardless of FAB setting."""
+ from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ True if key == "MCP_API_KEY_ENABLED" else default
+ )
+
+ assert get_mcp_api_key_enabled(mock_app) is True
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Incomplete test coverage</b></div>
<div id="fix">
Add a unit test that calls `get_mcp_api_key_enabled(mock_app, startup_warning=True)` when `FAB_API_KEY_ENABLED=True`, patch `superset.mcp_service.mcp_config.logger`, and assert that `logger.warning` is called.
</div>
</div>
<small><i>Code Review Run #6a33e2</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
##########
tests/unit_tests/mcp_service/test_mcp_config.py:
##########
@@ -224,3 +224,133 @@ def test_get_mcp_config_respects_app_config_override() -> None:
custom = {"execute_sql", "health_check"}
config = get_mcp_config({"MCP_DISABLED_TOOLS": custom})
assert config["MCP_DISABLED_TOOLS"] == custom
+
+
+def test_build_composite_verifier_string_prefix():
+ """A plain-string FAB_API_KEY_PREFIXES is wrapped into a single-element list."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ "sst_" if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_",)
+
+
+def test_build_composite_verifier_list_prefix():
+ """A list FAB_API_KEY_PREFIXES is passed through as-is."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ ["sst_", "api_"] if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_", "api_")
+
+
+def test_build_composite_verifier_invalid_prefix_falls_back_to_default():
+ """A non-iterable FAB_API_KEY_PREFIXES (e.g. None) falls back to ['sst_']."""
+ from superset.mcp_service.mcp_config import _build_composite_verifier
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ None if key == "FAB_API_KEY_PREFIXES" else default
+ )
+
+ result = _build_composite_verifier(mock_app, jwt_verifier=None)
+
+ assert result._api_key_prefixes == ("sst_",)
+
+
+# -- get_mcp_api_key_enabled --
+
+
+def test_get_mcp_api_key_enabled_explicit_true():
+ """MCP_API_KEY_ENABLED=True returns True regardless of FAB setting."""
+ from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ True if key == "MCP_API_KEY_ENABLED" else default
+ )
+
+ assert get_mcp_api_key_enabled(mock_app) is True
+
+
+def test_get_mcp_api_key_enabled_explicit_false():
+ """MCP_API_KEY_ENABLED=False returns False even when FAB setting is True."""
+ from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ False if key == "MCP_API_KEY_ENABLED" else True
+ )
+
+ assert get_mcp_api_key_enabled(mock_app) is False
+
+
+def test_get_mcp_api_key_enabled_falls_back_to_fab():
+ """When MCP_API_KEY_ENABLED is not set, falls back to FAB_API_KEY_ENABLED."""
+ from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ None
+ if key == "MCP_API_KEY_ENABLED"
+ else (True if key == "FAB_API_KEY_ENABLED" else default)
+ )
+
+ assert get_mcp_api_key_enabled(mock_app) is True
+
+
+def test_get_mcp_api_key_enabled_both_absent_returns_false():
+ """When neither setting is configured, returns False."""
+ from superset.mcp_service.mcp_config import get_mcp_api_key_enabled
+
+ mock_app = MagicMock()
+ mock_app.config.get.return_value = None
+
+ assert get_mcp_api_key_enabled(mock_app) is False
+
+
+# -- create_default_mcp_auth_factory --
+
+
+def test_create_default_mcp_auth_factory_returns_none_when_disabled():
+ """Returns None when neither MCP_AUTH_ENABLED nor API key auth is on."""
+ from superset.mcp_service.mcp_config import create_default_mcp_auth_factory
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: (
+ False
+ if key in ("MCP_AUTH_ENABLED", "MCP_API_KEY_ENABLED", "FAB_API_KEY_ENABLED")
+ else default
+ )
+
+ result = create_default_mcp_auth_factory(mock_app)
+
+ assert result is None
+
+
+def test_create_default_mcp_auth_factory_api_key_only():
+ """Returns a CompositeTokenVerifier when only API key auth is enabled."""
+ from superset.mcp_service.composite_token_verifier import CompositeTokenVerifier
+ from superset.mcp_service.mcp_config import create_default_mcp_auth_factory
+
+ mock_app = MagicMock()
+ mock_app.config.get.side_effect = lambda key, default=None: {
+ "MCP_AUTH_ENABLED": False,
+ "MCP_API_KEY_ENABLED": True,
+ "FAB_API_KEY_PREFIXES": ["sst_"],
+ "MCP_REQUIRED_SCOPES": [],
+ }.get(key, default)
+
+ result = create_default_mcp_auth_factory(mock_app)
+
+ assert isinstance(result, CompositeTokenVerifier)
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Incomplete test coverage for create_default_mcp_auth_factory</b></div>
<div id="fix">
BITO rule [11730] requires covering error scenarios. `create_default_mcp_auth_factory` has several untested paths: JWT enabled with keys, JWT enabled without keys, and JWT build failure. Only two of six+ meaningful branches are tested.
</div>
</div>
<small><i>Code Review Run #6a33e2</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3342387534
##########
tests/unit_tests/mcp_service/test_mcp_server.py:
##########
@@ -158,3 +158,26 @@ def test_create_event_store_returns_none_when_redis_store_fails():
result = create_event_store(config)
assert result is None
+
+
+def test_create_auth_provider_uses_default_factory_for_mcp_api_key_only() -> None:
+ """MCP_API_KEY_ENABLED=True should install auth even when FAB API keys are off."""
+ from superset.mcp_service.server import _create_auth_provider
+
+ flask_app = MagicMock()
+ flask_app.config.get.side_effect = lambda key, default=None: {
+ "MCP_AUTH_FACTORY": None,
+ "MCP_AUTH_ENABLED": False,
+ "MCP_API_KEY_ENABLED": True,
+ "FAB_API_KEY_ENABLED": False,
+ }.get(key, default)
+ auth_provider = MagicMock()
+
+ with patch(
+ "superset.mcp_service.mcp_config.create_default_mcp_auth_factory",
+ return_value=auth_provider,
+ ) as create_default_mcp_auth_factory:
+ result = _create_auth_provider(flask_app)
+
+ assert result is auth_provider
+ create_default_mcp_auth_factory.assert_called_once_with(flask_app)
Review Comment:
Done — added three tests in `test_mcp_config.py` (commit a28b3c0f) that directly invoke `_build_composite_verifier`:
1. String `FAB_API_KEY_PREFIXES` (`"sst_"`) → wrapped into `("sst_",)`
2. List `FAB_API_KEY_PREFIXES` (`["sst_", "api_"]`) → passed through as-is
3. `None` (non-iterable) → falls back to default `("sst_",)`
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3291840190
##########
superset/security/manager.py:
##########
@@ -3164,6 +3169,62 @@ def get_user_by_username(self, username: str) -> Optional[User]:
.one_or_none()
)
+ def find_user_with_relationships(
+ self,
+ username: Optional[str] = None,
+ email: Optional[str] = None,
+ ) -> Optional[User]:
+ """Find a user with roles and group roles eagerly loaded.
+
+ Mirrors FAB's ``SecurityManager.find_user``
+ (including ``auth_username_ci`` case-insensitive handling and
+ ``MultipleResultsFound`` guard) and additionally eager-loads
+ ``User.roles`` and ``User.groups.roles`` to prevent detached-instance
+ errors when the SQLAlchemy session is closed or rolled back after the
+ lookup — as happens in MCP tool-execution contexts.
+
+ FAB does not expose an eager-loading option on ``find_user``, so the
+ query logic is mirrored here with joinedload options added. Review this
+ method when upgrading FAB to ensure it stays in sync with upstream.
+ """
+ eager = [
+ joinedload(self.user_model.roles),
+ joinedload(self.user_model.groups).joinedload(self.group_model.roles),
+ ]
+ if username:
+ try:
+ if self.auth_username_ci:
+ return (
+ self.session.query(self.user_model)
+ .options(*eager)
+ .filter(
+ sa_func.lower(self.user_model.username)
+ == sa_func.lower(username)
+ )
+ .one_or_none()
+ )
+ return (
+ self.session.query(self.user_model)
+ .options(*eager)
+ .filter(self.user_model.username == username)
+ .one_or_none()
+ )
+ except MultipleResultsFound:
+ logger.error("Multiple results found for username lookup")
+ return None
+ if email:
+ try:
+ return (
+ self.session.query(self.user_model)
+ .options(*eager)
+ .filter_by(email=email)
Review Comment:
<div>
<div id="suggestion">
<div id="issue"><b>Query API inconsistency: email vs username</b></div>
<div id="fix">
Email lookup at line 3220 uses `.filter_by(email=email)` while username paths (lines 3209, 3201) use `.filter(self.user_model.username == ...)`. Mixing query styles creates maintenance risk if the model attribute name changes or if additional filters need to be added consistently.
</div>
</div>
<small><i>Code Review Run #3eb4cf</i></small>
</div>
---
Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
- [ ] Yes, avoid them
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3305649057
##########
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:
Addressed — the docstring was updated to reference the namespaced `API_KEY_PASSTHROUGH_CLAIM` (`_superset_mcp_api_key_passthrough`) in the same commit that fixed the claim naming. — agor claude on Amin's behalf
##########
superset/mcp_service/mcp_config.py:
##########
@@ -284,56 +287,88 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
- else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception:
Review Comment:
The current implementation uses `except TypeError:` specifically (not a bare `except Exception`), added intentionally to guard against non-iterable `FAB_API_KEY_PREFIXES` values like `None` or integers. This was addressed in an earlier commit. — agor claude on Amin's behalf
##########
superset/mcp_service/auth.py:
##########
@@ -218,6 +220,25 @@
if access_token is None:
return None
+ # API key pass-through: CompositeTokenVerifier accepted this token
+ # at the transport layer but defers actual validation to
+ # _resolve_user_from_api_key() (priority 2 in get_user_from_request).
+ # Require client_id=="api_key" (set by CompositeTokenVerifier) in addition
+ # to the claim so that an external IdP JWT that happens to include the
+ # claim name is not misclassified as an API-key pass-through.
+ claims = getattr(access_token, "claims", None)
+ if isinstance(claims, dict) and claims.get(API_KEY_PASSTHROUGH_CLAIM):
+ if getattr(access_token, "client_id", None) == "api_key":
+ logger.debug(
+ "API key pass-through token detected, deferring to API key auth"
+ )
+ return None
+ logger.debug(
+ "Ignoring %s claim on non-API-key token (client_id=%r); processing as JWT",
+ API_KEY_PASSTHROUGH_CLAIM,
Review Comment:
The CodeQL CI check (`Analyze (python)`) passes on this PR. The log statements in auth.py do not include raw token values — only metadata like user IDs and permission names. The alerts appear to be false positives from code scanning on earlier commits. — agor claude on Amin's behalf
##########
superset/mcp_service/mcp_config.py:
##########
@@ -284,56 +287,88 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
- else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception: # noqa: BLE001 — JWT lib raises many types; broad catch intentional
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ api_key_prefixes = app.config.get("FAB_API_KEY_PREFIXES", ["sst_"])
+ logger.info("API key auth enabled for MCP")
+ return CompositeTokenVerifier(
+ jwt_verifier=jwt_verifier,
+ api_key_prefixes=api_key_prefixes,
+ )
Review Comment:
Addressed. `FAB_API_KEY_PREFIXES` is now validated before being passed to `CompositeTokenVerifier`: plain strings are wrapped in a list, non-iterables fall back to the default, and `CompositeTokenVerifier.__init__` additionally filters out empty/non-string entries. — agor claude on Amin's behalf
##########
superset/mcp_service/composite_token_verifier.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.
+
+"""
+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)
+
Review Comment:
Addressed. `CompositeTokenVerifier.__init__` now validates and filters `api_key_prefixes` — non-string entries and empty/whitespace strings are dropped before the tuple is stored, and a warning is logged with the count of discarded entries (not the values themselves). — agor claude on Amin's behalf
##########
superset/mcp_service/composite_token_verifier.py:
##########
@@ -0,0 +1,113 @@
+# 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
+ valid: list[str] = [
+ p for p in api_key_prefixes if isinstance(p, str) and p.strip()
+ ]
+ invalid = [p for p in api_key_prefixes if p not in valid]
+ if invalid:
+ logger.warning(
+ "FAB_API_KEY_PREFIXES contains invalid entries (ignored): %r", invalid
Review Comment:
The CodeQL CI check (`Analyze (python)`) passes on this PR. The log statements in composite_token_verifier.py do not include raw token values — only count of invalid prefix entries and a generic prefix-match message. The alerts appear to be false positives. — agor claude on Amin's behalf
##########
tests/unit_tests/mcp_service/test_auth_api_key.py:
##########
@@ -54,100 +84,110 @@ def _disable_api_keys(app):
app.config["MCP_DEV_USERNAME"] = old_dev
+@contextmanager
+def _mock_sm_ctx(app: SupersetApp, mock_sm: MagicMock):
+ """Push an app context with g.user cleared and appbuilder.sm mocked.
+
+ Defaults find_user_with_relationships to None so JWT/dev-user lookups
+ that hit the SM (via load_user_with_relationships) behave as "user not
+ found" without a real DB, matching the pre-refactor db.session behavior.
+ Tests that need a specific return value should set it on mock_sm directly.
+ """
+ mock_sm.find_user_with_relationships.return_value = None
Review Comment:
`_mock_sm_ctx` does not access `find_user_with_relationships` directly — it only sets `app.appbuilder.sm = mock_sm`. Tests that need the `load_user_with_relationships` path also patch it directly via `patch('superset.mcp_service.auth.load_user_with_relationships', ...)`. All tests pass. — agor claude on Amin's behalf
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): create ApiKey permissions on init and support API keys with JWT auth [superset]
Posted by "github-advanced-security[bot] (via GitHub)" <gi...@apache.org>.
github-advanced-security[bot] commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3134629640
##########
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:
## CodeQL / Clear-text logging of sensitive information
This expression logs [sensitive data (password)](1) as clear text.
[Show more details](https://github.com/apache/superset/security/code-scanning/2277)
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): create ApiKey permissions on init and support API keys with JWT auth [superset]
Posted by "dpgaspar (via GitHub)" <gi...@apache.org>.
dpgaspar commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3209752054
##########
superset/security/manager.py:
##########
@@ -1361,6 +1361,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:
Adding `ApiKey` to `ADMIN_ONLY_VIEW_MENUS` should just work when FAB_API_KEY_ENABLED is True
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): create ApiKey permissions on init and support API keys with JWT auth [superset]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3210640701
##########
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 verify_token() says the pass-through AccessToken includes a ``_api_key_passthrough`` claim, but the implementation actually uses the namespaced claim constant API_KEY_PASSTHROUGH_CLAIM ("_superset_mcp_api_key_passthrough"). Please update the docstring to reflect the real claim name (or reference the constant) to avoid confusion when debugging auth flows.
##########
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:
This introduces new behavior in create_custom_permissions() to register ApiKey permissions when FAB_API_KEY_ENABLED is on, but there’s no accompanying unit test asserting these permissions get registered. There are already unit tests exercising create_custom_permissions() in the security test suite; please add coverage for the new ApiKey permissions to prevent regressions (e.g., permissions not being created and the API returning 403 again).
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4410745612
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4578845477
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3329454806
##########
superset/mcp_service/composite_token_verifier.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.
+
+"""
+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)
+
Review Comment:
Validation is in place in `CompositeTokenVerifier.__init__`. Prefixes are filtered to non-empty, non-whitespace strings via `[p for p in api_key_prefixes if isinstance(p, str) and p.strip()]`, and a warning (logging only the count, not the values) is emitted for any discarded entries. Tests covering empty, whitespace-only, non-string, and all-invalid-prefix cases are in `test_composite_token_verifier.py`.
##########
superset/mcp_service/composite_token_verifier.py:
##########
@@ -0,0 +1,113 @@
+# 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
+ valid: list[str] = [
+ p for p in api_key_prefixes if isinstance(p, str) and p.strip()
+ ]
+ invalid = [p for p in api_key_prefixes if p not in valid]
+ if invalid:
+ logger.warning(
+ "FAB_API_KEY_PREFIXES contains invalid entries (ignored): %r", invalid
Review Comment:
The current code does not log the token value. Debug messages in `verify_token` use fixed strings without interpolating the `token` parameter. This alert was filed against an earlier version of the file; no sensitive data is logged in the current implementation.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi merged PR #39604:
URL: https://github.com/apache/superset/pull/39604
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3245004464
##########
superset/security/manager.py:
##########
@@ -3164,6 +3169,60 @@ def get_user_by_username(self, username: str) -> Optional[User]:
.one_or_none()
)
+ def find_user_with_relationships(
+ self,
+ username: Optional[str] = None,
+ email: Optional[str] = None,
+ ) -> Optional[User]:
+ """Find a user with roles and group roles eagerly loaded.
+
+ Mirrors FAB's ``SecurityManager.find_user``
+ (including ``auth_username_ci`` case-insensitive handling and
+ ``MultipleResultsFound`` guard) and additionally eager-loads
+ ``User.roles`` and ``User.groups.roles`` to prevent detached-instance
+ errors when the SQLAlchemy session is closed or rolled back after the
+ lookup — as happens in MCP tool-execution contexts.
+ """
+ eager = [
+ joinedload(self.user_model.roles),
+ joinedload(self.user_model.groups).joinedload("roles"),
Review Comment:
Addressed — switched to `self.group_model.roles` (class-bound `InstrumentedAttribute`) in the `joinedload` chain.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "Copilot (via GitHub)" <gi...@apache.org>.
Copilot commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3245104183
##########
superset/mcp_service/mcp_config.py:
##########
@@ -291,56 +294,94 @@
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``FAB_API_KEY_ENABLED=True`` (API-key-only verifier that
+ rejects all non-API-key Bearer tokens at the transport).
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = app.config.get("FAB_API_KEY_ENABLED", False)
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except Exception: # noqa: BLE001 — JWT lib raises many types; broad catch intentional
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ raw_prefixes = app.config.get("FAB_API_KEY_PREFIXES", ["sst_"])
+ # Normalize: a plain string (e.g. "sst_") would iterate as characters;
+ # wrap it in a list so CompositeTokenVerifier receives a proper sequence.
+ if isinstance(raw_prefixes, str):
+ api_key_prefixes = [raw_prefixes]
else:
- # Default JWTVerifier: minimal logging, generic error responses.
- from fastmcp.server.auth.providers.jwt import JWTVerifier
+ api_key_prefixes = list(raw_prefixes)
Review Comment:
`FAB_API_KEY_PREFIXES` is read from `app.config` as `Any`, and the `else` branch does `api_key_prefixes = list(raw_prefixes)`. With Superset's strict mypy settings (`disallow_any_generics = true`), `list(raw_prefixes)` will be inferred as `list[Any]` (and can also raise at runtime if `raw_prefixes` is `None`/non-iterable). Consider narrowing/casting `raw_prefixes` to a `Sequence[str]` (and/or validating type and falling back to `["sst_"]` with a warning) before calling `list()` so both mypy and runtime behavior are robust.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3350593182
##########
superset/mcp_service/mcp_config.py:
##########
@@ -303,57 +314,142 @@
}
+def get_mcp_api_key_enabled(app: Flask, *, startup_warning: bool = False) -> bool:
+ """Return whether API key auth is enabled for the MCP transport.
+
+ Prefers ``MCP_API_KEY_ENABLED`` when explicitly set; falls back to
+ ``FAB_API_KEY_ENABLED``. When ``startup_warning=True`` and the value
+ is inherited from ``FAB_API_KEY_ENABLED``, logs a warning so operators
+ know a FAB config change now also affects the MCP transport.
+ """
+ if (mcp_setting := app.config.get("MCP_API_KEY_ENABLED", None)) is not None:
+ return bool(mcp_setting)
+ fab_enabled = bool(app.config.get("FAB_API_KEY_ENABLED", False))
+ if startup_warning and fab_enabled:
+ logger.warning(
+ "MCP API key auth is enabled via FAB_API_KEY_ENABLED=True. "
+ "Set MCP_API_KEY_ENABLED=True to silence this warning or "
+ "MCP_API_KEY_ENABLED=False to disable API keys on the MCP "
+ "transport without affecting the FAB REST API."
+ )
+ return fab_enabled
Review Comment:
Added in commit 8cef3fb2c2: four dedicated unit tests for `get_mcp_api_key_enabled` in `test_mcp_config.py` covering explicit `True`/`False` override, FAB fallback, and both-absent → `False`.
##########
superset/mcp_service/mcp_config.py:
##########
@@ -303,57 +314,142 @@
}
+def get_mcp_api_key_enabled(app: Flask, *, startup_warning: bool = False) -> bool:
+ """Return whether API key auth is enabled for the MCP transport.
+
+ Prefers ``MCP_API_KEY_ENABLED`` when explicitly set; falls back to
+ ``FAB_API_KEY_ENABLED``. When ``startup_warning=True`` and the value
+ is inherited from ``FAB_API_KEY_ENABLED``, logs a warning so operators
+ know a FAB config change now also affects the MCP transport.
+ """
+ if (mcp_setting := app.config.get("MCP_API_KEY_ENABLED", None)) is not None:
+ return bool(mcp_setting)
+ fab_enabled = bool(app.config.get("FAB_API_KEY_ENABLED", False))
+ if startup_warning and fab_enabled:
+ logger.warning(
+ "MCP API key auth is enabled via FAB_API_KEY_ENABLED=True. "
+ "Set MCP_API_KEY_ENABLED=True to silence this warning or "
+ "MCP_API_KEY_ENABLED=False to disable API keys on the MCP "
+ "transport without affecting the FAB REST API."
+ )
+ return fab_enabled
+
+
def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
- """Default MCP auth factory using app.config values."""
- if not app.config.get("MCP_AUTH_ENABLED", False):
- return None
+ """Default MCP auth factory using app.config values.
- jwks_uri = app.config.get("MCP_JWKS_URI")
- public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
- secret = app.config.get("MCP_JWT_SECRET")
+ Returns an auth provider when ``MCP_AUTH_ENABLED=True`` (JWT verifier,
+ optionally wrapped with ``CompositeTokenVerifier`` for API keys) or
+ when only ``MCP_API_KEY_ENABLED=True`` (or ``FAB_API_KEY_ENABLED=True``
+ as a fallback) — API-key-only verifier that rejects all non-API-key
+ Bearer tokens at the transport.
- if not (jwks_uri or public_key or secret):
- logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ ``MCP_API_KEY_ENABLED=None`` (default) defers to ``FAB_API_KEY_ENABLED``
+ and logs a startup warning when that setting is True, so operators are
+ aware that a FAB config change now also affects the MCP transport.
+ """
+ auth_enabled = app.config.get("MCP_AUTH_ENABLED", False)
+ api_key_enabled = get_mcp_api_key_enabled(app, startup_warning=True)
+
+ if not (auth_enabled or api_key_enabled):
return None
- try:
- debug_errors = app.config.get("MCP_JWT_DEBUG_ERRORS", False)
+ jwt_verifier: Any | None = None
- common_kwargs: dict[str, Any] = {
- "issuer": app.config.get("MCP_JWT_ISSUER"),
- "audience": app.config.get("MCP_JWT_AUDIENCE"),
- "required_scopes": app.config.get("MCP_REQUIRED_SCOPES", []),
- }
+ if auth_enabled:
+ jwks_uri = app.config.get("MCP_JWKS_URI")
+ public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
+ secret = app.config.get("MCP_JWT_SECRET")
- # For HS256 (symmetric), use the secret as the public_key parameter
- if app.config.get("MCP_JWT_ALGORITHM") == "HS256" and secret:
- common_kwargs["public_key"] = secret
- common_kwargs["algorithm"] = "HS256"
+ if not (jwks_uri or public_key or secret):
+ logger.warning("MCP_AUTH_ENABLED is True but no JWT keys/secret configured")
+ if not api_key_enabled:
+ return None
else:
- # For RS256 (asymmetric), use public key or JWKS
- common_kwargs["jwks_uri"] = jwks_uri
- common_kwargs["public_key"] = public_key
- common_kwargs["algorithm"] = app.config.get("MCP_JWT_ALGORITHM", "RS256")
-
- if debug_errors:
- # DetailedJWTVerifier: detailed server-side logging of JWT
- # validation failures. HTTP responses are always generic per
- # RFC 6750 Section 3.1.
- from superset.mcp_service.jwt_verifier import DetailedJWTVerifier
-
- auth_provider = DetailedJWTVerifier(**common_kwargs)
- else:
- # MCPJWTVerifier: minimal logging + browser-friendly error page.
- from superset.mcp_service.jwt_verifier import MCPJWTVerifier
-
- auth_provider = MCPJWTVerifier(**common_kwargs)
+ try:
+ jwt_verifier = _build_jwt_verifier(
+ app=app,
+ jwks_uri=jwks_uri,
+ public_key=public_key,
+ secret=secret,
+ )
+ except (ValueError, JoseError):
+ # Do not log the exception — it may contain secrets (e.g., key material)
+ logger.error("Failed to create MCP JWT verifier")
+ if not api_key_enabled:
+ return None
+
+ if api_key_enabled:
+ return _build_composite_verifier(app, jwt_verifier)
+
+ return jwt_verifier
Review Comment:
Added in commit 8cef3fb2c2: two direct unit tests for `create_default_mcp_auth_factory` in `test_mcp_config.py`: both-disabled → `None`, and API-key-only → `CompositeTokenVerifier`.
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "aminghadersohi (via GitHub)" <gi...@apache.org>.
aminghadersohi commented on code in PR #39604:
URL: https://github.com/apache/superset/pull/39604#discussion_r3305647526
##########
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:
Acknowledged. The behaviour is covered indirectly by the integration-level permission creation tests in , but a dedicated unit test asserting the PVM registration would improve confidence. Adding that unit test is a reasonable follow-up; it is out of scope for this auth-fix PR. — agor claude on Amin's behalf
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org
Re: [PR] fix(mcp): API key authentication for MCP — transport, validation, and RBAC [superset]
Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #39604:
URL: https://github.com/apache/superset/pull/39604#issuecomment-4557842157
AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
<details>
<summary>
Bito Usage Guide
</summary>
**Commands**
Type the following command in the pull request comment and save the comment.
- `/review` - Manually triggers a full AI review.
- `/pause` - Pauses automatic reviews on this pull request.
- `/resume` - Resumes automatic reviews.
- `/resolve` - Marks all Bito-posted review comments as resolved.
- `/abort` - Cancels all in-progress reviews.
Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
**Configuration**
This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
**Documentation & Help**
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
- <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
</details>
--
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: notifications-unsubscribe@superset.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org