Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
62 changes: 40 additions & 22 deletions openhands/automation/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
1. API key via Authorization: Bearer header
2. API key via X-Session-API-Key header (matches agent-server convention,
useful behind reverse proxies that overwrite the Authorization header)
3. Cookie: keycloak_auth cookie from the OpenHands web UI
3. Cookie: the OpenHands web UI session cookie, either the new OAuth v2
``openhands_auth`` JWT cookie or the legacy ``keycloak_auth`` cookie

All methods validate against the OpenHands API GET /api/v1/users/me endpoint
to get the user and organization identity.
Expand Down Expand Up @@ -38,7 +39,14 @@

# Auth cache - initialized lazily to use config values
_auth_cache: TTLCache[str, "AuthenticatedUser"] | None = None
SESSION_COOKIE_NAME = "keycloak_auth"

# Session cookies accepted from the OpenHands web UI. ``openhands_auth`` is
# the OAuth v2 JWT cookie issued to new logins; ``keycloak_auth`` is the
# legacy chunked cookie that existing sessions still carry. Both are checked,
# new first, so a client mid-migration that holds the old cookie keeps working
# while new logins authenticate with the new one. ``keycloak_auth`` alone is
# chunked, but we reassemble either name defensively.
SESSION_COOKIE_NAMES = ("openhands_auth", "keycloak_auth")
X_ORG_ID_HEADER = "X-Org-Id"
# Keep parity with OpenHands' cookie chunking helper: 8 * 3000 bytes is
# comfortably above expected session token sizes while staying bounded.
Expand Down Expand Up @@ -348,44 +356,52 @@ def _extract_api_key(request: Request) -> str | None:
return session_key or None


def _extract_session_cookie(request: Request) -> str | None:
"""Read OpenHands' possibly chunked session cookie.
def _extract_session_cookie(request: Request) -> tuple[str, str] | None:
"""Read OpenHands' session cookie and return ``(name, value)``.

OpenHands splits large keycloak_auth values across keycloak_auth,
keycloak_auth_1, keycloak_auth_2, etc. Automation validates by forwarding
the reassembled token back to OpenHands /api/v1/users/me.
Accepts the new ``openhands_auth`` JWT cookie and the legacy
``keycloak_auth`` cookie, preferring the new one. OpenHands splits large
``keycloak_auth`` values across ``keycloak_auth``, ``keycloak_auth_1``,
etc.; the chunks are reassembled here and the whole ``name=value`` pair is
forwarded to OpenHands ``/api/v1/users/me`` so upstream sees the cookie
under its original name.
"""
first = request.cookies.get(SESSION_COOKIE_NAME)
if not first:
return None
for name in SESSION_COOKIE_NAMES:
first = request.cookies.get(name)
if not first:
continue

parts = [first]
for index in range(1, MAX_SESSION_COOKIE_CHUNKS):
part = request.cookies.get(f"{SESSION_COOKIE_NAME}_{index}")
if part is None:
break
parts.append(part)
return "".join(parts)
parts = [first]
for index in range(1, MAX_SESSION_COOKIE_CHUNKS):
part = request.cookies.get(f"{name}_{index}")
if part is None:
break
parts.append(part)
return name, "".join(parts)
return None


def _extract_credential(request: Request) -> tuple[str, AuthMethod]:
"""Extract a credential and its auth method from the request.

Priority: Authorization: Bearer → X-Session-API-Key → keycloak_auth cookie.
Raises 401 if nothing usable is found.
Priority: Authorization: Bearer → X-Session-API-Key → session cookie
(``openhands_auth`` or ``keycloak_auth``). For cookie auth the credential
is the full ``name=value`` pair so the original cookie name reaches
upstream. Raises 401 if nothing usable is found.
"""
api_key = _extract_api_key(request)
if api_key:
return api_key, AuthMethod.API_KEY

cookie = _extract_session_cookie(request)
if cookie:
return cookie, AuthMethod.COOKIE
name, value = cookie
return f"{name}={value}", AuthMethod.COOKIE

raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Authentication required: provide Bearer token, "
"X-Session-API-Key header, or keycloak_auth cookie",
"X-Session-API-Key header, or session cookie",
)


Expand All @@ -395,7 +411,9 @@ def _upstream_headers(
headers = (
{"Authorization": f"Bearer {credential}"}
if auth_method == AuthMethod.API_KEY
else {"Cookie": f"{SESSION_COOKIE_NAME}={credential}"}
# For cookie auth ``credential`` is already ``name=value``; preserve
# the caller's cookie name so upstream parses it correctly.
else {"Cookie": credential}
)
if x_org_id:
headers[X_ORG_ID_HEADER] = x_org_id
Expand Down
99 changes: 99 additions & 0 deletions tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,6 +471,66 @@ async def test_no_auth_raises_401(self, mock_request, mock_http_client):
assert exc_info.value.status_code == 401
assert "Authentication required" in exc_info.value.detail

async def test_authenticate_valid_openhands_auth_cookie(
self, mock_request, mock_http_client
):
"""Valid openhands_auth (OAuth v2) cookie returns AuthenticatedUser."""
_set_mock_headers(mock_request, {})
mock_request.cookies = {"openhands_auth": "v2-cookie-value"}

mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = MOCK_USERS_ME_RESPONSE
mock_http_client.get = AsyncMock(return_value=mock_response)

result = await authenticate_request(mock_request, client=mock_http_client)

assert result.auth_method == AuthMethod.COOKIE

# The original cookie name must reach upstream so it parses the JWT
# cookie rather than the legacy chunked one.
headers = mock_http_client.get.call_args[1]["headers"]
assert headers["Cookie"] == "openhands_auth=v2-cookie-value"
assert "Authorization" not in headers

async def test_openhands_auth_preferred_over_keycloak_auth(
self, mock_request, mock_http_client
):
"""When both cookies are present, the new openhands_auth cookie wins."""
_set_mock_headers(mock_request, {})
mock_request.cookies = {
"openhands_auth": "v2-cookie-value",
"keycloak_auth": "legacy-cookie-value",
}

mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = MOCK_USERS_ME_RESPONSE
mock_http_client.get = AsyncMock(return_value=mock_response)

await authenticate_request(mock_request, client=mock_http_client)

headers = mock_http_client.get.call_args[1]["headers"]
assert headers["Cookie"] == "openhands_auth=v2-cookie-value"

async def test_falls_back_to_keycloak_auth_when_new_cookie_absent(
self, mock_request, mock_http_client
):
"""A session still holding only the legacy cookie keeps working."""
_set_mock_headers(mock_request, {})
mock_request.cookies = {"keycloak_auth": "legacy-cookie-value"}

mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = MOCK_USERS_ME_RESPONSE
mock_http_client.get = AsyncMock(return_value=mock_response)

result = await authenticate_request(mock_request, client=mock_http_client)

assert result.auth_method == AuthMethod.COOKIE
headers = mock_http_client.get.call_args[1]["headers"]
assert headers["Cookie"] == "keycloak_auth=legacy-cookie-value"

async def test_cookie_openhands_unavailable(self, mock_request, mock_http_client):
"""Connection error to OpenHands API with cookie auth raises 502."""
_set_mock_headers(mock_request, {})
Expand Down Expand Up @@ -692,6 +752,45 @@ async def override_get_session():
finally:
app.dependency_overrides.clear()

async def test_valid_openhands_auth_cookie_through_api(
self, async_engine, async_session_factory
):
"""Valid openhands_auth cookie flows through auth middleware."""
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.json.return_value = MOCK_USERS_ME_RESPONSE

async def override_get_session():
async with async_session_factory() as session:
yield session

app.dependency_overrides[get_session] = override_get_session
app.state.engine = async_engine
app.state.session_factory = async_session_factory

mock_client = AsyncMock()
mock_client.get = AsyncMock(return_value=mock_response)
mock_client.is_closed = False
app.state.http_client = mock_client

try:
async with AsyncClient(
transport=ASGITransport(app=app), base_url="http://test"
) as client:
response = await client.get(
"/api/automation/v1",
cookies={"openhands_auth": "valid-v2-cookie-123"},
)

assert response.status_code == 200
data = response.json()
assert "automations" in data
# The v2 cookie name is forwarded to OpenHands unchanged.
headers = mock_client.get.call_args[1]["headers"]
assert headers["Cookie"] == "openhands_auth=valid-v2-cookie-123"
finally:
app.dependency_overrides.clear()

async def test_missing_auth_header_through_api(
self, async_engine, async_session_factory
):
Expand Down
Loading