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

vincbeck pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/airflow.git


The following commit(s) were added to refs/heads/main by this push:
     new 997913ad79d Enhance API JWT invalidation for FAB auth manager (#77138)
997913ad79d is described below

commit 997913ad79d548630720382b7ea08a2e0870107b
Author: Kevin Yang <[email protected]>
AuthorDate: Tue Nov 24 12:04:17 2026 -0500

    Enhance API JWT invalidation for FAB auth manager (#77138)
---
 providers/fab/docs/changelog.rst                   |   9 +
 providers/fab/docs/migrations-ref.rst              |   4 +-
 .../fab/auth_manager/api_fastapi/services/users.py |   2 +-
 .../providers/fab/auth_manager/fab_auth_manager.py |  81 ++--
 .../providers/fab/auth_manager/models/__init__.py  |   3 +
 .../providers/fab/auth_manager/models/db.py        |   1 +
 .../fab/auth_manager/security_manager/override.py  |  28 +-
 .../0002_3_12_0_add_token_generation_to_ab_user.py |  78 ++++
 providers/fab/src/airflow/providers/fab/www/app.py |   7 +-
 .../providers/fab/www/extensions/init_session.py   |  21 ++
 .../api_fastapi/services/test_users.py             |   4 +-
 .../auth_manager/security_manager/test_override.py |  22 ++
 .../unit/fab/auth_manager/test_fab_auth_manager.py | 410 ++++++++++++++++++++-
 .../unit/fab/www/extensions/test_init_session.py   |  66 ++++
 providers/fab/tests/unit/fab/www/test_app.py       |  34 ++
 .../fab/www/views/test_views_custom_user_views.py  |  28 +-
 16 files changed, 730 insertions(+), 68 deletions(-)

diff --git a/providers/fab/docs/changelog.rst b/providers/fab/docs/changelog.rst
index 3be4b062b9f..4af8261c43f 100644
--- a/providers/fab/docs/changelog.rst
+++ b/providers/fab/docs/changelog.rst
@@ -20,6 +20,15 @@
 Changelog
 ---------
 
+.. note::
+    This release includes a database migration that adds a 
``token_generation`` column to the
+    ``ab_user`` table. Run ``airflow db migrate`` after upgrading the provider.
+
+    Changing or resetting a password now ends the API tokens and UI sessions 
issued before the
+    change. API servers cache users for up to ``[fab] cache_ttl`` seconds, so 
for a change made
+    from another process, such as ``airflow users reset-password`` or another 
API server, the
+    earlier API tokens stop working there once its cached user expires.
+
 3.11.1
 ......
 
diff --git a/providers/fab/docs/migrations-ref.rst 
b/providers/fab/docs/migrations-ref.rst
index 3667d875c1f..80612a18140 100644
--- a/providers/fab/docs/migrations-ref.rst
+++ b/providers/fab/docs/migrations-ref.rst
@@ -34,7 +34,9 @@ Here's the list of all the Database Migrations that are 
executed via when you ru
 
+-------------------------+------------------+---------------+-----------------------------------------+
 | Revision ID             | Revises ID       | Fab Version   | Description     
                        |
 
+=========================+==================+===============+=========================================+
-| ``02ca36b0235b`` (head) | ``6709f7a774b9`` | ``3.5.0``     | Fix fab db 
inconsistencies.             |
+| ``20f2f9e27083`` (head) | ``02ca36b0235b`` | ``3.12.0``    | Add 
token_generation to ab_user.        |
++-------------------------+------------------+---------------+-----------------------------------------+
+| ``02ca36b0235b``        | ``6709f7a774b9`` | ``3.5.0``     | Fix fab db 
inconsistencies.             |
 
+-------------------------+------------------+---------------+-----------------------------------------+
 | ``6709f7a774b9`` (base) | ``None``         | ``1.4.0``     | Create User and 
Role tables if missing. |
 
+-------------------------+------------------+---------------+-----------------------------------------+
diff --git 
a/providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/services/users.py
 
b/providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/services/users.py
index 83a7cfc8c06..36c98019a73 100644
--- 
a/providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/services/users.py
+++ 
b/providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/services/users.py
@@ -185,7 +185,7 @@ class FABAuthManagerUsers:
 
         password_changed = False
         if "password" in fields_to_update and body.password is not None:
-            user.password = 
security_manager._hash_password(body.password.get_secret_value())
+            security_manager.set_user_password(user, 
body.password.get_secret_value())
             password_changed = True
 
         if "username" in fields_to_update and body.username is not None:
diff --git 
a/providers/fab/src/airflow/providers/fab/auth_manager/fab_auth_manager.py 
b/providers/fab/src/airflow/providers/fab/auth_manager/fab_auth_manager.py
index bdd0c25349d..370efce2dec 100644
--- a/providers/fab/src/airflow/providers/fab/auth_manager/fab_auth_manager.py
+++ b/providers/fab/src/airflow/providers/fab/auth_manager/fab_auth_manager.py
@@ -27,7 +27,7 @@ from typing import TYPE_CHECKING, Any
 from urllib.parse import urlencode, urljoin
 from weakref import WeakValueDictionary
 
-from cachetools import TTLCache, cachedmethod
+from cachetools import TTLCache
 from fastapi import FastAPI
 from fastapi.middleware.wsgi import WSGIMiddleware
 from flask import current_app, g
@@ -185,6 +185,8 @@ _MAP_MENU_ITEM_TO_FAB_RESOURCE_TYPE = {
 }
 
 CACHE_TTL = conf.getint("fab", "cache_ttl", fallback=30)
+TOKEN_GENERATION_CLAIM = "token_generation"
+
 
 if AIRFLOW_V_3_1_PLUS:
     from airflow.providers.fab.www.security.permissions import 
RESOURCE_HITL_DETAIL
@@ -213,7 +215,12 @@ class FabAuthManager(BaseAuthManager[User]):
     This auth manager is responsible for providing a backward compatible user 
management experience to users.
     """
 
+    # Pop a user only after their change is committed: a request served in 
between would
+    # cache the row as it was before the change.
     cache: TTLCache = TTLCache(maxsize=1024, ttl=CACHE_TTL)
+    # ``TTLCache`` is not thread-safe: requests read it on the event loop, 
while user updates pop
+    # from it in threadpool and WSGI threads. Hold this lock for every access 
to ``cache``.
+    cache_lock = threading.Lock()
     _user_fetch_locks: WeakValueDictionary[int, asyncio.Lock] = 
WeakValueDictionary()
     appbuilder: AirflowAppBuilder | None = None
     flask_app: Flask | None = None
@@ -326,14 +333,47 @@ class FabAuthManager(BaseAuthManager[User]):
             raise ValueError(f"User with id {user_id} is not active")
         return user
 
-    @cachedmethod(lambda self: self.cache, key=lambda _, token: 
int(token["sub"]))
+    @staticmethod
+    def _get_token_generation(token: dict[str, Any]) -> int:
+        # Tokens issued before the claim existed count as the initial 
generation.
+        token_generation = token.get(TOKEN_GENERATION_CLAIM, 0)
+        if type(token_generation) is not int:
+            raise ValueError(
+                f"Token of user with id {token['sub']} has an invalid 
{TOKEN_GENERATION_CLAIM} claim"
+            )
+        return token_generation
+
+    def _get_cached_user(self, user_id: int, token_generation: int) -> User | 
None:
+        """
+        Return the cached user, unless the token is newer than it.
+
+        A newer token was issued after a password change that the cached user 
predates, so the
+        cached user is dropped: it must not match tokens from before the 
change either.
+        """
+        with self.cache_lock:
+            user = self.cache.get(user_id)
+            if user is not None and user.token_generation < token_generation:
+                self.cache.pop(user_id, None)
+                return None
+        return user
+
     def deserialize_user(self, token: dict[str, Any]) -> User:
         user_id = int(token["sub"])
+        token_generation = self._get_token_generation(token)
+        user = self._get_cached_user(user_id, token_generation)
+        if user is None:
+            user = self._load_active_user(user_id)
+            with self.cache_lock:
+                self.cache[user_id] = user
+        if token_generation != user.token_generation:
+            raise ValueError(f"Token of user with id {user_id} was issued 
before their last password change")
+        return user
 
+    def _load_active_user(self, user_id: int) -> User:
         def _fetch_user() -> User:
             with create_session() as session:
                 user = session.scalars(select(User).where(User.id == 
user_id)).one_or_none()
-                return self._validate_user(user, token["sub"])
+                return self._validate_user(user, str(user_id))
 
         try:
             return _fetch_user()
@@ -359,27 +399,24 @@ class FabAuthManager(BaseAuthManager[User]):
             return self.deserialize_user(token)
 
         user_id = int(token["sub"])
-        try:
-            return self.cache[user_id]
-        except KeyError:
-            pass
-
-        lock = self._user_fetch_locks.setdefault(user_id, asyncio.Lock())
-        async with lock:
-            try:
-                return self.cache[user_id]
-            except KeyError:
-                pass
-
-            async with create_session_async() as session:
-                user = (await session.scalars(select(User).where(User.id == 
user_id))).one_or_none()
-                user = self._validate_user(user, token["sub"])
-
-            self.cache[user_id] = user
-            return user
+        token_generation = self._get_token_generation(token)
+        user = self._get_cached_user(user_id, token_generation)
+        if user is None:
+            lock = self._user_fetch_locks.setdefault(user_id, asyncio.Lock())
+            async with lock:
+                user = self._get_cached_user(user_id, token_generation)
+                if user is None:
+                    async with create_session_async() as session:
+                        user = (await 
session.scalars(select(User).where(User.id == user_id))).one_or_none()
+                        user = self._validate_user(user, token["sub"])
+                    with self.cache_lock:
+                        self.cache[user_id] = user
+        if token_generation != user.token_generation:
+            raise ValueError(f"Token of user with id {user_id} was issued 
before their last password change")
+        return user
 
     def serialize_user(self, user: User) -> dict[str, Any]:
-        return {"sub": str(user.id)}
+        return {"sub": str(user.id), TOKEN_GENERATION_CLAIM: 
user.token_generation}
 
     def is_logged_in(self) -> bool:
         """Return whether the user is logged in."""
diff --git 
a/providers/fab/src/airflow/providers/fab/auth_manager/models/__init__.py 
b/providers/fab/src/airflow/providers/fab/auth_manager/models/__init__.py
index ecdac36f421..7d708eb1b82 100644
--- a/providers/fab/src/airflow/providers/fab/auth_manager/models/__init__.py
+++ b/providers/fab/src/airflow/providers/fab/auth_manager/models/__init__.py
@@ -276,6 +276,9 @@ class User(Model, BaseUser):
     last_login: Mapped[datetime.datetime | None] = mapped_column(DateTime, 
nullable=True)
     login_count: Mapped[int | None] = mapped_column(Integer, nullable=True)
     fail_login_count: Mapped[int | None] = mapped_column(Integer, 
nullable=True)
+    # Incremented on every password change. Tokens and sessions record the 
value they were issued
+    # under and stop being accepted once it moves on.
+    token_generation: Mapped[int] = mapped_column(Integer, nullable=False, 
default=0, server_default="0")
     roles: Mapped[list[Role]] = relationship(
         "Role",
         secondary=assoc_user_role,
diff --git a/providers/fab/src/airflow/providers/fab/auth_manager/models/db.py 
b/providers/fab/src/airflow/providers/fab/auth_manager/models/db.py
index 04eb86cc633..13b70f58224 100644
--- a/providers/fab/src/airflow/providers/fab/auth_manager/models/db.py
+++ b/providers/fab/src/airflow/providers/fab/auth_manager/models/db.py
@@ -32,6 +32,7 @@ PACKAGE_DIR = Path(__file__).parents[2]
 _REVISION_HEADS_MAP: dict[str, str] = {
     "1.4.0": "6709f7a774b9",
     "3.5.0": "02ca36b0235b",
+    "3.12.0": "20f2f9e27083",
 }
 
 
diff --git 
a/providers/fab/src/airflow/providers/fab/auth_manager/security_manager/override.py
 
b/providers/fab/src/airflow/providers/fab/auth_manager/security_manager/override.py
index a0f50fe7279..c2f01c73858 100644
--- 
a/providers/fab/src/airflow/providers/fab/auth_manager/security_manager/override.py
+++ 
b/providers/fab/src/airflow/providers/fab/auth_manager/security_manager/override.py
@@ -614,6 +614,17 @@ class 
FabAirflowSecurityManagerOverride(AirflowSecurityManagerV2):
         method = current_app.config.get("FAB_PASSWORD_HASH_METHOD", "scrypt")
         return generate_password_hash(password, method=method)
 
+    def set_user_password(self, user: User, password: str) -> None:
+        """
+        Set a new password and invalidate the API tokens and Flask sessions 
issued under the old one.
+
+        Nothing is committed: the caller persists both changes together, 
normally with
+        ``update_user``.
+        """
+        user.password = self._hash_password(password)
+        # Incremented in SQL so that concurrent password changes cannot write 
the same value.
+        user.token_generation = self.user_model.token_generation + 1
+
     def reset_password(self, userid: int, password: str) -> bool:
         """
         Change/Reset a user's password for auth db.
@@ -626,7 +637,7 @@ class 
FabAirflowSecurityManagerOverride(AirflowSecurityManagerV2):
         user = self.get_user_by_id(userid)
         if not user:
             return False
-        user.password = self._hash_password(password)
+        self.set_user_password(user, password)
         self.reset_user_sessions(user)
         return self.update_user(user)
 
@@ -660,17 +671,6 @@ class 
FabAirflowSecurityManagerOverride(AirflowSecurityManagerV2):
                     if session_user_id is not None and str(session_user_id) == 
str(user.id):
                         session.delete(s)
                 session.commit()
-        else:
-            safe_username = escape(user.username)
-            self._cli_safe_flash(
-                "Since you are using `securecookie` session backend mechanism, 
we cannot prevent "
-                f"some old sessions for user {safe_username} to be reused.<br> 
If you want to make sure "
-                "that the user is logged out from all sessions, you should 
consider using "
-                "`database` session backend mechanism.<br> You can also change 
the 'secret_key` "
-                "webserver configuration for all your webserver instances and 
restart the webserver. "
-                "This however will logout all users from all sessions.",
-                "warning",
-            )
 
     def load_user_jwt(self, _jwt_header, jwt_data) -> User | None:
         identity = jwt_data["sub"]
@@ -1712,6 +1712,10 @@ class 
FabAirflowSecurityManagerOverride(AirflowSecurityManagerV2):
             log.error(const.LOGMSG_ERR_SEC_UPD_USER, e)
             self.session.rollback()
             return False
+        from airflow.providers.fab.auth_manager.fab_auth_manager import 
FabAuthManager
+
+        with FabAuthManager.cache_lock:
+            FabAuthManager.cache.pop(user.id, None)
         return True
 
     @staticmethod
diff --git 
a/providers/fab/src/airflow/providers/fab/migrations/versions/0002_3_12_0_add_token_generation_to_ab_user.py
 
b/providers/fab/src/airflow/providers/fab/migrations/versions/0002_3_12_0_add_token_generation_to_ab_user.py
new file mode 100644
index 00000000000..99f4c0b7ad1
--- /dev/null
+++ 
b/providers/fab/src/airflow/providers/fab/migrations/versions/0002_3_12_0_add_token_generation_to_ab_user.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.
+
+"""
+Add token_generation to ab_user.
+
+Revision ID: 20f2f9e27083
+Revises: 02ca36b0235b
+Create Date: 2026-11-18 02:34:33.000000
+
+"""
+
+from __future__ import annotations
+
+from collections.abc import Iterator
+from contextlib import contextmanager
+
+import sqlalchemy as sa
+from alembic import op
+
+revision = "20f2f9e27083"
+down_revision = "02ca36b0235b"
+branch_labels = None
+depends_on = None
+fab_version = "3.12.0"
+
+
+@contextmanager
+def _sqlite_rebuilds() -> Iterator[None]:
+    """
+    Run SQLite table rebuilds with foreign keys off, rolling back atomically 
on failure.
+
+    Same as ``airflow.migrations.utils.sqlite_rebuilds``, which Airflow 
versions this provider
+    supports do not all have. Dropping a column rebuilds ``ab_user`` on 
SQLite, and dropping the old
+    table with foreign keys on cascades into ``ab_user_role``, deleting every 
role assignment.
+    ``PRAGMA foreign_keys`` is ignored inside a transaction, hence the 
autocommit blocks.
+    """
+    if op.get_bind().dialect.name != "sqlite":
+        yield
+        return
+    if op.get_context().as_sql:
+        raise RuntimeError("SQLite offline SQL cannot render this migration's 
table rebuilds")
+    enabled = op.get_bind().exec_driver_sql("PRAGMA foreign_keys").scalar()
+    with op.get_context().autocommit_block():
+        op.execute("PRAGMA foreign_keys=OFF")
+    try:
+        with op.get_bind().begin_nested():
+            yield
+    finally:
+        with op.get_context().autocommit_block():
+            op.execute(f"PRAGMA foreign_keys={1 if enabled else 0}")
+
+
+def upgrade() -> None:
+    """Add the token_generation column to ab_user."""
+    with op.batch_alter_table("ab_user", schema=None) as batch_op:
+        batch_op.add_column(sa.Column("token_generation", sa.Integer(), 
nullable=False, server_default="0"))
+
+
+def downgrade() -> None:
+    """Remove the token_generation column from ab_user."""
+    with _sqlite_rebuilds(), op.batch_alter_table("ab_user", schema=None) as 
batch_op:
+        batch_op.drop_column("token_generation")
diff --git a/providers/fab/src/airflow/providers/fab/www/app.py 
b/providers/fab/src/airflow/providers/fab/www/app.py
index 82d38db7d61..47f4f89d00f 100644
--- a/providers/fab/src/airflow/providers/fab/www/app.py
+++ b/providers/fab/src/airflow/providers/fab/www/app.py
@@ -38,6 +38,7 @@ from airflow.providers.fab.www.extensions.init_security 
import init_api_auth
 from airflow.providers.fab.www.extensions.init_session import (
     init_airflow_session_interface,
     init_session_max_lifetime,
+    init_session_token_generation,
 )
 from airflow.providers.fab.www.extensions.init_views import (
     init_error_handlers,
@@ -126,11 +127,15 @@ def create_app(enable_plugins: bool):
         # FAB auth manager. One example is ``run_update_fastapi_api_spec``, it 
calls
         # ``FabAuthManager().get_fastapi_app()`` to generate the openapi 
documentation regardless of the
         # configured auth manager.
+        is_fab_auth_manager = isinstance(get_auth_manager(), FabAuthManager)
         if enable_plugins:
             init_plugins(flask_app)
-        elif isinstance(get_auth_manager(), FabAuthManager):
+        elif is_fab_auth_manager:
             init_airflow_session_interface(flask_app, db)
             init_session_max_lifetime(flask_app)
+        if is_fab_auth_manager:
+            # The plugins app reads the FAB login session too, with the 
``securecookie`` backend.
+            init_session_token_generation(flask_app)
         init_jinja_globals(flask_app, enable_plugins=enable_plugins)
         init_wsgi_middleware(flask_app)
     return flask_app
diff --git 
a/providers/fab/src/airflow/providers/fab/www/extensions/init_session.py 
b/providers/fab/src/airflow/providers/fab/www/extensions/init_session.py
index 6ca31ddb296..ec134844c7c 100644
--- a/providers/fab/src/airflow/providers/fab/www/extensions/init_session.py
+++ b/providers/fab/src/airflow/providers/fab/www/extensions/init_session.py
@@ -32,6 +32,8 @@ from airflow.providers.fab.www.session import (
 log = logging.getLogger(__name__)
 
 SESSION_LOGIN_TIME_KEY = "_login_at"
+# The ``User.token_generation`` a Flask session was created under.
+SESSION_TOKEN_GENERATION_KEY = "_token_generation"
 
 
 def init_airflow_session_interface(app, db):
@@ -121,3 +123,22 @@ def init_session_max_lifetime(app):
             # crossed the deadline is itself unauthenticated.
             logout_user()
             builtin_flask_session.pop(SESSION_LOGIN_TIME_KEY, None)
+
+
+def _record_session_token_generation(sender, user, **kwargs) -> None:
+    builtin_flask_session[SESSION_TOKEN_GENERATION_KEY] = user.token_generation
+
+
+def _end_session_from_before_password_change() -> None:
+    # Sessions created before the key existed count as the initial generation.
+    if current_user.is_authenticated and (
+        builtin_flask_session.get(SESSION_TOKEN_GENERATION_KEY, 0) != 
current_user.token_generation
+    ):
+        logout_user()
+
+
+def init_session_token_generation(app):
+    """End sessions created before their user's last password change."""
+    # Scoped to this app: ``user_logged_in`` is shared by every Flask app in 
the process.
+    user_logged_in.connect(_record_session_token_generation, sender=app)
+    app.before_request(_end_session_from_before_password_change)
diff --git 
a/providers/fab/tests/unit/fab/auth_manager/api_fastapi/services/test_users.py 
b/providers/fab/tests/unit/fab/auth_manager/api_fastapi/services/test_users.py
index 127dcdec97c..aaced1da552 100644
--- 
a/providers/fab/tests/unit/fab/auth_manager/api_fastapi/services/test_users.py
+++ 
b/providers/fab/tests/unit/fab/auth_manager/api_fastapi/services/test_users.py
@@ -666,12 +666,10 @@ class TestUsersService:
             password=password_mock,
         )
 
-        security_manager._hash_password.return_value = "hashed_password"
         FABAuthManagerUsers.update_user("alice", patch_body, 
update_mask="password")
 
         password_mock.get_secret_value.assert_called_once()
-        security_manager._hash_password.assert_called_once_with("newpassword")
-        assert user_obj.password == "hashed_password"
+        security_manager.set_user_password.assert_called_once_with(user_obj, 
"newpassword")
 
     # delete_user tests
 
diff --git 
a/providers/fab/tests/unit/fab/auth_manager/security_manager/test_override.py 
b/providers/fab/tests/unit/fab/auth_manager/security_manager/test_override.py
index c6142dc6ffc..1a6779e5c7e 100644
--- 
a/providers/fab/tests/unit/fab/auth_manager/security_manager/test_override.py
+++ 
b/providers/fab/tests/unit/fab/auth_manager/security_manager/test_override.py
@@ -24,11 +24,14 @@ import pytest
 import requests
 from authlib.jose import JsonWebKey, jwt as authlib_jwt
 from authlib.jose.errors import InvalidClaimError
+from cachetools import TTLCache
 from flask import Flask
 from flask_appbuilder import const
 from sqlalchemy.exc import IntegrityError
 from sqlalchemy.orm import Session
 
+from airflow.api_fastapi.auth.managers.base_auth_manager import BaseAuthManager
+from airflow.providers.fab.auth_manager.fab_auth_manager import FabAuthManager
 from airflow.providers.fab.auth_manager.models import (
     Action,
     Group,
@@ -468,6 +471,25 @@ class TestFabAirflowSecurityManagerOverride:
         assert mock_merged_user._perms is None
         mock_session.commit.assert_called_once_with()
 
+    @mock.patch("airflow.providers.fab.www.utils.get_auth_manager", 
autospec=True)
+    @mock.patch.object(FabAuthManager, "cache", new_callable=lambda: 
TTLCache(maxsize=1, ttl=60))
+    @mock.patch.object(EmptySecurityManager, "session", new_callable=lambda: 
Mock(spec=Session))
+    def test_update_user_drops_cached_user_without_needing_fab_auth_manager(
+        self, mock_session, cache, mock_get_auth_manager
+    ):
+        """
+        ``update_user`` drops the user from ``FabAuthManager.cache`` even when 
the configured auth
+        manager is not a ``FabAuthManager``, instead of failing after the 
change is committed.
+        """
+        mock_get_auth_manager.return_value = Mock(spec=BaseAuthManager)
+        mock_session.get.return_value = None
+        user = Mock(spec=User, id=1, roles=[], groups=[])
+        cache[user.id] = Mock(spec=User)
+
+        assert EmptySecurityManager().update_user(user)
+
+        assert user.id not in cache
+
     @pytest.mark.parametrize(
         ("provider", "resp", "user_info"),
         [
diff --git a/providers/fab/tests/unit/fab/auth_manager/test_fab_auth_manager.py 
b/providers/fab/tests/unit/fab/auth_manager/test_fab_auth_manager.py
index 351acb9e269..020d12aa7c2 100644
--- a/providers/fab/tests/unit/fab/auth_manager/test_fab_auth_manager.py
+++ b/providers/fab/tests/unit/fab/auth_manager/test_fab_auth_manager.py
@@ -18,22 +18,25 @@ from __future__ import annotations
 
 import asyncio
 import time
-from contextlib import ExitStack, asynccontextmanager, contextmanager, suppress
-from itertools import chain
+from contextlib import ExitStack, asynccontextmanager, contextmanager, 
nullcontext, suppress
+from itertools import chain, count
 from typing import TYPE_CHECKING
 from unittest import mock
 from unittest.mock import MagicMock, Mock
 from urllib.parse import urlencode
 
 import pytest
+from cachetools import TTLCache
 from flask import g
 from flask_appbuilder.const import AUTH_DB, AUTH_LDAP, AUTH_OAUTH, 
AUTH_REMOTE_USER
+from pydantic import SecretStr
+from sqlalchemy import select, update
 from sqlalchemy.exc import OperationalError, PendingRollbackError
 from sqlalchemy.orm import Session
 
 from airflow import settings
 from airflow.api_fastapi.app import AUTH_MANAGER_FASTAPI_APP_PREFIX
-from airflow.api_fastapi.auth.managers.base_auth_manager import BaseAuthManager
+from airflow.api_fastapi.auth.managers.base_auth_manager import 
COOKIE_NAME_JWT_TOKEN, BaseAuthManager
 from airflow.api_fastapi.common.types import MenuItem
 from airflow.exceptions import AirflowConfigException, 
AirflowProviderDeprecationWarning
 from airflow.providers.fab.www.app import create_app
@@ -44,6 +47,7 @@ from airflow.utils.db import resetdb
 from tests_common.test_utils.asserts import assert_queries_count
 from tests_common.test_utils.config import conf_vars
 from unit.fab.auth_manager.test_utils import create_role, create_user, 
delete_role, delete_user
+from unit.fab.utils import client_with_login
 
 with suppress(ImportError):
     from airflow.api_fastapi.auth.managers.models.resource_details import (
@@ -57,7 +61,11 @@ from airflow.providers.common.compat.security.permissions 
import (
     RESOURCE_ASSET_ALIAS,
     RESOURCE_BACKFILL,
 )
+from airflow.providers.fab.auth_manager.api_fastapi.datamodels.roles import 
Role as RoleRef
+from airflow.providers.fab.auth_manager.api_fastapi.datamodels.users import 
UserPatchBody
+from airflow.providers.fab.auth_manager.api_fastapi.services.users import 
FABAuthManagerUsers
 from airflow.providers.fab.auth_manager.fab_auth_manager import 
DAG_BUNDLES_ACCESS_VIEW, FabAuthManager
+from airflow.providers.fab.auth_manager.models import User
 from airflow.providers.fab.auth_manager.security_manager.override import 
FabAirflowSecurityManagerOverride
 from airflow.providers.fab.www.security.permissions import (
     ACTION_CAN_ACCESS_MENU,
@@ -80,6 +88,7 @@ from airflow.providers.fab.www.security.permissions import (
     RESOURCE_VARIABLE,
     RESOURCE_WEBSITE,
 )
+from airflow.utils.session import create_session, create_session_async
 
 from tests_common.test_utils.dag import sync_dag_to_db
 from tests_common.test_utils.version_compat import AIRFLOW_V_3_1_PLUS
@@ -181,6 +190,64 @@ def auth_manager():
     return FabAuthManager(None)
 
 
+ISSUED_BEFORE_PASSWORD_CHANGE = "was issued before their last password change"
+
+
+def _set_stored_token_generation(user_id: int, token_generation: int) -> None:
+    """Write ``token_generation`` to the database only, leaving any cached 
``User`` as it is."""
+    with create_session() as session:
+        session.execute(update(User).where(User.id == 
user_id).values(token_generation=token_generation))
+
+
+def _get_stored_token_generation(user_id: int) -> int | None:
+    with create_session() as session:
+        return session.scalar(select(User.token_generation).where(User.id == 
user_id))
+
+
+# Reading a user runs two queries: the user row, then its roles 
(``lazy="selectin"``).
+QUERIES_PER_USER_READ = 2
+
+
+class _LockCheckingCache(TTLCache):
+    """A ``TTLCache`` that fails any read or write made without holding 
``FabAuthManager.cache_lock``."""
+
+    def __init__(self):
+        super().__init__(maxsize=1024, ttl=60)
+
+    def __getitem__(self, key):
+        assert FabAuthManager.cache_lock.locked()
+        return super().__getitem__(key)
+
+    def __setitem__(self, key, value):
+        assert FabAuthManager.cache_lock.locked()
+        super().__setitem__(key, value)
+
+    def __delitem__(self, key):
+        assert FabAuthManager.cache_lock.locked()
+        super().__delitem__(key)
+
+
+def _change_password(auth_manager: FabAuthManager, username: str) -> None:
+    FABAuthManagerUsers.update_user(
+        username, UserPatchBody(password=SecretStr("new-password")), 
update_mask="password"
+    )
+
+
+def _reset_password(auth_manager: FabAuthManager, username: str) -> None:
+    security_manager = auth_manager.security_manager
+    user = security_manager.find_user(username=username)
+    assert user is not None
+    assert security_manager.reset_password(user.id, "new-password")
+
+
+def _get_issued_api_token(response) -> str | None:
+    for cookie in response.headers.getlist("Set-Cookie"):
+        name, _, value = cookie.partition(";")[0].partition("=")
+        if name == COOKIE_NAME_JWT_TOKEN and value:
+            return value
+    return None
+
+
 @pytest.fixture
 def flask_app():
     with conf_vars(
@@ -201,6 +268,18 @@ def auth_manager_with_appbuilder(flask_app):
     return get_fab_auth_manager()
 
 
[email protected](params=["sync", "async"])
+def deserialize(request, auth_manager_with_appbuilder):
+    """Both ways a token becomes a user: older Airflow cores call the 
synchronous method."""
+    if request.param == "async":
+        return auth_manager_with_appbuilder.deserialize_user_async
+
+    async def deserialize_user(token):
+        return auth_manager_with_appbuilder.deserialize_user(token)
+
+    return deserialize_user
+
+
 @pytest.mark.db_test
 class TestFabAuthManager:
     @mock.patch("flask_login.utils._get_user")
@@ -262,9 +341,10 @@ class TestFabAuthManager:
         self, mock_create_session_async, auth_manager_with_appbuilder
     ):
         user_id = 99996
-        user = Mock(spec=["id", "is_active"])
+        user = Mock(spec=["id", "is_active", "token_generation"])
         user.id = user_id
         user.is_active = True
+        user.token_generation = 0
         query_result = Mock(spec=["one_or_none"])
         query_result.one_or_none.return_value = user
         query_started = asyncio.Event()
@@ -440,9 +520,11 @@ class TestFabAuthManager:
         assert user.get_id() == result.get_id()
 
     def test_serialize_user(self, flask_app, auth_manager_with_appbuilder):
-        user = create_user(flask_app, "test")
+        user_id = create_user(flask_app, "test").id
+        _set_stored_token_generation(user_id, 3)
+        user = 
auth_manager_with_appbuilder.security_manager.get_user_by_id(user_id)
         result = auth_manager_with_appbuilder.serialize_user(user)
-        assert result == {"sub": str(user.id)}
+        assert result == {"sub": str(user_id), "token_generation": 3}
 
     @mock.patch.object(FabAuthManager, "get_user")
     def test_is_logged_in(self, mock_get_user, auth_manager_with_appbuilder):
@@ -1396,6 +1478,321 @@ def test_resetdb(
         mock_init.assert_called_once()
 
 
[email protected]_test
+class TestTokenGeneration:
+    """
+    A token carries the ``token_generation`` its user had when it was issued, 
and is accepted only
+    while it still matches. Password changes and resets increment it.
+    """
+
+    # Issuing
+
+    @mock.patch.object(
+        FabAirflowSecurityManagerOverride,
+        "update_user_auth_stat",
+        autospec=True,
+        side_effect=FabAirflowSecurityManagerOverride.update_user_auth_stat,
+    )
+    def 
test_login_racing_password_change_issues_token_for_the_generation_it_read(
+        self, mock_update_user_auth_stat, flask_app, 
auth_manager_with_appbuilder
+    ):
+        """
+        A login that checked the old password issues a token for the 
generation it read, so a
+        password change committed before the token is issued still ends it.
+        """
+        user_id = create_user(flask_app, "test_login_race").id
+        security_manager = auth_manager_with_appbuilder.security_manager
+        record_login = mock_update_user_auth_stat.side_effect
+
+        def change_password_then_record_login(sm, user, success=True):
+            with settings.engine.begin() as connection:
+                connection.execute(
+                    update(User).where(User.id == 
user_id).values(token_generation=User.token_generation + 1)
+                )
+            record_login(sm, user, success)
+
+        mock_update_user_auth_stat.side_effect = 
change_password_then_record_login
+        user = security_manager.auth_user_db("test_login_race", 
"test_login_race", rotate_session_id=False)
+        token = auth_manager_with_appbuilder.serialize_user(user)
+        auth_manager_with_appbuilder.cache.clear()
+
+        assert _get_stored_token_generation(user_id) == 1
+        with pytest.raises(ValueError, match=ISSUED_BEFORE_PASSWORD_CHANGE):
+            auth_manager_with_appbuilder.deserialize_user(token)
+
+    def test_concurrent_password_updates_both_increment_token_generation(
+        self, flask_app, auth_manager_with_appbuilder
+    ):
+        """
+        Two password changes made on copies of the user loaded before either 
commits both count.
+
+        Otherwise the second change would write the value the first one did, 
and a token issued
+        between the two changes would survive the second.
+        """
+        user_id = create_user(flask_app, "test_concurrent_password_updates").id
+        security_manager = auth_manager_with_appbuilder.security_manager
+
+        with Session(settings.engine) as first, Session(settings.engine) as 
second:
+            first_copy, second_copy = first.get(User, user_id), 
second.get(User, user_id)
+            security_manager.set_user_password(first_copy, "first-password")
+            security_manager.set_user_password(second_copy, "second-password")
+            first.commit()
+            second.commit()
+
+        assert _get_stored_token_generation(user_id) == 2
+
+    # Checking, on both the synchronous and the asynchronous path
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize(
+        ("cached", "stored", "token_generation", "accepted", "user_reads"),
+        [
+            pytest.param(1, 1, 1, True, 0, id="same-as-cached-user"),
+            pytest.param(1, 1, 0, False, 0, id="older-than-cached-user"),
+            pytest.param(1, 2, 2, True, 1, id="newer-than-cached-user"),
+            pytest.param(1, 1, 2, False, 1, id="newer-than-stored-user"),
+            pytest.param(0, 0, None, True, 0, 
id="no-claim-before-any-password-change"),
+            pytest.param(1, 1, None, False, 0, 
id="no-claim-after-a-password-change"),
+        ],
+    )
+    async def test_compares_token_generation(
+        self,
+        flask_app,
+        auth_manager_with_appbuilder,
+        deserialize,
+        cached,
+        stored,
+        token_generation,
+        accepted,
+        user_reads,
+    ):
+        """
+        Tokens are compared with the cached user, which is re-read only when 
the token is newer.
+
+        ``cached`` and ``stored`` are the user's ``token_generation`` in the 
cache and in the
+        database. A token without the claim was issued before it existed and 
counts as 0.
+        """
+        user_id = create_user(flask_app, "test_token_generation").id
+        _set_stored_token_generation(user_id, cached)
+        auth_manager_with_appbuilder.cache.clear()
+        await deserialize({"sub": str(user_id), "token_generation": cached})
+        _set_stored_token_generation(user_id, stored)
+        token = {"sub": str(user_id)}
+        if token_generation is not None:
+            token["token_generation"] = token_generation
+
+        outcome = (
+            nullcontext() if accepted else pytest.raises(ValueError, 
match=ISSUED_BEFORE_PASSWORD_CHANGE)
+        )
+        with assert_queries_count(user_reads * QUERIES_PER_USER_READ), outcome:
+            assert (await deserialize(token)).id == user_id
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize("token_generation", ["0", 0.0, True, None], 
ids=["str", "float", "bool", "null"])
+    async def test_rejects_non_integer_token_generation(self, flask_app, 
deserialize, token_generation):
+        """A claim that is not an integer fails as an invalid token rather 
than a server error."""
+        user_id = create_user(flask_app, "test_invalid_token_generation").id
+
+        with pytest.raises(ValueError, match="has an invalid token_generation 
claim"):
+            await deserialize({"sub": str(user_id), "token_generation": 
token_generation})
+
+    @pytest.mark.asyncio
+    async def 
test_token_issued_after_password_change_ends_earlier_tokens_at_once(
+        self, flask_app, auth_manager_with_appbuilder, deserialize
+    ):
+        """
+        A token issued after a password change works right away, even where 
the cached user predates
+        the change, and from then on earlier tokens fail without waiting for 
the cache to expire.
+
+        The change is written to the database only: a change made by another 
process, such as the
+        CLI or another API server, leaves this process's cache as it was.
+        """
+        user_id = create_user(flask_app, "test_stale_cache").id
+        old_token = {"sub": str(user_id), "token_generation": 0}
+        new_token = {"sub": str(user_id), "token_generation": 1}
+        auth_manager_with_appbuilder.cache.clear()
+        await deserialize(old_token)
+        _set_stored_token_generation(user_id, 1)
+
+        with assert_queries_count(QUERIES_PER_USER_READ):
+            assert (await deserialize(new_token)).id == user_id
+            with pytest.raises(ValueError, 
match=ISSUED_BEFORE_PASSWORD_CHANGE):
+                await deserialize(old_token)
+
+    @pytest.mark.asyncio
+    async def test_failed_reload_does_not_keep_outdated_cached_user(
+        self, flask_app, auth_manager_with_appbuilder, deserialize
+    ):
+        """
+        When re-reading the user for a newer token fails, the outdated cached 
user is dropped too.
+
+        Here the user was deactivated after a password change made by another 
process, so earlier
+        tokens must fail as well instead of matching the user cached before 
the change.
+        """
+        user_id = create_user(flask_app, "test_failed_reload").id
+        old_token = {"sub": str(user_id), "token_generation": 0}
+        auth_manager_with_appbuilder.cache.clear()
+        await deserialize(old_token)
+        with create_session() as session:
+            session.execute(update(User).where(User.id == 
user_id).values(token_generation=1, active=False))
+
+        with pytest.raises(ValueError, match="is not active"):
+            await deserialize({"sub": str(user_id), "token_generation": 1})
+        with pytest.raises(ValueError, match="is not active"):
+            await deserialize(old_token)
+
+    @mock.patch.object(
+        FabAuthManager,
+        "cache",
+        new_callable=lambda: TTLCache(maxsize=1024, ttl=10, 
timer=count(step=6).__next__),
+    )
+    @pytest.mark.asyncio
+    async def 
test_newer_token_accepted_when_cached_user_expires_as_it_is_dropped(
+        self, _, flask_app, deserialize
+    ):
+        """
+        A cached user that expires between being read and being dropped as 
outdated does not turn a
+        newer token into a failure.
+
+        Every read of the cache's clock moves it forward by more than half the 
TTL, so the cached
+        user is still valid when it is read and has expired by the time it is 
dropped.
+        """
+        user_id = create_user(flask_app, "test_expiring_cached_user").id
+        await deserialize({"sub": str(user_id), "token_generation": 0})
+        _set_stored_token_generation(user_id, 1)
+
+        user = await deserialize({"sub": str(user_id), "token_generation": 1})
+
+        assert user.token_generation == 1
+
+    # The user cache: updates made by this process, and concurrent requests
+
+    @pytest.mark.asyncio
+    @pytest.mark.parametrize(
+        "update_password",
+        [pytest.param(_change_password, id="change"), 
pytest.param(_reset_password, id="reset")],
+    )
+    async def test_password_update_ends_earlier_tokens_at_once(
+        self, flask_app, auth_manager_with_appbuilder, update_password
+    ):
+        """After a password change or reset, earlier tokens fail at once on 
the API server that made it."""
+        user = create_user(flask_app, "test_password_update")
+        old_token = auth_manager_with_appbuilder.serialize_user(user)
+        auth_manager_with_appbuilder.cache.clear()
+        await auth_manager_with_appbuilder.deserialize_user_async(old_token)
+
+        update_password(auth_manager_with_appbuilder, "test_password_update")
+
+        with pytest.raises(ValueError, match=ISSUED_BEFORE_PASSWORD_CHANGE):
+            await 
auth_manager_with_appbuilder.deserialize_user_async(old_token)
+
+    @pytest.mark.asyncio
+    async def test_role_update_applies_at_once(self, flask_app, 
auth_manager_with_appbuilder):
+        """Roles changed through the users API apply to the next request, not 
after the cache expires."""
+        user = create_user(flask_app, "test_role_update", 
role_name="test_role_update_before")
+        create_role(flask_app, "test_role_update_after")
+        token = auth_manager_with_appbuilder.serialize_user(user)
+        auth_manager_with_appbuilder.cache.clear()
+        await auth_manager_with_appbuilder.deserialize_user_async(token)
+
+        FABAuthManagerUsers.update_user(
+            "test_role_update",
+            UserPatchBody(roles=[RoleRef(name="test_role_update_after")]),
+            update_mask="roles",
+        )
+
+        roles = (await 
auth_manager_with_appbuilder.deserialize_user_async(token)).roles
+        assert [role.name for role in roles] == ["test_role_update_after"]
+
+    @mock.patch.object(FabAuthManager, "cache", 
new_callable=_LockCheckingCache)
+    @pytest.mark.asyncio
+    async def test_cache_is_accessed_only_under_cache_lock(
+        self, cache, flask_app, auth_manager_with_appbuilder
+    ):
+        """
+        Every read and write of the user cache holds ``cache_lock``: caching a 
user on either path,
+        dropping it for a newer token, and dropping it after a user update.
+        """
+        user_id = create_user(flask_app, "test_cache_lock").id
+
+        auth_manager_with_appbuilder.deserialize_user({"sub": str(user_id), 
"token_generation": 0})
+        _set_stored_token_generation(user_id, 1)
+        await auth_manager_with_appbuilder.deserialize_user_async(
+            {"sub": str(user_id), "token_generation": 1}
+        )
+        assert user_id in cache
+        _change_password(auth_manager_with_appbuilder, "test_cache_lock")
+
+        assert user_id not in cache
+
+    
@mock.patch("airflow.providers.fab.auth_manager.fab_auth_manager.create_session_async",
 autospec=True)
+    @pytest.mark.asyncio
+    async def test_newer_token_waiting_for_outdated_load_reloads(
+        self, mock_create_session_async, flask_app, 
auth_manager_with_appbuilder
+    ):
+        """
+        A token that waits for another request to load its user does not take 
what that load cached
+        when the load read the user from before a password change the token 
was issued after.
+        """
+        user_id = create_user(flask_app, "test_outdated_load").id
+        auth_manager_with_appbuilder.cache.clear()
+        first_load_read = asyncio.Event()
+        release_first_load = asyncio.Event()
+
+        @asynccontextmanager
+        async def create_session_then_hold_first_load():
+            async with create_session_async() as session:
+                yield session
+            if not first_load_read.is_set():
+                first_load_read.set()
+                await release_first_load.wait()
+
+        mock_create_session_async.side_effect = 
create_session_then_hold_first_load
+        old_request = asyncio.create_task(
+            auth_manager_with_appbuilder.deserialize_user_async({"sub": 
str(user_id), "token_generation": 0})
+        )
+        await first_load_read.wait()
+        _set_stored_token_generation(user_id, 1)
+        new_request = asyncio.create_task(
+            auth_manager_with_appbuilder.deserialize_user_async({"sub": 
str(user_id), "token_generation": 1})
+        )
+        # Lets the new request run until it waits for the old request's load.
+        await asyncio.sleep(0)
+        release_first_load.set()
+        old_user, new_user = await asyncio.gather(old_request, new_request)
+
+        assert (old_user.token_generation, new_user.token_generation) == (0, 1)
+
+    # Flask sessions
+
+    @conf_vars(
+        {
+            ("core", "auth_manager"): 
"airflow.providers.fab.auth_manager.fab_auth_manager.FabAuthManager",
+            ("fab", "session_backend"): "securecookie",
+        }
+    )
+    def 
test_session_from_before_password_reset_no_longer_issues_api_tokens(self):
+        """
+        The login page issues API tokens from a Flask session only while the 
session matches the
+        user's ``token_generation``, so a ``securecookie`` session cannot 
outlive a password reset.
+        """
+        app = create_app(enable_plugins=False)
+        app.config["WTF_CSRF_ENABLED"] = False
+        # Requests run outside this test's app context: a request reuses an 
active app context,
+        # and with it the user Flask-Login cached in ``g`` by an earlier 
request.
+        with app.app_context():
+            user_id = create_user(app, "test_session_reset").id
+        old_session = client_with_login(app, username="test_session_reset", 
password="test_session_reset")
+        assert _get_issued_api_token(old_session.get("/login/"))
+
+        with app.app_context():
+            assert app.appbuilder.sm.reset_password(user_id, "new-password")
+
+        assert _get_issued_api_token(old_session.get("/login/")) is None
+        new_session = client_with_login(app, username="test_session_reset", 
password="new-password")
+        assert _get_issued_api_token(new_session.get("/login/"))
+
+
 @pytest.mark.db_test
 @pytest.mark.skipif(
     not AIRFLOW_V_3_1_PLUS,
@@ -1493,6 +1890,7 @@ class TestDeserializeUserSessionCleanup:
         """A transient DB disconnect is recovered by removing session and 
retrying once."""
         user = Mock()
         user.id = 99996
+        user.token_generation = 0
         original_exc = OperationalError("connection dropped", None, 
Exception())
         retry_query_result = Mock()
         retry_query_result.one_or_none.return_value = user
diff --git a/providers/fab/tests/unit/fab/www/extensions/test_init_session.py 
b/providers/fab/tests/unit/fab/www/extensions/test_init_session.py
index 0390bd04fcd..2c070bdd913 100644
--- a/providers/fab/tests/unit/fab/www/extensions/test_init_session.py
+++ b/providers/fab/tests/unit/fab/www/extensions/test_init_session.py
@@ -29,8 +29,10 @@ from flask_login import LoginManager, current_user, 
login_user
 
 from airflow.providers.fab.www.extensions.init_session import (
     SESSION_LOGIN_TIME_KEY,
+    SESSION_TOKEN_GENERATION_KEY,
     get_remaining_session_lifetime,
     init_session_max_lifetime,
+    init_session_token_generation,
 )
 
 from tests_common.test_utils.config import conf_vars
@@ -43,6 +45,9 @@ class FakeUser:
     is_active = True
     is_anonymous = False
 
+    def __init__(self, token_generation: int = 0):
+        self.token_generation = token_generation
+
     def get_id(self):
         return "1"
 
@@ -73,6 +78,29 @@ def build_client(max_lifetime_minutes: int, 
remember_cookie_name: str | None = N
         yield app.test_client()
 
 
+@contextmanager
+def build_token_generation_client(user: FakeUser):
+    """Yield a test client for an app that ends sessions created before a 
password change."""
+    app = Flask(__name__)
+    app.secret_key = "test-secret-key"
+
+    login_manager = LoginManager(app)
+    login_manager.session_protection = None
+    login_manager.user_loader(lambda user_id: user if user_id == "1" else None)
+
+    @app.route("/login")
+    def login():
+        login_user(user)
+        return ""
+
+    @app.route("/whoami")
+    def whoami():
+        return "authenticated" if current_user.is_authenticated else 
"anonymous"
+
+    init_session_token_generation(app)
+    yield app.test_client()
+
+
 def get_body(response) -> str:
     return response.get_data(as_text=True)
 
@@ -155,3 +183,41 @@ def 
test_remaining_session_lifetime_is_unknown_without_a_login_stamp():
 
     with conf_vars({("fab", "session_max_lifetime_minutes"): "30"}), 
app.test_request_context():
         assert get_remaining_session_lifetime() is None
+
+
+def test_login_records_token_generation_only_on_the_fab_app():
+    """
+    A login on the FAB app records the user's ``token_generation`` in its 
session, while a login
+    on another Flask app in the same process leaves that app's session alone.
+    """
+    user = FakeUser(token_generation=3)
+    other_app = Flask(__name__)
+    other_app.secret_key = "test-secret-key"
+    LoginManager(other_app)
+
+    with build_token_generation_client(user) as client:
+        client.get("/login")
+        with client.session_transaction() as flask_session:
+            assert flask_session[SESSION_TOKEN_GENERATION_KEY] == 3
+        with other_app.test_request_context():
+            assert login_user(user)
+            assert SESSION_TOKEN_GENERATION_KEY not in builtin_flask_session
+
+
[email protected](("password_changes", "expected"), [(0, 
"authenticated"), (1, "anonymous")])
+def test_session_ends_once_its_user_changes_password(password_changes, 
expected):
+    user = FakeUser(token_generation=3)
+    with build_token_generation_client(user) as client:
+        client.get("/login")
+        assert get_body(client.get("/whoami")) == "authenticated"
+        user.token_generation += password_changes
+        assert get_body(client.get("/whoami")) == expected
+
+
[email protected](("token_generation", "expected"), [(0, 
"authenticated"), (1, "anonymous")])
+def 
test_session_predating_the_key_counts_as_the_initial_generation(token_generation,
 expected):
+    with 
build_token_generation_client(FakeUser(token_generation=token_generation)) as 
client:
+        with client.session_transaction() as flask_session:
+            flask_session["_user_id"] = "1"
+
+        assert get_body(client.get("/whoami")) == expected
diff --git a/providers/fab/tests/unit/fab/www/test_app.py 
b/providers/fab/tests/unit/fab/www/test_app.py
index 6ee442c3d84..d1ba700caac 100644
--- a/providers/fab/tests/unit/fab/www/test_app.py
+++ b/providers/fab/tests/unit/fab/www/test_app.py
@@ -16,13 +16,19 @@
 # under the License.
 from __future__ import annotations
 
+from unittest import mock
+
 import pytest
 
 from airflow import settings
+from airflow.api_fastapi.auth.managers.base_auth_manager import BaseAuthManager
+from airflow.providers.fab.auth_manager.fab_auth_manager import FabAuthManager
 from airflow.providers.fab.www.app import create_app
 
 from tests_common.test_utils.config import conf_vars
 
+FAB_AUTH_MANAGER = 
"airflow.providers.fab.auth_manager.fab_auth_manager.FabAuthManager"
+
 
 @pytest.mark.db_test
 class TestCreateApp:
@@ -36,3 +42,31 @@ class TestCreateApp:
         with flask_app.app_context():
             db = flask_app.extensions["sqlalchemy"]
             assert db.engine is settings.engine
+
+    @pytest.mark.parametrize(
+        ("auth_manager_cls", "enable_plugins", "called"),
+        [
+            pytest.param(FabAuthManager, False, True, id="fab-app"),
+            pytest.param(FabAuthManager, True, True, id="plugins-app"),
+            pytest.param(BaseAuthManager, True, False, 
id="plugins-app-without-fab-auth-manager"),
+        ],
+    )
+    @conf_vars({("core", "auth_manager"): FAB_AUTH_MANAGER})
+    @mock.patch("airflow.providers.fab.www.app.init_session_token_generation", 
autospec=True)
+    @mock.patch("airflow.providers.fab.www.app.get_auth_manager", 
autospec=True)
+    def test_sessions_checked_wherever_fab_login_sessions_are_read(
+        self,
+        mock_get_auth_manager,
+        mock_init_session_token_generation,
+        auth_manager_cls,
+        enable_plugins,
+        called,
+    ):
+        """The plugins app reads the FAB login session too, with the 
``securecookie`` backend."""
+        mock_get_auth_manager.return_value = mock.Mock(spec=auth_manager_cls)
+        flask_app = create_app(enable_plugins=enable_plugins)
+
+        if called:
+            
mock_init_session_token_generation.assert_called_once_with(flask_app)
+        else:
+            mock_init_session_token_generation.assert_not_called()
diff --git 
a/providers/fab/tests/unit/fab/www/views/test_views_custom_user_views.py 
b/providers/fab/tests/unit/fab/www/views/test_views_custom_user_views.py
index 08709a87fdc..f582b733680 100644
--- a/providers/fab/tests/unit/fab/www/views/test_views_custom_user_views.py
+++ b/providers/fab/tests/unit/fab/www/views/test_views_custom_user_views.py
@@ -25,6 +25,7 @@ from flask.sessions import SecureCookieSessionInterface
 from sqlalchemy import delete, func, select
 
 from airflow.api_fastapi.app import get_auth_manager
+from airflow.providers.fab.auth_manager.security_manager.override import 
FabAirflowSecurityManagerOverride
 from airflow.providers.fab.www import app as application
 from airflow.providers.fab.www.security import permissions
 
@@ -431,19 +432,13 @@ class TestResetUserSessions:
         assert self.get_session_by_id("session_id_1") is not None
         assert self.get_session_by_id("session_id_2") is not None
 
-    
@mock.patch("airflow.providers.fab.auth_manager.security_manager.override.flash")
-    @mock.patch(
-        
"airflow.providers.fab.auth_manager.security_manager.override.has_request_context",
 return_value=True
-    )
-    def test_warn_securecookie(self, _mock_has_context, flash_mock):
+    @mock.patch.object(FabAirflowSecurityManagerOverride, "_cli_safe_flash", 
autospec=True)
+    def test_no_warning_with_securecookie(self, cli_safe_flash):
+        """Sessions from before the reset end on their next request, whatever 
the session backend."""
         self.app.session_interface = SecureCookieSessionInterface()
         with self.app.app_context():
-            self.security_manager.reset_password(self.user_1.id, 
"new_password")
-        assert flash_mock.called
-        assert (
-            "Since you are using `securecookie` session backend mechanism, we 
cannot"
-            in flash_mock.call_args[0][0]
-        )
+            assert self.security_manager.reset_password(self.user_1.id, 
"new_password")
+        cli_safe_flash.assert_not_called()
 
     
@mock.patch("airflow.providers.fab.auth_manager.security_manager.override.log")
     @mock.patch(
@@ -467,14 +462,3 @@ class TestResetUserSessions:
         assert 
self.session.scalar(select(func.count()).select_from(self.model)) == 2
         assert self.get_session_by_id("session_id_1") is not None
         assert self.get_session_by_id("session_id_2") is not None
-
-    
@mock.patch("airflow.providers.fab.auth_manager.security_manager.override.log")
-    def test_warn_securecookie_cli(self, log_mock):
-        self.app.session_interface = SecureCookieSessionInterface()
-        with self.app.app_context():
-            self.security_manager.reset_password(self.user_1.id, 
"new_password")
-        assert log_mock.warning.called
-        assert (
-            "Since you are using `securecookie` session backend mechanism, we 
cannot"
-            in log_mock.warning.call_args[0][0]
-        )

Reply via email to