π OpenHands: AI-Driven Development
fix(auth): don't revoke offline_tokens on bearer-auth failures or bro⦠(#14666)
chuckbutkus0b7ccbace885
diff --git a/enterprise/server/middleware.py b/enterprise/server/middleware.pyindex be7d2e158f..ab28f11c95 100644--- a/enterprise/server/middleware.py+++ b/enterprise/server/middleware.py@@ -78,10 +78,19 @@ class SetAuthCookieMiddleware:)except AuthError as e:logger.warning('auth_error', exc_info=True)- try:- await self._logout(request)- except Exception as logout_error:- logger.debug(str(logout_error))+ # Only attempt a Keycloak logout when this looked like a cookie+ # session going bad. Bearer-token auth failures (e.g., a+ # ``BearerTokenError`` from a transient Keycloak refresh+ # failure) must NOT revoke the user's offline session β that+ # would brick every subsequent API-key call until the user+ # logs back in through the browser. The API key's lifecycle is+ # managed via key mint/delete, not via per-request refresh+ # outcomes. See ``_logout`` for the defense-in-depth check.+ if keycloak_auth_cookie:+ try:+ await self._logout(request)+ except Exception as logout_error:+ logger.debug(str(logout_error))# Send a response that deletes the auth cookie if neededresponse = JSONResponse(@@ -187,10 +196,25 @@ class SetAuthCookieMiddleware:return is_api_route or is_mcpasync def _logout(self, request: Request):- # Log out of keycloak - this prevents issues where you did not log in with the idp you believe you used+ # Log out of keycloak - this prevents issues where you did not log in with the idp you believe you used.+ #+ # IMPORTANT: only terminate the Keycloak session when the request+ # carried a *cookie* (browser session). For bearer-token (API+ # key) requests, ``user_auth.refresh_token`` is the user's stored+ # *offline_token* loaded from ``OfflineTokenStore``. Calling+ # ``token_manager.logout`` with that value asks Keycloak to+ # revoke the offline session, which permanently breaks every API+ # key minted for the user until they re-authenticate through the+ # browser (``/keycloak/callback`` rewrites the offline_token).+ # A single transient Keycloak hiccup that surfaces as+ # ``BearerTokenError`` must not be allowed to cause this damage.try:user_auth = cast(SaasUserAuth, await get_user_auth(request))- if user_auth and user_auth.refresh_token:+ if (+ user_auth+ and user_auth.refresh_token+ and user_auth.auth_type == AuthType.COOKIE+ ):await token_manager.logout(user_auth.refresh_token.get_secret_value())except Exception:logger.debug('Error logging out')diff --git a/enterprise/server/routes/auth.py b/enterprise/server/routes/auth.pyindex 910cb27777..d72964ce35 100644--- a/enterprise/server/routes/auth.py+++ b/enterprise/server/routes/auth.py@@ -70,7 +70,7 @@ from openhands.app_server.integrations.provider import ()from openhands.app_server.integrations.service_types import ProviderType, TokenResponsefrom openhands.app_server.user_auth import get_access_token-from openhands.app_server.user_auth.user_auth import get_user_auth+from openhands.app_server.user_auth.user_auth import AuthType, get_user_authfrom openhands.app_server.utils.logger import openhands_logger as loggerwith warnings.catch_warnings():@@ -1075,10 +1075,25 @@ async def logout(request: Request):samesite=get_cookie_samesite(),)- # Try to properly logout from Keycloak, but don't fail if it doesn't work+ # Try to properly logout from Keycloak, but don't fail if it doesn't work.+ #+ # IMPORTANT: only terminate the Keycloak session when the resolved+ # auth is the *cookie* (browser session). ``get_user_auth`` resolves+ # bearer tokens before cookies, so a request that carries both an+ # ``Authorization: Bearer <api-key>`` header *and* a+ # ``keycloak_auth`` cookie would otherwise have its API-key-bound+ # *offline_token* terminated when the user clicked "logout" in the+ # browser. The browser intent is to drop the cookie session, not to+ # revoke a long-lived API key. The cookie itself is always deleted+ # above; we just must not nuke an offline session that belongs to a+ # different auth surface.try:user_auth = cast(SaasUserAuth, await get_user_auth(request))- if user_auth and user_auth.refresh_token:+ if (+ user_auth+ and user_auth.refresh_token+ and user_auth.auth_type == AuthType.COOKIE+ ):refresh_token = user_auth.refresh_token.get_secret_value()await token_manager.logout(refresh_token)except Exception as e:diff --git a/enterprise/tests/unit/server/routes/test_auth_offline_token.py b/enterprise/tests/unit/server/routes/test_auth_offline_token.pyindex 3c548ace60..80958aa282 100644--- a/enterprise/tests/unit/server/routes/test_auth_offline_token.py+++ b/enterprise/tests/unit/server/routes/test_auth_offline_token.py@@ -28,6 +28,8 @@ from fastapi import Request, statusfrom fastapi.responses import JSONResponse, RedirectResponsefrom server.routes.auth import keycloak_offline_callback, logout+from openhands.app_server.user_auth.user_auth import AuthType+@pytest.fixturedef mock_request():@@ -152,6 +154,11 @@ class TestOfflineTokenSurvivesLogout:logout_request.headers = {}mock_user_auth = MagicMock()+ # The user is logging out via the browser, so the resolved+ # auth is the cookie session β express that explicitly so the+ # logout route's bearer-vs-cookie guard exercises the+ # cookie-auth branch.+ mock_user_auth.auth_type = AuthType.COOKIEmock_user_auth.refresh_token = MagicMock()mock_user_auth.refresh_token.get_secret_value.return_value = (online_refresh_tokendiff --git a/enterprise/tests/unit/test_auth_middleware.py b/enterprise/tests/unit/test_auth_middleware.pyindex 2518fbfa01..240d9ce9a2 100644--- a/enterprise/tests/unit/test_auth_middleware.py+++ b/enterprise/tests/unit/test_auth_middleware.py@@ -7,6 +7,7 @@ from fastapi.responses import JSONResponsefrom pydantic import SecretStrfrom server.auth.auth_error import (AuthError,+ BearerTokenError,CookieError,ExpiredError,NoCredentialsError,@@ -204,6 +205,112 @@ async def test_middleware_with_other_auth_error(middleware, mock_request):mock_logger.warning.assert_called_once()+async def test_middleware_bearer_only_auth_error_does_not_revoke_offline_token(+ middleware, mock_request+):+ """Bearer-only auth failures must not revoke the offline session.++ A bearer-only request whose route handler raises ``BearerTokenError``+ must NOT trigger a Keycloak logout β that would revoke the user's+ offline session and brick every API key minted for them. The cookie+ deletion side effect also must not happen because there was no+ cookie.+ """+ mock_request.cookies = {} # bearer-only: no keycloak_auth cookie+ mock_call_next = AsyncMock(+ side_effect=BearerTokenError('refresh failed transiently')+ )++ with patch.object(middleware, '_logout', new=AsyncMock()) as mock_logout:+ result = await middleware(mock_request, mock_call_next)++ # _logout must not be called for bearer-only failures.+ mock_logout.assert_not_called()++ assert isinstance(result, JSONResponse)+ assert result.status_code == status.HTTP_401_UNAUTHORIZED+ # There was no cookie, so we must not emit a Set-Cookie header.+ assert 'set-cookie' not in result.headers+++async def test_middleware_cookie_auth_error_still_triggers_logout(+ middleware, mock_request+):+ """Cookie-bearing requests that fail auth still log out at Keycloak.++ That's the legitimate cookie-session-going-bad case the middleware+ was designed for, and the new bearer guard must not break it.+ """+ with _mock_jwt_decode():+ mock_request.cookies = {'keycloak_auth': 'test_cookie'}+ mock_call_next = AsyncMock(side_effect=AuthError('General auth error'))++ with patch.object(middleware, '_logout', new=AsyncMock()) as mock_logout:+ result = await middleware(mock_request, mock_call_next)++ mock_logout.assert_awaited_once_with(mock_request)+ assert isinstance(result, JSONResponse)+ assert result.status_code == status.HTTP_401_UNAUTHORIZED+ # Cookie must still be deleted.+ assert 'set-cookie' in result.headers+++async def test_logout_skips_keycloak_for_bearer_auth():+ """``_logout`` must skip Keycloak when the resolved auth is bearer.++ Defense-in-depth: even if ``_logout`` is reached for a bearer-auth+ user (e.g., from a future call site), the offline_token must not be+ revoked. Only ``AuthType.COOKIE`` sessions get logged out at+ Keycloak.+ """+ middleware = SetAuthCookieMiddleware()+ mock_request = MagicMock(spec=Request)+ mock_request.cookies = {}++ bearer_user_auth = MagicMock(spec=SaasUserAuth)+ bearer_user_auth.auth_type = AuthType.BEARER+ bearer_user_auth.refresh_token = SecretStr('the-users-offline-token')++ with patch(+ 'server.middleware.get_user_auth',+ new=AsyncMock(return_value=bearer_user_auth),+ ), patch(+ 'server.middleware.token_manager.logout', new=AsyncMock()+ ) as mock_kc_logout:+ await middleware._logout(mock_request)++ mock_kc_logout.assert_not_called()+++async def test_logout_invokes_keycloak_for_cookie_auth():+ """Cookie auth must still terminate the Keycloak session.++ This is the path the middleware was originally written for; the new+ bearer-vs-cookie guard inside ``_logout`` must not regress it.+ """+ middleware = SetAuthCookieMiddleware()+ mock_request = MagicMock(spec=Request)+ mock_request.cookies = {'keycloak_auth': 'test_cookie'}++ cookie_user_auth = MagicMock(spec=SaasUserAuth)+ cookie_user_auth.auth_type = AuthType.COOKIE+ cookie_user_auth.refresh_token = SecretStr('cookie-refresh-token')++ with patch(+ 'server.middleware.get_user_auth',+ new=AsyncMock(return_value=cookie_user_auth),+ ), patch(+ 'server.middleware.token_manager.logout', new=AsyncMock()+ ) as mock_kc_logout:+ await middleware._logout(mock_request)++ mock_kc_logout.assert_awaited_once_with('cookie-refresh-token')++@pytest.mark.asyncioasync def test_middleware_ignores_email_resend_path(middleware, mock_request, mock_responsediff --git a/enterprise/tests/unit/test_auth_routes.py b/enterprise/tests/unit/test_auth_routes.pyindex a1f8339b62..3b769f16e5 100644--- a/enterprise/tests/unit/test_auth_routes.py+++ b/enterprise/tests/unit/test_auth_routes.py@@ -19,6 +19,7 @@ from server.routes.auth import ()from openhands.app_server.integrations.service_types import ProviderType+from openhands.app_server.user_auth.user_auth import AuthTypedef create_mock_user_authorizer(success: bool = True, error_detail: str | None = None):@@ -928,6 +929,61 @@ async def test_logout_without_refresh_token():assert 'set-cookie' in result.headers+async def test_logout_with_bearer_auth_does_not_revoke_offline_token():+ """``/api/logout`` must not revoke the offline_token for bearer auth.++ A logout call that resolves to a *bearer* auth user (e.g., the+ browser also carried an ``Authorization: Bearer <api-key>`` header)+ must NOT invoke Keycloak's logout β that would revoke the user's+ offline session and break every API key minted for them. The cookie+ itself must still be deleted.+ """+ mock_request = MagicMock()+ mock_request.state.user_auth = SaasUserAuth(+ refresh_token=SecretStr('the-users-offline-token'),+ user_id='test_user_id',+ auth_type=AuthType.BEARER,+ )++ with patch('server.routes.auth.token_manager') as mock_token_manager:+ mock_token_manager.logout = AsyncMock()+ result = await logout(mock_request)++ assert isinstance(result, JSONResponse)+ assert result.status_code == status.HTTP_200_OK+ assert 'User logged out' in result.body.decode()++ # The offline token must NOT be revoked by a browser logout click.+ mock_token_manager.logout.assert_not_called()+ # The cookie itself is always removed.+ assert 'set-cookie' in result.headers+++async def test_logout_with_cookie_auth_terminates_keycloak_session():+ """Cookie-auth logout still terminates the Keycloak session.++ The bearer-auth guard added to ``/api/logout`` must not regress this+ common case.+ """+ mock_request = MagicMock()+ mock_request.state.user_auth = SaasUserAuth(+ refresh_token=SecretStr('cookie-refresh-token'),+ user_id='test_user_id',+ auth_type=AuthType.COOKIE,+ )++ with patch('server.routes.auth.token_manager') as mock_token_manager:+ mock_token_manager.logout = AsyncMock()+ result = await logout(mock_request)++ assert isinstance(result, JSONResponse)+ assert result.status_code == status.HTTP_200_OK+ mock_token_manager.logout.assert_awaited_once_with('cookie-refresh-token')+ assert 'set-cookie' in result.headers++@pytest.mark.asyncioasync def test_keycloak_callback_blocked_email_domain(mock_request, mock_background_tasks, create_keycloak_user_info