vincbeck commented on code in PR #70707:
URL: https://github.com/apache/airflow/pull/70707#discussion_r4603858972


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py:
##########
@@ -52,263 +59,235 @@ def get_cookie_path() -> str:
         return "/"
 
 
-# The core route that revokes the Airflow JWT sent with the request, relative 
to the root path.
-LOGOUT_PATH = "/api/v2/auth/logout"
+if AIRFLOW_V_3_4_PLUS:
+    from airflow.api_fastapi.auth.middlewares.refresh_token import 
UNAUTHENTICATED_PATHS
+else:
+    # Unauthenticated endpoints that never read the user, so resolving it 
there would only cost a
+    # JWT decode and a revocation lookup on every health check and UI boot.
+    UNAUTHENTICATED_PATHS = frozenset(["/api/v2/monitor/health", 
"/api/v2/version"])
 
 if TYPE_CHECKING:
-    from fastapi import Request, Response
+    from starlette.types import ASGIApp, Message, Receive, Scope, Send
 
-    from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import 
KeycloakAuthManager
+    from airflow.api_fastapi.auth.managers.models.base_user import BaseUser
     from airflow.providers.keycloak.auth_manager.user import 
KeycloakAuthManagerUser
 
+if AIRFLOW_V_3_4_1_PLUS:
+    from airflow.api_fastapi.app import request_cookie_is_secure
+    from airflow.api_fastapi.auth.middlewares.refresh_token import 
JWTRefreshMiddleware  # pyright: ignore[reportAssignmentType]
+else:
 
-class KeycloakJWTMiddleware(BaseHTTPMiddleware):
-    """
-    Attach the Keycloak JWT tokens to the user.
+    def request_cookie_is_secure(request: Request) -> bool:
+        return request.base_url.scheme == "https" or bool(conf.get("api", 
"ssl_cert", fallback=""))
 
-    Gets the Keycloak JWT tokens from the request cookies
-    and attaches them to the user. If the token is expired,
-    attempt to refresh it using the refresh token.
-    """
+    class JWTRefreshMiddleware(metaclass=ABCMeta):
+        """Backport of JWTRefreshMiddleware."""
 
-    async def dispatch(self, request: Request, call_next):
-        user = None
-        new_token = None
-        new_user = None
-        session_invalidated = False
-        try:
-            try:
-                new_user, current_user = await self._refresh_user(request)
-                user = new_user or current_user
-            except (
-                AuthManagerRefreshTokenExpiredException,
-                HTTPException,
-            ):
-                new_token = ""
-                # The session ends here and the response clears the Airflow 
JWT. Hide it
-                # from the inner middlewares and the route too: resolving it 
again without
-                # the Keycloak tokens yields no user, which ``get_user`` would 
hand to the
-                # authorization checks instead of answering 401. The logout 
route needs no
-                # user and revokes the JWT it receives, so it keeps it.
-                if not self._is_logout(request):
-                    self._drop_cookie(request, COOKIE_NAME_JWT_TOKEN)
-
-            if user is not None:
-                request.state.user = user
-
-                user_injected = getattr(
-                    core_api_security,
-                    "USER_INJECTED_BY_TRUSTED_MIDDLEWARE",
-                    None,
-                )
-                if user_injected is not None:
-                    request.state.user_authenticated_via = user_injected
+        def __init__(self, app: ASGIApp, skip_path_prefixes: tuple[str, ...] = 
()) -> None:
+            self.app = app
+            self.skip_path_prefixes = skip_path_prefixes
 
-            response = await call_next(request)
+        async def __call__(self, scope: Scope, receive: Receive, send: Send) 
-> None:
+            if scope["type"] != "http" or self._is_skipped(scope):
+                await self.app(scope, receive, send)
+                return
 
-            if new_token == "" and getattr(request.state, "jwt_token_issued", 
False):
-                new_token = None
+            request = Request(scope)
+            current_token = request.cookies.get(COOKIE_NAME_JWT_TOKEN)
+            if current_token is None:
+                await self.app(scope, receive, send)
+                return
 
-            if new_user and not await self._is_jwt_still_valid(request):
-                # The Airflow JWT sent with the request was invalidated while 
the request was
-                # handled (e.g. by the logout route). Do not replace it with a 
freshly signed
-                # one -- that would keep the session alive -- and clear the 
session cookies.
-                new_user = None
+            new_user = None
+            session_invalidated = False
+            try:
+                new_user, current_user = await self.refresh_user(request)
+                if user := (new_user or current_user):
+                    # Stamp the trust sentinel alongside the user so 
`get_user()`
+                    # can distinguish this trusted assignment from a stray 
write
+                    # by unrelated middleware.
+                    request.state.user = user
+                    request.state.user_authenticated_via = getattr(
+                        core_api_security,
+                        "USER_INJECTED_BY_TRUSTED_MIDDLEWARE",
+                        None,
+                    )
+            except (HTTPException, AuthManagerRefreshTokenExpiredException):
+                # Receive a HTTPException when the Airflow token is expired
+                # Receive a AuthManagerRefreshTokenExpiredException when the 
potential underlying refresh
+                # token used by the auth manager is expired
                 session_invalidated = True

Review Comment:
   This removes the fix from #76353 (`_drop_cookie`). When the Keycloak session 
has ended (refresh token expired or no Keycloak cookies), `_token` stays on the 
request and the route resolves it again. On 3.3 and 3.4.0, 
`get_user_from_token` returns `None` and the authorization checks fail with a 
500 (#76352). On 3.4.1+ it returns a user with no access token, which is why 
`test_ended_keycloak_session_answers_200_and_clears_the_cookie` now gets a 200 
where it used to get a 401. Fix: keep removing `_token` from the request when 
the session ends (e.g. in `refresh_user` before raising, so it works with the 
core middleware too), except on the logout route, and keep the 401 in the test.



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py:
##########
@@ -52,263 +59,235 @@ def get_cookie_path() -> str:
         return "/"
 
 
-# The core route that revokes the Airflow JWT sent with the request, relative 
to the root path.
-LOGOUT_PATH = "/api/v2/auth/logout"
+if AIRFLOW_V_3_4_PLUS:
+    from airflow.api_fastapi.auth.middlewares.refresh_token import 
UNAUTHENTICATED_PATHS
+else:
+    # Unauthenticated endpoints that never read the user, so resolving it 
there would only cost a
+    # JWT decode and a revocation lookup on every health check and UI boot.
+    UNAUTHENTICATED_PATHS = frozenset(["/api/v2/monitor/health", 
"/api/v2/version"])
 
 if TYPE_CHECKING:
-    from fastapi import Request, Response
+    from starlette.types import ASGIApp, Message, Receive, Scope, Send
 
-    from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import 
KeycloakAuthManager
+    from airflow.api_fastapi.auth.managers.models.base_user import BaseUser
     from airflow.providers.keycloak.auth_manager.user import 
KeycloakAuthManagerUser
 
+if AIRFLOW_V_3_4_1_PLUS:

Review Comment:
   Why `AIRFLOW_V_3_4_1_PLUS` here and `_middleware_handles_cookies()` 
everywhere else? I would use the same check for both, otherwise the base class 
and the registration can disagree.



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py:
##########
@@ -206,7 +208,13 @@ async def get_user_from_token(
         :param refresh_token: Keycloak refresh JWT
         """
         user = cast("KeycloakAuthManagerUser", await 
super().get_user_from_token(token))
-        if not AIRFLOW_V_3_3_PLUS:
+        if self._middleware_handles_cookies() or not AIRFLOW_V_3_3_PLUS:
+            # For Airflow v3.2- the access_token and refresh_token are 
included in the
+            # Airflow JWT claims.
+            # For Airflow v3.5.0+ the access_token and refresh_token are added 
to the user
+            # from the cookies by 
KeycloakJWTMiddleware._get_user_from_request().

Review Comment:
   nit: there is no `_get_user_from_request()`, it is `refresh_user`. And this 
applies from 3.4.1, not 3.5.0.



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py:
##########
@@ -52,263 +59,235 @@ def get_cookie_path() -> str:
         return "/"
 
 
-# The core route that revokes the Airflow JWT sent with the request, relative 
to the root path.
-LOGOUT_PATH = "/api/v2/auth/logout"
+if AIRFLOW_V_3_4_PLUS:
+    from airflow.api_fastapi.auth.middlewares.refresh_token import 
UNAUTHENTICATED_PATHS
+else:
+    # Unauthenticated endpoints that never read the user, so resolving it 
there would only cost a
+    # JWT decode and a revocation lookup on every health check and UI boot.
+    UNAUTHENTICATED_PATHS = frozenset(["/api/v2/monitor/health", 
"/api/v2/version"])
 
 if TYPE_CHECKING:
-    from fastapi import Request, Response
+    from starlette.types import ASGIApp, Message, Receive, Scope, Send
 
-    from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import 
KeycloakAuthManager
+    from airflow.api_fastapi.auth.managers.models.base_user import BaseUser
     from airflow.providers.keycloak.auth_manager.user import 
KeycloakAuthManagerUser
 
+if AIRFLOW_V_3_4_1_PLUS:
+    from airflow.api_fastapi.app import request_cookie_is_secure
+    from airflow.api_fastapi.auth.middlewares.refresh_token import 
JWTRefreshMiddleware  # pyright: ignore[reportAssignmentType]
+else:
 
-class KeycloakJWTMiddleware(BaseHTTPMiddleware):
-    """
-    Attach the Keycloak JWT tokens to the user.
+    def request_cookie_is_secure(request: Request) -> bool:
+        return request.base_url.scheme == "https" or bool(conf.get("api", 
"ssl_cert", fallback=""))
 
-    Gets the Keycloak JWT tokens from the request cookies
-    and attaches them to the user. If the token is expired,
-    attempt to refresh it using the refresh token.
-    """
+    class JWTRefreshMiddleware(metaclass=ABCMeta):
+        """Backport of JWTRefreshMiddleware."""
 
-    async def dispatch(self, request: Request, call_next):
-        user = None
-        new_token = None
-        new_user = None
-        session_invalidated = False
-        try:
-            try:
-                new_user, current_user = await self._refresh_user(request)
-                user = new_user or current_user
-            except (
-                AuthManagerRefreshTokenExpiredException,
-                HTTPException,
-            ):
-                new_token = ""
-                # The session ends here and the response clears the Airflow 
JWT. Hide it
-                # from the inner middlewares and the route too: resolving it 
again without
-                # the Keycloak tokens yields no user, which ``get_user`` would 
hand to the
-                # authorization checks instead of answering 401. The logout 
route needs no
-                # user and revokes the JWT it receives, so it keeps it.
-                if not self._is_logout(request):
-                    self._drop_cookie(request, COOKIE_NAME_JWT_TOKEN)
-
-            if user is not None:
-                request.state.user = user
-
-                user_injected = getattr(
-                    core_api_security,
-                    "USER_INJECTED_BY_TRUSTED_MIDDLEWARE",
-                    None,
-                )
-                if user_injected is not None:
-                    request.state.user_authenticated_via = user_injected
+        def __init__(self, app: ASGIApp, skip_path_prefixes: tuple[str, ...] = 
()) -> None:
+            self.app = app
+            self.skip_path_prefixes = skip_path_prefixes
 
-            response = await call_next(request)
+        async def __call__(self, scope: Scope, receive: Receive, send: Send) 
-> None:
+            if scope["type"] != "http" or self._is_skipped(scope):
+                await self.app(scope, receive, send)
+                return
 
-            if new_token == "" and getattr(request.state, "jwt_token_issued", 
False):
-                new_token = None
+            request = Request(scope)
+            current_token = request.cookies.get(COOKIE_NAME_JWT_TOKEN)
+            if current_token is None:
+                await self.app(scope, receive, send)
+                return
 
-            if new_user and not await self._is_jwt_still_valid(request):
-                # The Airflow JWT sent with the request was invalidated while 
the request was
-                # handled (e.g. by the logout route). Do not replace it with a 
freshly signed
-                # one -- that would keep the session alive -- and clear the 
session cookies.
-                new_user = None
+            new_user = None
+            session_invalidated = False
+            try:
+                new_user, current_user = await self.refresh_user(request)
+                if user := (new_user or current_user):
+                    # Stamp the trust sentinel alongside the user so 
`get_user()`
+                    # can distinguish this trusted assignment from a stray 
write
+                    # by unrelated middleware.
+                    request.state.user = user
+                    request.state.user_authenticated_via = getattr(
+                        core_api_security,
+                        "USER_INJECTED_BY_TRUSTED_MIDDLEWARE",
+                        None,
+                    )
+            except (HTTPException, AuthManagerRefreshTokenExpiredException):
+                # Receive a HTTPException when the Airflow token is expired
+                # Receive a AuthManagerRefreshTokenExpiredException when the 
potential underlying refresh
+                # token used by the auth manager is expired
                 session_invalidated = True
 
-            if new_user or new_token is not None or session_invalidated:
-                secure = request.base_url.scheme == "https" or 
bool(conf.get("api", "ssl_cert", fallback=""))
-                cookie_path = get_cookie_path()
-                if new_token == "":
-                    response.set_cookie(
-                        COOKIE_NAME_JWT_TOKEN,
-                        new_token,
-                        path=cookie_path,
-                        httponly=True,
-                        secure=secure,
-                        samesite="lax",
-                        max_age=0,
+            if session_invalidated or new_user is not None:

Review Comment:
   On 3.3 a logout can leave a fresh JWT behind. If the Keycloak access token 
has expired, this mints a new JWT before the route runs. The 3.3 logout route 
revokes the old JWT and redirects to Keycloak without touching `_token`, so 
`route_set_token` is False and the new, unrevoked JWT is sent. Only 
`logout_callback` clears it, so if the user never comes back from the Keycloak 
end-session page, the session survives the logout. That is the case 
`_is_jwt_still_valid` covered, so on 3.3 it is still needed in some form. Fix: 
skip the refresh on the logout route in the backport.



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to