stephen-bracken commented on code in PR #70707:
URL: https://github.com/apache/airflow/pull/70707#discussion_r4615832206
##########
providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py:
##########
@@ -52,263 +59,235 @@ def get_cookie_path() -> str:
return "/"
-# The core route that revokes the Airflow JWT sent with the request, relative
to the root path.
-LOGOUT_PATH = "/api/v2/auth/logout"
+if AIRFLOW_V_3_4_PLUS:
+ from airflow.api_fastapi.auth.middlewares.refresh_token import
UNAUTHENTICATED_PATHS
+else:
+ # Unauthenticated endpoints that never read the user, so resolving it
there would only cost a
+ # JWT decode and a revocation lookup on every health check and UI boot.
+ UNAUTHENTICATED_PATHS = frozenset(["/api/v2/monitor/health",
"/api/v2/version"])
if TYPE_CHECKING:
- from fastapi import Request, Response
+ from starlette.types import ASGIApp, Message, Receive, Scope, Send
- from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import
KeycloakAuthManager
+ from airflow.api_fastapi.auth.managers.models.base_user import BaseUser
from airflow.providers.keycloak.auth_manager.user import
KeycloakAuthManagerUser
+if AIRFLOW_V_3_4_1_PLUS:
+ from airflow.api_fastapi.app import request_cookie_is_secure
+ from airflow.api_fastapi.auth.middlewares.refresh_token import
JWTRefreshMiddleware # pyright: ignore[reportAssignmentType]
+else:
-class KeycloakJWTMiddleware(BaseHTTPMiddleware):
- """
- Attach the Keycloak JWT tokens to the user.
+ def request_cookie_is_secure(request: Request) -> bool:
+ return request.base_url.scheme == "https" or bool(conf.get("api",
"ssl_cert", fallback=""))
- 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.
- """
+ class JWTRefreshMiddleware(metaclass=ABCMeta):
+ """Backport of JWTRefreshMiddleware."""
- async def dispatch(self, request: Request, call_next):
- user = None
- new_token = None
- 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 = ""
- # The session ends here and the response clears the Airflow
JWT. Hide it
- # from the inner middlewares and the route too: resolving it
again without
- # the Keycloak tokens yields no user, which ``get_user`` would
hand to the
- # authorization checks instead of answering 401. The logout
route needs no
- # user and revokes the JWT it receives, so it keeps it.
- if not self._is_logout(request):
- self._drop_cookie(request, COOKIE_NAME_JWT_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
+ def __init__(self, app: ASGIApp, skip_path_prefixes: tuple[str, ...] =
()) -> None:
+ self.app = app
+ self.skip_path_prefixes = skip_path_prefixes
- response = await call_next(request)
+ async def __call__(self, scope: Scope, receive: Receive, send: Send)
-> None:
+ if scope["type"] != "http" or self._is_skipped(scope):
+ await self.app(scope, receive, send)
+ return
- if new_token == "" and getattr(request.state, "jwt_token_issued",
False):
- new_token = None
+ request = Request(scope)
+ current_token = request.cookies.get(COOKIE_NAME_JWT_TOKEN)
+ if current_token is None:
+ await self.app(scope, receive, send)
+ return
- 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
+ new_user = None
+ session_invalidated = False
+ try:
+ 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
+ request.state.user_authenticated_via = getattr(
+ core_api_security,
+ "USER_INJECTED_BY_TRUSTED_MIDDLEWARE",
+ None,
+ )
+ except (HTTPException, AuthManagerRefreshTokenExpiredException):
+ # 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
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 session_invalidated or new_user is not None:
Review Comment:
re-applied fix in `refresh_user()`
--
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]