You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@superset.apache.org by "rusackas (via GitHub)" <gi...@apache.org> on 2026/06/03 00:56:12 UTC

[PR] feat(security): terminate active sessions when an account is disabled [superset]

rusackas opened a new pull request, #40695:
URL: https://github.com/apache/superset/pull/40695

   ### SUMMARY
   
   Implements **Part A2** of the session/token-lifecycle SIP (#40674) as a self-contained, tested change: a backend-agnostic **per-user session-invalidation epoch** that terminates a disabled account's outstanding sessions on their next request.
   
   Previously, disabling a user only audit-logged; access lingered until a passive check, and for client-side cookie sessions there was no server-side session to delete at all.
   
   **How it works**
   - `UserAttribute.sessions_invalidated_at` (new column + migration) records the invalidation epoch.
   - `on_user_login` stamps `session["_login_at"]`.
   - A `before_request` hook forces logout of any session whose login predates the user's epoch, then lets the request continue as anonymous so each route responds correctly for its type (**401** for the REST API, **redirect-to-login** for HTML views) — no route-kind branching needed. Fails **open** on any error (never locks everyone out on a bug).
   - A SQLAlchemy `after_update` listener stamps the epoch when `active` flips to `False`, so it fires regardless of the disable path (**admin UI, REST API, or CLI**) and for **both** client-side cookie and server-side session backends. Deleted users are already rejected by Flask-Login's loader, so deletion needs no epoch.
   
   **Backwards compatible by default**: inert for users that were never disabled (NULL epoch). The naive-UTC column comparison is handled explicitly.
   
   Closes part of #40674 (A2). A1/A3/Part B remain in the SIP.
   
   ### TESTING INSTRUCTIONS
   
   ```bash
   pytest tests/unit_tests/security/test_session_invalidation.py
   pytest tests/integration_tests/security/session_invalidation_tests.py
   ```
   
   **Validated end-to-end against a local Docker stack:**
   - Migration applies cleanly to Postgres.
   - Disabling a user via the ORM fires the event and stamps the epoch (incl. the INSERT-upsert path for users with no attribute row).
   - Full HTTP flow: login → `/api/v1/me/` returns **200** → admin disables the user → same session → `/api/v1/me/` returns **401**.
   
   Unit tests cover the epoch comparison incl. the UTC/naive-datetime correctness; the integration test covers the login → disable → forced-logout flow and the "active user is unaffected" case.
   
   ### ADDITIONAL INFORMATION
   
   - [ ] Has associated issue:
   - [ ] Required feature flags:
   - [ ] Changes UI
   - [x] Includes DB Migration
   - [x] Introduces new feature or API
   - [ ] Removes existing feature or API
   
   🤖 Generated with [Claude Code](https://claude.com/claude-code)


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "codecov[bot] (via GitHub)" <gi...@apache.org>.
codecov[bot] commented on PR #40695:
URL: https://github.com/apache/superset/pull/40695#issuecomment-4609081028

   ## [Codecov](https://app.codecov.io/gh/apache/superset/pull/40695?dropdown=coverage&src=pr&el=h1&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) Report
   :x: Patch coverage is `60.81081%` with `29 lines` in your changes missing coverage. Please review.
   :white_check_mark: Project coverage is 55.42%. Comparing base ([`12bef03`](https://app.codecov.io/gh/apache/superset/commit/12bef03f4aff4308c8a35d97d600616e8102e08a?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)) to head ([`c6c1824`](https://app.codecov.io/gh/apache/superset/commit/c6c18240a7a920e1190e4edfa527e74cea856337?dropdown=coverage&el=desc&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache)).
   
   | [Files with missing lines](https://app.codecov.io/gh/apache/superset/pull/40695?dropdown=coverage&src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Patch % | Lines |
   |---|---|---|
   | [superset/security/session\_invalidation.py](https://app.codecov.io/gh/apache/superset/pull/40695?src=pr&el=tree&filepath=superset%2Fsecurity%2Fsession_invalidation.py&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#diff-c3VwZXJzZXQvc2VjdXJpdHkvc2Vzc2lvbl9pbnZhbGlkYXRpb24ucHk=) | 54.68% | [24 Missing and 5 partials :warning: ](https://app.codecov.io/gh/apache/superset/pull/40695?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) |
   
   <details><summary>Additional details and impacted files</summary>
   
   
   
   ```diff
   @@            Coverage Diff             @@
   ##           master   #40695      +/-   ##
   ==========================================
   - Coverage   55.45%   55.42%   -0.03%     
   ==========================================
     Files        2662     2663       +1     
     Lines      143267   143340      +73     
     Branches    32943    32954      +11     
   ==========================================
   + Hits        79451    79453       +2     
   - Misses      63107    63173      +66     
   - Partials      709      714       +5     
   ```
   
   | [Flag](https://app.codecov.io/gh/apache/superset/pull/40695/flags?src=pr&el=flags&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | Coverage Δ | |
   |---|---|---|
   | [hive](https://app.codecov.io/gh/apache/superset/pull/40695/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `?` | |
   | [presto](https://app.codecov.io/gh/apache/superset/pull/40695/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `41.41% <60.81%> (+0.02%)` | :arrow_up: |
   | [python](https://app.codecov.io/gh/apache/superset/pull/40695/flags?src=pr&el=flag&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache) | `41.41% <60.81%> (-0.05%)` | :arrow_down: |
   
   Flags with carried forward coverage won't be shown. [Click here](https://docs.codecov.io/docs/carryforward-flags?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache#carryforward-flags-in-the-pull-request-comment) to find out more.
   </details>
   
   [:umbrella: View full report in Codecov by Sentry](https://app.codecov.io/gh/apache/superset/pull/40695?dropdown=coverage&src=pr&el=continue&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).   
   :loudspeaker: Have feedback on the report? [Share it here](https://about.codecov.io/codecov-pr-comment-feedback/?utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=apache).
   <details><summary> :rocket: New features to boost your workflow: </summary>
   
   - :snowflake: [Test Analytics](https://docs.codecov.com/docs/test-analytics): Detect flaky tests, report on failures, and find test suite problems.
   - :package: [JS Bundle Analysis](https://docs.codecov.com/docs/javascript-bundle-analysis): Save yourself from yourself by tracking and limiting bundle sizes in JS merges.
   </details>


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3385394810


##########
superset/security/session_invalidation.py:
##########
@@ -0,0 +1,205 @@
+# 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.
+"""
+Backend-agnostic session invalidation.
+
+Outstanding sessions are terminated by comparing the time a session was
+authenticated (``session["_login_at"]``, stamped at login) against a per-user
+invalidation epoch (``UserAttribute.sessions_invalidated_at``). When a session
+predates the user's epoch it is forced to log out on its next request.
+
+The epoch is stamped whenever an account is *disabled* (``active`` flips to
+``False``), via a SQLAlchemy ``after_update`` listener so it fires regardless of
+the code path that disabled the user (FAB admin UI, REST API, or CLI). This
+works for both client-side cookie sessions and server-side session stores
+without enumerating the store by user. A deleted user is already rejected by
+Flask-Login's user loader, so deletion needs no epoch.
+
+The mechanism is inert until an epoch is set: users that were never disabled
+(NULL epoch) are never affected, so it is backwards compatible by default.
+"""
+
+import logging
+import math
+from datetime import datetime, timezone
+from typing import Any, Optional
+
+from flask import flash, session
+from flask_babel import gettext as __
+from flask_login import current_user, logout_user
+from sqlalchemy import event, inspect
+from sqlalchemy.exc import IntegrityError
+from werkzeug.wrappers import Response
+
+logger = logging.getLogger(__name__)
+
+#: Session key holding the epoch-seconds timestamp of when the session logged in.
+SESSION_LOGIN_AT_KEY = "_login_at"
+
+
+def _utcnow() -> datetime:
+    return datetime.now(timezone.utc)
+
+
+def stamp_login_time() -> None:
+    """Record the current session's authentication time. Call on login."""
+    session[SESSION_LOGIN_AT_KEY] = _utcnow().timestamp()
+
+
+def _as_utc_timestamp(value: datetime) -> float:
+    """Epoch seconds for ``value``, treating naive datetimes as UTC.
+
+    The ``sessions_invalidated_at`` column is a naive ``DateTime`` storing a UTC
+    instant; calling ``.timestamp()`` on a naive datetime would otherwise assume
+    *local* time and skew the comparison by the local UTC offset.
+    """
+    if value.tzinfo is None:
+        value = value.replace(tzinfo=timezone.utc)
+    return value.timestamp()
+
+
+def is_session_invalidated(
+    login_at: Optional[float], invalidated_at: Optional[datetime]
+) -> bool:
+    """
+    Return True if a session authenticated at ``login_at`` is invalidated by an
+    epoch of ``invalidated_at``.
+
+    - No epoch (``invalidated_at is None``) ⇒ never invalidated (the common case
+      and the reason the feature is inert/backwards compatible by default).
+    - An epoch with no recorded login time ⇒ invalidated. A session old enough
+      to predate the feature carries no ``_login_at``; if the user has since
+      been disabled, fail closed.
+    - Otherwise the session is invalidated iff it logged in before the epoch.
+    """
+    if invalidated_at is None:
+        return False
+    if login_at is None:
+        return True
+    return login_at < _as_utc_timestamp(invalidated_at)
+
+
+def _get_user_invalidated_at(user: Any) -> Optional[datetime]:
+    extra_attributes = getattr(user, "extra_attributes", None)
+    if not extra_attributes:
+        return None
+    return extra_attributes[0].sessions_invalidated_at
+
+
+def enforce_session_validity() -> Optional[Response]:
+    """
+    ``before_request`` hook: force logout of sessions invalidated by the user's
+    epoch.
+
+    Fails open — any error here logs a warning and allows the request rather
+    than risk locking everyone out on a bug in the check.
+    """
+    try:
+        user = current_user
+        if not user or not getattr(user, "is_authenticated", False):
+            return None
+        # Guest (embedded) users are not FAB users and have their own
+        # revocation mechanism; skip them.
+        if getattr(user, "is_guest_user", False):
+            return None
+        invalidated_at = _get_user_invalidated_at(user)
+        if invalidated_at is None:
+            return None
+        login_at = session.get(SESSION_LOGIN_AT_KEY)
+        if not is_session_invalidated(login_at, invalidated_at):
+            return None
+
+        # Clear the authenticated session and let the request continue as
+        # anonymous: each route's own decorator then responds correctly for its
+        # type (401 for the REST API, redirect-to-login for HTML views) without
+        # this hook needing to know the route kind.
+        logout_user()
+        session.clear()
+        flash(__("Your session has ended. Please sign in again."), "warning")
+        return None
+    except Exception:  # noqa: BLE001  # pylint: disable=broad-except
+        logger.warning(
+            "Session-invalidation check failed; allowing request", exc_info=True
+        )
+        return None

Review Comment:
   <!-- Bito Reply -->
   The race condition identified in the review has been addressed. The implementation now includes a unique constraint on `user_attribute.user_id` and uses a `SAVEPOINT` with `IntegrityError` handling in `invalidate_user_sessions` to ensure atomic updates and prevent duplicate rows.



##########
superset/initialization/__init__.py:
##########
@@ -764,6 +764,23 @@ def cleanup_analytics_memory(response: Response) -> Response:
                 gc.collect()
             return response
 
+        @self.superset_app.before_request
+        def enforce_session_validity() -> Any:

Review Comment:
   <!-- Bito Reply -->
   The suggestion is acknowledged. Since the `Optional` type is already imported and the function signature is correctly defined as `-> Optional[Response]`, no further action is required for this specific code block.
   
   **superset/initialization/__init__.py**
   ```
   @self.superset_app.before_request
           def enforce_session_validity() -> Any:
   ```



##########
superset/security/session_invalidation.py:
##########
@@ -0,0 +1,205 @@
+# 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.
+"""
+Backend-agnostic session invalidation.
+
+Outstanding sessions are terminated by comparing the time a session was
+authenticated (``session["_login_at"]``, stamped at login) against a per-user
+invalidation epoch (``UserAttribute.sessions_invalidated_at``). When a session
+predates the user's epoch it is forced to log out on its next request.
+
+The epoch is stamped whenever an account is *disabled* (``active`` flips to
+``False``), via a SQLAlchemy ``after_update`` listener so it fires regardless of
+the code path that disabled the user (FAB admin UI, REST API, or CLI). This
+works for both client-side cookie sessions and server-side session stores
+without enumerating the store by user. A deleted user is already rejected by
+Flask-Login's user loader, so deletion needs no epoch.
+
+The mechanism is inert until an epoch is set: users that were never disabled
+(NULL epoch) are never affected, so it is backwards compatible by default.
+"""
+
+import logging
+import math
+from datetime import datetime, timezone
+from typing import Any, Optional
+
+from flask import flash, session
+from flask_babel import gettext as __
+from flask_login import current_user, logout_user
+from sqlalchemy import event, inspect
+from sqlalchemy.exc import IntegrityError
+from werkzeug.wrappers import Response
+
+logger = logging.getLogger(__name__)
+
+#: Session key holding the epoch-seconds timestamp of when the session logged in.
+SESSION_LOGIN_AT_KEY = "_login_at"
+
+
+def _utcnow() -> datetime:
+    return datetime.now(timezone.utc)
+
+
+def stamp_login_time() -> None:
+    """Record the current session's authentication time. Call on login."""
+    session[SESSION_LOGIN_AT_KEY] = _utcnow().timestamp()
+
+
+def _as_utc_timestamp(value: datetime) -> float:
+    """Epoch seconds for ``value``, treating naive datetimes as UTC.
+
+    The ``sessions_invalidated_at`` column is a naive ``DateTime`` storing a UTC
+    instant; calling ``.timestamp()`` on a naive datetime would otherwise assume
+    *local* time and skew the comparison by the local UTC offset.
+    """
+    if value.tzinfo is None:
+        value = value.replace(tzinfo=timezone.utc)
+    return value.timestamp()
+
+
+def is_session_invalidated(
+    login_at: Optional[float], invalidated_at: Optional[datetime]
+) -> bool:
+    """
+    Return True if a session authenticated at ``login_at`` is invalidated by an
+    epoch of ``invalidated_at``.
+
+    - No epoch (``invalidated_at is None``) ⇒ never invalidated (the common case
+      and the reason the feature is inert/backwards compatible by default).
+    - An epoch with no recorded login time ⇒ invalidated. A session old enough
+      to predate the feature carries no ``_login_at``; if the user has since
+      been disabled, fail closed.
+    - Otherwise the session is invalidated iff it logged in before the epoch.
+    """
+    if invalidated_at is None:
+        return False
+    if login_at is None:
+        return True
+    return login_at < _as_utc_timestamp(invalidated_at)
+
+
+def _get_user_invalidated_at(user: Any) -> Optional[datetime]:
+    extra_attributes = getattr(user, "extra_attributes", None)
+    if not extra_attributes:
+        return None
+    return extra_attributes[0].sessions_invalidated_at
+
+
+def enforce_session_validity() -> Optional[Response]:
+    """
+    ``before_request`` hook: force logout of sessions invalidated by the user's
+    epoch.
+
+    Fails open — any error here logs a warning and allows the request rather
+    than risk locking everyone out on a bug in the check.
+    """
+    try:
+        user = current_user
+        if not user or not getattr(user, "is_authenticated", False):
+            return None
+        # Guest (embedded) users are not FAB users and have their own
+        # revocation mechanism; skip them.
+        if getattr(user, "is_guest_user", False):
+            return None
+        invalidated_at = _get_user_invalidated_at(user)
+        if invalidated_at is None:
+            return None
+        login_at = session.get(SESSION_LOGIN_AT_KEY)
+        if not is_session_invalidated(login_at, invalidated_at):
+            return None
+
+        # Clear the authenticated session and let the request continue as
+        # anonymous: each route's own decorator then responds correctly for its
+        # type (401 for the REST API, redirect-to-login for HTML views) without
+        # this hook needing to know the route kind.
+        logout_user()
+        session.clear()
+        flash(__("Your session has ended. Please sign in again."), "warning")
+        return None
+    except Exception:  # noqa: BLE001  # pylint: disable=broad-except
+        logger.warning(
+            "Session-invalidation check failed; allowing request", exc_info=True
+        )
+        return None
+
+
+def invalidate_user_sessions(connection: Any, user_id: int) -> None:
+    """Stamp the invalidation epoch for ``user_id`` using ``connection``.
+
+    Upserts the user's ``UserAttribute`` row so the mechanism works even for
+    users that have no attribute row yet. ``user_attribute.user_id`` carries a
+    unique constraint, so the insert is safe against a concurrent disable of the
+    same user: the loser's insert raises ``IntegrityError``, which is caught and
+    retried as an update rather than creating a duplicate row.
+    """
+    # pylint: disable=import-outside-toplevel
+    from superset.models.user_attributes import UserAttribute
+
+    table = UserAttribute.__table__
+    # Round the epoch up to the next whole second. Some backends (e.g. MySQL)
+    # store ``DATETIME`` columns without sub-second precision and truncate the
+    # value; a session that logged in earlier in the same wall-clock second
+    # carries a fractional ``_login_at`` that would otherwise compare as >= the
+    # truncated epoch and survive invalidation. Ceiling the stamp guarantees it
+    # strictly exceeds any login time from the same second.
+    now_epoch = _utcnow().timestamp()
+    now = datetime.fromtimestamp(math.ceil(now_epoch), timezone.utc).replace(
+        tzinfo=None
+    )
+
+    def _stamp_existing() -> int:
+        return connection.execute(
+            table.update()
+            .where(table.c.user_id == user_id)
+            .values(sessions_invalidated_at=now, changed_on=now)
+        ).rowcount
+
+    if _stamp_existing():
+        return
+
+    try:
+        with connection.begin_nested():
+            connection.execute(
+                table.insert().values(
+                    user_id=user_id,
+                    sessions_invalidated_at=now,
+                    created_on=now,
+                    changed_on=now,
+                )
+            )
+    except IntegrityError:
+        # A concurrent disable inserted the row first; stamp it instead.
+        _stamp_existing()
+

Review Comment:
   <!-- Bito Reply -->
   The reviewer's suggestion to add unit tests for `invalidate_user_sessions` is valid and has been addressed. The implementation now includes comprehensive test coverage for the three primary execution paths:
   
   1. **Update existing row:** Verifies that an existing `UserAttribute` row is correctly updated without an INSERT or SAVEPOINT.
   2. **Insert new row:** Verifies that a new row is created within a SAVEPOINT when no `UserAttribute` row exists.
   3. **IntegrityError retry:** Verifies that if a concurrent disable operation wins the insert race, the `IntegrityError` is caught and the row is correctly updated instead of duplicated.
   
   These tests ensure the robustness of the atomic upsert logic and the race condition handling.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40695:
URL: https://github.com/apache/superset/pull/40695#issuecomment-4608179248

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large 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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40695:
URL: https://github.com/apache/superset/pull/40695#issuecomment-4625856737

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3383930123


##########
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

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Invalid module name with hyphens</b></div>
   <div id="fix">
   
   The filename contains hyphens which are invalid in Python module names. Rename the file to use underscores instead (e.g., `2026_06_02_12_00_c4d5e6f7a8b9_add_guest_token_revoked_before.py`).
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #8320b7</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "netlify[bot] (via GitHub)" <gi...@apache.org>.
netlify[bot] commented on PR #40695:
URL: https://github.com/apache/superset/pull/40695#issuecomment-4624626043

   ### <span aria-hidden="true">✅</span> Deploy Preview for *superset-docs-preview* ready!
   
   
   |  Name | Link |
   |:-:|------------------------|
   |<span aria-hidden="true">🔨</span> Latest commit | 2e58d95a5595ad766e41fd80be953eb6fcdeb129 |
   |<span aria-hidden="true">🔍</span> Latest deploy log | https://app.netlify.com/projects/superset-docs-preview/deploys/6a21b5fb2d75470008292d49 |
   |<span aria-hidden="true">😎</span> Deploy Preview | [https://deploy-preview-40695--superset-docs-preview.netlify.app](https://deploy-preview-40695--superset-docs-preview.netlify.app) |
   |<span aria-hidden="true">📱</span> Preview on mobile | <details><summary> Toggle QR Code... </summary><br /><br />![QR Code](https://app.netlify.com/qr-code/eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1cmwiOiJodHRwczovL2RlcGxveS1wcmV2aWV3LTQwNjk1LS1zdXBlcnNldC1kb2NzLXByZXZpZXcubmV0bGlmeS5hcHAifQ.tgEMg9qQGLU7hxtuYpSXnkYyUT3-V6QcRzUEKymbkqE)<br /><br />_Use your smartphone camera to open QR code link._</details> |
   |<span aria-hidden="true">🤖</span> Make changes | [Run an agent on this branch](https://app.netlify.com/projects/superset-docs-preview/agent-runs#FcpBCoAgEEDRu8zayESzukHHGBslwVRSgojunu3-h_dAPtORKywADMyJcdtbO4u1L7YUn2Ln44XBE9Z_bE5NMCCbQ7pXanhEMRjljCCtpOacT2IWJGd4Pw) |
   ---
   <!-- [superset-docs-preview Preview](https://deploy-preview-40695--superset-docs-preview.netlify.app) -->
   _To edit notification comments on pull requests, go to your [Netlify project configuration](https://app.netlify.com/projects/superset-docs-preview/configuration/notifications#deploy-notifications)._


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "codeant-ai-for-open-source[bot] (via GitHub)" <gi...@apache.org>.
codeant-ai-for-open-source[bot] commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3345347867


##########
superset/security/session_invalidation.py:
##########
@@ -0,0 +1,181 @@
+# 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.
+"""
+Backend-agnostic session invalidation.
+
+Outstanding sessions are terminated by comparing the time a session was
+authenticated (``session["_login_at"]``, stamped at login) against a per-user
+invalidation epoch (``UserAttribute.sessions_invalidated_at``). When a session
+predates the user's epoch it is forced to log out on its next request.
+
+The epoch is stamped whenever an account is *disabled* (``active`` flips to
+``False``), via a SQLAlchemy ``after_update`` listener so it fires regardless of
+the code path that disabled the user (FAB admin UI, REST API, or CLI). This
+works for both client-side cookie sessions and server-side session stores
+without enumerating the store by user. A deleted user is already rejected by
+Flask-Login's user loader, so deletion needs no epoch.
+
+The mechanism is inert until an epoch is set: users that were never disabled
+(NULL epoch) are never affected, so it is backwards compatible by default.
+"""
+
+import logging
+from datetime import datetime, timezone
+from typing import Any, Optional
+
+from flask import flash, session
+from flask_babel import gettext as __
+from flask_login import current_user, logout_user
+from sqlalchemy import event, inspect
+from werkzeug.wrappers import Response
+
+logger = logging.getLogger(__name__)
+
+#: Session key holding the epoch-seconds timestamp of when the session logged in.
+SESSION_LOGIN_AT_KEY = "_login_at"
+
+
+def _utcnow() -> datetime:
+    return datetime.now(timezone.utc)
+
+
+def stamp_login_time() -> None:
+    """Record the current session's authentication time. Call on login."""
+    session[SESSION_LOGIN_AT_KEY] = _utcnow().timestamp()
+
+
+def _as_utc_timestamp(value: datetime) -> float:
+    """Epoch seconds for ``value``, treating naive datetimes as UTC.
+
+    The ``sessions_invalidated_at`` column is a naive ``DateTime`` storing a UTC
+    instant; calling ``.timestamp()`` on a naive datetime would otherwise assume
+    *local* time and skew the comparison by the local UTC offset.
+    """
+    if value.tzinfo is None:
+        value = value.replace(tzinfo=timezone.utc)
+    return value.timestamp()
+
+
+def is_session_invalidated(
+    login_at: Optional[float], invalidated_at: Optional[datetime]
+) -> bool:
+    """
+    Return True if a session authenticated at ``login_at`` is invalidated by an
+    epoch of ``invalidated_at``.
+
+    - No epoch (``invalidated_at is None``) ⇒ never invalidated (the common case
+      and the reason the feature is inert/backwards compatible by default).
+    - An epoch with no recorded login time ⇒ invalidated. A session old enough
+      to predate the feature carries no ``_login_at``; if the user has since
+      been disabled, fail closed.
+    - Otherwise the session is invalidated iff it logged in before the epoch.
+    """
+    if invalidated_at is None:
+        return False
+    if login_at is None:
+        return True
+    return login_at < _as_utc_timestamp(invalidated_at)
+
+
+def _get_user_invalidated_at(user: Any) -> Optional[datetime]:
+    extra_attributes = getattr(user, "extra_attributes", None)
+    if not extra_attributes:
+        return None
+    return extra_attributes[0].sessions_invalidated_at
+
+
+def enforce_session_validity() -> Optional[Response]:
+    """
+    ``before_request`` hook: force logout of sessions invalidated by the user's
+    epoch.
+
+    Fails open — any error here logs a warning and allows the request rather
+    than risk locking everyone out on a bug in the check.
+    """
+    try:
+        user = current_user
+        if not user or not getattr(user, "is_authenticated", False):
+            return None
+        # Guest (embedded) users are not FAB users and have their own
+        # revocation mechanism; skip them.
+        if getattr(user, "is_guest_user", False):
+            return None
+        invalidated_at = _get_user_invalidated_at(user)
+        if invalidated_at is None:
+            return None
+        login_at = session.get(SESSION_LOGIN_AT_KEY)
+        if not is_session_invalidated(login_at, invalidated_at):
+            return None
+
+        # Clear the authenticated session and let the request continue as
+        # anonymous: each route's own decorator then responds correctly for its
+        # type (401 for the REST API, redirect-to-login for HTML views) without
+        # this hook needing to know the route kind.
+        logout_user()
+        session.clear()
+        flash(__("Your session has ended. Please sign in again."), "warning")
+        return None
+    except Exception:  # noqa: BLE001  # pylint: disable=broad-except
+        logger.warning(
+            "Session-invalidation check failed; allowing request", exc_info=True
+        )
+        return None
+
+
+def invalidate_user_sessions(connection: Any, user_id: int) -> None:
+    """Stamp the invalidation epoch for ``user_id`` using ``connection``.
+
+    Upserts the user's ``UserAttribute`` row so the mechanism works even for
+    users that have no attribute row yet.
+    """
+    # pylint: disable=import-outside-toplevel
+    from superset.models.user_attributes import UserAttribute
+
+    table = UserAttribute.__table__
+    now = _utcnow().replace(tzinfo=None)
+    result = connection.execute(
+        table.update()
+        .where(table.c.user_id == user_id)
+        .values(sessions_invalidated_at=now, changed_on=now)
+    )
+    if result.rowcount == 0:
+        connection.execute(
+            table.insert().values(
+                user_id=user_id,
+                sessions_invalidated_at=now,
+                created_on=now,
+                changed_on=now,
+            )
+        )

Review Comment:
   **Suggestion:** The manual update-then-insert upsert is race-prone: two concurrent disable operations for the same user can both observe `rowcount == 0` and both insert a `user_attribute` row. Because `user_id` is not unique, this creates duplicate rows and inconsistent invalidation state. Use an atomic DB upsert (`ON CONFLICT ... DO UPDATE`) backed by a unique constraint on `user_id`, or otherwise serialize this write path. [race condition]
   
   <details>
   <summary><b>Severity Level:</b> Major ⚠️</summary>
   
   ```mdx
   - ❌ Duplicate user_attribute rows cause inconsistent avatar/session attribute reads.
   - ⚠️ Session invalidation epoch may conflict between multiple attribute rows.
   ```
   </details>
   <details>
   <summary><b>Steps of Reproduction ✅ </b></summary>
   
   ```mdx
   1. Create a user with no `UserAttribute` row, following the pattern in
   `tests/integration_tests/security/session_invalidation_tests.py:26-35` (user created and
   committed, attributes deleted in `tearDown()`).
   
   2. Open two independent DB connections via `db.engine.connect()` and in each connection
   call `invalidate_user_sessions(connection, user.id)` from
   `superset/security/session_invalidation.py:139-163` concurrently (for example, from two
   threads or processes).
   
   3. In both connections, the `table.update().where(table.c.user_id == user_id)` call at
   `session_invalidation.py:151-153` sees zero matching rows (because no `user_attribute`
   exists yet), so `result.rowcount == 0` in both connections and each proceeds into the `if
   result.rowcount == 0:` insert block at `session_invalidation.py:155-163`.
   
   4. After committing both transactions, query `UserAttribute` with
   `db.session.query(UserAttribute).filter_by(user_id=user.id).all()` using the model defined
   in `superset/models/user_attributes.py:17-30` and observe two rows with the same
   `user_id`, confirming the non-atomic upsert created duplicate per-user attribute rows due
   to the lack of a unique constraint on `user_id` (see migration
   `2018-08-06_14-38_0c5070e96b57_add_user_attributes_table.py:35-41` which defines no
   `UniqueConstraint`).
   ```
   </details>
   
   [Fix in Cursor](https://app.codeant.ai/fix-in-ide?tool=cursor&prompt_id=3e002ece4e224c5abc8530b7a3f4bc52&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset) | [Fix in VSCode Claude](https://app.codeant.ai/fix-in-ide?tool=vscode-claude&prompt_id=3e002ece4e224c5abc8530b7a3f4bc52&service=github&base_url=https%3A%2F%2Fgithub.com&org=apache&repo=apache%2Fsuperset)
   
   *(Use Cmd/Ctrl + Click for best experience)*
   <details>
   <summary><b>Prompt for AI Agent 🤖 </b></summary>
   
   ```mdx
   This is a comment left during a code review.
   
   **Path:** superset/security/session_invalidation.py
   **Line:** 150:163
   **Comment:**
   	*Race Condition: The manual update-then-insert upsert is race-prone: two concurrent disable operations for the same user can both observe `rowcount == 0` and both insert a `user_attribute` row. Because `user_id` is not unique, this creates duplicate rows and inconsistent invalidation state. Use an atomic DB upsert (`ON CONFLICT ... DO UPDATE`) backed by a unique constraint on `user_id`, or otherwise serialize this write path.
   
   Validate the correctness of the flagged issue. If correct, How can I resolve this? If you propose a fix, implement it and please make it concise.
   Once fix is implemented, also check other comments on the same PR, and ask user if the user wants to fix the rest of the comments as well. if said yes, then fetch all the comments validate the correctness and implement a minimal fix
   ```
   </details>
   <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40695&comment_hash=db35e37b5d78c86de90a77d92dabe05b73e3279f51673b0e7a668a2bf51edbf1&reaction=like'>👍</a> | <a href='https://app.codeant.ai/feedback?pr_url=https%3A%2F%2Fgithub.com%2Fapache%2Fsuperset%2Fpull%2F40695&comment_hash=db35e37b5d78c86de90a77d92dabe05b73e3279f51673b0e7a668a2bf51edbf1&reaction=dislike'>👎</a>



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40695:
URL: https://github.com/apache/superset/pull/40695#issuecomment-4610069184

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3385294154


##########
superset/initialization/__init__.py:
##########
@@ -764,6 +764,23 @@ def cleanup_analytics_memory(response: Response) -> Response:
                 gc.collect()
             return response
 
+        @self.superset_app.before_request
+        def enforce_session_validity() -> Any:

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Incorrect return type for before_request hook</b></div>
   <div id="fix">
   
   Change the return type of `enforce_session_validity` to `-> Optional[Response]` and add `Optional` to the `from typing import` line to match the callee's signature.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #a1913b</i></small>
   </div><div>
   
   
   <div id="suggestion">
   <div id="issue"><b>CWE-1024: Weak Type Validation</b></div>
   <div id="fix">
   
   The `before_request` handler `enforce_session_validity()` is annotated `-> Any` but the function it calls returns `Optional[Response]`. Flask `before_request` handlers must return `None` to continue processing or a `Response` to short-circuit. The incorrect `Any` annotation hides this contract and may cause type-checking tools to miss related issues. (See also: [CWE-1024](https://cwe.mitre.org/data/definitions/1024.html))
   </div>
   
   
   <details>
   <summary>
   <b>Code suggestion</b>
   </summary>
   <blockquote>Check the AI-generated fix before applying</blockquote>
   <div id="code">
   
   
   ```
    --- superset/initialization/__init__.py
    +++ superset/initialization/__init__.py
    @@ -765,7 +765,7 @@
                 return response
    
             @self.superset_app.before_request
    -        def enforce_session_validity() -> Any:
    +        def enforce_session_validity() -> Optional[Response]:
                 """Force logout of sessions invalidated by a per-user epoch."""
                 from superset.security.session_invalidation import (
                     enforce_session_validity as _enforce,
   ```
   
   </div>
   </details>
   
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #02e482</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/migrations/versions/2026-06-02_10-00_f7a1c93e0b21_add_sessions_invalidated_at.py:
##########
@@ -0,0 +1,177 @@
+# Licensed to the Apache Software Foundation (ASF) under one

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Invalid Python module name</b></div>
   <div id="fix">
   
   The module name contains hyphens and a timestamp which violates PEP 8 naming conventions. Consider renaming to a valid Python identifier.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #02e482</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40695:
URL: https://github.com/apache/superset/pull/40695#issuecomment-4635274369

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40695:
URL: https://github.com/apache/superset/pull/40695#issuecomment-4666078726

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3364271577


##########
superset/security/manager.py:
##########
@@ -633,6 +633,12 @@ def create_login_manager(self, app: Flask) -> LoginManager:
         return lm
 
     def on_user_login(self, user: Any) -> None:
+        # pylint: disable=import-outside-toplevel
+        from superset.security.session_invalidation import stamp_login_time
+
+        # Record the authentication time so outstanding sessions can be
+        # invalidated when the account is later disabled.
+        stamp_login_time()

Review Comment:
   <!-- Bito Reply -->
   The update to the test case is appropriate. By adding the mock for `stamp_login_time` and asserting it is called once, the test now correctly verifies that the session stamping logic is executed during the user login process, addressing the previously identified coverage gap.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40695:
URL: https://github.com/apache/superset/pull/40695#issuecomment-4667495117

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: terminate active sessions when an account is disabled [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on PR #40695:
URL: https://github.com/apache/superset/pull/40695#issuecomment-4665547187

   @sadpandajoe fixed up the things you caught, if you wanna take another pass at it. Thanks.


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3358358194


##########
tests/integration_tests/security/session_invalidation_tests.py:
##########
@@ -0,0 +1,78 @@
+# 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.
+
+from superset import db
+from superset.models.user_attributes import UserAttribute
+from tests.integration_tests.base_tests import SupersetTestCase
+
+USERNAME = "session_invalidation_user"
+PASSWORD = "general"  # noqa: S105
+
+
+class TestSessionInvalidation(SupersetTestCase):
+    def setUp(self) -> None:
+        self.create_user(
+            USERNAME,
+            PASSWORD,
+            "Admin",
+            email="session_invalidation_user@fab.org",
+        )
+        db.session.commit()
+
+    def tearDown(self) -> None:
+        if user := self.get_user(USERNAME):
+            db.session.query(UserAttribute).filter_by(user_id=user.id).delete()
+            db.session.delete(user)
+            db.session.commit()
+
+    def _set_active(self, active: bool) -> None:
+        # Update via the ORM so the after_update event fires (mirrors the
+        # FAB admin UI / REST API path that flips ``active``).
+        user = self.get_user(USERNAME)
+        user.active = active
+        db.session.commit()
+
+    def test_disabling_user_forces_logout_of_active_session(self) -> None:
+        self.login(USERNAME, PASSWORD)
+
+        # Authenticated request works before the account is disabled.
+        assert self.client.get("/api/v1/me/").status_code == 200
+
+        # Disabling the account stamps the per-user invalidation epoch...
+        self._set_active(False)
+        user = self.get_user(USERNAME)
+        attribute = (
+            db.session.query(UserAttribute).filter_by(user_id=user.id).one_or_none()
+        )
+        assert attribute is not None
+        assert attribute.sessions_invalidated_at is not None
+
+        # ...so the previously-authenticated session is now forced out.
+        assert self.client.get("/api/v1/me/").status_code != 200

Review Comment:
   Should we use `== 401` here? `!= 200` means the test would pass with 500 or 403. If we wanted to have more status codes we accept, we could maybe compare the `status_code` to an array of status codes we accept?



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: terminate active sessions when an account is disabled [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3384757317


##########
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

Review Comment:
   This refers to a file (`add_guest_token_revoked_before.py`) that no longer exists — the guest-token revocation work was dropped from this PR. The only migration here is `2026-06-02_10-00_f7a1c93e0b21_add_sessions_invalidated_at.py`, which follows the standard Superset migration naming convention shared by all 349 existing migration files (e.g. `2015-09-21_17-30_4e6a06bad7a8_init.py`). Alembic loads these by file path rather than importing them as Python modules, so the hyphenated date prefix is intentional and valid.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40695:
URL: https://github.com/apache/superset/pull/40695#issuecomment-4608220748

   <!-- Bito Reply -->
   The flagged issue regarding a race condition in the `invalidate_user_sessions` function is correct. The current implementation performs a non-atomic update-then-insert, which can lead to duplicate `UserAttribute` rows if two concurrent processes attempt to disable the same user simultaneously.
   
   To resolve this, you can use a database-level upsert. Since Superset supports multiple database backends, the most robust approach is to use SQLAlchemy's `dialects` to handle `ON CONFLICT` (for PostgreSQL/SQLite) or to serialize the operation using a `SELECT ... FOR UPDATE` lock.
   
   Given the context, a simple and effective fix is to use a `SELECT ... FOR UPDATE` lock to serialize the check-and-insert operation:
   
   ```python
   def invalidate_user_sessions(connection: Any, user_id: int) -> None:
       from superset.models.user_attributes import UserAttribute
       table = UserAttribute.__table__
       now = _utcnow().replace(tzinfo=None)
       
       # Serialize the check-and-insert using a row-level lock
       with connection.begin_nested():
           existing = connection.execute(
               table.select().where(table.c.user_id == user_id).with_for_update()
           ).fetchone()
           
           if existing:
               connection.execute(
                   table.update().where(table.c.user_id == user_id).values(sessions_invalidated_at=now, changed_on=now)
               )
           else:
               connection.execute(
                   table.insert().values(user_id=user_id, sessions_invalidated_at=now, created_on=now, changed_on=now)
               )
   ```
   
   Would you like me to check the other comments on this PR and implement fixes for them as well?
   
   **superset/security/session_invalidation.py**
   ```
   # Serialize the check-and-insert using a row-level lock
       with connection.begin_nested():
           existing = connection.execute(
               table.select().where(table.c.user_id == user_id).with_for_update()
           ).fetchone()
           
           if existing:
               connection.execute(
                   table.update().where(table.c.user_id == user_id).values(sessions_invalidated_at=now, changed_on=now)
               )
           else:
               connection.execute(
                   table.insert().values(user_id=user_id, sessions_invalidated_at=now, created_on=now, changed_on=now)
               )
   ```


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3358346742


##########
superset/migrations/versions/2026-06-02_10-00_f7a1c93e0b21_add_sessions_invalidated_at.py:
##########
@@ -0,0 +1,67 @@
+# 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 sessions_invalidated_at to user_attribute
+
+Revision ID: f7a1c93e0b21
+Revises: 33d7e0e21daa
+Create Date: 2026-06-02 10:00:00.000000
+
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "f7a1c93e0b21"
+down_revision = "33d7e0e21daa"
+
+TABLE = "user_attribute"
+COLUMN = "sessions_invalidated_at"
+INDEX = "ix_user_attribute_sessions_invalidated_at"
+UQ = "uq_user_attribute_user_id"
+
+
+def upgrade():
+    add_columns(TABLE, sa.Column(COLUMN, sa.DateTime(), nullable=True))

Review Comment:
   If an account is disabled today and re-enabled after this lands, the old session has `no _login_at` and no epoch. `is_session_invalidated(None, None)` returns `False` and the stale session revives. UPDATING.md says re-enabling starts a fresh session, but the code doesn't enforce that for pre-existing disabled accounts. We should backfill `sessions_invalidated_at` for `ab_user.active=false` users here, or stamp an epoch on re-enable when none exists.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3364684065


##########
superset/migrations/versions/2026-06-02_10-00_f7a1c93e0b21_add_sessions_invalidated_at.py:
##########
@@ -0,0 +1,67 @@
+# 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 sessions_invalidated_at to user_attribute
+
+Revision ID: f7a1c93e0b21
+Revises: 33d7e0e21daa
+Create Date: 2026-06-02 10:00:00.000000
+
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "f7a1c93e0b21"
+down_revision = "33d7e0e21daa"
+
+TABLE = "user_attribute"
+COLUMN = "sessions_invalidated_at"
+INDEX = "ix_user_attribute_sessions_invalidated_at"
+UQ = "uq_user_attribute_user_id"
+
+
+def upgrade():
+    add_columns(TABLE, sa.Column(COLUMN, sa.DateTime(), nullable=True))
+    create_index(TABLE, INDEX, [COLUMN])
+    # The model treats ``user_attribute`` as one row per user (all readers use
+    # ``extra_attributes[0]``). Enforce that invariant so the session-invalidation
+    # upsert is race-safe. Drop any pre-existing duplicates, keeping the lowest
+    # ``id`` per user, before adding the unique constraint.
+    op.execute(

Review Comment:
   Good catch — fixed in fe314e55d8. Before deleting duplicates the migration now backfills the kept (MIN id) row from any higher-id sibling: for each of avatar_url, welcome_dashboard_id and sessions_invalidated_at, a kept row that is NULL takes the lowest-id non-NULL value from its duplicates. So a setting that lived only on a non-MIN row is merged forward rather than dropped. The subqueries are plain correlated SQL so they run on SQLite/MySQL/Postgres alike.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: terminate active sessions when an account is disabled [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3391800617


##########
superset/migrations/versions/2026-06-02_10-00_f7a1c93e0b21_add_sessions_invalidated_at.py:
##########
@@ -0,0 +1,177 @@
+# Licensed to the Apache Software Foundation (ASF) under one

Review Comment:
   Same as the earlier thread on this file: this follows the standard Superset Alembic migration naming convention shared by all existing migration files (e.g. `2015-09-21_17-30_4e6a06bad7a8_init.py`). Alembic loads these by file path rather than importing them as Python modules, so the hyphenated date prefix is intentional and valid — PEP 8 module-name rules do not apply here.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3364270481


##########
superset/security/manager.py:
##########
@@ -633,6 +633,12 @@ def create_login_manager(self, app: Flask) -> LoginManager:
         return lm
 
     def on_user_login(self, user: Any) -> None:
+        # pylint: disable=import-outside-toplevel
+        from superset.security.session_invalidation import stamp_login_time
+
+        # Record the authentication time so outstanding sessions can be
+        # invalidated when the account is later disabled.
+        stamp_login_time()

Review Comment:
   Good call — added a patch of `stamp_login_time` to `test_on_user_login_logs_event` and assert it's called once, alongside the existing audit-log assertion. Done in 29e0ded865.



##########
tests/integration_tests/security/session_invalidation_tests.py:
##########
@@ -0,0 +1,78 @@
+# 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.
+
+from superset import db
+from superset.models.user_attributes import UserAttribute
+from tests.integration_tests.base_tests import SupersetTestCase
+
+USERNAME = "session_invalidation_user"
+PASSWORD = "general"  # noqa: S105
+
+
+class TestSessionInvalidation(SupersetTestCase):
+    def setUp(self) -> None:
+        self.create_user(
+            USERNAME,
+            PASSWORD,
+            "Admin",
+            email="session_invalidation_user@fab.org",
+        )
+        db.session.commit()
+
+    def tearDown(self) -> None:
+        if user := self.get_user(USERNAME):
+            db.session.query(UserAttribute).filter_by(user_id=user.id).delete()
+            db.session.delete(user)
+            db.session.commit()
+
+    def _set_active(self, active: bool) -> None:
+        # Update via the ORM so the after_update event fires (mirrors the
+        # FAB admin UI / REST API path that flips ``active``).
+        user = self.get_user(USERNAME)
+        user.active = active
+        db.session.commit()
+
+    def test_disabling_user_forces_logout_of_active_session(self) -> None:
+        self.login(USERNAME, PASSWORD)
+
+        # Authenticated request works before the account is disabled.
+        assert self.client.get("/api/v1/me/").status_code == 200
+
+        # Disabling the account stamps the per-user invalidation epoch...
+        self._set_active(False)
+        user = self.get_user(USERNAME)
+        attribute = (
+            db.session.query(UserAttribute).filter_by(user_id=user.id).one_or_none()
+        )
+        assert attribute is not None
+        assert attribute.sessions_invalidated_at is not None
+
+        # ...so the previously-authenticated session is now forced out.
+        assert self.client.get("/api/v1/me/").status_code != 200

Review Comment:
   Agreed — tightened it to `== 401`. The `enforce_session_validity` hook clears the session and continues anonymous, so the protected REST route (`/api/v1/me/`) answers 401 specifically; asserting the exact code catches a regression that turned a forced-logout into an unrelated 500/403. Fixed in 29e0ded865.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3365038449


##########
superset/migrations/versions/2026-06-02_10-00_f7a1c93e0b21_add_sessions_invalidated_at.py:
##########
@@ -0,0 +1,67 @@
+# 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 sessions_invalidated_at to user_attribute
+
+Revision ID: f7a1c93e0b21
+Revises: 33d7e0e21daa
+Create Date: 2026-06-02 10:00:00.000000
+
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "f7a1c93e0b21"
+down_revision = "33d7e0e21daa"
+
+TABLE = "user_attribute"
+COLUMN = "sessions_invalidated_at"
+INDEX = "ix_user_attribute_sessions_invalidated_at"
+UQ = "uq_user_attribute_user_id"
+
+
+def upgrade():
+    add_columns(TABLE, sa.Column(COLUMN, sa.DateTime(), nullable=True))

Review Comment:
   Good catch — fixed in 9ec28e3c67. The migration now backfills `sessions_invalidated_at` for any account that is already disabled (`ab_user.active` is false) at upgrade time, upserting one `user_attribute` row per such user. That way re-enabling a previously-disabled account does not revive a pre-existing session (which carries no recorded login time), so the behavior matches what UPDATING.md describes for accounts disabled before this lands as well.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3345982580


##########
superset/security/session_invalidation.py:
##########
@@ -0,0 +1,181 @@
+# 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.
+"""
+Backend-agnostic session invalidation.
+
+Outstanding sessions are terminated by comparing the time a session was
+authenticated (``session["_login_at"]``, stamped at login) against a per-user
+invalidation epoch (``UserAttribute.sessions_invalidated_at``). When a session
+predates the user's epoch it is forced to log out on its next request.
+
+The epoch is stamped whenever an account is *disabled* (``active`` flips to
+``False``), via a SQLAlchemy ``after_update`` listener so it fires regardless of
+the code path that disabled the user (FAB admin UI, REST API, or CLI). This
+works for both client-side cookie sessions and server-side session stores
+without enumerating the store by user. A deleted user is already rejected by
+Flask-Login's user loader, so deletion needs no epoch.
+
+The mechanism is inert until an epoch is set: users that were never disabled
+(NULL epoch) are never affected, so it is backwards compatible by default.
+"""
+
+import logging
+from datetime import datetime, timezone
+from typing import Any, Optional
+
+from flask import flash, session
+from flask_babel import gettext as __
+from flask_login import current_user, logout_user
+from sqlalchemy import event, inspect
+from werkzeug.wrappers import Response
+
+logger = logging.getLogger(__name__)
+
+#: Session key holding the epoch-seconds timestamp of when the session logged in.
+SESSION_LOGIN_AT_KEY = "_login_at"
+
+
+def _utcnow() -> datetime:
+    return datetime.now(timezone.utc)
+
+
+def stamp_login_time() -> None:
+    """Record the current session's authentication time. Call on login."""
+    session[SESSION_LOGIN_AT_KEY] = _utcnow().timestamp()
+
+
+def _as_utc_timestamp(value: datetime) -> float:
+    """Epoch seconds for ``value``, treating naive datetimes as UTC.
+
+    The ``sessions_invalidated_at`` column is a naive ``DateTime`` storing a UTC
+    instant; calling ``.timestamp()`` on a naive datetime would otherwise assume
+    *local* time and skew the comparison by the local UTC offset.
+    """
+    if value.tzinfo is None:
+        value = value.replace(tzinfo=timezone.utc)
+    return value.timestamp()
+
+
+def is_session_invalidated(
+    login_at: Optional[float], invalidated_at: Optional[datetime]
+) -> bool:
+    """
+    Return True if a session authenticated at ``login_at`` is invalidated by an
+    epoch of ``invalidated_at``.
+
+    - No epoch (``invalidated_at is None``) ⇒ never invalidated (the common case
+      and the reason the feature is inert/backwards compatible by default).
+    - An epoch with no recorded login time ⇒ invalidated. A session old enough
+      to predate the feature carries no ``_login_at``; if the user has since
+      been disabled, fail closed.
+    - Otherwise the session is invalidated iff it logged in before the epoch.
+    """
+    if invalidated_at is None:
+        return False
+    if login_at is None:
+        return True
+    return login_at < _as_utc_timestamp(invalidated_at)
+
+
+def _get_user_invalidated_at(user: Any) -> Optional[datetime]:
+    extra_attributes = getattr(user, "extra_attributes", None)
+    if not extra_attributes:
+        return None
+    return extra_attributes[0].sessions_invalidated_at
+
+
+def enforce_session_validity() -> Optional[Response]:
+    """
+    ``before_request`` hook: force logout of sessions invalidated by the user's
+    epoch.
+
+    Fails open — any error here logs a warning and allows the request rather
+    than risk locking everyone out on a bug in the check.
+    """
+    try:
+        user = current_user
+        if not user or not getattr(user, "is_authenticated", False):
+            return None
+        # Guest (embedded) users are not FAB users and have their own
+        # revocation mechanism; skip them.
+        if getattr(user, "is_guest_user", False):
+            return None
+        invalidated_at = _get_user_invalidated_at(user)
+        if invalidated_at is None:
+            return None
+        login_at = session.get(SESSION_LOGIN_AT_KEY)
+        if not is_session_invalidated(login_at, invalidated_at):
+            return None
+
+        # Clear the authenticated session and let the request continue as
+        # anonymous: each route's own decorator then responds correctly for its
+        # type (401 for the REST API, redirect-to-login for HTML views) without
+        # this hook needing to know the route kind.
+        logout_user()
+        session.clear()
+        flash(__("Your session has ended. Please sign in again."), "warning")
+        return None
+    except Exception:  # noqa: BLE001  # pylint: disable=broad-except
+        logger.warning(
+            "Session-invalidation check failed; allowing request", exc_info=True
+        )
+        return None
+
+
+def invalidate_user_sessions(connection: Any, user_id: int) -> None:
+    """Stamp the invalidation epoch for ``user_id`` using ``connection``.
+
+    Upserts the user's ``UserAttribute`` row so the mechanism works even for
+    users that have no attribute row yet.
+    """
+    # pylint: disable=import-outside-toplevel
+    from superset.models.user_attributes import UserAttribute
+
+    table = UserAttribute.__table__
+    now = _utcnow().replace(tzinfo=None)
+    result = connection.execute(
+        table.update()
+        .where(table.c.user_id == user_id)
+        .values(sessions_invalidated_at=now, changed_on=now)
+    )
+    if result.rowcount == 0:
+        connection.execute(
+            table.insert().values(
+                user_id=user_id,
+                sessions_invalidated_at=now,
+                created_on=now,
+                changed_on=now,
+            )
+        )

Review Comment:
   Good catch. Fixed in 9f23786582: I added a unique constraint on `user_attribute.user_id` (the model already treats it as one row per user — every reader uses `extra_attributes[0]`), with the migration de-duplicating any pre-existing rows first. `invalidate_user_sessions` now does update-then-insert inside a SAVEPOINT and, if a concurrent disable wins the insert race, catches the resulting `IntegrityError` and retries as an update, so no duplicate rows can be created.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3358841531


##########
superset/security/manager.py:
##########
@@ -633,6 +633,12 @@ def create_login_manager(self, app: Flask) -> LoginManager:
         return lm
 
     def on_user_login(self, user: Any) -> None:
+        # pylint: disable=import-outside-toplevel
+        from superset.security.session_invalidation import stamp_login_time
+
+        # Record the authentication time so outstanding sessions can be
+        # invalidated when the account is later disabled.
+        stamp_login_time()

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Test coverage gap for session stamping</b></div>
   <div id="fix">
   
   In `test_on_user_login_logs_event`, add a mock for `stamp_login_time` and assert it’s called. For example:
   
   ```python
   @patch('superset.security.manager.stamp_login_time')
   @patch('superset.security.manager._log_audit_event')
   def test_on_user_login_logs_event(mock_log, mock_stamp_login_time):
       sm = SupersetSecurityManager.__new__(SupersetSecurityManager)
       user = MagicMock(spec=User)
       user.username = 'testuser'
       user.id = 7
   
       sm.on_user_login(user)
   
       mock_stamp_login_time.assert_called_once()
       mock_log.assert_called_once_with(
           'UserLoggedIn', {'username': 'testuser', 'user_id': 7}
       )
   ```
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #c3b63e</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3384758489


##########
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

Review Comment:
   <!-- Bito Reply -->
   The suggestion to rename the migration file to avoid hyphens is not applicable in this context. Alembic migration files in Superset follow a specific naming convention that includes date-based prefixes with hyphens, and Alembic loads these files by path rather than by importing them as Python modules, making the hyphenated format both intentional and valid.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: terminate active sessions when an account is disabled [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas merged PR #40695:
URL: https://github.com/apache/superset/pull/40695


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat(security): terminate active sessions when an account is disabled [superset]

Posted by "sadpandajoe (via GitHub)" <gi...@apache.org>.
sadpandajoe commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3358336732


##########
superset/migrations/versions/2026-06-02_10-00_f7a1c93e0b21_add_sessions_invalidated_at.py:
##########
@@ -0,0 +1,67 @@
+# 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 sessions_invalidated_at to user_attribute
+
+Revision ID: f7a1c93e0b21
+Revises: 33d7e0e21daa
+Create Date: 2026-06-02 10:00:00.000000
+
+"""
+
+import sqlalchemy as sa
+from alembic import op
+
+from superset.migrations.shared.utils import (
+    add_columns,
+    create_index,
+    drop_columns,
+    drop_index,
+)
+
+# revision identifiers, used by Alembic.
+revision = "f7a1c93e0b21"
+down_revision = "33d7e0e21daa"
+
+TABLE = "user_attribute"
+COLUMN = "sessions_invalidated_at"
+INDEX = "ix_user_attribute_sessions_invalidated_at"
+UQ = "uq_user_attribute_user_id"
+
+
+def upgrade():
+    add_columns(TABLE, sa.Column(COLUMN, sa.DateTime(), nullable=True))
+    create_index(TABLE, INDEX, [COLUMN])
+    # The model treats ``user_attribute`` as one row per user (all readers use
+    # ``extra_attributes[0]``). Enforce that invariant so the session-invalidation
+    # upsert is race-safe. Drop any pre-existing duplicates, keeping the lowest
+    # ``id`` per user, before adding the unique constraint.
+    op.execute(

Review Comment:
   This drops `avatar_url` / `welcome_dashboard_id` from any `non-MIN(id)` row without merging them into the kept row. Operators upgrading from deployments with duplicates will silently lose those settings. Shouldn't we merge non-NULL fields first, or fail the migration with operator instructions for the duplicate-row case.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40695:
URL: https://github.com/apache/superset/pull/40695#issuecomment-4663731828

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: terminate active sessions when an account is disabled [superset]

Posted by "rusackas (via GitHub)" <gi...@apache.org>.
rusackas commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3385394039


##########
superset/security/session_invalidation.py:
##########
@@ -0,0 +1,205 @@
+# 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.
+"""
+Backend-agnostic session invalidation.
+
+Outstanding sessions are terminated by comparing the time a session was
+authenticated (``session["_login_at"]``, stamped at login) against a per-user
+invalidation epoch (``UserAttribute.sessions_invalidated_at``). When a session
+predates the user's epoch it is forced to log out on its next request.
+
+The epoch is stamped whenever an account is *disabled* (``active`` flips to
+``False``), via a SQLAlchemy ``after_update`` listener so it fires regardless of
+the code path that disabled the user (FAB admin UI, REST API, or CLI). This
+works for both client-side cookie sessions and server-side session stores
+without enumerating the store by user. A deleted user is already rejected by
+Flask-Login's user loader, so deletion needs no epoch.
+
+The mechanism is inert until an epoch is set: users that were never disabled
+(NULL epoch) are never affected, so it is backwards compatible by default.
+"""
+
+import logging
+import math
+from datetime import datetime, timezone
+from typing import Any, Optional
+
+from flask import flash, session
+from flask_babel import gettext as __
+from flask_login import current_user, logout_user
+from sqlalchemy import event, inspect
+from sqlalchemy.exc import IntegrityError
+from werkzeug.wrappers import Response
+
+logger = logging.getLogger(__name__)
+
+#: Session key holding the epoch-seconds timestamp of when the session logged in.
+SESSION_LOGIN_AT_KEY = "_login_at"
+
+
+def _utcnow() -> datetime:
+    return datetime.now(timezone.utc)
+
+
+def stamp_login_time() -> None:
+    """Record the current session's authentication time. Call on login."""
+    session[SESSION_LOGIN_AT_KEY] = _utcnow().timestamp()
+
+
+def _as_utc_timestamp(value: datetime) -> float:
+    """Epoch seconds for ``value``, treating naive datetimes as UTC.
+
+    The ``sessions_invalidated_at`` column is a naive ``DateTime`` storing a UTC
+    instant; calling ``.timestamp()`` on a naive datetime would otherwise assume
+    *local* time and skew the comparison by the local UTC offset.
+    """
+    if value.tzinfo is None:
+        value = value.replace(tzinfo=timezone.utc)
+    return value.timestamp()
+
+
+def is_session_invalidated(
+    login_at: Optional[float], invalidated_at: Optional[datetime]
+) -> bool:
+    """
+    Return True if a session authenticated at ``login_at`` is invalidated by an
+    epoch of ``invalidated_at``.
+
+    - No epoch (``invalidated_at is None``) ⇒ never invalidated (the common case
+      and the reason the feature is inert/backwards compatible by default).
+    - An epoch with no recorded login time ⇒ invalidated. A session old enough
+      to predate the feature carries no ``_login_at``; if the user has since
+      been disabled, fail closed.
+    - Otherwise the session is invalidated iff it logged in before the epoch.
+    """
+    if invalidated_at is None:
+        return False
+    if login_at is None:
+        return True
+    return login_at < _as_utc_timestamp(invalidated_at)
+
+
+def _get_user_invalidated_at(user: Any) -> Optional[datetime]:
+    extra_attributes = getattr(user, "extra_attributes", None)
+    if not extra_attributes:
+        return None
+    return extra_attributes[0].sessions_invalidated_at
+
+
+def enforce_session_validity() -> Optional[Response]:
+    """
+    ``before_request`` hook: force logout of sessions invalidated by the user's
+    epoch.
+
+    Fails open — any error here logs a warning and allows the request rather
+    than risk locking everyone out on a bug in the check.
+    """
+    try:
+        user = current_user
+        if not user or not getattr(user, "is_authenticated", False):
+            return None
+        # Guest (embedded) users are not FAB users and have their own
+        # revocation mechanism; skip them.
+        if getattr(user, "is_guest_user", False):
+            return None
+        invalidated_at = _get_user_invalidated_at(user)
+        if invalidated_at is None:
+            return None
+        login_at = session.get(SESSION_LOGIN_AT_KEY)
+        if not is_session_invalidated(login_at, invalidated_at):
+            return None
+
+        # Clear the authenticated session and let the request continue as
+        # anonymous: each route's own decorator then responds correctly for its
+        # type (401 for the REST API, redirect-to-login for HTML views) without
+        # this hook needing to know the route kind.
+        logout_user()
+        session.clear()
+        flash(__("Your session has ended. Please sign in again."), "warning")
+        return None
+    except Exception:  # noqa: BLE001  # pylint: disable=broad-except
+        logger.warning(
+            "Session-invalidation check failed; allowing request", exc_info=True
+        )
+        return None

Review Comment:
   Added in 6234ed3ada. `tests/unit_tests/security/test_session_invalidation.py` now unit-tests every branch of `enforce_session_validity`: unauthenticated user, guest user (skipped), no-epoch, a valid session that logged in after the epoch, an invalidated session (asserts `logout_user`/`session.clear`/`flash` fire), and the fail-open handler (asserts the warning is logged and the request is allowed).



##########
superset/security/session_invalidation.py:
##########
@@ -0,0 +1,205 @@
+# 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.
+"""
+Backend-agnostic session invalidation.
+
+Outstanding sessions are terminated by comparing the time a session was
+authenticated (``session["_login_at"]``, stamped at login) against a per-user
+invalidation epoch (``UserAttribute.sessions_invalidated_at``). When a session
+predates the user's epoch it is forced to log out on its next request.
+
+The epoch is stamped whenever an account is *disabled* (``active`` flips to
+``False``), via a SQLAlchemy ``after_update`` listener so it fires regardless of
+the code path that disabled the user (FAB admin UI, REST API, or CLI). This
+works for both client-side cookie sessions and server-side session stores
+without enumerating the store by user. A deleted user is already rejected by
+Flask-Login's user loader, so deletion needs no epoch.
+
+The mechanism is inert until an epoch is set: users that were never disabled
+(NULL epoch) are never affected, so it is backwards compatible by default.
+"""
+
+import logging
+import math
+from datetime import datetime, timezone
+from typing import Any, Optional
+
+from flask import flash, session
+from flask_babel import gettext as __
+from flask_login import current_user, logout_user
+from sqlalchemy import event, inspect
+from sqlalchemy.exc import IntegrityError
+from werkzeug.wrappers import Response
+
+logger = logging.getLogger(__name__)
+
+#: Session key holding the epoch-seconds timestamp of when the session logged in.
+SESSION_LOGIN_AT_KEY = "_login_at"
+
+
+def _utcnow() -> datetime:
+    return datetime.now(timezone.utc)
+
+
+def stamp_login_time() -> None:
+    """Record the current session's authentication time. Call on login."""
+    session[SESSION_LOGIN_AT_KEY] = _utcnow().timestamp()
+
+
+def _as_utc_timestamp(value: datetime) -> float:
+    """Epoch seconds for ``value``, treating naive datetimes as UTC.
+
+    The ``sessions_invalidated_at`` column is a naive ``DateTime`` storing a UTC
+    instant; calling ``.timestamp()`` on a naive datetime would otherwise assume
+    *local* time and skew the comparison by the local UTC offset.
+    """
+    if value.tzinfo is None:
+        value = value.replace(tzinfo=timezone.utc)
+    return value.timestamp()
+
+
+def is_session_invalidated(
+    login_at: Optional[float], invalidated_at: Optional[datetime]
+) -> bool:
+    """
+    Return True if a session authenticated at ``login_at`` is invalidated by an
+    epoch of ``invalidated_at``.
+
+    - No epoch (``invalidated_at is None``) ⇒ never invalidated (the common case
+      and the reason the feature is inert/backwards compatible by default).
+    - An epoch with no recorded login time ⇒ invalidated. A session old enough
+      to predate the feature carries no ``_login_at``; if the user has since
+      been disabled, fail closed.
+    - Otherwise the session is invalidated iff it logged in before the epoch.
+    """
+    if invalidated_at is None:
+        return False
+    if login_at is None:
+        return True
+    return login_at < _as_utc_timestamp(invalidated_at)
+
+
+def _get_user_invalidated_at(user: Any) -> Optional[datetime]:
+    extra_attributes = getattr(user, "extra_attributes", None)
+    if not extra_attributes:
+        return None
+    return extra_attributes[0].sessions_invalidated_at
+
+
+def enforce_session_validity() -> Optional[Response]:
+    """
+    ``before_request`` hook: force logout of sessions invalidated by the user's
+    epoch.
+
+    Fails open — any error here logs a warning and allows the request rather
+    than risk locking everyone out on a bug in the check.
+    """
+    try:
+        user = current_user
+        if not user or not getattr(user, "is_authenticated", False):
+            return None
+        # Guest (embedded) users are not FAB users and have their own
+        # revocation mechanism; skip them.
+        if getattr(user, "is_guest_user", False):
+            return None
+        invalidated_at = _get_user_invalidated_at(user)
+        if invalidated_at is None:
+            return None
+        login_at = session.get(SESSION_LOGIN_AT_KEY)
+        if not is_session_invalidated(login_at, invalidated_at):
+            return None
+
+        # Clear the authenticated session and let the request continue as
+        # anonymous: each route's own decorator then responds correctly for its
+        # type (401 for the REST API, redirect-to-login for HTML views) without
+        # this hook needing to know the route kind.
+        logout_user()
+        session.clear()
+        flash(__("Your session has ended. Please sign in again."), "warning")
+        return None
+    except Exception:  # noqa: BLE001  # pylint: disable=broad-except
+        logger.warning(
+            "Session-invalidation check failed; allowing request", exc_info=True
+        )
+        return None
+
+
+def invalidate_user_sessions(connection: Any, user_id: int) -> None:
+    """Stamp the invalidation epoch for ``user_id`` using ``connection``.
+
+    Upserts the user's ``UserAttribute`` row so the mechanism works even for
+    users that have no attribute row yet. ``user_attribute.user_id`` carries a
+    unique constraint, so the insert is safe against a concurrent disable of the
+    same user: the loser's insert raises ``IntegrityError``, which is caught and
+    retried as an update rather than creating a duplicate row.
+    """
+    # pylint: disable=import-outside-toplevel
+    from superset.models.user_attributes import UserAttribute
+
+    table = UserAttribute.__table__
+    # Round the epoch up to the next whole second. Some backends (e.g. MySQL)
+    # store ``DATETIME`` columns without sub-second precision and truncate the
+    # value; a session that logged in earlier in the same wall-clock second
+    # carries a fractional ``_login_at`` that would otherwise compare as >= the
+    # truncated epoch and survive invalidation. Ceiling the stamp guarantees it
+    # strictly exceeds any login time from the same second.
+    now_epoch = _utcnow().timestamp()
+    now = datetime.fromtimestamp(math.ceil(now_epoch), timezone.utc).replace(
+        tzinfo=None
+    )
+
+    def _stamp_existing() -> int:
+        return connection.execute(
+            table.update()
+            .where(table.c.user_id == user_id)
+            .values(sessions_invalidated_at=now, changed_on=now)
+        ).rowcount
+
+    if _stamp_existing():
+        return
+
+    try:
+        with connection.begin_nested():
+            connection.execute(
+                table.insert().values(
+                    user_id=user_id,
+                    sessions_invalidated_at=now,
+                    created_on=now,
+                    changed_on=now,
+                )
+            )
+    except IntegrityError:
+        # A concurrent disable inserted the row first; stamp it instead.
+        _stamp_existing()
+

Review Comment:
   Added in 6234ed3ada. There are now unit tests for `invalidate_user_sessions` covering all three paths: the update of an existing row (no INSERT/SAVEPOINT), the insert of a missing row inside a SAVEPOINT, and the IntegrityError retry where a concurrent disable wins the insert race and the row is stamped via UPDATE instead of duplicated.



##########
superset/initialization/__init__.py:
##########
@@ -764,6 +764,23 @@ def cleanup_analytics_memory(response: Response) -> Response:
                 gc.collect()
             return response
 
+        @self.superset_app.before_request
+        def enforce_session_validity() -> Any:

Review Comment:
   This is already the case: `enforce_session_validity` is declared `-> Optional[Response]` and `Optional` is imported on the `from typing import Any, Optional` line. No change needed.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on PR #40695:
URL: https://github.com/apache/superset/pull/40695#issuecomment-4674714397

   AI Code Review is in progress (usually takes 3 to 15 minutes unless it's a very large PR).
   
   <details>
   <summary>
   Bito Usage Guide
   </summary>
   
   **Commands**
         
   Type the following command in the pull request comment and save the comment.
         
   - `/review` - Manually triggers a full AI review.
   
   - `/pause` - Pauses automatic reviews on this pull request.
   - `/resume` - Resumes automatic reviews.
   - `/resolve` - Marks all Bito-posted review comments as resolved.
   - `/abort` - Cancels all in-progress reviews.
   
         
   Refer to the <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/available-commands" target="_blank" rel="noopener noreferrer">documentation</a> for additional commands.
         
   **Configuration**
   
   This repository uses `Superset` You can customize the agent settings <a href="https://alpha.bito.ai/home/ai-agents/code-review-agent" target="_blank" rel="noopener noreferrer">here</a> or contact your Bito workspace admin at evan@preset.io.
         
   **Documentation & Help**
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/getting-started/install-run-using-bito-cloud/create-or-customize-an-agent-instance" target="_blank" rel="noopener noreferrer">Customize agent settings</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/implementing-custom-code-review-rules" target="_blank" rel="noopener noreferrer">Review rules</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent" target="_blank" rel="noopener noreferrer">General documentation</a>
   - <a href="https://docs.bito.ai/bito-dev-agents/ai-code-review-agent/faqs" target="_blank" rel="noopener noreferrer">FAQ</a>
   
   </details>
   


-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3391801340


##########
superset/migrations/versions/2026-06-02_10-00_f7a1c93e0b21_add_sessions_invalidated_at.py:
##########
@@ -0,0 +1,177 @@
+# Licensed to the Apache Software Foundation (ASF) under one

Review Comment:
   <!-- Bito Reply -->
   The suggestion to rename the migration file is not necessary in this case. As you noted, the hyphenated date prefix is a standard naming convention for Superset Alembic migrations, and these files are loaded by path rather than imported as modules, making PEP 8 naming rules inapplicable here.



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org


Re: [PR] feat: terminate active sessions when an account is disabled [superset]

Posted by "bito-code-review[bot] (via GitHub)" <gi...@apache.org>.
bito-code-review[bot] commented on code in PR #40695:
URL: https://github.com/apache/superset/pull/40695#discussion_r3385294154


##########
superset/initialization/__init__.py:
##########
@@ -764,6 +764,23 @@ def cleanup_analytics_memory(response: Response) -> Response:
                 gc.collect()
             return response
 
+        @self.superset_app.before_request
+        def enforce_session_validity() -> Any:

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Incorrect return type for before_request hook</b></div>
   <div id="fix">
   
   Change the return type of `enforce_session_validity` to `-> Optional[Response]` and add `Optional` to the `from typing import` line to match the callee's signature.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #a1913b</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/security/session_invalidation.py:
##########
@@ -0,0 +1,205 @@
+# 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.
+"""
+Backend-agnostic session invalidation.
+
+Outstanding sessions are terminated by comparing the time a session was
+authenticated (``session["_login_at"]``, stamped at login) against a per-user
+invalidation epoch (``UserAttribute.sessions_invalidated_at``). When a session
+predates the user's epoch it is forced to log out on its next request.
+
+The epoch is stamped whenever an account is *disabled* (``active`` flips to
+``False``), via a SQLAlchemy ``after_update`` listener so it fires regardless of
+the code path that disabled the user (FAB admin UI, REST API, or CLI). This
+works for both client-side cookie sessions and server-side session stores
+without enumerating the store by user. A deleted user is already rejected by
+Flask-Login's user loader, so deletion needs no epoch.
+
+The mechanism is inert until an epoch is set: users that were never disabled
+(NULL epoch) are never affected, so it is backwards compatible by default.
+"""
+
+import logging
+import math
+from datetime import datetime, timezone
+from typing import Any, Optional
+
+from flask import flash, session
+from flask_babel import gettext as __
+from flask_login import current_user, logout_user
+from sqlalchemy import event, inspect
+from sqlalchemy.exc import IntegrityError
+from werkzeug.wrappers import Response
+
+logger = logging.getLogger(__name__)
+
+#: Session key holding the epoch-seconds timestamp of when the session logged in.
+SESSION_LOGIN_AT_KEY = "_login_at"
+
+
+def _utcnow() -> datetime:
+    return datetime.now(timezone.utc)
+
+
+def stamp_login_time() -> None:
+    """Record the current session's authentication time. Call on login."""
+    session[SESSION_LOGIN_AT_KEY] = _utcnow().timestamp()
+
+
+def _as_utc_timestamp(value: datetime) -> float:
+    """Epoch seconds for ``value``, treating naive datetimes as UTC.
+
+    The ``sessions_invalidated_at`` column is a naive ``DateTime`` storing a UTC
+    instant; calling ``.timestamp()`` on a naive datetime would otherwise assume
+    *local* time and skew the comparison by the local UTC offset.
+    """
+    if value.tzinfo is None:
+        value = value.replace(tzinfo=timezone.utc)
+    return value.timestamp()
+
+
+def is_session_invalidated(
+    login_at: Optional[float], invalidated_at: Optional[datetime]
+) -> bool:
+    """
+    Return True if a session authenticated at ``login_at`` is invalidated by an
+    epoch of ``invalidated_at``.
+
+    - No epoch (``invalidated_at is None``) ⇒ never invalidated (the common case
+      and the reason the feature is inert/backwards compatible by default).
+    - An epoch with no recorded login time ⇒ invalidated. A session old enough
+      to predate the feature carries no ``_login_at``; if the user has since
+      been disabled, fail closed.
+    - Otherwise the session is invalidated iff it logged in before the epoch.
+    """
+    if invalidated_at is None:
+        return False
+    if login_at is None:
+        return True
+    return login_at < _as_utc_timestamp(invalidated_at)
+
+
+def _get_user_invalidated_at(user: Any) -> Optional[datetime]:
+    extra_attributes = getattr(user, "extra_attributes", None)
+    if not extra_attributes:
+        return None
+    return extra_attributes[0].sessions_invalidated_at
+
+
+def enforce_session_validity() -> Optional[Response]:
+    """
+    ``before_request`` hook: force logout of sessions invalidated by the user's
+    epoch.
+
+    Fails open — any error here logs a warning and allows the request rather
+    than risk locking everyone out on a bug in the check.
+    """
+    try:
+        user = current_user
+        if not user or not getattr(user, "is_authenticated", False):
+            return None
+        # Guest (embedded) users are not FAB users and have their own
+        # revocation mechanism; skip them.
+        if getattr(user, "is_guest_user", False):
+            return None
+        invalidated_at = _get_user_invalidated_at(user)
+        if invalidated_at is None:
+            return None
+        login_at = session.get(SESSION_LOGIN_AT_KEY)
+        if not is_session_invalidated(login_at, invalidated_at):
+            return None
+
+        # Clear the authenticated session and let the request continue as
+        # anonymous: each route's own decorator then responds correctly for its
+        # type (401 for the REST API, redirect-to-login for HTML views) without
+        # this hook needing to know the route kind.
+        logout_user()
+        session.clear()
+        flash(__("Your session has ended. Please sign in again."), "warning")
+        return None
+    except Exception:  # noqa: BLE001  # pylint: disable=broad-except
+        logger.warning(
+            "Session-invalidation check failed; allowing request", exc_info=True
+        )
+        return None
+
+
+def invalidate_user_sessions(connection: Any, user_id: int) -> None:
+    """Stamp the invalidation epoch for ``user_id`` using ``connection``.
+
+    Upserts the user's ``UserAttribute`` row so the mechanism works even for
+    users that have no attribute row yet. ``user_attribute.user_id`` carries a
+    unique constraint, so the insert is safe against a concurrent disable of the
+    same user: the loser's insert raises ``IntegrityError``, which is caught and
+    retried as an update rather than creating a duplicate row.
+    """
+    # pylint: disable=import-outside-toplevel
+    from superset.models.user_attributes import UserAttribute
+
+    table = UserAttribute.__table__
+    # Round the epoch up to the next whole second. Some backends (e.g. MySQL)
+    # store ``DATETIME`` columns without sub-second precision and truncate the
+    # value; a session that logged in earlier in the same wall-clock second
+    # carries a fractional ``_login_at`` that would otherwise compare as >= the
+    # truncated epoch and survive invalidation. Ceiling the stamp guarantees it
+    # strictly exceeds any login time from the same second.
+    now_epoch = _utcnow().timestamp()
+    now = datetime.fromtimestamp(math.ceil(now_epoch), timezone.utc).replace(
+        tzinfo=None
+    )
+
+    def _stamp_existing() -> int:
+        return connection.execute(
+            table.update()
+            .where(table.c.user_id == user_id)
+            .values(sessions_invalidated_at=now, changed_on=now)
+        ).rowcount
+
+    if _stamp_existing():
+        return
+
+    try:
+        with connection.begin_nested():
+            connection.execute(
+                table.insert().values(
+                    user_id=user_id,
+                    sessions_invalidated_at=now,
+                    created_on=now,
+                    changed_on=now,
+                )
+            )
+    except IntegrityError:
+        # A concurrent disable inserted the row first; stamp it instead.
+        _stamp_existing()
+

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing tests for invalidate_user_sessions</b></div>
   <div id="fix">
   
   The `invalidate_user_sessions()` function has no unit tests despite implementing the core upsert logic with race condition handling. Test both update and insert paths, including the IntegrityError retry mechanism.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #a1913b</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



##########
superset/security/session_invalidation.py:
##########
@@ -0,0 +1,205 @@
+# 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.
+"""
+Backend-agnostic session invalidation.
+
+Outstanding sessions are terminated by comparing the time a session was
+authenticated (``session["_login_at"]``, stamped at login) against a per-user
+invalidation epoch (``UserAttribute.sessions_invalidated_at``). When a session
+predates the user's epoch it is forced to log out on its next request.
+
+The epoch is stamped whenever an account is *disabled* (``active`` flips to
+``False``), via a SQLAlchemy ``after_update`` listener so it fires regardless of
+the code path that disabled the user (FAB admin UI, REST API, or CLI). This
+works for both client-side cookie sessions and server-side session stores
+without enumerating the store by user. A deleted user is already rejected by
+Flask-Login's user loader, so deletion needs no epoch.
+
+The mechanism is inert until an epoch is set: users that were never disabled
+(NULL epoch) are never affected, so it is backwards compatible by default.
+"""
+
+import logging
+import math
+from datetime import datetime, timezone
+from typing import Any, Optional
+
+from flask import flash, session
+from flask_babel import gettext as __
+from flask_login import current_user, logout_user
+from sqlalchemy import event, inspect
+from sqlalchemy.exc import IntegrityError
+from werkzeug.wrappers import Response
+
+logger = logging.getLogger(__name__)
+
+#: Session key holding the epoch-seconds timestamp of when the session logged in.
+SESSION_LOGIN_AT_KEY = "_login_at"
+
+
+def _utcnow() -> datetime:
+    return datetime.now(timezone.utc)
+
+
+def stamp_login_time() -> None:
+    """Record the current session's authentication time. Call on login."""
+    session[SESSION_LOGIN_AT_KEY] = _utcnow().timestamp()
+
+
+def _as_utc_timestamp(value: datetime) -> float:
+    """Epoch seconds for ``value``, treating naive datetimes as UTC.
+
+    The ``sessions_invalidated_at`` column is a naive ``DateTime`` storing a UTC
+    instant; calling ``.timestamp()`` on a naive datetime would otherwise assume
+    *local* time and skew the comparison by the local UTC offset.
+    """
+    if value.tzinfo is None:
+        value = value.replace(tzinfo=timezone.utc)
+    return value.timestamp()
+
+
+def is_session_invalidated(
+    login_at: Optional[float], invalidated_at: Optional[datetime]
+) -> bool:
+    """
+    Return True if a session authenticated at ``login_at`` is invalidated by an
+    epoch of ``invalidated_at``.
+
+    - No epoch (``invalidated_at is None``) ⇒ never invalidated (the common case
+      and the reason the feature is inert/backwards compatible by default).
+    - An epoch with no recorded login time ⇒ invalidated. A session old enough
+      to predate the feature carries no ``_login_at``; if the user has since
+      been disabled, fail closed.
+    - Otherwise the session is invalidated iff it logged in before the epoch.
+    """
+    if invalidated_at is None:
+        return False
+    if login_at is None:
+        return True
+    return login_at < _as_utc_timestamp(invalidated_at)
+
+
+def _get_user_invalidated_at(user: Any) -> Optional[datetime]:
+    extra_attributes = getattr(user, "extra_attributes", None)
+    if not extra_attributes:
+        return None
+    return extra_attributes[0].sessions_invalidated_at
+
+
+def enforce_session_validity() -> Optional[Response]:
+    """
+    ``before_request`` hook: force logout of sessions invalidated by the user's
+    epoch.
+
+    Fails open — any error here logs a warning and allows the request rather
+    than risk locking everyone out on a bug in the check.
+    """
+    try:
+        user = current_user
+        if not user or not getattr(user, "is_authenticated", False):
+            return None
+        # Guest (embedded) users are not FAB users and have their own
+        # revocation mechanism; skip them.
+        if getattr(user, "is_guest_user", False):
+            return None
+        invalidated_at = _get_user_invalidated_at(user)
+        if invalidated_at is None:
+            return None
+        login_at = session.get(SESSION_LOGIN_AT_KEY)
+        if not is_session_invalidated(login_at, invalidated_at):
+            return None
+
+        # Clear the authenticated session and let the request continue as
+        # anonymous: each route's own decorator then responds correctly for its
+        # type (401 for the REST API, redirect-to-login for HTML views) without
+        # this hook needing to know the route kind.
+        logout_user()
+        session.clear()
+        flash(__("Your session has ended. Please sign in again."), "warning")
+        return None
+    except Exception:  # noqa: BLE001  # pylint: disable=broad-except
+        logger.warning(
+            "Session-invalidation check failed; allowing request", exc_info=True
+        )
+        return None

Review Comment:
   <div>
   
   
   <div id="suggestion">
   <div id="issue"><b>Missing tests for enforce_session_validity</b></div>
   <div id="fix">
   
   The `enforce_session_validity()` before_request hook has no unit tests. This is the main orchestration function that calls multiple helpers. Test all branches including the fail-open exception handler.
   </div>
   
   
   </div>
   
   
   
   
   <small><i>Code Review Run #a1913b</i></small>
   </div>
   
   ---
   Should Bito avoid suggestions like this for future reviews? (<a href=https://alpha.bito.ai/home/ai-agents/review-rules>Manage Rules</a>)
   - [ ] Yes, avoid them



-- 
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: notifications-unsubscribe@superset.apache.org

For queries about this service, please contact Infrastructure at:
users@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: notifications-unsubscribe@superset.apache.org
For additional commands, e-mail: notifications-help@superset.apache.org