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 d485b9d84fb End the FAB auth manager session on logout (#77619)
d485b9d84fb is described below

commit d485b9d84fb969f7b181461b81bc695b95dbbd5a
Author: Kevin Yang <[email protected]>
AuthorDate: Mon Nov 30 13:00:24 2026 -0500

    End the FAB auth manager session on logout (#77619)
    
    Logging out from the UI cleared the browser's cookies but did not end
    the Flask session of the FAB auth manager. Logout now goes through
    Flask-AppBuilder's own logout view, so the session ends with it.
    
    ---------
    
    Co-authored-by: Vincent <[email protected]>
---
 .../openapi/v2-fab-auth-manager-generated.yaml     |  3 +-
 .../fab/auth_manager/api_fastapi/routes/login.py   | 35 ++++++------
 .../fab/auth_manager/security_manager/override.py  |  9 ++-
 .../providers/fab/auth_manager/views/auth_login.py | 30 ++++++++--
 .../providers/fab/auth_manager/views/auth_oauth.py |  7 ++-
 .../auth_manager/api_fastapi/routes/test_login.py  | 64 ++++++++++++++++++----
 .../unit/fab/auth_manager/views/test_auth_login.py | 38 ++++++++++++-
 7 files changed, 144 insertions(+), 42 deletions(-)

diff --git 
a/providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/openapi/v2-fab-auth-manager-generated.yaml
 
b/providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/openapi/v2-fab-auth-manager-generated.yaml
index faf2688e66f..33dd2e19652 100644
--- 
a/providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/openapi/v2-fab-auth-manager-generated.yaml
+++ 
b/providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/openapi/v2-fab-auth-manager-generated.yaml
@@ -91,7 +91,8 @@ paths:
       tags:
       - FabAuthManager
       summary: Logout
-      description: Clear session cookies and redirect to the login page.
+      description: Clear the API token cookie and redirect to the Flask logout 
view,
+        which ends the session.
       operationId: logout
       responses:
         '307':
diff --git 
a/providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/routes/login.py
 
b/providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/routes/login.py
index 88fc531da6f..e936037684c 100644
--- 
a/providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/routes/login.py
+++ 
b/providers/fab/src/airflow/providers/fab/auth_manager/api_fastapi/routes/login.py
@@ -32,6 +32,7 @@ from 
airflow.providers.fab.auth_manager.api_fastapi.datamodels.login import Logi
 from airflow.providers.fab.auth_manager.api_fastapi.routes.router import 
auth_router
 from airflow.providers.fab.auth_manager.api_fastapi.services.login import 
FABAuthManagerLogin
 from airflow.providers.fab.version_compat import AIRFLOW_V_3_1_8_PLUS
+from airflow.providers.fab.www.utils import get_fab_auth_manager
 
 if AIRFLOW_V_3_1_8_PLUS:
     from airflow.api_fastapi.app import get_cookie_path
@@ -129,22 +130,18 @@ def create_token_cli(request: Request, body: dict[str, 
Any] = Body(...)) -> Logi
     status_code=status.HTTP_307_TEMPORARY_REDIRECT,
 )
 def logout(request: Request) -> RedirectResponse:
-    """Clear session cookies and redirect to the login page."""
-    with _get_flask_app().app_context(), _release_scoped_session():
-        login_url = get_auth_manager().get_url_login()
-        secure = request.base_url.scheme == "https" or bool(conf.get("api", 
"ssl_cert", fallback=""))
-        cookie_path = get_cookie_path()
-        response = RedirectResponse(login_url)
-        response.delete_cookie(
-            key="session",
-            path=cookie_path,
-            secure=secure,
-            httponly=True,
-        )
-        response.delete_cookie(
-            key=COOKIE_NAME_JWT_TOKEN,
-            path=cookie_path,
-            secure=secure,
-            httponly=True,
-        )
-        return response
+    """Clear the API token cookie and redirect to the Flask logout view, which 
ends the session."""
+    # The trailing slash routes to the Flask app's own logout view. The 
``session`` cookie is
+    # left in place so that the browser sends it there and the Flask session 
it points at is
+    # signed out.
+    flask_logout_url = f"{get_fab_auth_manager().get_url_logout()}/"
+    secure = request.base_url.scheme == "https" or bool(conf.get("api", 
"ssl_cert", fallback=""))
+    cookie_path = get_cookie_path()
+    response = RedirectResponse(flask_logout_url)
+    response.delete_cookie(
+        key=COOKIE_NAME_JWT_TOKEN,
+        path=cookie_path,
+        secure=secure,
+        httponly=True,
+    )
+    return response
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 3a00754b6c7..01d737ac61a 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
@@ -53,7 +53,6 @@ from flask_appbuilder.security.registerviews import (
     RegisterUserOAuthView,
 )
 from flask_appbuilder.security.views import (
-    AuthRemoteUserView,
     AuthView,
     RegisterUserModelView,
     UserGroupModelView,
@@ -86,7 +85,11 @@ from airflow.providers.fab.auth_manager.models import (
 from airflow.providers.fab.auth_manager.models.anonymous_user import 
AnonymousUser
 from airflow.providers.fab.auth_manager.security_manager.constants import 
EXISTING_ROLES
 from airflow.providers.fab.auth_manager.security_manager.passwords import 
is_empty_password
-from airflow.providers.fab.auth_manager.views.auth_login import 
CustomAuthDBView, CustomAuthLDAPView
+from airflow.providers.fab.auth_manager.views.auth_login import (
+    CustomAuthDBView,
+    CustomAuthLDAPView,
+    CustomAuthRemoteUserView,
+)
 from airflow.providers.fab.auth_manager.views.auth_oauth import 
CustomAuthOAuthView
 from airflow.providers.fab.auth_manager.views.permissions import (
     ActionModelView,
@@ -219,7 +222,7 @@ class 
FabAirflowSecurityManagerOverride(AirflowSecurityManagerV2):
     """ Override if you want your own Authentication LDAP view """
     authoauthview = CustomAuthOAuthView
     """ Custom Authentication OAuth view with session commit fix for #57981 """
-    authremoteuserview = AuthRemoteUserView
+    authremoteuserview = CustomAuthRemoteUserView
     """ Override if you want your own Authentication REMOTE_USER view """
     registeruserdbview = RegisterUserDBView
     """ Override if you want your own register user db view """
diff --git 
a/providers/fab/src/airflow/providers/fab/auth_manager/views/auth_login.py 
b/providers/fab/src/airflow/providers/fab/auth_manager/views/auth_login.py
index 9dc2bba91cf..078536f83e5 100644
--- a/providers/fab/src/airflow/providers/fab/auth_manager/views/auth_login.py
+++ b/providers/fab/src/airflow/providers/fab/auth_manager/views/auth_login.py
@@ -14,16 +14,16 @@
 # KIND, either express or implied.  See the License for the
 # specific language governing permissions and limitations
 # under the License.
-"""Login views that honor ``next`` when the user is already authenticated."""
+"""Authentication views that honor ``next`` on login and end the Flask session 
on logout."""
 
 from __future__ import annotations
 
 from typing import TYPE_CHECKING
 
-from flask import g, request
+from flask import current_app, g, redirect as flask_redirect, request, session
 from flask_appbuilder import expose
 from flask_appbuilder.security.decorators import no_cache
-from flask_appbuilder.security.views import AuthDBView, AuthLDAPView
+from flask_appbuilder.security.views import AuthDBView, AuthLDAPView, 
AuthRemoteUserView, AuthView
 
 from airflow.providers.fab.www.views import get_safe_url, redirect
 
@@ -45,7 +45,23 @@ def redirect_if_authenticated() -> Response | None:
     return None
 
 
-class CustomAuthDBView(AuthDBView):
+class EndSessionOnLogoutMixin(AuthView):
+    """
+    End the whole Flask session on logout and redirect to the login page.
+
+    ``LOGOUT_REDIRECT_URL`` takes precedence over the login page when it is 
set.
+    """
+
+    @expose("/logout/")
+    def logout(self):
+        super().logout()
+        session.clear()
+        return flask_redirect(
+            current_app.config.get("LOGOUT_REDIRECT_URL", 
self.appbuilder.get_url_for_login)
+        )
+
+
+class CustomAuthDBView(EndSessionOnLogoutMixin, AuthDBView):
     """Database login view that honors ``next`` for already-authenticated 
users."""
 
     @expose("/login/", methods=["GET", "POST"])
@@ -56,7 +72,7 @@ class CustomAuthDBView(AuthDBView):
         return super().login()
 
 
-class CustomAuthLDAPView(AuthLDAPView):
+class CustomAuthLDAPView(EndSessionOnLogoutMixin, AuthLDAPView):
     """LDAP login view that honors ``next`` for already-authenticated users."""
 
     @expose("/login/", methods=["GET", "POST"])
@@ -65,3 +81,7 @@ class CustomAuthLDAPView(AuthLDAPView):
         if (response := redirect_if_authenticated()) is not None:
             return response
         return super().login()
+
+
+class CustomAuthRemoteUserView(EndSessionOnLogoutMixin, AuthRemoteUserView):
+    """Remote user authentication view that ends the Flask session on 
logout."""
diff --git 
a/providers/fab/src/airflow/providers/fab/auth_manager/views/auth_oauth.py 
b/providers/fab/src/airflow/providers/fab/auth_manager/views/auth_oauth.py
index e9140152ff8..f26abbb4c46 100644
--- a/providers/fab/src/airflow/providers/fab/auth_manager/views/auth_oauth.py
+++ b/providers/fab/src/airflow/providers/fab/auth_manager/views/auth_oauth.py
@@ -26,12 +26,15 @@ from flask_appbuilder import expose
 from flask_appbuilder.security.views import AuthOAuthView
 
 from airflow.providers.common.compat.sdk import conf
-from airflow.providers.fab.auth_manager.views.auth_login import 
redirect_if_authenticated
+from airflow.providers.fab.auth_manager.views.auth_login import (
+    EndSessionOnLogoutMixin,
+    redirect_if_authenticated,
+)
 
 log = logging.getLogger(__name__)
 
 
-class CustomAuthOAuthView(AuthOAuthView):
+class CustomAuthOAuthView(EndSessionOnLogoutMixin, AuthOAuthView):
     """
     Custom OAuth authentication view that ensures session is committed before 
redirect.
 
diff --git 
a/providers/fab/tests/unit/fab/auth_manager/api_fastapi/routes/test_login.py 
b/providers/fab/tests/unit/fab/auth_manager/api_fastapi/routes/test_login.py
index 6ed9691300a..3a04eb68307 100644
--- a/providers/fab/tests/unit/fab/auth_manager/api_fastapi/routes/test_login.py
+++ b/providers/fab/tests/unit/fab/auth_manager/api_fastapi/routes/test_login.py
@@ -20,10 +20,15 @@ from __future__ import annotations
 from unittest.mock import patch
 
 import pytest
+from flask import session
+from flask_login import login_user
+from sqlalchemy import select
 
 from airflow.api_fastapi.auth.managers.base_auth_manager import 
COOKIE_NAME_JWT_TOKEN
 from airflow.providers.fab.auth_manager.api_fastapi.datamodels.login import 
LoginResponse
 
+from unit.fab.auth_manager.test_utils import create_user, delete_user
+
 SUBPATH = "/team-a/"
 
 
@@ -58,27 +63,66 @@ class TestLogin:
         assert response.status_code == 201
         assert response.json()["access_token"] == self.dummy_token.access_token
 
-    
@patch("airflow.providers.fab.auth_manager.api_fastapi.routes.login._get_flask_app")
-    def test_logout(self, mock_get_flask_app, test_client):
-        
mock_get_flask_app.return_value.app_context.return_value.__enter__.return_value 
= None
+    
@patch("airflow.providers.fab.auth_manager.api_fastapi.routes.login.get_fab_auth_manager",
 autospec=True)
+    def test_logout(self, mock_get_fab_auth_manager, test_client):
+        mock_get_fab_auth_manager.return_value.get_url_logout.return_value = 
"/auth/logout"
         response = test_client.get("/logout", follow_redirects=False)
         assert response.status_code == 307
-        assert response.headers["location"] == "/auth/login"
+        assert response.headers["location"] == "/auth/logout/"
         cookies = response.headers.get_list("set-cookie")
-        assert any("session=" in c for c in cookies)
+        assert not any(c.startswith("session=") for c in cookies)
         assert any(f"{COOKIE_NAME_JWT_TOKEN}=" in c for c in cookies)
 
-    
@patch("airflow.providers.fab.auth_manager.api_fastapi.routes.login._get_flask_app")
+    
@patch("airflow.providers.fab.auth_manager.api_fastapi.routes.login.get_fab_auth_manager",
 autospec=True)
     @patch(
         
"airflow.providers.fab.auth_manager.api_fastapi.routes.login.get_cookie_path", 
return_value=SUBPATH
     )
-    def test_logout_cookie_uses_subpath(self, mock_cookie_path, 
mock_get_flask_app, test_client):
+    def test_logout_cookie_uses_subpath(self, mock_cookie_path, 
mock_get_fab_auth_manager, test_client):
         """Cookies on logout must be scoped to the configured subpath."""
-        
mock_get_flask_app.return_value.app_context.return_value.__enter__.return_value 
= None
+        mock_get_fab_auth_manager.return_value.get_url_logout.return_value = 
"/auth/logout"
         response = test_client.get("/logout", follow_redirects=False)
         assert response.status_code == 307
         cookies = response.headers.get_list("set-cookie")
-        session_cookie = next(c for c in cookies if "session=" in c)
         token_cookie = next(c for c in cookies if f"{COOKIE_NAME_JWT_TOKEN}=" 
in c)
-        assert f"Path={SUBPATH}" in session_cookie
         assert f"Path={SUBPATH}" in token_cookie
+
+    def test_logout_ends_the_flask_session(self, real_app_client):
+        """Following the logout redirects deletes the Flask session and lands 
on the login page."""
+        auth_manager, client = real_app_client
+        flask_app = auth_manager.flask_app
+        with flask_app.app_context():
+            user = create_user(flask_app, "test_logout_user", 
role_name="test_logout_role")
+        try:
+            with flask_app.test_request_context():
+                login_user(user)
+                session_id = session.sid
+                login_response = 
flask_app.process_response(flask_app.response_class())
+            session_cookie = login_response.headers["Set-Cookie"].split(";")[0]
+
+            def get(path):
+                # Send only the session cookie, as the browser does after the 
token cookie is deleted.
+                client.cookies.clear()
+                return client.get(path, headers={"Cookie": session_cookie}, 
follow_redirects=False)
+
+            assert get("/login/").cookies.get(COOKIE_NAME_JWT_TOKEN)
+
+            flask_logout_url = get("/logout").headers["location"]
+            response = get(flask_logout_url.removeprefix("/auth"))
+
+            assert response.is_redirect
+            assert response.headers["location"].endswith("/login/")
+            session_cookies = [c for c in 
response.headers.get_list("set-cookie") if c.startswith("session=")]
+            assert len(session_cookies) == 1
+            assert "Max-Age=0" in session_cookies[0]
+            with flask_app.app_context():
+                interface = flask_app.session_interface
+                model = interface.sql_session_model
+                stored = 
interface.client.session.scalar(select(model).where(model.session_id == 
session_id))
+                assert stored is None
+
+            login_page = get("/login/")
+            assert login_page.status_code == 200
+            assert not login_page.cookies.get(COOKIE_NAME_JWT_TOKEN)
+        finally:
+            with flask_app.app_context():
+                delete_user(flask_app, "test_logout_user")
diff --git a/providers/fab/tests/unit/fab/auth_manager/views/test_auth_login.py 
b/providers/fab/tests/unit/fab/auth_manager/views/test_auth_login.py
index d6cdfa999a3..52bce85b948 100644
--- a/providers/fab/tests/unit/fab/auth_manager/views/test_auth_login.py
+++ b/providers/fab/tests/unit/fab/auth_manager/views/test_auth_login.py
@@ -20,13 +20,15 @@ from __future__ import annotations
 from unittest import mock
 
 import pytest
-from flask import Flask, Response, g
-from flask_appbuilder.security.views import AuthDBView, AuthLDAPView, 
AuthOAuthView
+from flask import Flask, Response, g, session
+from flask_appbuilder import AppBuilder
+from flask_appbuilder.security.views import AuthDBView, AuthLDAPView, 
AuthOAuthView, AuthView
 
 from airflow.providers.fab.auth_manager.views import auth_login
 from airflow.providers.fab.auth_manager.views.auth_login import (
     CustomAuthDBView,
     CustomAuthLDAPView,
+    CustomAuthRemoteUserView,
     redirect_if_authenticated,
 )
 from airflow.providers.fab.auth_manager.views.auth_oauth import 
CustomAuthOAuthView
@@ -140,6 +142,38 @@ class TestCustomLoginViews:
         parent_login.assert_called_once_with(*expected_args)
 
 
+class TestEndSessionOnLogout:
+    @pytest.mark.parametrize(
+        "view_class",
+        [CustomAuthDBView, CustomAuthLDAPView, CustomAuthOAuthView, 
CustomAuthRemoteUserView],
+    )
+    @pytest.mark.parametrize(
+        ("logout_redirect_url", "expected_location"),
+        [
+            (None, "/login/"),
+            ("https://idp.example.com/logout";, 
"https://idp.example.com/logout";),
+        ],
+    )
+    @mock.patch.object(AuthView, "logout", autospec=True, 
return_value=Response(status=302))
+    def test_logout_clears_session_and_redirects(
+        self, parent_logout, flask_app, view_class, logout_redirect_url, 
expected_location
+    ):
+        flask_app.secret_key = "test-secret"
+        if logout_redirect_url:
+            flask_app.config["LOGOUT_REDIRECT_URL"] = logout_redirect_url
+        view = view_class()
+        view.appbuilder = mock.Mock(spec=AppBuilder, 
get_url_for_login="/login/")
+        with flask_app.test_request_context("/logout/"):
+            session["csrf_token"] = "token"
+            response = view.logout()
+
+            assert not session
+
+        parent_logout.assert_called_once_with(view)
+        assert response.status_code == 302
+        assert response.location == expected_location
+
+
 def test_module_uses_token_setting_redirect():
     from airflow.providers.fab.www import views
 

Reply via email to