rusackas commented on code in PR #40671:
URL: https://github.com/apache/superset/pull/40671#discussion_r3383924366


##########
superset/cli/guest_token.py:
##########
@@ -0,0 +1,54 @@
+# 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.
+import logging
+
+import click
+from flask import current_app
+from flask.cli import with_appcontext
+
+logger = logging.getLogger(__name__)
+
+
[email protected]()
+@with_appcontext
+def revoke_guest_tokens() -> None:
+    """
+    Revoke all outstanding embedded guest tokens.
+
+    Bumps the guest-token revocation version stored in the metadata database,
+    which invalidates every guest token minted with a lower version. New tokens
+    minted after this command will carry the bumped version and remain valid.
+
+    Requires ``GUEST_TOKEN_REVOCATION_ENABLED = True``; otherwise the bumped
+    version is not enforced at validation time.
+    """
+    # pylint: disable=import-outside-toplevel
+    from superset.security.guest_token import 
bump_guest_token_revocation_version
+
+    if not current_app.config["GUEST_TOKEN_REVOCATION_ENABLED"]:
+        click.secho(
+            "Warning: GUEST_TOKEN_REVOCATION_ENABLED is False. The version 
will "
+            "be bumped but is NOT enforced at validation time until you enable 
"
+            "the feature.",
+            fg="yellow",
+        )
+
+    new_version = bump_guest_token_revocation_version()
+    click.secho(
+        f"Revoked outstanding guest tokens. Revocation version is now 
{new_version}.",
+        fg="green",
+    )

Review Comment:
   Good call — added a dedicated CLI test module 
`tests/unit_tests/cli/guest_token_test.py` covering the `revoke-guest-tokens` 
command: the success path (exit code 0, bump invoked, new version reported in 
output) and the feature-disabled path (still bumps, but emits the 
`GUEST_TOKEN_REVOCATION_ENABLED is False` warning). Done in this PR.



##########
superset/security/manager.py:
##########
@@ -3673,6 +3692,8 @@ def get_guest_user_from_request(self, req: Request) -> 
Optional[GuestUser]:
                 raise ValueError("Guest token does not contain an rls_rules 
claim")
             if token.get("type") != "guest":
                 raise ValueError("This is not a guest token.")
+            if self._is_guest_token_revoked(token):
+                raise ValueError("This guest token has been revoked.")
         except Exception:  # pylint: disable=broad-except
             # The login manager will handle sending 401s.
             # We don't need to send a special error message.

Review Comment:
   Added a test exercising the full request->parse->revocation flow: 
`test_revoked_token_rejected_through_request_flow` mints a real token, then 
bumps the expected version and asserts `get_guest_user_from_request` returns 
`None` (so the login manager issues a 401), and that the same token resolves to 
a guest user when the version matches. Kept it at the unit level per our 
testing-strategy preference (unit over integration), but it covers the 
end-to-end revocation rejection path you flagged. Done in this PR.



##########
superset/security/guest_token.py:
##########
@@ -14,13 +14,70 @@
 # KIND, either express or implied.  See the License for the
 # specific language governing permissions and limitations
 # under the License.
+import logging
 from typing import Optional, TypedDict, Union
 
 from flask_appbuilder.security.sqla.models import Group, Role
 from flask_login import AnonymousUserMixin
 
 from superset.utils.backports import StrEnum
 
+logger = logging.getLogger(__name__)
+
+# JWT claim that carries the revocation version a token was minted with.
+GUEST_TOKEN_REVOCATION_CLAIM = "rev"  # noqa: S105
+
+# Tokens minted before the revocation feature existed carry no version claim.
+# They are treated as version 0, which is only rejected once an admin has
+# explicitly bumped the expected version above 0.
+DEFAULT_GUEST_TOKEN_REVOCATION_VERSION = 0
+
+
+def get_current_guest_token_revocation_version() -> int:
+    """
+    Return the minimum guest-token revocation version accepted at validation 
time.
+
+    The value is stored in the metadata database via the ``key_value`` store 
so it
+    can be bumped at runtime (e.g. via the ``revoke-guest-tokens`` CLI command)
+    without a code deploy. A missing entry means revocation has never been
+    triggered, so the default version is returned.
+    """
+    # pylint: disable=import-outside-toplevel
+    from superset.key_value.shared_entries import get_shared_value
+    from superset.key_value.types import SharedKey
+
+    try:
+        value = get_shared_value(SharedKey.GUEST_TOKEN_REVOCATION_VERSION)
+    except Exception:  # pylint: disable=broad-except

Review Comment:
   Added `test_get_version_falls_back_on_store_error`, which makes 
`get_shared_value` raise and asserts the broad-except branch returns the 
default version (0), plus 
`test_get_version_falls_back_on_malformed_stored_value` for the non-integer 
stored-value path. The fail-open fallback is now exercised so a future refactor 
that breaks it would be caught. Done in this 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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to