You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@superset.apache.org by ru...@apache.org on 2026/06/03 04:33:16 UTC

(superset) 01/01: feat(security): per-dashboard guest token revocation

This is an automated email from the ASF dual-hosted git repository.

rusackas pushed a commit to branch feat/guest-token-per-dashboard-revocation
in repository https://gitbox.apache.org/repos/asf/superset.git

commit 239a6caa44d933d85979710920071b425eb7d3e3
Author: Claude Code <no...@anthropic.com>
AuthorDate: Tue Jun 2 21:32:57 2026 -0700

    feat(security): per-dashboard guest token revocation
    
    Implements Part A3 of the session/token-lifecycle SIP (#40674): granular,
    per-embedded-dashboard guest-token revocation that complements the global
    revocation mechanism.
    
    - `embedded_dashboards.guest_token_revoked_before` (migration) records the
      revocation instant for one embedded dashboard.
    - `get_guest_user_from_request` rejects a guest token whose `iat` predates the
      `guest_token_revoked_before` of any dashboard resource it references (UTC-safe
      comparison). Tokens issued afterwards, and dashboards never revoked (NULL),
      are unaffected.
    - `POST /api/v1/dashboard/<id_or_slug>/embedded/revoke` (gated by the existing
      `can_set_embedded` permission) stamps the timestamp via
      `EmbeddedDashboardDAO.revoke_guest_tokens`.
    
    Guest tokens already carry `iat`, so no token-format change is needed.
    Validated end-to-end against a local Docker stack (token valid -> revoke ->
    rejected -> new token valid; revoke endpoint returns 200) plus integration
    tests.
    
    Co-Authored-By: Claude Opus 4.8 <no...@anthropic.com>
---
 UPDATING.md                                        |   4 +
 superset/daos/dashboard.py                         |  13 ++-
 superset/dashboards/api.py                         |  51 +++++++++
 ..._c4d5e6f7a8b9_add_guest_token_revoked_before.py |  42 +++++++
 superset/models/embedded_dashboard.py              |   6 +-
 superset/security/manager.py                       |  37 +++++++
 .../security/guest_token_revocation_tests.py       | 123 +++++++++++++++++++++
 7 files changed, 274 insertions(+), 2 deletions(-)

diff --git a/UPDATING.md b/UPDATING.md
index ea73f6adf63..0343cf945fa 100644
--- a/UPDATING.md
+++ b/UPDATING.md
@@ -24,6 +24,10 @@ assists people when migrating to a new version.
 
 ## Next
 
+### Per-dashboard guest token revocation
+
+Embedded dashboards can now revoke their outstanding guest tokens without affecting other dashboards or rotating the global `GUEST_TOKEN_JWT_SECRET`. `POST /api/v1/dashboard/<id_or_slug>/embedded/revoke` stamps `embedded_dashboards.guest_token_revoked_before` (added by a migration); guest tokens for that dashboard whose `iat` predates the timestamp are then rejected. Tokens issued afterwards are unaffected, and dashboards that were never revoked (NULL) behave exactly as before.
+
 ### Dataset import validates catalog against the target connection
 
 Importing a dataset now validates the `catalog` field against the target database connection. When the connection has multi-catalog disabled (`allow_multi_catalog` off) and the dataset's catalog is not the connection's default catalog, the import fails instead of silently persisting the non-default catalog. This matches the validation already enforced on the dataset update path and prevents imported datasets from querying an unintended database.
diff --git a/superset/daos/dashboard.py b/superset/daos/dashboard.py
index 5377734ecde..705063a3ceb 100644
--- a/superset/daos/dashboard.py
+++ b/superset/daos/dashboard.py
@@ -18,7 +18,7 @@ from __future__ import annotations
 
 import logging
 from collections import defaultdict
-from datetime import datetime
+from datetime import datetime, timezone
 from typing import Any, Dict, List
 
 from flask import g
@@ -619,6 +619,17 @@ class EmbeddedDashboardDAO(BaseDAO[EmbeddedDashboard]):
         dashboard.embedded = [embedded]
         return embedded
 
+    @staticmethod
+    def revoke_guest_tokens(dashboard: Dashboard) -> None:
+        """
+        Revoke outstanding guest tokens for this dashboard's embedded
+        configuration by stamping ``guest_token_revoked_before`` to now. Guest
+        tokens issued before this instant are rejected on their next request.
+        """
+        now = datetime.now(timezone.utc).replace(tzinfo=None)
+        for embedded in dashboard.embedded:
+            embedded.guest_token_revoked_before = now
+
     @classmethod
     def create(
         cls,
diff --git a/superset/dashboards/api.py b/superset/dashboards/api.py
index 3deb304c009..86a8c6f633e 100644
--- a/superset/dashboards/api.py
+++ b/superset/dashboards/api.py
@@ -244,6 +244,7 @@ class DashboardRestApi(CustomTagsOptimizationMixin, BaseSupersetModelRestApi):
         "get_embedded",
         "set_embedded",
         "delete_embedded",
+        "revoke_embedded",
         "thumbnail",
         "copy_dash",
         "cache_dashboard_screenshot",
@@ -2134,6 +2135,56 @@ class DashboardRestApi(CustomTagsOptimizationMixin, BaseSupersetModelRestApi):
         DeleteEmbeddedDashboardCommand(dashboard).run()
         return self.response(200, message="OK")
 
+    @expose("/<id_or_slug>/embedded/revoke", methods=("POST",))
+    @protect()
+    @safe
+    @permission_name("set_embedded")
+    @statsd_metrics
+    @event_logger.log_this_with_context(
+        action=lambda self, *args, **kwargs: (
+            f"{self.__class__.__name__}.revoke_embedded"
+        ),
+        log_to_statsd=False,
+    )
+    @with_dashboard
+    def revoke_embedded(self, dashboard: Dashboard) -> Response:
+        """Revoke outstanding guest tokens for the dashboard's embedded config.
+        ---
+        post:
+          summary: Revoke active guest sessions for the dashboard
+          description: >-
+            Rejects guest tokens for this dashboard that were issued before now,
+            terminating outstanding embedded guest sessions without affecting
+            other dashboards.
+          parameters:
+          - in: path
+            schema:
+              type: string
+            name: id_or_slug
+            description: The dashboard id or slug
+          responses:
+            200:
+              description: Successfully revoked active guest tokens
+              content:
+                application/json:
+                  schema:
+                    type: object
+                    properties:
+                      message:
+                        type: string
+            401:
+              $ref: '#/components/responses/401'
+            404:
+              $ref: '#/components/responses/404'
+            500:
+              $ref: '#/components/responses/500'
+        """
+        if not dashboard.embedded:
+            return self.response_404()
+        EmbeddedDashboardDAO.revoke_guest_tokens(dashboard)
+        db.session.commit()  # pylint: disable=consider-using-transaction
+        return self.response(200, message="OK")
+
     @expose("/<id_or_slug>/copy/", methods=("POST",))
     @protect()
     @safe
diff --git a/superset/migrations/versions/2026-06-02_12-00_c4d5e6f7a8b9_add_guest_token_revoked_before.py b/superset/migrations/versions/2026-06-02_12-00_c4d5e6f7a8b9_add_guest_token_revoked_before.py
new file mode 100644
index 00000000000..c97b941686b
--- /dev/null
+++ b/superset/migrations/versions/2026-06-02_12-00_c4d5e6f7a8b9_add_guest_token_revoked_before.py
@@ -0,0 +1,42 @@
+# 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.
+"""add guest_token_revoked_before to embedded_dashboards
+
+Revision ID: c4d5e6f7a8b9
+Revises: 33d7e0e21daa
+Create Date: 2026-06-02 12:00:00.000000
+
+"""
+
+import sqlalchemy as sa
+
+from superset.migrations.shared.utils import add_columns, drop_columns
+
+# revision identifiers, used by Alembic.
+revision = "c4d5e6f7a8b9"
+down_revision = "33d7e0e21daa"
+
+TABLE = "embedded_dashboards"
+COLUMN = "guest_token_revoked_before"
+
+
+def upgrade():
+    add_columns(TABLE, sa.Column(COLUMN, sa.DateTime(), nullable=True))
+
+
+def downgrade():
+    drop_columns(TABLE, COLUMN)
diff --git a/superset/models/embedded_dashboard.py b/superset/models/embedded_dashboard.py
index 3aed89534bf..b2fcc7e488a 100644
--- a/superset/models/embedded_dashboard.py
+++ b/superset/models/embedded_dashboard.py
@@ -17,7 +17,7 @@
 import uuid
 
 from flask_appbuilder import Model
-from sqlalchemy import Column, ForeignKey, Integer, Text
+from sqlalchemy import Column, DateTime, ForeignKey, Integer, Text
 from sqlalchemy.orm import relationship
 from sqlalchemy_utils import UUIDType
 
@@ -50,6 +50,10 @@ class EmbeddedDashboard(Model, AuditMixinNullable):
         back_populates="embedded",
         foreign_keys=[dashboard_id],
     )
+    # Guest tokens for this embedded dashboard issued (``iat``) before this
+    # timestamp are rejected, revoking outstanding guest sessions for just this
+    # dashboard. NULL means "never revoked".
+    guest_token_revoked_before = Column(DateTime, nullable=True)
 
     @property
     def allowed_domains(self) -> list[str]:
diff --git a/superset/security/manager.py b/superset/security/manager.py
index a62daa528d3..7d3c356691f 100644
--- a/superset/security/manager.py
+++ b/superset/security/manager.py
@@ -3492,6 +3492,8 @@ class SupersetSecurityManager(  # pylint: disable=too-many-public-methods
                 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._guest_token_is_revoked(token):
+                raise ValueError("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.
@@ -3500,6 +3502,41 @@ class SupersetSecurityManager(  # pylint: disable=too-many-public-methods
 
         return self.get_guest_user_from_token(cast(GuestToken, token))
 
+    def _guest_token_is_revoked(self, token: dict[str, Any]) -> bool:
+        """
+        Return True if any dashboard resource referenced by the token has been
+        revoked since the token was issued — i.e. the token's ``iat`` predates
+        that embedded dashboard's ``guest_token_revoked_before``.
+
+        Revocation is per embedded dashboard, so revoking one embed does not
+        affect guest tokens for other dashboards. Tokens with no ``iat`` (none
+        are issued without one) are treated as not revoked.
+        """
+        # pylint: disable=import-outside-toplevel
+        from datetime import timezone
+
+        from superset.daos.dashboard import EmbeddedDashboardDAO
+
+        iat = token.get("iat")
+        if iat is None:
+            return False
+        for resource in token.get("resources") or []:
+            if resource.get("type") != GuestTokenResourceType.DASHBOARD.value:
+                continue
+            embedded = EmbeddedDashboardDAO.find_by_id(str(resource["id"]))
+            revoked_before = (
+                embedded.guest_token_revoked_before if embedded else None
+            )
+            if revoked_before is None:
+                continue
+            # The column is a naive UTC ``DateTime``; compare in UTC so the
+            # check isn't skewed by the server's local offset.
+            if revoked_before.tzinfo is None:
+                revoked_before = revoked_before.replace(tzinfo=timezone.utc)
+            if iat < revoked_before.timestamp():
+                return True
+        return False
+
     def get_guest_user_from_token(self, token: GuestToken) -> GuestUser:
         return self.guest_user_cls(
             token=token,
diff --git a/tests/integration_tests/security/guest_token_revocation_tests.py b/tests/integration_tests/security/guest_token_revocation_tests.py
new file mode 100644
index 00000000000..c4a5230c2ac
--- /dev/null
+++ b/tests/integration_tests/security/guest_token_revocation_tests.py
@@ -0,0 +1,123 @@
+# 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 time
+from datetime import datetime, timezone
+from typing import Optional
+from unittest.mock import patch
+
+import pytest
+from flask import request
+
+from superset import db, security_manager
+from superset.daos.dashboard import EmbeddedDashboardDAO
+from superset.security.guest_token import GuestTokenResourceType
+from tests.integration_tests.base_tests import SupersetTestCase
+from tests.integration_tests.test_app import app
+
+
+@pytest.mark.usefixtures("load_birth_names_dashboard_with_slices_class_scope")
+class TestGuestTokenRevocation(SupersetTestCase):
+    def setUp(self) -> None:
+        with app.app_context():
+            app.config["EMBEDDED_SUPERSET"] = True
+        self.dash = self.get_dash_by_slug("births")
+        self.embedded = EmbeddedDashboardDAO.upsert(self.dash, [])
+        db.session.commit()
+
+    def tearDown(self) -> None:
+        self.embedded.guest_token_revoked_before = None
+        db.session.commit()
+
+    def _mint(self, iat: int) -> str:
+        resources = [
+            {
+                "type": GuestTokenResourceType.DASHBOARD.value,
+                "id": str(self.embedded.uuid),
+            }
+        ]
+        with patch.object(
+            security_manager, "_get_current_epoch_time", return_value=iat
+        ):
+            token = security_manager.create_guest_access_token({}, resources, [])
+        return token if isinstance(token, str) else token.decode()
+
+    def _validate(self, token: str) -> Optional[object]:
+        header = app.config["GUEST_TOKEN_HEADER_NAME"]
+        with app.test_request_context(headers={header: token}):
+            return security_manager.get_guest_user_from_request(request)
+
+    def test_token_issued_before_revocation_is_rejected(self) -> None:
+        base = int(time.time())
+        token = self._mint(iat=base)
+
+        # Valid before any revocation.
+        assert self._validate(token) is not None
+
+        # Revoke at base + 10: tokens issued before that instant are rejected.
+        self.embedded.guest_token_revoked_before = datetime.fromtimestamp(
+            base + 10, timezone.utc
+        ).replace(tzinfo=None)
+        db.session.commit()
+        assert self._validate(token) is None
+
+        # A token issued after the revocation instant is still accepted.
+        newer_token = self._mint(iat=base + 20)
+        assert self._validate(newer_token) is not None
+
+    def test_revoke_endpoint_revokes_outstanding_tokens(self) -> None:
+        base = int(time.time())
+        token = self._mint(iat=base)
+        assert self._validate(token) is not None
+
+        self.login(username="admin")
+        response = self.client.post(
+            f"/api/v1/dashboard/{self.dash.id}/embedded/revoke"
+        )
+        assert response.status_code == 200
+
+        db.session.expire_all()
+        assert self.embedded.guest_token_revoked_before is not None
+        # The token issued before the revoke call is now rejected.
+        assert self._validate(token) is None
+
+    def test_revoking_one_dashboard_does_not_affect_others(self) -> None:
+        base = int(time.time())
+        token = self._mint(iat=base)
+        self.embedded.guest_token_revoked_before = datetime.fromtimestamp(
+            base + 10, timezone.utc
+        ).replace(tzinfo=None)
+        db.session.commit()
+        # Token is revoked for this dashboard...
+        assert self._validate(token) is None
+        # ...but a token for a *different* (unrevoked) resource is unaffected.
+        other_resources = [
+            {
+                "type": GuestTokenResourceType.DASHBOARD.value,
+                "id": "06383667-3e02-4e5e-843f-44e9c5896b6c",
+            }
+        ]
+        with patch.object(
+            security_manager, "_get_current_epoch_time", return_value=base
+        ):
+            other_token = security_manager.create_guest_access_token(
+                {}, other_resources, []
+            )
+        other_token = (
+            other_token if isinstance(other_token, str) else other_token.decode()
+        )
+        # Not revoked (no embedded config / no revoked_before for that id).
+        assert self._validate(other_token) is not None