stephen-bracken commented on code in PR #70707:
URL: https://github.com/apache/airflow/pull/70707#discussion_r4602488963


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py:
##########
@@ -68,99 +103,113 @@ class KeycloakJWTMiddleware(BaseHTTPMiddleware):
     attempt to refresh it using the refresh token.
     """
 
-    async def dispatch(self, request: Request, call_next):
-        user = None
-        new_token = None
+    async def __call__(self, scope: Scope, receive: Receive, send: Send) -> 
None:
+        if AIRFLOW_V_3_5_PLUS:
+            return await super().__call__(scope, receive, send)
+
+        # For Airflow v3.4.0- we mirror the implementation from 
JWTRefreshMiddleware.__call__()
+        if scope["type"] != "http" or self._is_skipped(scope):
+            await self.app(scope, receive, send)
+            return
+
+        request = Request(scope)
+        current_token = request.cookies.get(COOKIE_NAME_JWT_TOKEN)
+        if current_token is None:
+            await self.app(scope, receive, send)
+            return
+
         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 = ""
-
-            if user is not None:
+            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
-
-                user_injected = getattr(
+                request.state.user_authenticated_via = getattr(
                     core_api_security,
                     "USER_INJECTED_BY_TRUSTED_MIDDLEWARE",
                     None,
                 )
-                if user_injected is not None:
-                    request.state.user_authenticated_via = user_injected
-
-            response = await call_next(request)
-
-            if new_token == "" and getattr(request.state, "jwt_token_issued", 
False):
-                new_token = None
-
-            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
-                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 cookie_path != "/":
-                        response.set_cookie(
-                            COOKIE_NAME_JWT_TOKEN,
-                            "",
-                            path="/",
-                            httponly=True,
-                            secure=secure,
-                            samesite="lax",
-                            max_age=0,
-                        )
-                else:
-                    response = await self._set_new_token(new_user, secure, 
response, cookie_path)
+        except (HTTPException, AuthManagerRefreshTokenExpiredException) as e:
+            # 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
+            log.error("Session Invalidated: %s", e)
+            session_invalidated = True
+
+        if session_invalidated or new_user is not None:
+            extra_cookies = self.get_extra_cookies(request, new_user)
+            token_cookie, cleanup_cookies = self.build_cookie_headers(
+                request, await self.generate_new_user_token(request, 
new_user), extra_cookies
+            )
+        else:
+            token_cookie, cleanup_cookies = (None, [])
+        response_started = False
+
+        async def send_with_cookies(message: Message) -> None:
+            nonlocal response_started
+            if message["type"] == "http.response.start":
+                response_started = True
+                headers = MutableHeaders(scope=message)
+                route_cookies = headers.getlist("set-cookie")
+                route_set_token = any(
+                    value.startswith(f"{COOKIE_NAME_JWT_TOKEN}=") for value in 
route_cookies
+                )
+                del headers["set-cookie"]
+                # The route owns the token it sets: never send ours, so a 
refreshed token can't outlive a logout.
+                cookie_values = (
+                    cleanup_cookies
+                    if route_set_token or not token_cookie
+                    else [token_cookie, *cleanup_cookies]
+                )
+                # Ours go first: for the same cookie name and path the later 
Set-Cookie wins, so the
+                # cookies set by the route itself take precedence.
+                for value in [*cookie_values, *route_cookies]:
+                    headers.append("set-cookie", value)
+            await send(message)
 
+        try:
+            await self.app(scope, receive, send_with_cookies)
         except HTTPException as exc:
-            # If any HTTPException is raised during user resolution or 
refresh, return it as response
-            return JSONResponse(status_code=exc.status_code, 
content={"detail": exc.detail})
-
-        return response
-
-    @classmethod
-    async def _set_new_token(
-        cls,
-        new_user: KeycloakAuthManagerUser | None,
-        secure: bool,
-        response: Response,
-        cookie_path: str | None = None,
-    ) -> Response:
-        """
-        Set Cookies in the response based on a new JWT token and a new user 
model.
+            if response_started:
+                raise
+            # An HTTPException escaping the inner middlewares is returned as a 
response
+            response = JSONResponse(status_code=exc.status_code, 
content={"detail": exc.detail})
+            await response(scope, receive, send)
 
-        :param new_user: User model for the JWT token
-        :param secure: HTTP secure property for cookies
-        :param response: FastAPI response object to set the cookies on
-        :param cookie_path: Path for cookies in the response
-        """
-        if cookie_path is None:
-            cookie_path = get_cookie_path()
+    def _is_skipped(self, scope: Scope) -> bool:
+        path = scope["path"].removeprefix(scope.get("root_path", ""))
+        return path in UNAUTHENTICATED_PATHS or 
path.startswith(self.skip_path_prefixes)
+
+    @staticmethod
+    def get_extra_cookies(request: Request, new_user: BaseUser | None) -> 
dict[str, str]:
         if new_user:
-            # If we created a new user, serialize it and set it as a cookie
-            new_token = get_auth_manager().generate_jwt(new_user)
-        else:
-            new_token = ""
+            user = cast("KeycloakAuthManagerUser", new_user)
+            return {
+                COOKIE_NAME_ACCESS_TOKEN: user.access_token,
+                COOKIE_NAME_REFRESH_TOKEN: user.refresh_token or "",
+            }
+        return {}
+
+    @staticmethod
+    async def generate_new_user_token(request: Request, new_user: BaseUser | 
None) -> str:
+        """If the Keycloak JWT is still valid, invalidate the Airflow JWT, 
otherwise generate a new JWT."""
+        if new_user:
+            if not await KeycloakJWTMiddleware._is_jwt_still_valid(request):

Review Comment:
   good point, I don't think this is necessary anymore. @potiuk can you check?



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