stephen-bracken commented on code in PR #70800: URL: https://github.com/apache/airflow/pull/70800#discussion_r3696676052
########## 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: The `HTTPException` except pattern is used in the original `JWTRefreshMiddleware` that this is based on: https://github.com/apache/airflow/blob/b2d1d8183dcea1813a92e2ef5a94aebac4c143e8/airflow-core/src/airflow/api_fastapi/auth/middlewares/refresh_token.py#L94 The pattern could be wrong, but I am being consistent with the existing JWT middleware here -- 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]
