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 5ce3771e763 End the Keycloak session when a user logs out of Airflow 
(#77569)
5ce3771e763 is described below

commit 5ce3771e763d49c7ad60299e81f314883c3d595a
Author: Baptiste Gouhoury <[email protected]>
AuthorDate: Fri Nov 27 16:39:06 2026 +0100

    End the Keycloak session when a user logs out of Airflow (#77569)
    
    Logging out only ended the Keycloak session if the browser completed the
    redirect to Keycloak's end_session_endpoint. When the id token cookie was
    missing or invalid, the tab was closed, or Keycloak refused the
    post-logout redirect, the Keycloak session stayed active, and its refresh
    token could still be used to get new tokens until it expired.
    
    A Keycloak failure while ending the session is logged and does not block
    the Airflow logout.
    
    Signed-off-by: Baptiste Gouhoury <[email protected]>
---
 .../keycloak/auth_manager/keycloak_auth_manager.py | 34 ++++++++-
 .../providers/keycloak/auth_manager/middleware.py  |  3 +
 .../auth_manager/test_keycloak_auth_manager.py     | 13 ++++
 .../unit/keycloak/auth_manager/test_middleware.py  | 83 ++++++++++++++++++++++
 4 files changed, 131 insertions(+), 2 deletions(-)

diff --git 
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py
 
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py
index 69118a26b90..150ac51f194 100644
--- 
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py
+++ 
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py
@@ -31,7 +31,7 @@ import requests
 from fastapi import FastAPI
 from jwt import InvalidTokenError
 from keycloak import KeycloakOpenID
-from keycloak.exceptions import KeycloakPostError
+from keycloak.exceptions import KeycloakError, KeycloakPostError
 from requests.adapters import HTTPAdapter
 from urllib3.util import Retry
 
@@ -76,6 +76,7 @@ from airflow.providers.keycloak.auth_manager.constants import 
(
 from airflow.providers.keycloak.auth_manager.exceptions import (
     KeycloakAuthorizationRequestError,
     KeycloakUnexpectedResponseError,
+    is_keycloak_outage,
 )
 from airflow.providers.keycloak.auth_manager.resources import KeycloakResource
 from airflow.providers.keycloak.auth_manager.user import 
KeycloakAuthManagerUser
@@ -499,12 +500,20 @@ class 
KeycloakAuthManager(BaseAuthManager[KeycloakAuthManagerUser]):
         return get_keycloak_cli_commands()
 
     @staticmethod
-    def get_keycloak_client(client_id: str | None = None, client_secret: str | 
None = None) -> KeycloakOpenID:
+    def get_keycloak_client(
+        client_id: str | None = None,
+        client_secret: str | None = None,
+        *,
+        timeout: int | None = None,
+        max_retries: int | None = None,
+    ) -> KeycloakOpenID:
         """
         Get a KeycloakOpenID client instance.
 
         :param client_id: Optional client ID to override config. If provided, 
client_secret must also be provided.
         :param client_secret: Optional client secret to override config. If 
provided, client_id must also be provided.
+        :param timeout: Optional request timeout in seconds. Defaults to the 
python-keycloak default.
+        :param max_retries: Optional number of retries per request. Defaults 
to the python-keycloak default.
         """
         if (client_id is None) != (client_secret is None):
             raise ValueError(
@@ -517,14 +526,35 @@ class 
KeycloakAuthManager(BaseAuthManager[KeycloakAuthManagerUser]):
 
         realm = conf.get(CONF_SECTION_NAME, CONF_REALM_KEY)
         server_url = conf.get(CONF_SECTION_NAME, CONF_SERVER_URL_KEY)
+        connection_kwargs: dict[str, Any] = {}
+        if timeout is not None:
+            connection_kwargs["timeout"] = timeout
+        if max_retries is not None:
+            connection_kwargs["max_retries"] = max_retries
 
         return KeycloakOpenID(
             server_url=server_url,
             client_id=client_id,
             client_secret_key=client_secret,
             realm_name=realm,
+            **connection_kwargs,
         )
 
+    @staticmethod
+    def _end_keycloak_session(refresh_token: str) -> None:
+        # python-keycloak retries POST by default, which would multiply the 
timeout.
+        client = KeycloakAuthManager.get_keycloak_client(timeout=5, 
max_retries=0)
+        try:
+            client.logout(refresh_token)
+        except KeycloakError as e:
+            # A 400 invalid_grant is the normal answer when the Keycloak 
session already expired.
+            log.log(
+                logging.WARNING if is_keycloak_outage(e) else logging.DEBUG,
+                "Could not end the Keycloak session on logout (%s, response 
code %s)",
+                type(e).__name__,
+                e.response_code,
+            )
+
     def _is_authorized(
         self,
         *,
diff --git 
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py 
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py
index cd32fe5857e..a9e0f8e1c02 100644
--- 
a/providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py
+++ 
b/providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py
@@ -293,6 +293,9 @@ class KeycloakJWTMiddleware(JWTRefreshMiddleware):
         except InvalidTokenError:
             raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, 
detail="Invalid JWT token")
         if KeycloakJWTMiddleware._is_logout(request):
+            # Last request that carries the refresh token cookie.
+            if user.refresh_token:
+                await 
run_in_threadpool(KeycloakAuthManager._end_keycloak_session, user.refresh_token)
             # On logout return the user as new_user without refreshing to 
allow the Keycloak
             # Cookies to be cleared by get_extra_cookies().
             return user, user
diff --git 
a/providers/keycloak/tests/unit/keycloak/auth_manager/test_keycloak_auth_manager.py
 
b/providers/keycloak/tests/unit/keycloak/auth_manager/test_keycloak_auth_manager.py
index b00017dfd4e..3268b50ccfa 100644
--- 
a/providers/keycloak/tests/unit/keycloak/auth_manager/test_keycloak_auth_manager.py
+++ 
b/providers/keycloak/tests/unit/keycloak/auth_manager/test_keycloak_auth_manager.py
@@ -1253,6 +1253,19 @@ class TestKeycloakAuthManager:
         )
         assert client == mock_keycloak_openid.return_value
 
+    
@patch("airflow.providers.keycloak.auth_manager.keycloak_auth_manager.KeycloakOpenID")
+    def test_get_keycloak_client_with_connection_settings(self, 
mock_keycloak_openid, auth_manager):
+        auth_manager.get_keycloak_client(timeout=5, max_retries=0)
+
+        mock_keycloak_openid.assert_called_once_with(
+            server_url="server_url",
+            realm_name="realm",
+            client_id="client_id",
+            client_secret_key="client_secret",
+            timeout=5,
+            max_retries=0,
+        )
+
     @pytest.mark.parametrize(
         ("client_id", "permission", "attributes", "expected_claims"),
         [
diff --git 
a/providers/keycloak/tests/unit/keycloak/auth_manager/test_middleware.py 
b/providers/keycloak/tests/unit/keycloak/auth_manager/test_middleware.py
index 7bad391eca3..e00584dd0f4 100644
--- a/providers/keycloak/tests/unit/keycloak/auth_manager/test_middleware.py
+++ b/providers/keycloak/tests/unit/keycloak/auth_manager/test_middleware.py
@@ -16,6 +16,7 @@
 # under the License.
 from __future__ import annotations
 
+import logging
 import re
 import threading
 from http.cookies import SimpleCookie
@@ -28,6 +29,7 @@ from fastapi.responses import PlainTextResponse, 
StreamingResponse
 from fastapi.staticfiles import StaticFiles
 from fastapi.testclient import TestClient
 from jwt import InvalidTokenError
+from keycloak import KeycloakConnectionError, KeycloakPostError
 
 from airflow.api_fastapi import app as api_fastapi_app
 from airflow.api_fastapi.auth.managers.base_auth_manager import 
COOKIE_NAME_JWT_TOKEN, BaseAuthManager
@@ -409,6 +411,86 @@ class TestKeycloakJWTMiddleware:
             for refreshed_token in ["new_token", "new_refresh_token", 
access_token]
         )
 
+    @pytest.mark.parametrize(
+        ("refresh_token", "expected_calls"),
+        [
+            pytest.param("refresh_token", [call("refresh_token")], 
id="with_refresh_token"),
+            pytest.param(None, [], id="without_refresh_token"),
+        ],
+    )
+    @patch(f"{MODULE}.KeycloakAuthManager.get_keycloak_client", autospec=True)
+    def test_logout_ends_keycloak_session(
+        self, mock_get_keycloak_client, mock_auth_manager, refresh_token, 
expected_calls
+    ):
+        cookies = {COOKIE_NAME_JWT_TOKEN: "valid_token", 
COOKIE_NAME_ACCESS_TOKEN: keycloak_token("user_id")}
+        if refresh_token:
+            cookies[COOKIE_NAME_REFRESH_TOKEN] = refresh_token
+        app, _ = _build_app()
+        app.state.auth_manager = mock_auth_manager
+
+        TestClient(app, cookies=cookies).get("/api/v2/auth/logout", 
follow_redirects=False)
+
+        assert mock_get_keycloak_client.return_value.logout.call_args_list == 
expected_calls
+        if expected_calls:
+            mock_get_keycloak_client.assert_called_once_with(timeout=5, 
max_retries=0)
+
+    @pytest.mark.parametrize(
+        ("error", "expected_event", "expected_log_level"),
+        [
+            pytest.param(
+                KeycloakPostError(error_message="invalid_grant", 
response_code=400),
+                "Could not end the Keycloak session on logout 
(KeycloakPostError, response code 400)",
+                "debug",
+                id="session_already_expired",
+            ),
+            pytest.param(
+                KeycloakPostError(error_message="server error", 
response_code=503),
+                "Could not end the Keycloak session on logout 
(KeycloakPostError, response code 503)",
+                "warning",
+                id="keycloak_server_error",
+            ),
+            pytest.param(
+                KeycloakConnectionError(error_message="connection refused"),
+                "Could not end the Keycloak session on logout 
(KeycloakConnectionError, response code None)",
+                "warning",
+                id="keycloak_unreachable",
+            ),
+        ],
+    )
+    @patch(f"{MODULE}.KeycloakAuthManager.get_keycloak_client", autospec=True)
+    def test_logout_completes_when_keycloak_cannot_end_the_session(
+        self,
+        mock_get_keycloak_client,
+        mock_auth_manager,
+        caplog,
+        error,
+        expected_event,
+        expected_log_level,
+    ):
+        mock_get_keycloak_client.return_value.logout.side_effect = error
+        caplog.set_level(
+            logging.DEBUG, 
logger="airflow.providers.keycloak.auth_manager.keycloak_auth_manager"
+        )
+        app, _ = _build_app()
+        app.state.auth_manager = mock_auth_manager
+
+        response = TestClient(
+            app,
+            cookies={
+                COOKIE_NAME_JWT_TOKEN: "valid_token",
+                COOKIE_NAME_ACCESS_TOKEN: keycloak_token("user_id"),
+                COOKIE_NAME_REFRESH_TOKEN: "refresh_token",
+            },
+        ).get("/api/v2/auth/logout", follow_redirects=False)
+
+        assert response.status_code == 307
+        assert _get_browser_cookies(response) == {
+            (COOKIE_NAME_JWT_TOKEN, "/"): None,
+            (COOKIE_NAME_ACCESS_TOKEN, "/"): None,
+            (COOKIE_NAME_REFRESH_TOKEN, "/"): None,
+        }
+        assert {"event": expected_event, "log_level": expected_log_level} in 
caplog
+
     def test_root_cookie_cleared_when_route_sets_token(self, 
mock_get_cookie_path, mock_auth_manager):
         mock_auth_manager.get_user_from_token.side_effect = InvalidTokenError
         app, _ = _build_app()
@@ -883,6 +965,7 @@ class TestKeycloakJWTMiddlewareInTheApiServer:
                 
"airflow.providers.keycloak.auth_manager.middleware.get_auth_manager", 
mock_get_auth_manager
             ),
             patch.object(KeycloakAuthManager, "_get_token_validator", 
return_value=token_validator),
+            patch.object(KeycloakAuthManager, "get_keycloak_client", 
autospec=True),
             patch.object(
                 KeycloakAuthManager,
                 "refresh_tokens",

Reply via email to