You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by jl...@apache.org on 2026/08/10 22:56:52 UTC
(superset) branch master updated: fix(mcp): require issuer-aware resolver for multi-issuer JWT, fix sanitizer input ordering (#42935)
This is an automated email from the ASF dual-hosted git repository.
sadpandajoe pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/superset.git
The following commit(s) were added to refs/heads/master by this push:
new 265269018e0 fix(mcp): require issuer-aware resolver for multi-issuer JWT, fix sanitizer input ordering (#42935)
265269018e0 is described below
commit 265269018e07afec5f81ebc5687c88bfdcdd8fe9
Author: Evan Rusackas <ev...@preset.io>
AuthorDate: Mon Aug 10 15:56:46 2026 -0700
fix(mcp): require issuer-aware resolver for multi-issuer JWT, fix sanitizer input ordering (#42935)
Co-authored-by: Amin Ghadersohi <am...@gmail.com>
Co-authored-by: Claude Sonnet 5 <no...@anthropic.com>
---
UPDATING.md | 1 +
superset/mcp_service/PRODUCTION.md | 7 +
superset/mcp_service/SECURITY.md | 7 +
superset/mcp_service/auth.py | 27 +--
superset/mcp_service/mcp_config.py | 49 +++++
superset/mcp_service/utils/sanitization.py | 60 +++++-
.../mcp_service/test_auth_user_resolution.py | 52 ++----
.../test_mcp_multi_issuer_identity_binding.py | 201 +++++++++++++++++++++
.../utils/test_sanitization_unicode_ordering.py | 192 ++++++++++++++++++++
9 files changed, 534 insertions(+), 62 deletions(-)
diff --git a/UPDATING.md b/UPDATING.md
index 17d6acab740..da74ec93f1e 100644
--- a/UPDATING.md
+++ b/UPDATING.md
@@ -24,6 +24,7 @@ assists people when migrating to a new version.
## Next
+- [42935](https://github.com/apache/superset/pull/42935): The MCP service now refuses to start (`MCPAuthConfigError`) when `MCP_JWT_ISSUER` trusts more than one issuer and no `MCP_USER_RESOLVER` is configured, instead of only logging a warning. This was already a documented misconfiguration (the default resolver isn't issuer-scoped, so distinct trusted issuers minting the same username/email would resolve to the same Superset user); deployments trusting multiple issuers must configure an [...]
- [42393](https://github.com/apache/superset/pull/42393): Exported dataset YAML now carries a `uuid` for each metric and column so that custom folder assignments (which reference metrics/columns by UUID) survive an import into another workspace. This affects any export bundle that contains datasets, not just a dataset export: chart, dashboard, database and full-asset exports all embed the same dataset YAML, so a dashboard exported from this release also fails to import into an older one [...]
### Soft delete is on by default, and purging is live
diff --git a/superset/mcp_service/PRODUCTION.md b/superset/mcp_service/PRODUCTION.md
index ad402fee266..3bfffc6d9f7 100644
--- a/superset/mcp_service/PRODUCTION.md
+++ b/superset/mcp_service/PRODUCTION.md
@@ -82,6 +82,13 @@ MCP_REQUIRED_SCOPES = ["superset:read"]
MCP_DEV_USERNAME = None
```
+**Trusting Multiple Issuers**: `MCP_JWT_ISSUER` can be set to a list of
+issuers instead of a single string. Because the default user resolver maps
+token claims to Superset users by username/email without binding the
+token's `iss` claim, trusting more than one issuer requires configuring a
+custom, issuer-aware `MCP_USER_RESOLVER` (e.g. deriving a compound
+`iss`+`sub` identity). Without one, the service refuses to start.
+
**JWT Issuer Setup Examples**:
**Auth0**:
diff --git a/superset/mcp_service/SECURITY.md b/superset/mcp_service/SECURITY.md
index 26c9ed421a3..5c97eb3fbe8 100644
--- a/superset/mcp_service/SECURITY.md
+++ b/superset/mcp_service/SECURITY.md
@@ -74,6 +74,13 @@ MCP_JWT_ALGORITHM = "HS256"
MCP_JWT_SECRET = "your-shared-secret-key"
```
+**Multiple Trusted Issuers**: `MCP_JWT_ISSUER` may also be set to a list of
+issuers. The default user resolver maps token claims to Superset users by
+username/email without binding the token's `iss` claim, so trusting more
+than one issuer requires a custom, issuer-aware `MCP_USER_RESOLVER` (e.g.
+one that derives a compound `iss`+`sub` identity). The service refuses to
+start in this configuration until such a resolver is provided.
+
**JWT Token Structure**:
```json
diff --git a/superset/mcp_service/auth.py b/superset/mcp_service/auth.py
index 92df7ce81c5..d4383ad489f 100644
--- a/superset/mcp_service/auth.py
+++ b/superset/mcp_service/auth.py
@@ -60,6 +60,7 @@ from superset.mcp_service.guest_token_verifier import GUEST_TOKEN_CLAIM
from superset.mcp_service.mcp_config import (
default_user_resolver,
get_mcp_api_key_enabled,
+ validate_multi_issuer_user_resolver,
)
from superset.mcp_service.utils.error_sanitization import (
sanitize_for_log as _sanitize_for_log,
@@ -526,6 +527,10 @@ def _resolve_user_from_jwt_context(app: Any) -> MCPUser | None: # noqa: C901
Raises:
ValueError: If JWT resolves a username that doesn't exist in the DB
(fail closed — do NOT fall through to weaker auth sources).
+ MCPAuthConfigError: If more than one JWT issuer is trusted
+ (``MCP_JWT_ISSUER`` is a list/tuple/set) and no issuer-aware
+ ``MCP_USER_RESOLVER`` is configured (fail closed — see
+ ``validate_multi_issuer_user_resolver``).
"""
try:
from fastmcp.server.dependencies import get_access_token
@@ -591,23 +596,11 @@ def _resolve_user_from_jwt_context(app: Any) -> MCPUser | None: # noqa: C901
# Single-issuer deployments (the common case) are safe — the issuer is
# already pinned by the verifier, so the username space is unambiguous and
# we keep the existing lookup key to avoid breaking them. For multi-issuer
- # configs we warn: operators should provide an issuer-aware MCP_USER_RESOLVER
- # that derives a compound (iss + sub) identity. This is the least-breaking
- # correct option (warn, don't change the key out from under existing
- # single-issuer deployments).
- configured_issuer = app.config.get("MCP_JWT_ISSUER")
- if isinstance(configured_issuer, (list, tuple, set)) and len(configured_issuer) > 1:
- if not app.config.get("MCP_USER_RESOLVER"):
- token_iss = claims.get("iss") if isinstance(claims, dict) else None
- logger.warning(
- "Multiple JWT issuers are trusted (MCP_JWT_ISSUER is a list) but "
- "the default user resolver maps token claims to Superset users by "
- "username/email without binding the issuer (iss=%s). Distinct "
- "issuers minting the same username/email will collide. Configure an "
- "issuer-aware MCP_USER_RESOLVER to derive a compound (iss+sub) "
- "identity.",
- _sanitize_for_log(token_iss),
- )
+ # configs without an issuer-aware MCP_USER_RESOLVER, fail closed rather
+ # than resolving an identity that isn't actually scoped to the trusted
+ # issuer (mirrors the startup-time config checks in
+ # create_default_mcp_auth_factory / superset.initialization).
+ validate_multi_issuer_user_resolver(app)
# Use configurable resolver or default
diff --git a/superset/mcp_service/mcp_config.py b/superset/mcp_service/mcp_config.py
index 612448b98ca..cf085d4b365 100644
--- a/superset/mcp_service/mcp_config.py
+++ b/superset/mcp_service/mcp_config.py
@@ -510,6 +510,8 @@ def create_default_mcp_auth_factory(app: Flask) -> Optional[Any]:
jwt_verifier: Any | None = None
if auth_enabled:
+ validate_multi_issuer_user_resolver(app)
+
jwks_uri = app.config.get("MCP_JWKS_URI")
public_key = app.config.get("MCP_JWT_PUBLIC_KEY")
secret = app.config.get("MCP_JWT_SECRET")
@@ -568,6 +570,53 @@ def _is_mcp_guest_auth_enabled(app: Flask) -> bool:
return True
+def validate_multi_issuer_user_resolver(app: Flask) -> None:
+ """Reject a multi-issuer JWT trust config that has no issuer-aware resolver.
+
+ ``default_user_resolver`` maps token claims to Superset users by
+ username/email without binding the token's ``iss`` claim. When more than
+ one issuer is trusted (``MCP_JWT_ISSUER`` configured as a list/tuple/set),
+ that lookup is not issuer-scoped: distinct issuers minting the same
+ username or email claim would resolve to the identical Superset user.
+ Single-issuer deployments are unaffected — the issuer is already pinned
+ by the verifier, so the username space is unambiguous.
+
+ Operators trusting more than one issuer must supply an ``MCP_USER_RESOLVER``
+ that derives its identity from the token's ``iss`` claim (e.g. a compound
+ iss+sub identity), not merely one that returns a username or email, before
+ the service will consider that configuration usable. This function can only
+ confirm that a resolver is configured -- it cannot verify an arbitrary
+ operator-supplied callable actually binds the issuer; enforcing that is the
+ operator's responsibility.
+ """
+ configured_issuer = app.config.get("MCP_JWT_ISSUER")
+ if (
+ isinstance(configured_issuer, (list, tuple, set))
+ # str()-normalize before deduplicating: a plain set() would raise
+ # TypeError on unhashable entries (e.g. an accidental nested list),
+ # and that TypeError is not MCPAuthConfigError, so the caller's
+ # except MCPAuthConfigError / except Exception split would swallow
+ # it and fail OPEN (start unauthenticated) instead of fail closed.
+ and len({str(issuer) for issuer in configured_issuer}) > 1
+ and not app.config.get("MCP_USER_RESOLVER")
+ ):
+ # MCPAuthConfigError specifically: callers re-raise this type to
+ # refuse startup / fail closed rather than silently proceeding with
+ # an identity lookup that is not scoped to the trusted issuer.
+ raise MCPAuthConfigError(
+ "MCP_JWT_ISSUER trusts multiple issuers but no MCP_USER_RESOLVER "
+ "is configured. The default user resolver maps token claims to "
+ "Superset users by username/email without binding the issuer, so "
+ "distinct trusted issuers minting the same username/email would "
+ "resolve to the same Superset user. This check only confirms a "
+ "resolver is configured, not that it binds the issuer -- the "
+ "configured MCP_USER_RESOLVER MUST derive its identity from the "
+ "token's iss claim (e.g. a compound iss+sub identity), not just "
+ "username/email, or the same collision risk persists under a "
+ "custom resolver that happens to be username/email-only too."
+ )
+
+
def _validate_guest_config(app: Flask) -> None:
"""Hard-fail on the default GUEST_TOKEN_JWT_SECRET; warn on an unset audience."""
if app.config.get("GUEST_TOKEN_JWT_SECRET") == CHANGE_ME_GUEST_TOKEN_JWT_SECRET:
diff --git a/superset/mcp_service/utils/sanitization.py b/superset/mcp_service/utils/sanitization.py
index 089d2095ce0..a5dfd732347 100644
--- a/superset/mcp_service/utils/sanitization.py
+++ b/superset/mcp_service/utils/sanitization.py
@@ -385,8 +385,31 @@ def sanitize_user_input(
f"Maximum allowed length is {max_length} characters."
)
- # Strip all HTML tags using nh3
+ # Remove dangerous Unicode characters BEFORE any check so zero-widths
+ # smuggled inside a denylisted keyword can't slip past the pattern
+ # checks below (mirrors sanitize_sql_expression's ordering).
+ value = _remove_dangerous_unicode(value)
+
+ # Canonicalization above can reduce a truthy input (e.g. a lone
+ # zero-width character) to "" — recheck emptiness so that case still
+ # honors the documented non-empty / allow_empty contract instead of
+ # silently returning "".
+ if not value:
+ if allow_empty:
+ return None
+ raise ValueError(f"{field_name} cannot be empty")
+
+ # Strip all HTML tags using nh3. This decodes HTML entities internally
+ # (see _strip_html_tags), which can turn an entity-encoded zero-width
+ # character (e.g. "​") into the raw character -- re-run the
+ # Unicode strip below so an entity-encoded smuggling attempt is caught
+ # too, not just a raw one. Deliberately no emptiness recheck here: nh3
+ # legitimately reduces tag-heavy input (e.g. "<script>...</script>") to
+ # an empty string as the correct sanitized result, not an error case --
+ # unlike the recheck above, which guards the value *before* any content
+ # has been intentionally stripped away.
value = _strip_html_tags(value)
+ value = _remove_dangerous_unicode(value)
# Check for dangerous patterns (URL schemes, event handlers)
_check_dangerous_patterns(value, field_name)
@@ -395,9 +418,6 @@ def sanitize_user_input(
if check_sql_keywords:
_check_sql_patterns(value, field_name)
- # Remove dangerous Unicode characters
- value = _remove_dangerous_unicode(value)
-
return value
@@ -433,8 +453,18 @@ def sanitize_filter_value(
f"Maximum allowed length is {max_length} characters."
)
- # Strip all HTML tags using nh3
+ # Remove dangerous Unicode characters BEFORE any check so zero-widths
+ # smuggled inside a denylisted pattern can't slip past the pattern
+ # checks below (mirrors sanitize_sql_expression's ordering).
+ value = _remove_dangerous_unicode(value)
+
+ # Strip all HTML tags using nh3. This decodes HTML entities internally
+ # (see _strip_html_tags), which can turn an entity-encoded zero-width
+ # character (e.g. "​") into the raw character -- re-run the
+ # Unicode strip below so an entity-encoded smuggling attempt is caught
+ # too, not just a raw one.
value = _strip_html_tags(value)
+ value = _remove_dangerous_unicode(value)
# Check for dangerous patterns
_check_dangerous_patterns(value, "Filter value")
@@ -466,9 +496,6 @@ def sanitize_filter_value(
if re.search(r"\\x[0-9a-fA-F]{2}", value):
raise ValueError("Filter value contains hex encoding which is not allowed.")
- # Remove dangerous Unicode characters
- value = _remove_dangerous_unicode(value)
-
return value
@@ -518,8 +545,11 @@ def sanitize_sql_expression( # noqa: C901
f"Maximum allowed length is {max_length} characters."
)
- # Strip + decode entities BEFORE any check so zero-widths and entity
- # encoding can't smuggle past the tag-pattern / keyword scans.
+ # Strip zero-widths, then decode entities, then strip again: decoding
+ # can turn an entity-encoded zero-width character (e.g. "​") into
+ # the raw character, so a single strip-then-decode order would let an
+ # entity-encoded smuggling attempt through the tag-pattern / keyword
+ # scans below.
value = _remove_dangerous_unicode(value)
prev: str | None = None
iterations = 0
@@ -527,6 +557,16 @@ def sanitize_sql_expression( # noqa: C901
prev = value
value = html.unescape(value)
iterations += 1
+ value = _remove_dangerous_unicode(value)
+
+ # Canonicalization above can reduce a truthy input (e.g. a lone
+ # zero-width character) to "" — recheck emptiness so that case still
+ # honors the documented non-empty / allow_empty contract instead of
+ # silently returning "".
+ if not value:
+ if allow_empty:
+ return None
+ raise ValueError(f"{field_name} cannot be empty")
if _HTML_TAG_LIKE_RE.search(value):
raise ValueError(
diff --git a/tests/unit_tests/mcp_service/test_auth_user_resolution.py b/tests/unit_tests/mcp_service/test_auth_user_resolution.py
index 28bdc2ee38a..33dc1354841 100644
--- a/tests/unit_tests/mcp_service/test_auth_user_resolution.py
+++ b/tests/unit_tests/mcp_service/test_auth_user_resolution.py
@@ -608,40 +608,28 @@ def test_setup_user_context_allows_active_user(app) -> None:
# -- Multi-issuer binding guard --
-def test_multi_issuer_warns_without_custom_resolver(app, caplog) -> None:
+def test_multi_issuer_fails_closed_without_custom_resolver(app) -> None:
"""When multiple issuers are trusted and no issuer-aware resolver is set,
- a WARNING is emitted about unbound (non-issuer-scoped) user resolution."""
- import logging
+ resolution fails closed (raises) instead of returning a user via an
+ unbound (non-issuer-scoped) lookup."""
+ from superset.mcp_service.mcp_config import MCPAuthConfigError
- mock_user = _make_mock_user("alice")
token = _make_access_token(claims={"sub": "alice", "iss": "issuer-a"})
with app.app_context():
app.config["MCP_JWT_ISSUER"] = ["issuer-a", "issuer-b"]
try:
- with (
- caplog.at_level(logging.WARNING),
- patch(
- "fastmcp.server.dependencies.get_access_token", return_value=token
- ),
- patch(
- "superset.mcp_service.auth.load_user_with_relationships",
- return_value=mock_user,
- ),
+ with patch(
+ "fastmcp.server.dependencies.get_access_token", return_value=token
):
- result = _resolve_user_from_jwt_context(app)
+ with pytest.raises(MCPAuthConfigError):
+ _resolve_user_from_jwt_context(app)
finally:
app.config.pop("MCP_JWT_ISSUER", None)
- assert result is not None
- warnings = [r.message for r in caplog.records if r.levelno == logging.WARNING]
- assert any("Multiple JWT issuers are trusted" in m for m in warnings)
-
-
-def test_single_issuer_does_not_warn(app, caplog) -> None:
- """A single configured issuer is safe and emits no multi-issuer warning."""
- import logging
+def test_single_issuer_does_not_fail_closed(app) -> None:
+ """A single configured issuer is safe and resolves normally."""
mock_user = _make_mock_user("alice")
token = _make_access_token(claims={"sub": "alice", "iss": "issuer-a"})
@@ -649,7 +637,6 @@ def test_single_issuer_does_not_warn(app, caplog) -> None:
app.config["MCP_JWT_ISSUER"] = "issuer-a"
try:
with (
- caplog.at_level(logging.WARNING),
patch(
"fastmcp.server.dependencies.get_access_token", return_value=token
),
@@ -658,19 +645,16 @@ def test_single_issuer_does_not_warn(app, caplog) -> None:
return_value=mock_user,
),
):
- _resolve_user_from_jwt_context(app)
+ result = _resolve_user_from_jwt_context(app)
finally:
app.config.pop("MCP_JWT_ISSUER", None)
- warnings = [r.message for r in caplog.records if r.levelno == logging.WARNING]
- assert not any("Multiple JWT issuers are trusted" in m for m in warnings)
-
+ assert result is mock_user
-def test_multi_issuer_no_warn_with_custom_resolver(app, caplog) -> None:
- """A custom MCP_USER_RESOLVER (assumed issuer-aware) suppresses the
- multi-issuer warning."""
- import logging
+def test_multi_issuer_does_not_fail_closed_with_custom_resolver(app) -> None:
+ """A custom MCP_USER_RESOLVER (assumed issuer-aware) is exempt from the
+ multi-issuer fail-closed guard and resolves normally."""
mock_user = _make_mock_user("alice")
token = _make_access_token(claims={"sub": "alice", "iss": "issuer-a"})
@@ -679,7 +663,6 @@ def test_multi_issuer_no_warn_with_custom_resolver(app, caplog) -> None:
app.config["MCP_USER_RESOLVER"] = MagicMock(return_value="alice")
try:
with (
- caplog.at_level(logging.WARNING),
patch(
"fastmcp.server.dependencies.get_access_token", return_value=token
),
@@ -688,10 +671,9 @@ def test_multi_issuer_no_warn_with_custom_resolver(app, caplog) -> None:
return_value=mock_user,
),
):
- _resolve_user_from_jwt_context(app)
+ result = _resolve_user_from_jwt_context(app)
finally:
app.config.pop("MCP_JWT_ISSUER", None)
app.config.pop("MCP_USER_RESOLVER", None)
- warnings = [r.message for r in caplog.records if r.levelno == logging.WARNING]
- assert not any("Multiple JWT issuers are trusted" in m for m in warnings)
+ assert result is mock_user
diff --git a/tests/unit_tests/mcp_service/test_mcp_multi_issuer_identity_binding.py b/tests/unit_tests/mcp_service/test_mcp_multi_issuer_identity_binding.py
new file mode 100644
index 00000000000..6e608657a89
--- /dev/null
+++ b/tests/unit_tests/mcp_service/test_mcp_multi_issuer_identity_binding.py
@@ -0,0 +1,201 @@
+# 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.
+
+"""Identity-binding behavior of ``_resolve_user_from_jwt_context`` when more
+than one JWT issuer is trusted (``MCP_JWT_ISSUER`` configured as a list).
+
+The default resolver (``default_user_resolver``) derives a Superset username
+from token claims (``preferred_username`` / ``username`` / ``email`` / ``sub``)
+without folding the token's ``iss`` claim into the lookup key. Without an
+issuer-aware ``MCP_USER_RESOLVER``, two tokens minted by different trusted
+issuers but sharing a username claim would otherwise resolve to the
+identical Superset user, since the DB lookup would be performed on username
+alone.
+
+To prevent that, ``_resolve_user_from_jwt_context`` fails closed (raises
+``MCPAuthConfigError``) when more than one issuer is trusted and no custom
+``MCP_USER_RESOLVER`` is configured, instead of proceeding with a lookup that
+isn't scoped to the trusted issuer. An operator-supplied, issuer-aware
+resolver (e.g. one deriving a compound iss+sub identity) is unaffected and
+continues to resolve normally.
+"""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from superset.mcp_service.auth import _resolve_user_from_jwt_context
+from superset.mcp_service.mcp_config import (
+ MCPAuthConfigError,
+ validate_multi_issuer_user_resolver,
+)
+
+
+def _make_mock_user(username: str = "alice") -> MagicMock:
+ user = MagicMock()
+ user.username = username
+ user.roles = []
+ user.groups = []
+ return user
+
+
+def _make_access_token(claims: dict[str, str]) -> MagicMock:
+ token = MagicMock()
+ token.claims = claims
+ token.client_id = ""
+ token.scopes = []
+ for attr in ("subject", "payload"):
+ delattr(token, attr)
+ return token
+
+
+def test_multi_issuer_without_custom_resolver_fails_closed(app) -> None:
+ """Multiple trusted issuers with no issuer-aware ``MCP_USER_RESOLVER``
+ refuses to resolve an identity rather than performing a username-only
+ lookup that isn't scoped to the trusted issuer."""
+ token = _make_access_token(
+ claims={"sub": "alice", "iss": "https://issuer-a.example.com"}
+ )
+
+ with app.app_context():
+ app.config["MCP_JWT_ISSUER"] = [
+ "https://issuer-a.example.com",
+ "https://issuer-b.example.com",
+ ]
+ app.config.pop("MCP_USER_RESOLVER", None)
+ try:
+ with patch(
+ "fastmcp.server.dependencies.get_access_token",
+ return_value=token,
+ ):
+ with pytest.raises(MCPAuthConfigError):
+ _resolve_user_from_jwt_context(app)
+ finally:
+ app.config.pop("MCP_JWT_ISSUER", None)
+
+
+def test_duplicate_issuer_entries_do_not_fail_closed(app) -> None:
+ """A list/tuple naming the same issuer more than once is one logical
+ issuer, not a multi-issuer trust configuration -- deduplicate before
+ counting so ``MCP_JWT_ISSUER = ["a", "a"]`` doesn't trigger the guard
+ the way ``["a", "b"]`` correctly does."""
+ token = _make_access_token(
+ claims={"sub": "alice", "iss": "https://issuer-a.example.com"}
+ )
+ shared_user = _make_mock_user("alice")
+
+ with app.app_context():
+ app.config["MCP_JWT_ISSUER"] = [
+ "https://issuer-a.example.com",
+ "https://issuer-a.example.com",
+ ]
+ app.config.pop("MCP_USER_RESOLVER", None)
+ try:
+ with (
+ patch(
+ "fastmcp.server.dependencies.get_access_token",
+ return_value=token,
+ ),
+ patch(
+ "superset.mcp_service.auth.load_user_with_relationships",
+ return_value=shared_user,
+ ),
+ ):
+ result = _resolve_user_from_jwt_context(app)
+ finally:
+ app.config.pop("MCP_JWT_ISSUER", None)
+
+ assert result is shared_user
+
+
+def test_unhashable_issuer_entries_fail_closed_not_typeerror(app) -> None:
+ """A malformed ``MCP_JWT_ISSUER`` containing unhashable entries (e.g. a
+ nested list from a bad config template) must still fail closed with
+ ``MCPAuthConfigError``, not raise a bare ``TypeError`` from ``set()``.
+ A plain ``TypeError`` isn't caught by the ``except MCPAuthConfigError``
+ re-raise in ``_create_auth_provider``, so it would be swallowed by the
+ trailing ``except Exception`` there and start the server unauthenticated."""
+ with app.app_context():
+ app.config["MCP_JWT_ISSUER"] = [["issuer-a"], ["issuer-b"]]
+ app.config.pop("MCP_USER_RESOLVER", None)
+ try:
+ with pytest.raises(MCPAuthConfigError):
+ validate_multi_issuer_user_resolver(app)
+ finally:
+ app.config.pop("MCP_JWT_ISSUER", None)
+
+
+def test_multi_issuer_with_custom_resolver_resolves_normally(app) -> None:
+ """An operator-supplied, issuer-aware ``MCP_USER_RESOLVER`` is unaffected
+ by the multi-issuer guard: legitimate multi-issuer deployments that
+ provide their own resolver continue to resolve users normally."""
+ shared_user = _make_mock_user("alice")
+ token_from_issuer_a = _make_access_token(
+ claims={"sub": "alice", "iss": "https://issuer-a.example.com"}
+ )
+ token_from_issuer_b = _make_access_token(
+ claims={"sub": "alice", "iss": "https://issuer-b.example.com"}
+ )
+
+ # A stand-in issuer-aware resolver: derives a compound iss+sub identity
+ # instead of the default username/email-only lookup.
+ def _issuer_aware_resolver(_app: object, access_token: MagicMock) -> str:
+ claims = access_token.claims
+ return f"{claims['iss']}:{claims['sub']}"
+
+ with app.app_context():
+ app.config["MCP_JWT_ISSUER"] = [
+ "https://issuer-a.example.com",
+ "https://issuer-b.example.com",
+ ]
+ app.config["MCP_USER_RESOLVER"] = _issuer_aware_resolver
+ try:
+ with (
+ patch(
+ "fastmcp.server.dependencies.get_access_token",
+ return_value=token_from_issuer_a,
+ ),
+ patch(
+ "superset.mcp_service.auth.load_user_with_relationships",
+ return_value=shared_user,
+ ) as mock_load_a,
+ ):
+ result_a = _resolve_user_from_jwt_context(app)
+
+ with (
+ patch(
+ "fastmcp.server.dependencies.get_access_token",
+ return_value=token_from_issuer_b,
+ ),
+ patch(
+ "superset.mcp_service.auth.load_user_with_relationships",
+ return_value=shared_user,
+ ) as mock_load_b,
+ ):
+ result_b = _resolve_user_from_jwt_context(app)
+ finally:
+ app.config.pop("MCP_JWT_ISSUER", None)
+ app.config.pop("MCP_USER_RESOLVER", None)
+
+ assert result_a is shared_user
+ assert result_b is shared_user
+
+ # The custom resolver's compound iss+sub key is what reaches the DB
+ # lookup, not a bare username — confirming the guard doesn't interfere
+ # with a resolver that already binds identity to the issuer.
+ mock_load_a.assert_called_once_with("https://issuer-a.example.com:alice")
+ mock_load_b.assert_called_once_with("https://issuer-b.example.com:alice")
diff --git a/tests/unit_tests/mcp_service/utils/test_sanitization_unicode_ordering.py b/tests/unit_tests/mcp_service/utils/test_sanitization_unicode_ordering.py
new file mode 100644
index 00000000000..849cb1098a1
--- /dev/null
+++ b/tests/unit_tests/mcp_service/utils/test_sanitization_unicode_ordering.py
@@ -0,0 +1,192 @@
+# 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.
+
+"""
+Ordering of the zero-width-character removal step relative to the
+keyword/pattern denylist checks and HTML-entity decoding in
+``sanitize_user_input``, ``sanitize_filter_value``, and
+``sanitize_sql_expression``.
+
+All three functions now run ``_remove_dangerous_unicode`` *both* before and
+after HTML-entity decoding happens (entity decoding is internal to
+``_strip_html_tags`` for the first two functions, and an explicit loop in
+the third). Zero-width characters (e.g. U+200B ZERO WIDTH SPACE) can sit in
+the middle of a denylisted keyword and break a ``\\b(KEYWORD)\\b`` style
+match, whether they appear as a raw character or as an HTML entity
+(``​`` / ``​``) that only becomes the raw character after
+decoding. Stripping only before decoding catches the raw form but lets an
+entity-encoded one survive decoding and reach the denylist checks intact;
+stripping again after decoding closes that gap.
+"""
+
+import pytest
+
+from superset.mcp_service.utils.sanitization import (
+ sanitize_filter_value,
+ sanitize_sql_expression,
+ sanitize_user_input,
+)
+
+ZERO_WIDTH_CHARS = [
+ "", # ZERO WIDTH SPACE
+ "", # ZERO WIDTH NON-JOINER
+ "", # ZERO WIDTH JOINER
+ "", # ZERO WIDTH NO-BREAK SPACE / BOM
+]
+
+# Decimal and hex HTML entity encodings of ZERO WIDTH SPACE (U+200B) --
+# distinct textual forms that both decode to the same raw character.
+ZERO_WIDTH_SPACE_ENTITIES = [
+ "​",
+ "​",
+ "​",
+]
+
+
+# --- sanitize_user_input(check_sql_keywords=True) ---
+
+
+def test_sanitize_user_input_rejects_unsplit_sql_keyword():
+ """Baseline: an un-obfuscated denylisted keyword is rejected as documented."""
+ with pytest.raises(ValueError, match="unsafe SQL keywords"):
+ sanitize_user_input("DROP TABLE users", "Column name", check_sql_keywords=True)
+
+
+@pytest.mark.parametrize("zwc", ZERO_WIDTH_CHARS)
+def test_sanitize_user_input_rejects_split_keyword_payload(zwc):
+ """
+ A zero-width character placed inside the denylisted keyword ``DROP``
+ no longer defeats the ``\\b(DROP|...)\\b`` regex: unicode canonicalization
+ now runs before the keyword check, so the reconstructed keyword is what
+ the denylist check sees and a ``ValueError`` is raised, same as the
+ unobfuscated baseline.
+ """
+ obfuscated = f"DR{zwc}OP TABLE users"
+
+ with pytest.raises(ValueError, match="unsafe SQL keywords"):
+ sanitize_user_input(obfuscated, "Column name", check_sql_keywords=True)
+
+
+@pytest.mark.parametrize("entity", ZERO_WIDTH_SPACE_ENTITIES)
+def test_sanitize_user_input_rejects_entity_encoded_split_keyword_payload(entity):
+ """
+ An HTML-entity-encoded zero-width character only becomes the raw
+ character once ``_strip_html_tags`` decodes it -- if nothing re-checks
+ for dangerous Unicode after that decoding step, the reconstructed
+ keyword reaches the denylist check without ever having been
+ canonicalized, and the entity-encoded payload slips through where the
+ raw-character form (above) is caught. Stripping again after decoding
+ closes that gap.
+ """
+ obfuscated = f"DR{entity}OP TABLE users"
+
+ with pytest.raises(ValueError, match="unsafe SQL keywords"):
+ sanitize_user_input(obfuscated, "Column name", check_sql_keywords=True)
+
+
+def test_sanitize_user_input_still_removes_a_raw_dangerous_unicode_char():
+ """
+ Regression check: the second Unicode-strip pass must not stop the
+ function from silently removing a dangerous character that arrives
+ HTML-entity-encoded and isn't part of a denylisted keyword -- e.g.
+ U+2028 LINE SEPARATOR, a statement terminator on some SQL drivers per
+ this module's own docstring. This should sanitize to plain text, not
+ raise, matching the documented "removes dangerous Unicode" contract.
+ """
+ assert sanitize_user_input("a
b", "Column name") == "ab"
+
+
+def test_sanitize_user_input_tag_only_payload_reduces_to_empty_string():
+ """
+ Regression check: a tag-heavy input that nh3 legitimately strips down
+ to "" (e.g. "<script>...</script>") must sanitize to an empty string,
+ not raise -- there is deliberately no emptiness recheck immediately
+ after ``_strip_html_tags`` (only before it), since reducing to "" here
+ is the correct sanitized result of intentionally-stripped content, not
+ an error case like an all-zero-width input would be.
+ """
+ assert (
+ sanitize_user_input(
+ "<script>alert(1)</script>", "Column name", allow_empty=True
+ )
+ == ""
+ )
+
+
+# --- sanitize_filter_value ---
+
+
+def test_sanitize_filter_value_rejects_unsplit_union_select():
+ """Baseline: an un-obfuscated ``UNION SELECT`` pattern is rejected as documented."""
+ with pytest.raises(ValueError, match="malicious SQL patterns"):
+ sanitize_filter_value("UNION SELECT password FROM users")
+
+
+@pytest.mark.parametrize("zwc", ZERO_WIDTH_CHARS)
+def test_sanitize_filter_value_rejects_split_union_select_payload(zwc):
+ """
+ Same ordering fix as ``sanitize_user_input``: splitting ``UNION`` with a
+ zero-width character no longer defeats the ``UNION\\s+SELECT`` pattern
+ check, since canonicalization now runs first and the pattern check sees
+ the reconstructed value.
+ """
+ obfuscated = f"UNI{zwc}ON SELECT password FROM users" # noqa: S608
+
+ with pytest.raises(ValueError, match="malicious SQL patterns"):
+ sanitize_filter_value(obfuscated)
+
+
+@pytest.mark.parametrize("entity", ZERO_WIDTH_SPACE_ENTITIES)
+def test_sanitize_filter_value_rejects_entity_encoded_split_union_select_payload(
+ entity,
+):
+ """Entity-encoded counterpart of the raw zero-width case above."""
+ obfuscated = f"UNI{entity}ON SELECT password FROM users" # noqa: S608
+
+ with pytest.raises(ValueError, match="malicious SQL patterns"):
+ sanitize_filter_value(obfuscated)
+
+
+# --- sanitize_sql_expression ---
+
+
+def test_sanitize_sql_expression_rejects_same_split_keyword_payload():
+ """
+ ``sanitize_sql_expression`` strips dangerous Unicode both before and
+ after decoding HTML entities, so the same zero-width obfuscation
+ technique used against the two functions above does not defeat it
+ either: the value is canonicalized, decoded, then canonicalized again,
+ and the reconstructed ``DROP`` keyword is caught by the denylist check
+ as normal.
+ """
+ obfuscated = f"DR{ZERO_WIDTH_CHARS[0]}OP TABLE users"
+
+ with pytest.raises(ValueError, match="disallowed SQL keyword"):
+ sanitize_sql_expression(obfuscated, "SQL expression")
+
+
+@pytest.mark.parametrize("entity", ZERO_WIDTH_SPACE_ENTITIES)
+def test_sanitize_sql_expression_rejects_entity_encoded_split_keyword_payload(entity):
+ """
+ Entity-encoded counterpart of the raw zero-width case above: decoding
+ happens between the two Unicode-strip passes, so a zero-width character
+ that only exists as an HTML entity until decoded is still caught.
+ """
+ obfuscated = f"DR{entity}OP TABLE users"
+
+ with pytest.raises(ValueError, match="disallowed SQL keyword"):
+ sanitize_sql_expression(obfuscated, "SQL expression")