vincbeck commented on code in PR #70707: URL: https://github.com/apache/airflow/pull/70707#discussion_r4644757317
########## providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py: ########## @@ -14,17 +14,18 @@ # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. - from __future__ import annotations +from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING, cast -from fastapi import HTTPException, status +from fastapi import HTTPException, Request, Response, status from fastapi.responses import JSONResponse from jwt import ExpiredSignatureError, InvalidTokenError -from starlette.middleware.base import BaseHTTPMiddleware +from starlette.concurrency import run_in_threadpool +from starlette.datastructures import MutableHeaders -from airflow.api_fastapi.app import get_auth_manager +from airflow.api_fastapi.app import get_auth_manager, get_cookie_path Review Comment: Why drop the `AIRFLOW_V_3_1_8_PLUS` guard? `get_cookie_path` was added in 3.1.8 and the provider supports 3.0+, so importing this module fails on 3.0.0 to 3.1.7. `test_keycloak_auth_manager.py` imports it at module level, so I think Compat 3.0.6 will fail. ########## providers/keycloak/tests/unit/keycloak/test_utils.py: ########## @@ -0,0 +1,40 @@ +# 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 base64 +import json +import time + + +def token_with_payload(payload: str) -> str: Review Comment: nit: there is no `keycloak/utils.py` for this to mirror, and pytest collects `test_*.py` files as test modules. Can you rename it, e.g. `utils.py`? ########## providers/keycloak/src/airflow/providers/keycloak/auth_manager/keycloak_auth_manager.py: ########## @@ -477,10 +465,20 @@ def get_fastapi_app(self) -> FastAPI | None: return app - def get_fastapi_middlewares(self): + def get_jwt_refresh_middleware(self) -> list[tuple[_MiddlewareFactory[[Any]], dict[str, Any]]]: Review Comment: nit: the base class uses `_MiddlewareFactory[Any]` ```suggestion def get_jwt_refresh_middleware(self) -> list[tuple[_MiddlewareFactory[Any], dict[str, Any]]]: ``` ########## providers/keycloak/src/airflow/providers/keycloak/auth_manager/middleware.py: ########## @@ -33,218 +34,272 @@ COOKIE_NAME_REFRESH_TOKEN, ) from airflow.providers.keycloak.auth_manager.exceptions import AuthManagerRefreshTokenExpiredException -from airflow.providers.keycloak.version_compat import AIRFLOW_V_3_1_8_PLUS +from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import KeycloakAuthManager +from airflow.providers.keycloak.version_compat import AIRFLOW_V_3_4_1_PLUS, AIRFLOW_V_3_4_PLUS -if AIRFLOW_V_3_1_8_PLUS: - from airflow.api_fastapi.app import get_cookie_path +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"]) - def get_cookie_path() -> str: - return "/" +if AIRFLOW_V_3_4_1_PLUS: + from airflow.api_fastapi.app import request_cookie_is_secure +else: + def request_cookie_is_secure(request: Request) -> bool: + return request.base_url.scheme == "https" or bool(conf.get("api", "ssl_cert", fallback="")) -# The core route that revokes the Airflow JWT sent with the request, relative to the root path. -LOGOUT_PATH = "/api/v2/auth/logout" 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 KeycloakAuthManager._middleware_handles_cookies(): + 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. + class JWTRefreshMiddleware(metaclass=ABCMeta): # type: ignore[no-redef] + """Backport of JWTRefreshMiddleware.""" - 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. - """ + def __init__(self, app: ASGIApp, skip_path_prefixes: tuple[str, ...] = ()) -> None: + self.app = app + self.skip_path_prefixes = skip_path_prefixes - async def dispatch(self, request: Request, call_next): - user = None - new_token = None - new_user = None - session_invalidated = False - try: + 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 + + request = Request(scope) + current_token = request.cookies.get(COOKIE_NAME_JWT_TOKEN) + if current_token is None: + await self.app(scope, receive, send) + return + + new_user = None + session_invalidated = False 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, + 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 session_invalidated or new_user is not None: + extra_cookies = self.get_extra_cookies(request, new_user) + token_cookie, cleanup_cookies = self.build_cookie_headers( + request, await self.generate_new_user_token(request, new_user), extra_cookies ) - if user_injected is not None: - request.state.user_authenticated_via = user_injected + else: + token_cookie, cleanup_cookies = (None, []) + response_started = False - response = await call_next(request) + async def send_with_cookies(message: Message) -> None: + nonlocal response_started + if message["type"] == "http.response.start": + response_started = True + headers = MutableHeaders(scope=message) + route_cookies = headers.getlist("set-cookie") + route_set_token = any( + value.startswith(f"{COOKIE_NAME_JWT_TOKEN}=") for value in route_cookies + ) + del headers["set-cookie"] + # The route owns the token it sets: never send ours, so a refreshed token can't outlive a logout. + cookie_values = ( + cleanup_cookies + if route_set_token or not token_cookie + else [token_cookie, *cleanup_cookies] + ) + # Ours go first: for the same cookie name and path the later Set-Cookie wins, so the + # cookies set by the route itself take precedence. + for value in [*cookie_values, *route_cookies]: + headers.append("set-cookie", value) + await send(message) - if new_token == "" and getattr(request.state, "jwt_token_issued", False): - new_token = None + try: + await self.app(scope, receive, send_with_cookies) + except HTTPException as exc: + if response_started: + raise + # An HTTPException escaping the inner middlewares is returned as a response + response = JSONResponse(status_code=exc.status_code, content={"detail": exc.detail}) + await response(scope, receive, send) - 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 - session_invalidated = True + def _is_skipped(self, scope: Scope) -> bool: + path = scope["path"].removeprefix(scope.get("root_path", "")) + return path in UNAUTHENTICATED_PATHS or path.startswith(self.skip_path_prefixes) - 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 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: - # If any HTTPException is raised during user resolution or refresh, return it as response - return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail}) - - return response - - @classmethod - async def _set_new_token( - cls, - new_user: KeycloakAuthManagerUser | None, - secure: bool, - response: Response, - cookie_path: str | None = None, - ) -> Response: - """ - Set Cookies in the response based on a new JWT token and a new user model. - - :param new_user: User model for the JWT token - :param secure: HTTP secure property for cookies - :param response: FastAPI response object to set the cookies on - :param cookie_path: Path for cookies in the response - """ - if cookie_path is None: + @staticmethod + def build_cookie_headers( + request: Request, new_token: str, extra_cookies: dict[str, str] + ) -> tuple[str, list[str]]: + """ + Return the ``Set-Cookie`` value of the token and those clearing stale token cookies. + + Any cookies with a nil value ("") will be cleared with Max-Age=0 + + :param request: FastAPI Request + :param new_token: New Airflow JWT token + :param extra_cookies: Additional cookie values to set + """ cookie_path = get_cookie_path() - if new_user: - # If we created a new user, serialize it and set it as a cookie - new_token = get_auth_manager().generate_jwt(new_user) - else: - new_token = "" - response.set_cookie( - COOKIE_NAME_JWT_TOKEN, - new_token, - path=cookie_path, - httponly=True, - secure=secure, - samesite="lax", - max_age=0 if new_token == "" else None, - ) - if new_user: - # Update keycloak token cookies + secure = request_cookie_is_secure(request) + # Only used to render the Set-Cookie header values + response = Response() response.set_cookie( - COOKIE_NAME_ACCESS_TOKEN, - new_user.access_token, + COOKIE_NAME_JWT_TOKEN, + new_token, path=cookie_path, + httponly=True, secure=secure, samesite="lax", - httponly=True, + max_age=0 if new_token == "" else None, ) - if new_user.refresh_token: - response.set_cookie( - COOKIE_NAME_REFRESH_TOKEN, - new_user.refresh_token, - path=cookie_path, + # Clear any stale _token cookie at root path "/". + # Older Airflow instances may have set the cookie there; + # without this, the root-path cookie keeps being sent on + # every request, causing an infinite redirect loop. + if cookie_path != "/": + response.delete_cookie( + key=COOKIE_NAME_JWT_TOKEN, + path="/", + httponly=True, secure=secure, samesite="lax", - httponly=True, ) - else: - # No refresh token + # Add any additional cookies required + for cookie, value in extra_cookies.items(): response.set_cookie( - COOKIE_NAME_REFRESH_TOKEN, - "", + cookie, + value, path=cookie_path, + httponly=True, secure=secure, samesite="lax", - httponly=True, - max_age=0, + max_age=0 if value == "" else None, ) - else: - # User is not populated, clear cookies for login - response.set_cookie( - COOKIE_NAME_ACCESS_TOKEN, - "", - path=cookie_path, - secure=secure, - samesite="lax", - httponly=True, - max_age=0, + token_cookie, *cleanup_cookies = ( + value.decode("latin-1") for key, value in response.raw_headers if key == b"set-cookie" ) - response.set_cookie( - COOKIE_NAME_REFRESH_TOKEN, - "", - path=cookie_path, - secure=secure, - samesite="lax", - httponly=True, - max_age=0, + return token_cookie, cleanup_cookies + + @staticmethod + @abstractmethod + def get_extra_cookies(request: Request, new_user: BaseUser | None) -> dict[str, str]: + """ + Get extra cookies from the request context to set in a new token response. + + Setting a cookie to "" will cause it to be cleared by build_cookie_headers(). A cookie with the + same name and path set by the route itself takes precedence over the one returned here. + """ + ... + + @staticmethod + @abstractmethod + async def generate_new_user_token(request: Request, new_user: BaseUser | None) -> str: + """Generate a new Airflow JWT token from the user model.""" + ... + + @staticmethod + @abstractmethod + async def refresh_user(request: Request) -> tuple[BaseUser | None, BaseUser | None]: + """ + Refresh the logged in user using the current JWT Token. + + If the user is not authenticated, return ``None, None`` + + :param request: FastAPI Request + """ + ... + + +# The core route that revokes the Airflow JWT sent with the request, relative to the root path. +LOGOUT_PATH = "/api/v2/auth/logout" + + +class KeycloakJWTMiddleware(JWTRefreshMiddleware): + """ + 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. + """ + + @staticmethod + def get_extra_cookies(request: Request, new_user: BaseUser | None) -> dict[str, str]: + is_logout = KeycloakJWTMiddleware._is_logout(request) + if new_user and not is_logout: # Don't issue a new token on logout + user = cast("KeycloakAuthManagerUser", new_user) + return { + COOKIE_NAME_ACCESS_TOKEN: user.access_token, + COOKIE_NAME_REFRESH_TOKEN: user.refresh_token or "", + } + if not is_logout: # Clear invalid JWT + KeycloakJWTMiddleware._drop_cookie(request, COOKIE_NAME_JWT_TOKEN) + return {COOKIE_NAME_ACCESS_TOKEN: "", COOKIE_NAME_REFRESH_TOKEN: ""} + + @staticmethod + async def refresh_user(request: Request): + user = None + jwt_token = request.cookies.get(COOKIE_NAME_JWT_TOKEN, "") + access_token = request.cookies.get(COOKIE_NAME_ACCESS_TOKEN) + if not jwt_token: + # User is not logged into Airflow. + return None, None + if not access_token: + raise HTTPException( + status_code=status.HTTP_401_UNAUTHORIZED, detail="User is not logged into Keycloak." ) - # Clear any stale _token cookie at root path "/". - # Older Airflow instances may have set the cookie there; - # without this, the root-path cookie keeps being sent on - # every request, causing an infinite redirect loop. - if cookie_path != "/": - response.set_cookie( - key=COOKIE_NAME_JWT_TOKEN, - path="/", - httponly=True, - secure=secure, - samesite="lax", - max_age=0, + try: + refresh_token = request.cookies.get(COOKIE_NAME_REFRESH_TOKEN) + auth_manager = cast("KeycloakAuthManager", get_auth_manager()) + base_user = cast( + "KeycloakAuthManagerUser", + await auth_manager.get_user_from_token(jwt_token, should_return_user=True), ) - return response + user = KeycloakAuthManager._attach_keycloak_tokens(base_user, access_token, refresh_token) + except ExpiredSignatureError: + raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Token Expired") + except InvalidTokenError: + raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Invalid JWT token") + if KeycloakJWTMiddleware._is_logout(request): + # On logout return a the user as new_user without refreshing to allow the Keycloak + # Cookies to be cleared by get_extra_cookies(). Review Comment: nit: typo ("return a the user") ```suggestion # On logout, return the user as `new_user` without refreshing it, so that # get_extra_cookies() clears the Keycloak cookies. ``` ########## providers/keycloak/tests/unit/keycloak/auth_manager/test_middleware.py: ########## @@ -561,42 +766,45 @@ def client(self, token_validator, revoke_token): ): auth_manager = KeycloakAuthManager() - app = FastAPI() + app, _ = _build_app() Review Comment: Why not `init_middlewares(app)` anymore? `_build_app()` only installs `KeycloakJWTMiddleware`, so this class no longer tests the middlewares as the API server installs them: core `JWTRefreshMiddleware` behind it on 3.3 and 3.4.0, and `get_jwt_refresh_middleware()` plus `get_fastapi_middlewares()` on 3.4.1+. ########## providers/keycloak/tests/unit/keycloak/auth_manager/test_middleware.py: ########## @@ -40,488 +42,699 @@ COOKIE_NAME_REFRESH_TOKEN, ) from airflow.providers.keycloak.auth_manager.keycloak_auth_manager import KeycloakAuthManager -from airflow.providers.keycloak.auth_manager.middleware import KeycloakJWTMiddleware from airflow.providers.keycloak.auth_manager.user import KeycloakAuthManagerUser from tests_common.test_utils.config import conf_vars -from tests_common.test_utils.version_compat import AIRFLOW_V_3_1_7_PLUS, AIRFLOW_V_3_3_PLUS +from tests_common.test_utils.version_compat import AIRFLOW_V_3_3_PLUS +from unit.keycloak.test_utils import keycloak_token, token_with_payload -if AIRFLOW_V_3_1_7_PLUS: - from airflow.api_fastapi.auth.managers.exceptions import AuthManagerRefreshTokenExpiredException -else: - AuthManagerRefreshTokenExpiredException = None # type: ignore[assignment,misc] +MODULE = "airflow.providers.keycloak.auth_manager.middleware" +_default_cookies = [ + "_token=issued_token; HttpOnly; Path=/; SameSite=lax", + "_access_token=issued_access_token; HttpOnly; Path=/; SameSite=lax", + "_refresh_token=issued_refresh_token; HttpOnly; Path=/; SameSite=lax", +] -def pytest_generate_tests(metafunc): - if "secure" in metafunc.fixturenames: - metafunc.parametrize("secure", [True, False], indirect=True) - - [email protected] -class TestKeycloakJWTMiddleware: - @pytest.fixture - def middleware(self): - return KeycloakJWTMiddleware(app=Mock(name="app")) - - @pytest.fixture - def mock_request(self, secure): - request = MagicMock(spec=Request, name="request") - request.base_url.scheme = "https" if secure else "http" - request.cookies = {} - request.headers = {} - request.scope = {"type": "http", "path": "/", "headers": []} - request.state = MagicMock(name="state", spec=[]) - request.state.user = None - del request.state.user_authenticated_via - return request - - @pytest.fixture - def mock_user(self): - user = Mock(name="user", spec=KeycloakAuthManagerUser) - user.user_id = "user_id" - user.name = "name" - user.access_token = "access_token" - user.refresh_token = "refresh_token" - return user - - @pytest.fixture - def call_next(self): - return AsyncMock(return_value=Mock(name="response"), name="call_next") - - @pytest.fixture - def auth_manager(self): - return Mock(name="auth_manager") - - @pytest.fixture - def secure(self, request): - return request.param - - @patch("airflow.providers.keycloak.auth_manager.middleware.get_auth_manager") - async def test_get_keycloak_tokens_from_cookies( - self, mock_get_auth_manager, auth_manager, call_next, mock_request, middleware, mock_user - ): - auth_manager.get_user_from_token = AsyncMock(return_value=mock_user) - auth_manager.refresh_user.return_value = None - mock_get_auth_manager.return_value = auth_manager - - mock_request.cookies = { - COOKIE_NAME_JWT_TOKEN: "token", - COOKIE_NAME_ACCESS_TOKEN: "access_token", - COOKIE_NAME_REFRESH_TOKEN: "refresh_token", - } - - await middleware.dispatch(mock_request, call_next) - - assert mock_request.state.user is mock_user - assert mock_request.state.user.access_token == "access_token" - assert mock_request.state.user.refresh_token == "refresh_token" - - trusted_marker = getattr( - core_api_security, - "USER_INJECTED_BY_TRUSTED_MIDDLEWARE", - None, - ) - - if trusted_marker is not None: - assert mock_request.state.user_authenticated_via is trusted_marker - else: - assert not hasattr(mock_request.state, "user_authenticated_via") - - auth_manager.get_user_from_token.assert_called_once_with("token", "access_token", "refresh_token") - auth_manager.refresh_user.assert_called_once_with(user=mock_user) - call_next.assert_awaited_once_with(mock_request) - - @patch("airflow.providers.keycloak.auth_manager.middleware.get_auth_manager") - async def test_refresh_keycloak_token( - self, - mock_get_auth_manager, - auth_manager, - call_next, - mock_request, - middleware, - mock_user, - secure, - ): - new_user = Mock(name="user", spec=KeycloakAuthManagerUser) - new_user.access_token = "new_access_token" - new_user.refresh_token = "new_refresh_token" - auth_manager.get_user_from_token = AsyncMock(return_value=mock_user) - auth_manager.refresh_user = Mock(return_value=new_user) - auth_manager.generate_jwt.return_value = "new_token" - mock_get_auth_manager.return_value = auth_manager - - mock_request.cookies = { - COOKIE_NAME_JWT_TOKEN: "token", - COOKIE_NAME_ACCESS_TOKEN: "access_token", - COOKIE_NAME_REFRESH_TOKEN: "refresh_token", - } - - response = await middleware.dispatch(mock_request, call_next) - - assert mock_request.state.user is new_user - assert mock_request.state.user.access_token == "new_access_token" - assert mock_request.state.user.refresh_token == "new_refresh_token" - response.set_cookie.assert_any_call( +def _get_browser_cookies(response) -> dict[tuple[str, str], str | None]: + """Apply the ``Set-Cookie`` headers in order like a browser, keyed on name and path; ``None`` is cleared.""" + cookies: dict[tuple[str, str], str | None] = {} + for header in response.headers.get_list("set-cookie"): + for name, morsel in SimpleCookie(header).items(): + cookies[(name, morsel["path"])] = None if morsel["max-age"] == "0" else morsel.value + return cookies + + +def _build_app(static_dir=None) -> tuple[FastAPI, dict]: + """Return an app wrapped by the middleware and a dict capturing what the endpoint saw.""" + from airflow.api_fastapi.app import get_cookie_path + from airflow.api_fastapi.core_api.routes.public.auth import auth_router + from airflow.api_fastapi.core_api.security import get_user + from airflow.providers.keycloak.auth_manager.middleware import KeycloakJWTMiddleware + + seen: dict = {} + app = FastAPI() + cookie_path = get_cookie_path() + + @app.get("/user") + def read_user(user=Depends(get_user)): + return {"name": user.get_name()} + + @app.get("/api/v2/dags") + def dags(request: Request): + seen["user"] = getattr(request.state, "user", None) + seen["authenticated_via"] = getattr(request.state, "user_authenticated_via", None) + return PlainTextResponse("ok") + + @app.get("/api/v2/monitor/health") + def health(): + return PlainTextResponse("healthy") + + @app.get("/api/v2/version") + def version(): + return PlainTextResponse("3.x") + + @app.get("/auth/login_callback") + def login_callback(): + response = PlainTextResponse("logged in") + response.set_cookie( COOKIE_NAME_JWT_TOKEN, - "new_token", - path="/", - secure=secure, - samesite="lax", + "issued_token", + path=cookie_path, httponly=True, - max_age=None, + samesite="lax", ) - response.set_cookie.assert_any_call( + response.set_cookie( COOKIE_NAME_ACCESS_TOKEN, - "new_access_token", - path="/", - samesite="lax", - secure=secure, + "issued_access_token", + path=cookie_path, httponly=True, + samesite="lax", ) - response.set_cookie.assert_any_call( + response.set_cookie( COOKIE_NAME_REFRESH_TOKEN, - "new_refresh_token", - path="/", - samesite="lax", - secure=secure, + "issued_refresh_token", + path=cookie_path, httponly=True, + samesite="lax", ) + return response - trusted_marker = getattr( - core_api_security, - "USER_INJECTED_BY_TRUSTED_MIDDLEWARE", - None, - ) + @app.get("/api/v2/stream") + def stream(): + return StreamingResponse(iter([b"chunk1-", b"chunk2-", b"chunk3"]), media_type="text/plain") - if trusted_marker is not None: - assert mock_request.state.user_authenticated_via is trusted_marker - else: - assert not hasattr(mock_request.state, "user_authenticated_via") + if static_dir is not None: + app.mount("/static", StaticFiles(directory=static_dir), name="webapp_static_folder") - # Once to resolve the user, once more after the endpoint ran to confirm the - # token is still accepted before a replacement is issued. - assert auth_manager.get_user_from_token.await_args_list == [ - call("token", "access_token", "refresh_token"), - call("token", "access_token", "refresh_token"), - ] - auth_manager.refresh_user.assert_called_once_with(user=mock_user) - auth_manager.generate_jwt.assert_called_once_with(new_user) - call_next.assert_awaited_once_with(mock_request) + app.include_router(auth_router, prefix="/api/v2") + app.add_middleware(KeycloakJWTMiddleware, skip_path_prefixes=("/static/",)) + return app, seen - @patch("airflow.providers.keycloak.auth_manager.middleware.get_auth_manager") - async def test_no_new_token_when_jwt_revoked_during_request( - self, - mock_get_auth_manager, - auth_manager, - call_next, - mock_request, - middleware, - mock_user, - secure, - ): - """ - When the endpoint revokes the token the request came with (the logout route does), - a refreshed session must not be turned into a new JWT; the session cookies are cleared. - """ - new_user = Mock(name="user", spec=KeycloakAuthManagerUser) - new_user.access_token = "new_access_token" - new_user.refresh_token = "new_refresh_token" - auth_manager.get_user_from_token = AsyncMock(return_value=mock_user) - auth_manager.refresh_user = Mock(return_value=new_user) - auth_manager.generate_jwt.return_value = "new_token" - mock_get_auth_manager.return_value = auth_manager - mock_request.cookies = { - COOKIE_NAME_JWT_TOKEN: "token", - COOKIE_NAME_ACCESS_TOKEN: "access_token", - COOKIE_NAME_REFRESH_TOKEN: "refresh_token", - } - - async def logout_endpoint(request): - # The endpoint revokes the presented token, so it is rejected from now on. - auth_manager.get_user_from_token.side_effect = InvalidTokenError("Token has been revoked") - return Mock(name="response") - - call_next.side_effect = logout_endpoint +def _build_user(user_id: str, name: str, access_token: str, refresh_token: str): + user = KeycloakAuthManagerUser(user_id=user_id, name=name, access_token="", refresh_token=None) + if not KeycloakAuthManager._middleware_handles_cookies(): + user.access_token = access_token + user.refresh_token = refresh_token + return user - response = await middleware.dispatch(mock_request, call_next) - auth_manager.generate_jwt.assert_not_called() - for cookie_name in (COOKIE_NAME_JWT_TOKEN, COOKIE_NAME_ACCESS_TOKEN, COOKIE_NAME_REFRESH_TOKEN): - assert any( - c.args[0] == cookie_name and c.args[1] == "" and c.kwargs.get("max_age") == 0 - for c in response.set_cookie.call_args_list - ), f"{cookie_name} cookie was not cleared" - issued_values = {c.args[1] for c in response.set_cookie.call_args_list if len(c.args) > 1} - assert issued_values.isdisjoint({"new_token", "new_access_token", "new_refresh_token"}) - - @patch("airflow.providers.keycloak.auth_manager.middleware.get_auth_manager") - async def test_new_token_when_jwt_expired_during_request( - self, - mock_get_auth_manager, - auth_manager, - call_next, - mock_request, - middleware, - mock_user, - secure, - ): - """A token that merely expired while the request was handled is still replaced.""" - new_user = Mock(name="user", spec=KeycloakAuthManagerUser) - new_user.access_token = "new_access_token" - new_user.refresh_token = "new_refresh_token" - auth_manager.get_user_from_token = AsyncMock(side_effect=[mock_user, ExpiredSignatureError()]) - auth_manager.refresh_user = Mock(return_value=new_user) - auth_manager.generate_jwt.return_value = "new_token" - mock_get_auth_manager.return_value = auth_manager - - mock_request.cookies = { - COOKIE_NAME_JWT_TOKEN: "token", - COOKIE_NAME_ACCESS_TOKEN: "access_token", - COOKIE_NAME_REFRESH_TOKEN: "refresh_token", [email protected](autouse=True) +def keycloak_config(): + with conf_vars( + { + ("api", "ssl_cert"): "", + (CONF_SECTION_NAME, CONF_CLIENT_ID_KEY): "client_id", + (CONF_SECTION_NAME, CONF_CLIENT_SECRET_KEY): "client_secret", + (CONF_SECTION_NAME, CONF_REALM_KEY): "realm", + (CONF_SECTION_NAME, CONF_SERVER_URL_KEY): "server_url", } + ): + yield + + [email protected] +def token_validator(): + token_validator = Mock(spec=JWTValidator) + token_validator.avalidated_claims.return_value = {"user_id": "user_id", "name": "name"} + token_validator.revoke_token.return_value = None + return token_validator + + [email protected](autouse=True) +def mock_get_auth_manager(): + """Patch get_auth_manager() to always return a KeycloakAuthManager instance.""" + auth_manager = KeycloakAuthManager() + get_auth_manager = create_autospec(api_fastapi_app.get_auth_manager, return_value=auth_manager) + with ( + patch("airflow.api_fastapi.app.get_auth_manager", get_auth_manager), + patch("airflow.api_fastapi.auth.middlewares.refresh_token.get_auth_manager", get_auth_manager), + patch("airflow.api_fastapi.core_api.security.get_auth_manager", get_auth_manager), + patch(f"{MODULE}.get_auth_manager", get_auth_manager), + ): + yield get_auth_manager + + [email protected] +def mock_auth_manager(mock_get_auth_manager, token_validator): + """Replaces the KeycloakAuthManager from get_auth_manager() with a mock.""" + mock_auth_manager = MagicMock(spec=KeycloakAuthManager) + mock_auth_manager.refresh_user.return_value = None + mock_user = _build_user( + user_id="user_id", + name="name", + access_token=keycloak_token("user_id"), + refresh_token="refresh_token", + ) + mock_auth_manager.get_user_from_token = AsyncMock(return_value=mock_user) + mock_auth_manager.generate_jwt.return_value = "new_token" + mock_auth_manager._token_subject = KeycloakAuthManager._token_subject + mock_auth_manager._token_expired = KeycloakAuthManager._token_expired + mock_auth_manager._get_token_validator.return_value = token_validator + mock_get_auth_manager.return_value = mock_auth_manager + return mock_auth_manager + + [email protected] +def mock_get_cookie_path(): + cookie_path = "/team-a/" + with ( + patch(f"{MODULE}.get_cookie_path", return_value=cookie_path), + patch("airflow.api_fastapi.auth.middlewares.refresh_token.get_cookie_path", return_value=cookie_path), + patch("airflow.api_fastapi.app.get_cookie_path", return_value=cookie_path), + ): + yield - response = await middleware.dispatch(mock_request, call_next) - auth_manager.generate_jwt.assert_called_once_with(new_user) - response.set_cookie.assert_any_call( - COOKIE_NAME_JWT_TOKEN, - "new_token", - path="/", - secure=secure, - samesite="lax", - httponly=True, - max_age=None, - ) [email protected]( + not AIRFLOW_V_3_3_PLUS, reason="KeycloakJWTMiddleware relies on custom middleware interface." +) +class TestKeycloakJWTMiddleware: + def test_no_token(self, mock_auth_manager): + app, _ = _build_app() - @patch("airflow.providers.keycloak.auth_manager.middleware.get_auth_manager") - async def test_no_keycloak_token( - self, mock_get_auth_manager, auth_manager, call_next, middleware, mock_request, secure - ): - mock_get_auth_manager.return_value = auth_manager + response = TestClient(app, cookies={}).get("/api/v2/dags") - mock_request.cookies = {COOKIE_NAME_JWT_TOKEN: "token"} + assert response.status_code == 200 + assert "set-cookie" not in response.headers + mock_auth_manager.get_user_from_token.assert_not_called() - response = await middleware.dispatch(mock_request, call_next) + def test_invalid_token_clears_cookie(self, mock_auth_manager): + mock_auth_manager.get_user_from_token.side_effect = HTTPException( + status_code=403, detail="Invalid JWT token" + ) + app, seen = _build_app() - auth_manager.get_user_from_token.assert_not_called() - auth_manager.refresh_user.assert_not_called() + response = TestClient(app, cookies={COOKIE_NAME_JWT_TOKEN: "invalid_token"}).get("/api/v2/dags") - assert mock_request.state.user is None + assert response.status_code == 200 + assert seen["user"] is None + assert '_token=""; HttpOnly; Max-Age=0; Path=/; SameSite=lax' in response.headers["set-cookie"] + mock_auth_manager.refresh_user.assert_not_called() + + def test_no_refreshed_user(self, mock_auth_manager): + access_token = keycloak_token("user_id") + mock_auth_manager.refresh_user.return_value = None + app, seen = _build_app() + + response = TestClient( + app, + cookies={ + COOKIE_NAME_JWT_TOKEN: "valid_token", + COOKIE_NAME_ACCESS_TOKEN: access_token, + COOKIE_NAME_REFRESH_TOKEN: "refresh_token", + }, + ).get("/api/v2/dags") trusted_marker = getattr( core_api_security, "USER_INJECTED_BY_TRUSTED_MIDDLEWARE", None, ) - if trusted_marker is not None: - assert getattr(mock_request.state, "user_authenticated_via", None) is not trusted_marker - else: - assert not hasattr(mock_request.state, "user_authenticated_via") - - call_next.assert_awaited_with(mock_request) + assert "set-cookie" not in response.headers + assert seen["user"] is mock_auth_manager.get_user_from_token.return_value + assert seen["authenticated_via"] is trusted_marker + mock_auth_manager.get_user_from_token.assert_called_once_with("valid_token", should_return_user=True) + mock_auth_manager.generate_jwt.assert_not_called() - response.set_cookie.assert_any_call( - COOKIE_NAME_JWT_TOKEN, - "", - path="/", - secure=secure, - httponly=True, - samesite="lax", - max_age=0, + def test_refreshed_user(self, mock_auth_manager): + access_token = keycloak_token("user_id") + current_user = _build_user( + user_id="user_id", name="name", access_token=access_token, refresh_token="refresh_token" ) - - @patch("airflow.providers.keycloak.auth_manager.middleware.get_auth_manager") - async def test_no_airflow_jwt_token( - self, mock_get_auth_manager, auth_manager, call_next, middleware, mock_request - ): - mock_get_auth_manager.return_value = auth_manager - - mock_request.cookies = { - COOKIE_NAME_ACCESS_TOKEN: "access_token", - COOKIE_NAME_REFRESH_TOKEN: "refresh_token", - } - - response = await middleware.dispatch(mock_request, call_next) - - auth_manager.get_user_from_token.assert_not_called() - auth_manager.refresh_user.assert_not_called() - - assert mock_request.state.user is None + refreshed_user = KeycloakAuthManagerUser( + user_id="user_id", name="name", access_token=access_token, refresh_token="new_refresh_token" + ) + mock_auth_manager.refresh_user.return_value = refreshed_user + mock_auth_manager.get_user_from_token.side_effect = [current_user, ExpiredSignatureError] + app, seen = _build_app() + + response = TestClient( + app, + cookies={ + COOKIE_NAME_JWT_TOKEN: "valid_token", + COOKIE_NAME_ACCESS_TOKEN: access_token, + COOKIE_NAME_REFRESH_TOKEN: "refresh_token", + }, + ).get("/api/v2/dags") trusted_marker = getattr( core_api_security, "USER_INJECTED_BY_TRUSTED_MIDDLEWARE", None, ) - if trusted_marker is not None: - assert getattr(mock_request.state, "user_authenticated_via", None) is not trusted_marker - else: - assert not hasattr(mock_request.state, "user_authenticated_via") + assert seen["user"] is refreshed_user + assert seen["authenticated_via"] is trusted_marker + mock_auth_manager.refresh_user.assert_called_once_with(user=current_user) + mock_auth_manager.generate_jwt.assert_called_once_with(refreshed_user) + assert ( + response.headers["set-cookie"] + == f"_token=new_token; HttpOnly; Path=/; SameSite=lax, _access_token={access_token}; HttpOnly; Path=/; SameSite=lax, _refresh_token=new_refresh_token; HttpOnly; Path=/; SameSite=lax" + ) - call_next.assert_awaited_once_with(mock_request) - response.set_cookie.assert_not_called() + def test_invalid_token_does_not_clear_token_set_by_route(self, mock_auth_manager): + mock_auth_manager.get_user_from_token.side_effect = HTTPException( + status_code=403, detail="Invalid JWT token" + ) + app, _ = _build_app() - @patch("airflow.providers.keycloak.auth_manager.middleware.get_auth_manager") - @pytest.mark.asyncio - async def test_dispatch_expired_token( - self, - mock_get_auth_manager, - auth_manager, - call_next, - middleware, - mock_request, - secure, - ): - mock_get_auth_manager.return_value = auth_manager - mock_request.cookies = { - COOKIE_NAME_JWT_TOKEN: "invalid_token", - COOKIE_NAME_ACCESS_TOKEN: "access_token", - COOKIE_NAME_REFRESH_TOKEN: "refresh_token", - } - auth_manager.get_user_from_token.side_effect = InvalidTokenError() + response = TestClient(app, cookies={COOKIE_NAME_JWT_TOKEN: "stale_token"}).get("/auth/login_callback") - response = await middleware.dispatch(mock_request, call_next) + assert response.headers.get_list("set-cookie") == [ + '_access_token=""; HttpOnly; Max-Age=0; Path=/; SameSite=lax', + '_refresh_token=""; HttpOnly; Max-Age=0; Path=/; SameSite=lax', + *_default_cookies, + ] - call_next.assert_called_once_with(mock_request) - auth_manager.get_user_from_token.assert_called_once_with( - "invalid_token", "access_token", "refresh_token" + def test_refreshed_token_does_not_override_logout(self, mock_auth_manager): + access_token = keycloak_token("user_id") + mock_auth_manager.refresh_user.return_value = KeycloakAuthManagerUser( + user_id="user_id", + name="name", + access_token=access_token, + refresh_token="new_refresh_token", ) - - response.set_cookie.assert_any_call( - COOKIE_NAME_JWT_TOKEN, - "", - path="/", - secure=secure, - httponly=True, - samesite="lax", - max_age=0, + mock_auth_manager.generate_jwt.return_value = "new_token" + app, _ = _build_app() + app.state.auth_manager = mock_auth_manager + + response = TestClient( + app, + cookies={ + COOKIE_NAME_JWT_TOKEN: "valid_token", + COOKIE_NAME_ACCESS_TOKEN: access_token, + COOKIE_NAME_REFRESH_TOKEN: "refresh_token", + }, + ).get("/api/v2/auth/logout", follow_redirects=False) + + assert _get_browser_cookies(response) == { + (COOKIE_NAME_JWT_TOKEN, "/"): None, + (COOKIE_NAME_ACCESS_TOKEN, "/"): None, + (COOKIE_NAME_REFRESH_TOKEN, "/"): None, + } + # Clients that don't apply Set-Cookie headers in order must not pick up a token minted during logout + assert all( + not any(refreshed_token in header for header in response.headers.get_list("set-cookie")) + for refreshed_token in ["new_token", "new_refresh_token", access_token] ) - @patch("airflow.providers.keycloak.auth_manager.middleware.get_auth_manager") - @pytest.mark.asyncio - async def test_dispatch_expired_keycloak_token( - self, - mock_get_auth_manager, - auth_manager, - call_next, - middleware, - mock_request, - mock_user, - secure, - ): - mock_get_auth_manager.return_value = auth_manager - mock_request.cookies = { - COOKIE_NAME_JWT_TOKEN: "token", - COOKIE_NAME_ACCESS_TOKEN: "expired_token", - COOKIE_NAME_REFRESH_TOKEN: "refresh_token", - } - mock_user.access_token = "expired_token" - mock_user.refresh_token = "refresh_token" - auth_manager.get_user_from_token = AsyncMock(return_value=mock_user) - if AIRFLOW_V_3_1_7_PLUS: - auth_manager.refresh_user.side_effect = AuthManagerRefreshTokenExpiredException() - else: - auth_manager.refresh_user.return_value = None + def test_root_cookie_cleared_when_route_sets_token(self, mock_get_cookie_path, mock_auth_manager): + mock_auth_manager.get_user_from_token.side_effect = InvalidTokenError + app, _ = _build_app() + app.state.auth_manager = mock_auth_manager - response = await middleware.dispatch(mock_request, call_next) + response = TestClient(app, cookies={COOKIE_NAME_JWT_TOKEN: "stale_token"}).get("/auth/login_callback") - call_next.assert_called_once_with(mock_request) - auth_manager.get_user_from_token.assert_called_once_with("token", "expired_token", "refresh_token") - auth_manager.refresh_user.assert_called_once_with(user=mock_user) + assert _get_browser_cookies(response) == { + (COOKIE_NAME_JWT_TOKEN, "/"): None, + (COOKIE_NAME_JWT_TOKEN, "/team-a/"): "issued_token", + (COOKIE_NAME_ACCESS_TOKEN, "/team-a/"): "issued_access_token", + (COOKIE_NAME_REFRESH_TOKEN, "/team-a/"): "issued_refresh_token", + } - if AIRFLOW_V_3_1_7_PLUS: - response.set_cookie.assert_any_call( - COOKIE_NAME_JWT_TOKEN, - "", - path="/", - secure=secure, - httponly=True, - samesite="lax", - max_age=0, - ) - auth_manager.generate_jwt.assert_not_called() + @patch(f"{MODULE}.KeycloakAuthManager._attach_keycloak_tokens") + def test_refresh_user_runs_off_the_event_loop(self, _mock_attach_tokens, mock_auth_manager): + """``refresh_user`` is synchronous and may do blocking I/O, so it must not block the loop.""" + refresh_threads = [] + mock_auth_manager.refresh_user.side_effect = lambda user: refresh_threads.append( + threading.get_ident() + ) + loop_threads = [] + mock_auth_manager.get_user_from_token.side_effect = lambda token, should_return_user: ( + loop_threads.append(threading.get_ident()) + ) + app, _ = _build_app() + + TestClient( + app, + cookies={ + COOKIE_NAME_JWT_TOKEN: "valid_token", + COOKIE_NAME_ACCESS_TOKEN: "access_token", + COOKIE_NAME_REFRESH_TOKEN: "refresh_token", + }, + ).get("/api/v2/dags") + + assert len(refresh_threads) == 1 + assert refresh_threads != loop_threads + + def test_streaming_response_passthrough(self, mock_auth_manager): + mock_auth_manager.refresh_user.return_value = KeycloakAuthManagerUser( + user_id="user_id", + name="name", + access_token=keycloak_token("user_id"), + refresh_token="refresh_token", + ) + mock_auth_manager.generate_jwt.return_value = "new_token" + app, _ = _build_app() + + response = TestClient( + app, + cookies={ + COOKIE_NAME_JWT_TOKEN: "valid_token", + COOKIE_NAME_ACCESS_TOKEN: keycloak_token("user_id"), + COOKIE_NAME_REFRESH_TOKEN: "refresh_token", + }, + ).get("/api/v2/stream") + + assert response.content == b"chunk1-chunk2-chunk3" + assert response.headers["content-type"].startswith("text/plain") + assert "_token=new_token" in response.headers["set-cookie"] + + def test_http_exception_from_inner_app_returned_as_response(self, mock_get_auth_manager): + from airflow.providers.keycloak.auth_manager.middleware import KeycloakJWTMiddleware + + mock_get_auth_manager.return_value = KeycloakAuthManager() + + async def raising_app(scope, receive, send): + raise HTTPException(status_code=418, detail="teapot") + + app = KeycloakJWTMiddleware(raising_app) + + response = TestClient( + app, + cookies={ + COOKIE_NAME_JWT_TOKEN: "valid_token", + COOKIE_NAME_ACCESS_TOKEN: "access_token", + COOKIE_NAME_REFRESH_TOKEN: "refresh_token", + }, + ).get("/api/v2/dags") + + assert response.status_code == 418 + assert response.json() == {"detail": "teapot"} + + @pytest.mark.parametrize("root_path", ["", "/team-a"]) + @pytest.mark.parametrize("path", ["/api/v2/monitor/health", "/api/v2/version", "/static/main.js"]) + def test_skipped_paths(self, mock_auth_manager, tmp_path, path, root_path): + """Static assets and unauthenticated endpoints never decode the JWT or hit the DB.""" + (tmp_path / "main.js").write_text("console.log('hi');") + app, _ = _build_app(static_dir=tmp_path) + client = TestClient( + app, + root_path=root_path, + cookies={ + COOKIE_NAME_JWT_TOKEN: "valid_token", + COOKIE_NAME_ACCESS_TOKEN: "access_token", + COOKIE_NAME_REFRESH_TOKEN: "refresh_token", + }, + ) - @patch("airflow.providers.keycloak.auth_manager.middleware.get_auth_manager") - async def test_dispatch_does_not_clear_fresh_token_set_by_endpoint( - self, - mock_get_auth_manager, - auth_manager, - call_next, - middleware, - mock_request, - mock_user, - ): - """ - An expired token on the request must not clear the cookie when the endpoint - set a fresh one on the response (e.g. the login callback exchanging the - authorization code while an expired token is still in the cookie jar). - """ - mock_get_auth_manager.return_value = auth_manager - mock_request.cookies = { - COOKIE_NAME_JWT_TOKEN: "expired", - COOKIE_NAME_ACCESS_TOKEN: "expired_token", - COOKIE_NAME_REFRESH_TOKEN: "refresh_token", - } - auth_manager.get_user_from_token = AsyncMock(side_effect=InvalidTokenError()) + response = client.get(f"{root_path}{path}") - async def call_endpoint(request): - # The endpoint (login callback) mints a fresh JWT and signals it - request.state.jwt_token_issued = True - return Mock(name="response") + assert response.status_code == 200 + assert "set-cookie" not in response.headers + mock_auth_manager.get_user_from_token.assert_not_called() + mock_auth_manager.refresh_user.assert_not_called() + + @pytest.mark.parametrize( + ("headers", "expected_status", "expected_body"), + [ + pytest.param({}, 200, b"0123456789", id="full"), + pytest.param({"range": "bytes=2-4"}, 206, b"234", id="range"), + ], + ) + def test_static_files_served_unchanged(self, tmp_path, headers, expected_status, expected_body): + (tmp_path / "main.js").write_bytes(b"0123456789") + app, _ = _build_app(static_dir=tmp_path) + client = TestClient( + app, + cookies={ + COOKIE_NAME_JWT_TOKEN: "valid_token", + COOKIE_NAME_ACCESS_TOKEN: "access_token", + COOKIE_NAME_REFRESH_TOKEN: "refresh_token", + }, + ) - call_next.side_effect = call_endpoint + response = client.get("/static/main.js", headers=headers) + + assert response.status_code == expected_status + assert response.content == expected_body + assert "etag" in response.headers + assert "last-modified" in response.headers + revalidated = client.get("/static/main.js", headers={"if-none-match": response.headers["etag"]}) + assert revalidated.status_code == 304 + + @pytest.mark.parametrize( + ("scheme", "ssl_cert", "expected_secure"), + [ + pytest.param("https", "", True, id="https-no-local-ssl-cert"), + pytest.param("http", "/etc/ssl/cert.pem", True, id="http-with-local-ssl-cert"), + pytest.param("https", "/etc/ssl/cert.pem", True, id="https-with-local-ssl-cert"), + pytest.param("http", "", False, id="http-no-local-ssl-cert"), + ], + ) + def test_cookie_secure_flag(self, mock_auth_manager, scheme, ssl_cert, expected_secure): + """The cookie Secure flag must follow the request scheme as well as the local ssl_cert.""" + mock_auth_manager.refresh_user.return_value = KeycloakAuthManagerUser( + user_id="user_id", + name="name", + access_token=keycloak_token("user_id"), + refresh_token="new_refresh_token", + ) + mock_auth_manager.generate_jwt.return_value = "new_token" + with conf_vars({("api", "ssl_cert"): ssl_cert}): + app, _ = _build_app() + client = TestClient( + app, + base_url=f"{scheme}://testserver", + cookies={ + COOKIE_NAME_JWT_TOKEN: "valid_token", + COOKIE_NAME_ACCESS_TOKEN: "access_token", + COOKIE_NAME_REFRESH_TOKEN: "refresh_token", + }, + ) - response = await middleware.dispatch(mock_request, call_next) + response = client.get("/api/v2/dags") - response.set_cookie.assert_not_called() + assert ("Secure" in response.headers["set-cookie"]) is expected_secure - @patch("airflow.providers.keycloak.auth_manager.middleware.get_cookie_path") - @patch("airflow.providers.keycloak.auth_manager.middleware.get_auth_manager") @pytest.mark.asyncio - async def test_dispatch_invalid_token_clears_root_cookie( + async def test_dispatch_expired_keycloak_token( self, - mock_get_auth_manager, - mock_get_cookie_path, - auth_manager, - call_next, - middleware, - mock_request, - secure, + mock_auth_manager, ): - mock_get_cookie_path.return_value = "/foo/" - mock_get_auth_manager.return_value = auth_manager - auth_manager.get_user_from_token.side_effect = InvalidTokenError() - """When a stale _token exists at root path, clearing must target both the subpath and root.""" - mock_request.cookies = { - COOKIE_NAME_JWT_TOKEN: "stale_root_token", - COOKIE_NAME_ACCESS_TOKEN: "access_token", - COOKIE_NAME_REFRESH_TOKEN: "refresh_token", - } - response = await middleware.dispatch(mock_request, call_next) + from airflow.api_fastapi.auth.managers.exceptions import AuthManagerRefreshTokenExpiredException - # Expect two delete cookies: one at the subpath and one at root "/" - response.set_cookie.assert_any_call( - "_token", "", path="/foo/", secure=secure, samesite="lax", httponly=True, max_age=0 + mock_user = KeycloakAuthManagerUser( + user_id="user_id", name="name", access_token="", refresh_token=None ) - response.set_cookie.assert_any_call( - "_token", "", path="/", secure=secure, samesite="lax", httponly=True, max_age=0 + mock_auth_manager.get_user_from_token = AsyncMock(return_value=mock_user) + mock_auth_manager.refresh_user.side_effect = AuthManagerRefreshTokenExpiredException + + with patch.object(KeycloakAuthManager, "_token_expired", return_value=True): Review Comment: nit: we usually use the decorator (same in a few other new tests) -- 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]
