This is an automated email from the ASF dual-hosted git repository. villebro pushed a commit to branch 7.0 in repository https://gitbox.apache.org/repos/asf/superset.git
commit 738fb6739f2f796af1c620b991f2f8aabc5f68bd Author: Shaitan <[email protected]> AuthorDate: Tue Nov 10 15:11:54 2026 +0000 fix(embedded): validate guest token identity fields (#45452) Co-authored-by: Claude Opus 4.8 <[email protected]> Co-authored-by: Evan Rusackas <[email protected]> (cherry picked from commit d52c31ef689683b4efb2fa866fb2cff5024f9215) --- UPDATING.md | 14 ++ superset/config.py | 10 + superset/mcp_service/guest_token_verifier.py | 11 ++ superset/security/api.py | 3 + superset/security/guest_token.py | 112 ++++++++++++ superset/security/manager.py | 10 +- tests/integration_tests/security/api_tests.py | 41 ++++- .../mcp_service/test_guest_token_auth.py | 46 ++++- .../security/test_guest_token_identity.py | 201 +++++++++++++++++++++ 9 files changed, 433 insertions(+), 15 deletions(-) diff --git a/UPDATING.md b/UPDATING.md index ed5e245bffb..fc62161e684 100644 --- a/UPDATING.md +++ b/UPDATING.md @@ -26,6 +26,20 @@ assists people when migrating to a new version. ## 7.0.0 +- **Guest token identities are validated (warn-first).** The `username`, + `first_name` and `last_name` in a guest token's `user` claim are expected to be + strings of at most 255 characters with no control characters (including tab, + newline and carriage return) or Unicode line/paragraph separators. In this + release a value outside those bounds is logged (`Guest token identity + violation`) but still accepted, both when a token is minted and when it is + consumed, so existing integrations are not broken. Violations are also counted + under the `security.GuestTokenIdentityViolation` metric. Setting + `GUEST_TOKEN_IDENTITY_ENFORCE = True` in `superset_config.py` enforces it, and a + later release will make that the default: minting such a value then returns + HTTP 400 and an already-issued token carrying one is treated as unauthenticated. + Host applications that pass long display names or names containing those + characters should truncate or normalize them before then. + - With `ENABLE_VIEWERS` and `VIEWER_PROMISCUOUS_MODE` on, the dashboard grant follows the legacy `DASHBOARD_RBAC` model: only the listed viewers of a published dashboard read its charts and datasets without dataset permissions, diff --git a/superset/config.py b/superset/config.py index 76c4453aae7..5885e0d2fb1 100644 --- a/superset/config.py +++ b/superset/config.py @@ -3103,6 +3103,16 @@ GUEST_TOKEN_VALIDATOR_HOOK = None # version 0, so nothing is revoked until an admin explicitly bumps the version. GUEST_TOKEN_REVOCATION_ENABLED = False +# Enforces validation of the identity strings (username, first_name, last_name) +# carried in a guest token's user claim: at most 255 characters, no control +# characters or Unicode line/paragraph separators. +# +# While False (warn-first), an invalid identity is logged and counted under the +# `security.GuestTokenIdentityViolation` metric but still accepted. When True, +# minting such a token returns HTTP 400 and an already-issued token carrying one +# is treated as unauthenticated. +GUEST_TOKEN_IDENTITY_ENFORCE = False + # A SQL dataset health check. Note if enabled it is strongly advised that the callable # be memoized to aid with performance, i.e., # diff --git a/superset/mcp_service/guest_token_verifier.py b/superset/mcp_service/guest_token_verifier.py index 8b4fb022285..acb0d12f2e3 100644 --- a/superset/mcp_service/guest_token_verifier.py +++ b/superset/mcp_service/guest_token_verifier.py @@ -43,6 +43,11 @@ from typing import Any from fastmcp.server.auth import AccessToken from fastmcp.server.auth.providers.jwt import TokenVerifier +from superset.security.guest_token import ( + enforce_guest_token_identity, + GuestTokenIdentityError, +) + logger = logging.getLogger(__name__) # Namespaced claim flagging an AccessToken as a verified guest token. The paired @@ -112,6 +117,12 @@ class GuestTokenVerifier(TokenVerifier): logger.debug("Guest token failed structural validation; deferring") return None + try: + enforce_guest_token_identity(parsed["user"], parsed["resources"]) + except GuestTokenIdentityError: + logger.debug("Guest token carries an invalid identity; deferring") + return None + if sm._is_guest_token_revoked(parsed): # noqa: SLF001 logger.debug("Guest token has been revoked; rejecting") return None diff --git a/superset/security/api.py b/superset/security/api.py index 085fc6f7a28..e6104b35a9e 100644 --- a/superset/security/api.py +++ b/superset/security/api.py @@ -46,6 +46,7 @@ from superset.exceptions import SupersetGenericErrorException from superset.extensions import db, event_logger from superset.security.guest_token import ( build_guest_token_audit_payload, + GuestTokenIdentityError, GuestTokenResourceType, ) from superset.utils.core import get_user_id @@ -278,6 +279,8 @@ class SecurityRestApi(BaseSupersetApi): return self.response(403, message=error.message) except ValidationError as error: return self.response_400(message=error.messages) + except GuestTokenIdentityError as error: + return self.response_400(message=str(error)) class RoleRestAPI(BaseSupersetApi): diff --git a/superset/security/guest_token.py b/superset/security/guest_token.py index a40cfaf646c..adc058282e0 100644 --- a/superset/security/guest_token.py +++ b/superset/security/guest_token.py @@ -16,8 +16,10 @@ # under the License. import hashlib import logging +import re from typing import Any, Optional, TypedDict, Union +from flask import current_app from flask_appbuilder.security.sqla.models import Group, Role from flask_login import AnonymousUserMixin @@ -26,6 +28,20 @@ from superset.utils.backports import StrEnum logger = logging.getLogger(__name__) +def incr_security_metric(action: str) -> None: + """Increment the ``security.<action>`` metric, never raising.""" + # Deferred: superset.extensions imports the security manager, which imports + # this module. + from superset.extensions import ( # pylint: disable=import-outside-toplevel + stats_logger_manager, + ) + + try: + stats_logger_manager.instance.incr(f"security.{action}") + except Exception: # pylint: disable=broad-except + logger.warning("Failed to emit audit metric: %s", action, exc_info=True) + + def build_guest_token_audit_payload( issuer_user_id: Optional[int], source_ip: Optional[str], @@ -138,6 +154,102 @@ class GuestTokenUser(TypedDict, total=False): attributes: Optional[dict[str, Any]] +# Upper bound for the identity strings carried in a guest token's ``user`` +# claim, a generous bound for a display identity. +GUEST_TOKEN_IDENTITY_MAX_LENGTH = 255 +GUEST_TOKEN_IDENTITY_FIELDS = ("username", "first_name", "last_name") +# C0/C1 control characters plus the Unicode line/paragraph separators, i.e. +# everything ``str.splitlines()`` treats as a line break. +_INVALID_IDENTITY_CHARS_RE = re.compile(r"[\x00-\x1f\x7f-\x9f\u2028\u2029]") + + +class GuestTokenIdentityError(ValueError): + """Raised when a guest token's ``user`` claim carries an invalid identity.""" + + +class GuestTokenIdentityShapeError(GuestTokenIdentityError): + """The ``user`` claim is not an object at all; never warn-only.""" + + +def validate_guest_token_identity(user: Optional[GuestTokenUser]) -> None: + """Validate the identity strings carried in a guest token's ``user`` claim. + + ``username``/``first_name``/``last_name`` are supplied by the host + application that mints the token and later surface in log lines, cache + keys, and request context. Constrain them to bounded, single-line strings + where they enter the system, consistent with how other request-supplied + strings are validated: a display identity has no reason to carry control + characters or line separators (e.g. an embedded newline) or an unbounded + value. + + ``attributes`` is not covered: it is free-form, host-defined data whose + values are not display strings. + + A missing ``user`` claim is not rejected here; that check belongs to the + point where the token is consumed. + + :param user: the ``user`` claim from a guest token + :raises GuestTokenIdentityError: if a provided identity field is not a + valid string + """ + if user is None: + return + if not isinstance(user, dict): + raise GuestTokenIdentityShapeError("Guest token user must be an object") + for field in GUEST_TOKEN_IDENTITY_FIELDS: + value = user.get(field) + if value is None: + continue + if not isinstance(value, str): + raise GuestTokenIdentityError(f"Guest token {field} must be a string") + if len(value) > GUEST_TOKEN_IDENTITY_MAX_LENGTH: + raise GuestTokenIdentityError( + f"Guest token {field} exceeds the maximum length" + ) + if _INVALID_IDENTITY_CHARS_RE.search(value): + raise GuestTokenIdentityError( + f"Guest token {field} contains invalid characters" + ) + + +def enforce_guest_token_identity( + user: Optional[GuestTokenUser], + resources: Optional["GuestTokenResources"] = None, +) -> None: + """Validate a guest token identity, honoring the warn-first rollout flag. + + While ``GUEST_TOKEN_IDENTITY_ENFORCE`` is False an invalid identity is logged, + counted (``security.GuestTokenIdentityViolation``) and allowed through; once it + is True the underlying ``GuestTokenIdentityError`` propagates and the caller + rejects the token. A ``user`` claim that is not an object is always rejected, + since nothing downstream can build a guest user from it. Mint and consume + paths call this rather than ``validate_guest_token_identity`` directly. + + :param user: the ``user`` claim from a guest token + :param resources: the token's ``resources`` claim, logged to attribute the + violation to the embedded resource it was minted for + """ + try: + validate_guest_token_identity(user) + except GuestTokenIdentityShapeError: + raise + except GuestTokenIdentityError as exc: + if current_app.config["GUEST_TOKEN_IDENTITY_ENFORCE"]: + raise + incr_security_metric("GuestTokenIdentityViolation") + # ``resources`` is an unvalidated claim on the consume path. + resource_ids = ( + [r.get("id") for r in resources if isinstance(r, dict)] + if isinstance(resources, list) + else [] + ) + logger.warning( + "Guest token identity violation (warn-only): %s; resources=%s", + exc, + resource_ids, + ) + + class GuestTokenResourceType(StrEnum): DASHBOARD = "dashboard" diff --git a/superset/security/manager.py b/superset/security/manager.py index 4365e9fec32..b4ce07860fd 100644 --- a/superset/security/manager.py +++ b/superset/security/manager.py @@ -86,6 +86,7 @@ from superset.exceptions import ( ) from superset.security.guest_token import ( DEFAULT_GUEST_TOKEN_REVOCATION_VERSION, + enforce_guest_token_identity, get_current_guest_token_revocation_version, GUEST_TOKEN_REVOCATION_CLAIM, GuestToken, @@ -94,6 +95,7 @@ from superset.security.guest_token import ( GuestTokenRlsRule, GuestTokenUser, GuestUser, + incr_security_metric, ) from superset.sql.parse import process_jinja_sql, Table from superset.tasks.utils import get_current_user @@ -286,13 +288,9 @@ def _log_audit_event(action: str, payload: dict[str, Any]) -> None: """ from superset.extensions import ( # pylint: disable=import-outside-toplevel event_logger, - stats_logger_manager, ) - try: - stats_logger_manager.instance.incr(f"security.{action}") - except Exception: # pylint: disable=broad-except - logger.warning("Failed to emit audit metric: %s", action, exc_info=True) + incr_security_metric(action) user_id = get_user_id() try: @@ -6144,6 +6142,7 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods rls: list[GuestTokenRlsRule], datasets: Optional[list[int]] = None, ) -> bytes: + enforce_guest_token_identity(user, resources) secret = get_conf()["GUEST_TOKEN_JWT_SECRET"] algo = get_conf()["GUEST_TOKEN_JWT_ALGO"] exp_seconds = get_conf()["GUEST_TOKEN_JWT_EXP_SECONDS"] @@ -6202,6 +6201,7 @@ class SupersetSecurityManager( # pylint: disable=too-many-public-methods raise ValueError("Guest token does not contain a user claim") if token.get("resources") is None: raise ValueError("Guest token does not contain a resources claim") + enforce_guest_token_identity(token["user"], token["resources"]) if token.get("rls_rules") is None: raise ValueError("Guest token does not contain an rls_rules claim") if token.get("type") != "guest": diff --git a/tests/integration_tests/security/api_tests.py b/tests/integration_tests/security/api_tests.py index 0dcdc13102e..a317b4c9333 100644 --- a/tests/integration_tests/security/api_tests.py +++ b/tests/integration_tests/security/api_tests.py @@ -368,6 +368,22 @@ class TestSecurityGuestTokenApi(SupersetTestCase): assert "attributes" not in decoded_token["user"] assert resource == decoded_token["resources"][0] + @with_config({"GUEST_TOKEN_IDENTITY_ENFORCE": True}) + @pytest.mark.usefixtures("load_birth_names_dashboard_with_slices") + def test_post_guest_token_invalid_identity(self) -> None: + self.dash = db.session.query(Dashboard).filter_by(slug="births").first() + self.embedded = EmbeddedDashboardDAO.upsert(self.dash, []) + self.login(ADMIN_USERNAME) + user = {"username": "bob\nalice", "first_name": "Bob", "last_name": "Bob"} + resource = {"type": "dashboard", "id": str(self.embedded.uuid)} + params = {"user": user, "resources": [resource], "rls": []} + + response = self.client.post( + self.uri, data=json.dumps(params), content_type="application/json" + ) + + self.assert400(response) + @pytest.mark.usefixtures("load_birth_names_dashboard_with_slices") def test_post_guest_token_bad_resources(self): self.login(ADMIN_USERNAME) @@ -437,6 +453,21 @@ class TestSecurityGuestTokenApiTokenValidator(SupersetTestCase): rls_rule = {"dataset": 1, "clause": "tenant_id=123"} self.assert200(self._get_guest_token_with_rls(rls_rule)) + @with_config( + { + "GUEST_TOKEN_VALIDATOR_HOOK": lambda x: ( + x["user"].update(username="bob\nalice") is None + ) + } + ) + @with_config({"GUEST_TOKEN_IDENTITY_ENFORCE": True}) + def test_guest_token_invalid_identity_after_hook(self): + """ + Security API: an identity made invalid by the validator hook is a 400 + """ + rls_rule = {"dataset": 1, "clause": "tenant_id=123"} + self.assert400(self._get_guest_token_with_rls(rls_rule)) + @with_config({"GUEST_TOKEN_VALIDATOR_HOOK": 123}) def test_guest_validator_hook_not_callable(self): """ @@ -456,8 +487,9 @@ class TestSecurityGuestTokenApiTokenValidator(SupersetTestCase): @with_config( { - "GUEST_TOKEN_VALIDATOR_HOOK": lambda x: len(x["rls"]) == 1 - and "tenant_id=" in x["rls"][0]["clause"] + "GUEST_TOKEN_VALIDATOR_HOOK": lambda x: ( + len(x["rls"]) == 1 and "tenant_id=" in x["rls"][0]["clause"] + ) } ) def test_guest_validator_hook_real_world_example_positive(self): @@ -472,8 +504,9 @@ class TestSecurityGuestTokenApiTokenValidator(SupersetTestCase): @with_config( { - "GUEST_TOKEN_VALIDATOR_HOOK": lambda x: len(x["rls"]) == 1 - and "tenant_id=" in x["rls"][0]["clause"] + "GUEST_TOKEN_VALIDATOR_HOOK": lambda x: ( + len(x["rls"]) == 1 and "tenant_id=" in x["rls"][0]["clause"] + ) } ) def test_guest_validator_hook_real_world_example_negative(self): diff --git a/tests/unit_tests/mcp_service/test_guest_token_auth.py b/tests/unit_tests/mcp_service/test_guest_token_auth.py index 09e5fca9830..0c6d343c7a5 100644 --- a/tests/unit_tests/mcp_service/test_guest_token_auth.py +++ b/tests/unit_tests/mcp_service/test_guest_token_auth.py @@ -26,7 +26,7 @@ Covers the three layers of the feature: - The guest deny-list for sensitive enumeration tools. """ -from contextlib import contextmanager +from contextlib import nullcontext from types import SimpleNamespace from typing import Any from unittest.mock import MagicMock, patch @@ -34,7 +34,7 @@ from unittest.mock import MagicMock, patch import jwt import pytest from fastmcp.server.auth import AccessToken -from flask import g +from flask import Flask, g from superset.app import SupersetApp from superset.constants import CHANGE_ME_GUEST_TOKEN_JWT_SECRET @@ -84,13 +84,17 @@ def _parsed_guest_claims(**overrides: Any) -> dict[str, Any]: class _FakeApp: """Minimal Flask-app stand-in for unit-testing GuestTokenVerifier.""" - def __init__(self, config: dict[str, Any], sm: Any) -> None: + def __init__(self, config: dict[str, Any], sm: Any, flask_app: Any = None) -> None: self.config = config self.appbuilder = SimpleNamespace(sm=sm) + # A real app whose context is pushed in the verifier's worker thread, for + # code under test that reads ``current_app``. + self._flask_app = flask_app - @contextmanager def app_context(self) -> Any: - yield + if self._flask_app is None: + return nullcontext() + return self._flask_app.app_context() def _make_guest_verifier( @@ -100,6 +104,7 @@ def _make_guest_verifier( revoked: bool = False, role_exists: bool = True, mcp_enabled: bool = True, + flask_app: Any = None, ) -> tuple[GuestTokenVerifier, MagicMock]: sm = MagicMock() if parse_error is not None: @@ -114,7 +119,7 @@ def _make_guest_verifier( "MCP_EMBEDDED_GUEST_AUTH_ENABLED": mcp_enabled, "GUEST_ROLE_NAME": "Public", } - return GuestTokenVerifier(app=_FakeApp(config, sm)), sm + return GuestTokenVerifier(app=_FakeApp(config, sm, flask_app)), sm # -- GuestTokenVerifier -- @@ -183,6 +188,35 @@ async def test_guest_verifier_rejects_missing_structural_claims() -> None: assert token is None [email protected] +async def test_guest_verifier_rejects_invalid_identity(app: Flask) -> None: + # enforce path: with the rollout flag on, a bad identity is rejected + verifier, _ = _make_guest_verifier( + parsed=_parsed_guest_claims(user={"username": "embed\nguest"}), + flask_app=app, + ) + with ( + patch("superset.is_feature_enabled", return_value=True), + patch.dict(app.config, {"GUEST_TOKEN_IDENTITY_ENFORCE": True}), + ): + token = await verifier.verify_token("raw-guest-token") + + assert token is None + + [email protected] +async def test_guest_verifier_warns_but_accepts_invalid_identity(app: Flask) -> None: + # warn-first default: a bad identity is logged but still accepted + verifier, _ = _make_guest_verifier( + parsed=_parsed_guest_claims(user={"username": "embed\nguest"}), + flask_app=app, + ) + with patch("superset.is_feature_enabled", return_value=True): + token = await verifier.verify_token("raw-guest-token") + + assert token is not None + + @pytest.mark.asyncio async def test_guest_verifier_rejects_revoked_token() -> None: verifier, _ = _make_guest_verifier(revoked=True) diff --git a/tests/unit_tests/security/test_guest_token_identity.py b/tests/unit_tests/security/test_guest_token_identity.py new file mode 100644 index 00000000000..a89abd15ef3 --- /dev/null +++ b/tests/unit_tests/security/test_guest_token_identity.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. +"""Validation of the identity strings carried in a guest token's user claim.""" + +from typing import Any, cast +from unittest.mock import patch + +import pytest +from flask import current_app +from pytest_mock import MockerFixture + +from superset.extensions import appbuilder +from superset.security.guest_token import ( + enforce_guest_token_identity, + GUEST_TOKEN_IDENTITY_FIELDS, + GUEST_TOKEN_IDENTITY_MAX_LENGTH, + GuestTokenIdentityError, + GuestTokenIdentityShapeError, + GuestTokenResources, + GuestTokenResourceType, + GuestTokenUser, + validate_guest_token_identity, +) +from superset.security.manager import SupersetSecurityManager + +RESOURCES: GuestTokenResources = [ + {"type": GuestTokenResourceType.DASHBOARD, "id": "some-uuid"} +] + + +def _identity(field: str, value: Any) -> GuestTokenUser: + """A single-field user claim, keyed dynamically for parametrized tests.""" + return cast(GuestTokenUser, {field: value}) + + +def test_plain_identity_is_accepted() -> None: + validate_guest_token_identity( + {"username": "[email protected]", "first_name": "Ada", "last_name": "Lovelace"} + ) + + +def test_missing_fields_are_accepted() -> None: + # every identity field is optional; absence must not raise + validate_guest_token_identity({}) + validate_guest_token_identity({"username": "only-username"}) + + +def test_missing_user_claim_is_accepted() -> None: + validate_guest_token_identity(None) + + +def test_non_object_user_claim_is_rejected() -> None: + with pytest.raises(GuestTokenIdentityShapeError, match="must be an object"): + validate_guest_token_identity(cast(GuestTokenUser, "[email protected]")) + + +def test_non_object_user_claim_is_rejected_while_warn_only(app_context: None) -> None: + # a non-object claim cannot become a guest user, so it is never warn-only + with pytest.raises(GuestTokenIdentityShapeError): + enforce_guest_token_identity(cast(GuestTokenUser, "[email protected]")) + + +def test_warn_only_violation_is_logged_and_counted( + mocker: MockerFixture, app_context: None +) -> None: + incr = mocker.patch("superset.extensions.stats_logger_manager.instance.incr") + warning = mocker.patch("superset.security.guest_token.logger.warning") + + enforce_guest_token_identity({"username": "bob\nalice"}, RESOURCES) + + incr.assert_called_once_with("security.GuestTokenIdentityViolation") + assert warning.call_args.args[-1] == ["some-uuid"] + + [email protected]("field", GUEST_TOKEN_IDENTITY_FIELDS) [email protected]( + "value", + [ + "line-one\nline-two", + "carriage\rreturn", + "tab\tseparated", + "trailing-newline\n", + "null\x00byte", + "line\u2028separator", + "paragraph\u2029separator", + ], +) +def test_control_characters_are_rejected(field: str, value: str) -> None: + with pytest.raises(ValueError, match="invalid characters"): + validate_guest_token_identity(_identity(field, value)) + + [email protected]("field", GUEST_TOKEN_IDENTITY_FIELDS) +def test_overlong_value_is_rejected(field: str) -> None: + with pytest.raises(ValueError, match="maximum length"): + validate_guest_token_identity( + _identity(field, "x" * (GUEST_TOKEN_IDENTITY_MAX_LENGTH + 1)) + ) + + +def test_value_at_maximum_length_is_accepted() -> None: + validate_guest_token_identity({"username": "x" * GUEST_TOKEN_IDENTITY_MAX_LENGTH}) + + [email protected]("field", GUEST_TOKEN_IDENTITY_FIELDS) +def test_non_string_value_is_rejected(field: str) -> None: + with pytest.raises(ValueError, match="must be a string"): + validate_guest_token_identity(_identity(field, 123)) + + +def test_mint_rejects_invalid_identity(app_context: None) -> None: + # enforce path: with the rollout flag on, minting a bad identity is rejected + sm = SupersetSecurityManager(appbuilder) + with ( + patch.dict(current_app.config, {"GUEST_TOKEN_IDENTITY_ENFORCE": True}), + pytest.raises(GuestTokenIdentityError), + ): + sm.create_guest_access_token({"username": "bob\nalice"}, RESOURCES, []) + + +def _guest_request(mocker: MockerFixture, raw_token: bytes) -> Any: + request = mocker.MagicMock() + request.headers = {current_app.config["GUEST_TOKEN_HEADER_NAME"]: raw_token} + request.form = {} + return request + + [email protected]( + "username", + ["x" * (GUEST_TOKEN_IDENTITY_MAX_LENGTH + 1), "trailing-newline\n"], + ids=["overlong", "trailing-newline"], +) +def test_invalid_identity_rejected_through_request_flow( + mocker: MockerFixture, app_context: None, username: str +) -> None: + """Enforce path: a token carrying a bad identity no longer resolves to a guest.""" + sm = SupersetSecurityManager(appbuilder) + # Stand in for a token minted before identity validation existed (skip the + # mint-time check so the consume-side check is what rejects it). + with patch("superset.security.manager.enforce_guest_token_identity"): + raw_token = sm.create_guest_access_token({"username": username}, RESOURCES, []) + + with patch.dict(current_app.config, {"GUEST_TOKEN_IDENTITY_ENFORCE": True}): + assert sm.get_guest_user_from_request(_guest_request(mocker, raw_token)) is None + + +def test_valid_identity_resolves_through_request_flow( + mocker: MockerFixture, app_context: None +) -> None: + sm = SupersetSecurityManager(appbuilder) + raw_token = sm.create_guest_access_token({"username": "guest"}, RESOURCES, []) + + guest_user = sm.get_guest_user_from_request(_guest_request(mocker, raw_token)) + assert guest_user is not None + assert guest_user.username == "guest" + + +def test_invalid_identity_still_resolves_under_default_config( + mocker: MockerFixture, app_context: None +) -> None: + """Warn-first default: a bad identity is minted and consumed, not rejected.""" + assert current_app.config["GUEST_TOKEN_IDENTITY_ENFORCE"] is False + sm = SupersetSecurityManager(appbuilder) + raw_token = sm.create_guest_access_token({"username": "bob\nalice"}, RESOURCES, []) + + guest_user = sm.get_guest_user_from_request(_guest_request(mocker, raw_token)) + assert guest_user is not None + assert guest_user.username == "bob\nalice" + + +def test_non_object_user_claim_rejected_through_request_flow( + mocker: MockerFixture, app_context: None +) -> None: + """Warn-first default: a non-object user claim is a 401, not a crash.""" + sm = SupersetSecurityManager(appbuilder) + with patch("superset.security.manager.enforce_guest_token_identity"): + raw_token = sm.create_guest_access_token( + cast(GuestTokenUser, "[email protected]"), RESOURCES, [] + ) + + assert sm.get_guest_user_from_request(_guest_request(mocker, raw_token)) is None + + +def test_warn_only_tolerates_malformed_resources_claim(app_context: None) -> None: + enforce_guest_token_identity( + {"username": "bob\nalice"}, cast(GuestTokenResources, "not-a-list") + )
