You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ma...@apache.org on 2026/10/06 19:45:19 UTC
(superset) 13/23: address PR comments and add new tests
This is an automated email from the ASF dual-hosted git repository.
madhushreeag pushed a commit to branch madhu-one-time-login-tokens
in repository https://gitbox.apache.org/repos/asf/superset.git
commit f40926a4aa7b64d619e13912468eff402ddc677f
Author: madhushree agarwal <ma...@apple.com>
AuthorDate: Mon Oct 5 22:43:51 2026 -0700
address PR comments and add new tests
---
superset/security/login_token.py | 13 ++++
.../security/login_token_api_tests.py | 86 +++++++++++++++++++++-
tests/unit_tests/security/login_token_test.py | 62 ++++++++++++++++
3 files changed, 159 insertions(+), 2 deletions(-)
diff --git a/superset/security/login_token.py b/superset/security/login_token.py
index 84039cd6d6d..07f64aa91be 100644
--- a/superset/security/login_token.py
+++ b/superset/security/login_token.py
@@ -185,6 +185,19 @@ def resolve_identity( # pylint: disable=too-many-return-statements
)
return None
+ # Normalize before validating, because ``auth_user_oauth`` selects on key
+ # *presence* rather than truthiness: ``if "username" in userinfo`` wins even
+ # when the value is empty, and the empty username is then rejected outright.
+ # A resolver returning {"username": "", "email": "jdoe@example.com"} would
+ # otherwise mint a perfectly good token that always fails redemption with a
+ # 401, instead of falling back to the email. Stripping and dropping empty
+ # string values keeps this check and FAB's in agreement.
+ userinfo = {
+ key: value.strip() if isinstance(value, str) else value
+ for key, value in userinfo.items()
+ if not (isinstance(value, str) and not value.strip())
+ }
+
if not (userinfo.get("username") or userinfo.get("email")):
# auth_user_oauth derives the username from one of these two; without
# either there is no identity to provision.
diff --git a/tests/integration_tests/security/login_token_api_tests.py b/tests/integration_tests/security/login_token_api_tests.py
index 8146231984e..557c0e05d2a 100644
--- a/tests/integration_tests/security/login_token_api_tests.py
+++ b/tests/integration_tests/security/login_token_api_tests.py
@@ -25,10 +25,12 @@ tests can see.
from typing import Any
from unittest.mock import patch
+from uuid import UUID
from flask_appbuilder.security.sqla.manager import user_updating
from superset import db
+from superset.daos.key_value import KeyValueDAO
from superset.key_value.models import KeyValueEntry
from superset.key_value.types import KeyValueResource
from superset.utils import json
@@ -53,6 +55,18 @@ def _resolver(request: Any, **kwargs: Any) -> dict[str, Any] | None:
return {"username": username} if username else None
+def _verbatim_resolver(request: Any, **kwargs: Any) -> dict[str, Any] | None:
+ """Return the request body as ``userinfo``, unmodified.
+
+ Lets a test drive an arbitrary resolver result through the real route, which
+ is the only way to cover shapes a sensible resolver would not produce but a
+ misbehaving one will.
+ """
+ if request.headers.get("X-Test-Mint-Secret") != MINT_SECRET:
+ return None
+ return request.get_json(silent=True) or None
+
+
class TestLoginTokenApi(SupersetTestCase):
def _mint(self, username: str = GAMMA_USERNAME) -> str:
"""Mint a token through the route and return it."""
@@ -75,6 +89,18 @@ class TestLoginTokenApi(SupersetTestCase):
.count()
)
+ @staticmethod
+ def _is_stored(token: str) -> bool:
+ """Whether this specific token still has a row.
+
+ Scoped to one key rather than counting the table: the metadata database
+ is shared across the suite, so an absolute count couples these
+ assertions to whatever other tests happen to have left behind.
+ """
+ return (
+ KeyValueDAO.get_entry(KeyValueResource.LOGIN_TOKEN, UUID(token)) is not None
+ )
+
# ---------------------------------------------------------------- closed off
def test_endpoints_are_404_without_the_feature_flag(self):
@@ -166,7 +192,7 @@ class TestLoginTokenApi(SupersetTestCase):
"the token was redeemable after a provisioning rollback -- the burn "
"was not committed independently of provisioning"
)
- assert self._stored_tokens() == 0
+ assert not self._is_stored(token)
@with_feature_flags(LOGIN_TOKEN=True)
@with_config({"LOGIN_TOKEN_IDENTITY_RESOLVER": _resolver})
@@ -215,7 +241,7 @@ class TestLoginTokenApi(SupersetTestCase):
"user_updating hook rolled the session back -- the burn must be "
"committed before provisioning runs"
)
- assert self._stored_tokens() == 0
+ assert not self._is_stored(token)
@with_feature_flags(LOGIN_TOKEN=True)
@with_config({"LOGIN_TOKEN_IDENTITY_RESOLVER": _resolver})
@@ -226,6 +252,62 @@ class TestLoginTokenApi(SupersetTestCase):
response = self.client.get(f"{ENDPOINT}?token={token}")
assert response.status_code == 401
+ @with_feature_flags(LOGIN_TOKEN=True)
+ @with_config({"LOGIN_TOKEN_IDENTITY_RESOLVER": _verbatim_resolver})
+ def test_empty_identity_keys_do_not_mint_a_doomed_token(self):
+ """A token that mints must be redeemable, end to end.
+
+ ``auth_user_oauth`` selects the identifier on key *presence*: ``if
+ "username" in userinfo`` wins even when the value is empty, and the empty
+ username is then rejected outright. So a resolver returning
+ ``{"username": "", "email": ...}`` used to mint a perfectly good token
+ that could only ever 401 on redemption, instead of falling back to the
+ email. Surrounding whitespace failed the same way, via ``find_user``.
+
+ Both now normalize before minting, so each of these redeems. Note FAB
+ uses whichever value it selected as the ``find_user`` lookup key, which
+ is why the email slot here holds a username rather than an address.
+ """
+ for userinfo in (
+ {"username": "", "email": GAMMA_USERNAME},
+ {"username": f" {GAMMA_USERNAME} "},
+ {"username": "", "first_name": "", "email": GAMMA_USERNAME},
+ ):
+ with self.subTest(userinfo=userinfo):
+ response = self.client.post(
+ ENDPOINT,
+ data=json.dumps(userinfo),
+ content_type="application/json",
+ headers={"X-Test-Mint-Secret": MINT_SECRET},
+ )
+ assert response.status_code == 200, response.data
+ token = json.loads(response.data)["access_token"]
+
+ redeemed = self.client.get(f"{ENDPOINT}?token={token}")
+ assert redeemed.status_code == 302, (
+ f"minted a token for {userinfo} that could not be redeemed "
+ f"({redeemed.status_code}) -- empty or padded identity keys "
+ "must be normalized before minting"
+ )
+
+ @with_feature_flags(LOGIN_TOKEN=True)
+ @with_config({"LOGIN_TOKEN_IDENTITY_RESOLVER": _verbatim_resolver})
+ def test_mint_rejects_an_identity_with_no_usable_identifier(self):
+ """If nothing survives normalization there is no identity to mint for."""
+ for userinfo in (
+ {"username": "", "email": ""},
+ {"username": " "},
+ {"first_name": "Jane", "last_name": "Doe"},
+ ):
+ with self.subTest(userinfo=userinfo):
+ response = self.client.post(
+ ENDPOINT,
+ data=json.dumps(userinfo),
+ content_type="application/json",
+ headers={"X-Test-Mint-Secret": MINT_SECRET},
+ )
+ assert response.status_code == 401, response.data
+
# --------------------------------------------------------------------- next
@with_feature_flags(LOGIN_TOKEN=True)
diff --git a/tests/unit_tests/security/login_token_test.py b/tests/unit_tests/security/login_token_test.py
index 888d475e372..36111d1b1f3 100644
--- a/tests/unit_tests/security/login_token_test.py
+++ b/tests/unit_tests/security/login_token_test.py
@@ -156,6 +156,68 @@ def test_resolve_identity_accepts_email_only(app_context: None) -> None:
_set_resolver(original)
+@pytest.mark.parametrize(
+ "resolved,expected",
+ [
+ # The key must be dropped, not merely falsy: auth_user_oauth branches on
+ # `if "username" in userinfo`, so an empty value still wins over the
+ # email and is then rejected, 401ing a token that was minted happily.
+ (
+ {"username": "", "email": "jdoe@example.com"},
+ {"email": "jdoe@example.com"},
+ ),
+ (
+ {"username": " ", "email": "jdoe@example.com"},
+ {"email": "jdoe@example.com"},
+ ),
+ # Surrounding whitespace would make find_user miss an existing account.
+ ({"username": " jdoe "}, {"username": "jdoe"}),
+ # Empty optional fields are dropped too, rather than stored and later
+ # written onto the user record as blanks.
+ (
+ {"username": "jdoe", "first_name": "", "last_name": "Doe"},
+ {"username": "jdoe", "last_name": "Doe"},
+ ),
+ # Non-string values are passed through untouched.
+ (
+ {"username": "jdoe", "role_keys": ["Gamma"]},
+ {"username": "jdoe", "role_keys": ["Gamma"]},
+ ),
+ ],
+)
+def test_resolve_identity_normalizes_empty_identity_keys(
+ app_context: None, resolved: dict[str, Any], expected: dict[str, Any]
+) -> None:
+ """Empty identity values are stripped away before a token is ever minted."""
+ original = current_app.config.get("LOGIN_TOKEN_IDENTITY_RESOLVER")
+ try:
+ _set_resolver(lambda request, **kwargs: resolved)
+ assert login_token.resolve_identity(object()) == expected
+ finally:
+ _set_resolver(original)
+
+
+@pytest.mark.parametrize(
+ "resolved",
+ [
+ {"username": "", "email": ""},
+ {"username": " ", "email": " "},
+ {"username": ""},
+ {"email": ""},
+ ],
+)
+def test_resolve_identity_rejects_only_empty_identifiers(
+ app_context: None, resolved: dict[str, Any]
+) -> None:
+ """If nothing usable survives normalization, reject rather than mint."""
+ original = current_app.config.get("LOGIN_TOKEN_IDENTITY_RESOLVER")
+ try:
+ _set_resolver(lambda request, **kwargs: resolved)
+ assert login_token.resolve_identity(object()) is None
+ finally:
+ _set_resolver(original)
+
+
def test_mint_then_consume_round_trip(app_context: None, kv_table: Session) -> None:
"""A minted token returns exactly the stored userinfo."""
token, expires_on = login_token.mint(USERINFO)