vincbeck commented on code in PR #51657: URL: https://github.com/apache/airflow/pull/51657#discussion_r2162450379
########## airflow-core/src/airflow/api_fastapi/auth/managers/middleware/refresh_token.py: ########## @@ -0,0 +1,54 @@ +# 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 + +import logging + +from fastapi import Request +from starlette.middleware.base import BaseHTTPMiddleware + +from airflow.api_fastapi.auth.managers.base_auth_manager import COOKIE_NAME_JWT_TOKEN, BaseAuthManager +from airflow.configuration import conf + +log = logging.getLogger(__name__) + + +class RefreshTokenMiddleware(BaseHTTPMiddleware): + """Middleware that refresh auth manager token and update JWT Token.""" + + def __init__(self, app, auth_manager: BaseAuthManager): + super().__init__(app) + self.auth_manager = auth_manager + + async def dispatch(self, request: Request, call_next): + # Extract Authorization header + auth = request.headers.get("authorization") + + if auth and auth.lower().startswith("bearer "): + token_str = auth.split(" ", 1)[1] + if token_str != "null": + user = await self.auth_manager.get_user_from_token(token_str) + if new_user := self.auth_manager.refresh_token(user=user): + new_token_with_updated_user = self.auth_manager.generate_jwt(user=new_user) + response = await call_next(request) + # Set the new access token in the cookies to update the state of the user in the token + secure = bool(conf.get("api", "ssl_cert", fallback="")) + response.set_cookie(COOKIE_NAME_JWT_TOKEN, new_token_with_updated_user, secure=secure) + return response + log.warning("User does not have a refresh token, cannot refresh.") Review Comment: I am not sure we should have this log statement, in particular a warning one. `refresh_token` is an optional method of many auth manager will not implement this method because simply it is not needed. Having a warning in that case feels wrong to me ########## airflow-core/src/airflow/api_fastapi/auth/managers/middleware/refresh_token.py: ########## @@ -0,0 +1,54 @@ +# 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 + +import logging + +from fastapi import Request +from starlette.middleware.base import BaseHTTPMiddleware + +from airflow.api_fastapi.auth.managers.base_auth_manager import COOKIE_NAME_JWT_TOKEN, BaseAuthManager +from airflow.configuration import conf + +log = logging.getLogger(__name__) + + +class RefreshTokenMiddleware(BaseHTTPMiddleware): + """Middleware that refresh auth manager token and update JWT Token.""" + + def __init__(self, app, auth_manager: BaseAuthManager): + super().__init__(app) + self.auth_manager = auth_manager + + async def dispatch(self, request: Request, call_next): + # Extract Authorization header + auth = request.headers.get("authorization") + + if auth and auth.lower().startswith("bearer "): + token_str = auth.split(" ", 1)[1] + if token_str != "null": Review Comment: Interesting. Is that really the value returned if there is no token? ########## providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py: ########## @@ -324,3 +326,40 @@ def _get_headers(access_token): "Authorization": f"Bearer {access_token}", "Content-Type": "application/x-www-form-urlencoded", } + + @staticmethod + def get_keycloak_client() -> KeycloakOpenID: + client_id = conf.get(CONF_SECTION_NAME, CONF_CLIENT_ID_KEY) + client_secret = conf.get(CONF_SECTION_NAME, CONF_CLIENT_SECRET_KEY) + realm = conf.get(CONF_SECTION_NAME, CONF_REALM_KEY) + server_url = conf.get(CONF_SECTION_NAME, CONF_SERVER_URL_KEY) + + return KeycloakOpenID( + server_url=server_url, + client_id=client_id, + client_secret_key=client_secret, + realm_name=realm, + ) + + def refresh_token(self, user: KeycloakAuthManagerUser) -> KeycloakAuthManagerUser | None: + """Refresh the access token for the user.""" + if self._is_token_expired(user=user) and user.access_token and user.refresh_token: + client = self.get_keycloak_client() + tokens = client.refresh_token(user.refresh_token) + user.access_token = tokens["access_token"] + user.refresh_token = tokens["refresh_token"] + return user + + def _is_token_expired(self, user: KeycloakAuthManagerUser) -> bool: + """Check if the access token is expired.""" + if not user.access_token: + return False + client = self.get_keycloak_client() + try: + result = client.introspect(user.access_token) + if not result["active"]: + log.warning("Nonono is not active") Review Comment: Left over? ########## airflow-core/src/airflow/api_fastapi/auth/managers/middleware/refresh_token.py: ########## @@ -0,0 +1,54 @@ +# 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 + +import logging + +from fastapi import Request +from starlette.middleware.base import BaseHTTPMiddleware + +from airflow.api_fastapi.auth.managers.base_auth_manager import COOKIE_NAME_JWT_TOKEN, BaseAuthManager +from airflow.configuration import conf + +log = logging.getLogger(__name__) + + +class RefreshTokenMiddleware(BaseHTTPMiddleware): Review Comment: I just realized this, we should execute this middleware only for the UI (not the APIs). ########## airflow-core/src/airflow/api_fastapi/auth/managers/base_auth_manager.py: ########## @@ -133,6 +133,15 @@ def get_url_logout(self) -> str | None: """ return None + def refresh_token(self, user: T) -> T | None: + """ + Refresh the JWT token if needed. + + This method is called when the JWT token expired. Returns the user if the token were being refreshed, None otherwise. Review Comment: My bad, sorry :) ```suggestion This method is called when the JWT token expired. Returns the user if the token was being refreshed, None otherwise. ``` ########## providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py: ########## @@ -324,3 +326,40 @@ def _get_headers(access_token): "Authorization": f"Bearer {access_token}", "Content-Type": "application/x-www-form-urlencoded", } + + @staticmethod + def get_keycloak_client() -> KeycloakOpenID: + client_id = conf.get(CONF_SECTION_NAME, CONF_CLIENT_ID_KEY) + client_secret = conf.get(CONF_SECTION_NAME, CONF_CLIENT_SECRET_KEY) + realm = conf.get(CONF_SECTION_NAME, CONF_REALM_KEY) + server_url = conf.get(CONF_SECTION_NAME, CONF_SERVER_URL_KEY) + + return KeycloakOpenID( + server_url=server_url, + client_id=client_id, + client_secret_key=client_secret, + realm_name=realm, + ) + + def refresh_token(self, user: KeycloakAuthManagerUser) -> KeycloakAuthManagerUser | None: + """Refresh the access token for the user.""" + if self._is_token_expired(user=user) and user.access_token and user.refresh_token: + client = self.get_keycloak_client() + tokens = client.refresh_token(user.refresh_token) + user.access_token = tokens["access_token"] + user.refresh_token = tokens["refresh_token"] + return user + + def _is_token_expired(self, user: KeycloakAuthManagerUser) -> bool: Review Comment: Pretty cool! -- 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]
