potiuk commented on code in PR #70800: URL: https://github.com/apache/airflow/pull/70800#discussion_r3696641142
########## 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: Renaming these leaves credentials behind in the browser that logout no longer clears. `access_token` becomes `_access_token` and `refresh_token` becomes `_refresh_token`, while `COOKIE_NAME_USER_ID` and `COOKIE_NAME_NAME` are dropped entirely. Anyone with a live session is holding cookies under the old names, and after this change nothing writes or deletes them — `logout_callback` only deletes the new names now, and the `delete_cookie` calls for `user_id` and `name` are removed outright. A refresh token is a credential, so "log out" leaving one in the browser is the wrong behaviour even for a short window. They are session cookies, with no `max_age` or `expires`, so they do go when the browser closes — that bounds the exposure but does not fix logout. Keeping the legacy names deleted in `logout_callback` for one release would close it. Worth noting the upgrade behaviour too, since nothing currently mentions it: an existing session sends the old cookie names, `_refresh_user` reads the new ones, gets `None`, raises 401, and `dispatch` clears the Airflow JWT. Every logged-in user is signed out by the upgrade. That is handled gracefully rather than erroring, but it should be a deliberate, documented choice rather than a side effect. ########## 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: "/" Review Comment: Minor: a `def` reads better than a lambda bound to a name here, and it is what ruff's E731 asks for where enabled. Same pattern appears in `routes/login.py`. ```python def get_cookie_path() -> str: return "/" ``` ########## 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: This `except` is scoped wider than the code it needs to protect — the `try` also wraps `await call_next(request)`. If an `HTTPException` escapes a downstream handler, this middleware converts it into its own `JSONResponse`, bypassing FastAPI's registered exception handlers and changing the error shape for responses that have nothing to do with authentication. I am not certain it is reachable: FastAPI's `ExceptionMiddleware` normally handles `HTTPException` inside `call_next`, so whether anything escapes depends on middleware ordering. So treat this as a question rather than a defect — but narrowing the `try` to just the refresh block removes the doubt entirely, and makes the intent obvious to the next reader. -- 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]
