potiuk commented on code in PR #70800:
URL: https://github.com/apache/airflow/pull/70800#discussion_r3700146795


##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/constants.py:
##########
@@ -27,9 +27,7 @@
 CONF_REQUESTS_RETRIES_KEY = "requests_retries"
 
 # Extra Cookie names
-COOKIE_NAME_ACCESS_TOKEN = "access_token"
+COOKIE_NAME_ACCESS_TOKEN = "_access_token"

Review Comment:
   You're right, and I checked it properly: those names were never released.
   
   At `providers-keycloak/0.8.2` the provider's `constants.py` contains only 
the `CONF_*` entries — no cookie names at all. `login.py` defined just 
`COOKIE_NAME_ID_TOKEN = "_id_token"` and `COOKIE_NAME_OAUTH_STATE = 
"_oauth_state"` locally (both unchanged by this PR) and imported 
`COOKIE_NAME_JWT_TOKEN` from core; the Keycloak `access_token`/`refresh_token` 
lived in the Airflow JWT claims, not in cookies. All six `COOKIE_NAME_*` 
constants arrived with #70550, which is not an ancestor of the 0.8.2 tag.
   
   So there are no legacy cookies in anyone's browser and nothing for 
`logout_callback` to miss. Withdrawing that.
   
   The upgrade behaviour is the part I would still like written down. A 0.8.2 
session carries the tokens in the JWT claims, so after upgrading 
`_refresh_user` finds no `_access_token`/`_refresh_token` cookie, returns 401, 
and `dispatch` clears the Airflow JWT — every logged-in user is signed out 
once. I agree that is the right call; it just deserves a line in the keycloak 
changelog for whichever release ships it, so operators are not surprised by a 
fleet-wide logout.
   
   ---
   Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting



##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py:
##########
@@ -0,0 +1,243 @@
+# 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.
+
+from __future__ import annotations
+
+from typing import TYPE_CHECKING, cast
+
+from fastapi import HTTPException, status
+from fastapi.responses import JSONResponse
+from jwt import ExpiredSignatureError, InvalidTokenError
+from starlette.middleware.base import BaseHTTPMiddleware
+
+from airflow.api_fastapi.app import get_auth_manager
+from airflow.api_fastapi.auth.managers.base_auth_manager import 
COOKIE_NAME_JWT_TOKEN
+from airflow.api_fastapi.core_api import security as core_api_security
+from airflow.providers.common.compat.sdk import conf
+from airflow.providers.keycloak.auth_manager.constants import (
+    COOKIE_NAME_ACCESS_TOKEN,
+    COOKIE_NAME_REFRESH_TOKEN,
+)
+from airflow.providers.keycloak.version_compat import AIRFLOW_V_3_1_8_PLUS
+
+try:
+    from airflow.api_fastapi.auth.managers.exceptions import 
AuthManagerRefreshTokenExpiredException
+except ImportError:
+
+    class AuthManagerRefreshTokenExpiredException(Exception):  # type: 
ignore[no-redef]
+        """In case it is using a version of Airflow without 
``AuthManagerRefreshTokenExpiredException``."""
+
+        pass
+
+
+if AIRFLOW_V_3_1_8_PLUS:
+    from airflow.api_fastapi.app import get_cookie_path
+else:
+    get_cookie_path = lambda: "/"
+
+if TYPE_CHECKING:
+    from fastapi import Request, Response
+
+    from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import 
KeycloakAuthManager
+    from airflow.providers.keycloak.auth_manager.user import 
KeycloakAuthManagerUser
+
+
+class KeycloakJWTMiddleware(BaseHTTPMiddleware):
+    """
+    Attach the Keycloak JWT tokens to the user.
+
+    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.
+    """
+
+    async def dispatch(self, request: Request, call_next):
+        user = None
+        new_token = None
+        new_user = None
+        try:
+            try:
+                new_user, current_user = await self._refresh_user(request)
+                user = new_user or current_user
+            except (
+                AuthManagerRefreshTokenExpiredException,
+                ExpiredSignatureError,
+                InvalidTokenError,
+                HTTPException,
+            ):
+                new_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
+
+            response = await call_next(request)
+
+            if new_user or new_token is not None:
+                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 as exc:

Review Comment:
   Fair — I checked core and you are right. `JWTRefreshMiddleware.dispatch` has 
the same shape: the `try` opens before `response = await call_next(request)` 
and the `except HTTPException` closes after it, so the wide scope is inherited 
rather than introduced here.
   
   That settles it for this PR — being consistent with the middleware you are 
subclassing is the right default, and I would rather not have the two drift. If 
the concern is real it applies to core first, so it belongs there rather than 
in a copy of it. Not blocking on this.
   
   ---
   Drafted-by: Claude Code (Opus 5); reviewed by @potiuk before posting



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