diff --git a/automation/auth.py b/automation/auth.py index 4b03987f..689f32f2 100644 --- a/automation/auth.py +++ b/automation/auth.py @@ -10,6 +10,7 @@ from dataclasses import dataclass import httpx +from cachetools import TTLCache from fastapi import Depends, HTTPException, Request, status from tenacity import ( RetryCallState, @@ -25,6 +26,14 @@ logger = logging.getLogger("automation.auth") +# Cache TTL in seconds +AUTH_CACHE_TTL_SECONDS = 20.0 + +# In-memory cache for authenticated users with 20 second TTL +_auth_cache: TTLCache[str, "AuthenticatedUser"] = TTLCache( + maxsize=1024, ttl=AUTH_CACHE_TTL_SECONDS +) + # Default timeout for HTTP client HTTP_CLIENT_TIMEOUT = 10.0 @@ -61,6 +70,11 @@ class AuthenticatedUser: api_key: str # The raw API key (needed for downstream API calls) +def clear_auth_cache() -> None: + """Clear all cached authentication data. Useful for testing.""" + _auth_cache.clear() + + def _is_rate_limited(response: httpx.Response) -> bool: """Check if response is a 429 rate limit response.""" return response.status_code == 429 @@ -120,6 +134,7 @@ async def authenticate_request( Calls the OpenHands API /api/keys/current to verify the key and get user/org identity. Implements retry with exponential backoff for rate limiting. + Results are cached in-memory for 20 seconds to reduce API calls. """ auth_header = request.headers.get("Authorization", "") if not auth_header.startswith("Bearer "): @@ -136,6 +151,14 @@ async def authenticate_request( detail="Empty API key", ) + # Check cache first + cached_user = _auth_cache.get(api_key) + if cached_user is not None: + logger.debug("Auth cache hit for user %s", cached_user.user_id) + return cached_user + + logger.debug("Auth cache miss, validating with OpenHands API") + settings = get_settings() try: resp = await _make_auth_request_with_retry( @@ -188,4 +211,6 @@ async def authenticate_request( detail="Invalid user_id or org_id format from OpenHands API", ) - return AuthenticatedUser(user_id=user_uuid, org_id=org_uuid, api_key=api_key) + user = AuthenticatedUser(user_id=user_uuid, org_id=org_uuid, api_key=api_key) + _auth_cache[api_key] = user + return user diff --git a/pyproject.toml b/pyproject.toml index 9db4a2c2..936b5667 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -12,6 +12,7 @@ classifiers = [ dependencies = [ "alembic>=1.14", "asyncpg>=0.30", + "cachetools>=7.0.5", "cloud-sql-python-connector[asyncpg]>=1.16", "croniter>=2", "fastapi>=0.115", diff --git a/tests/test_auth.py b/tests/test_auth.py index ad9faa60..c1508c56 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -5,14 +5,17 @@ import httpx import pytest +from cachetools import TTLCache from fastapi import HTTPException from httpx import ASGITransport, AsyncClient from automation.app import app from automation.auth import ( + AUTH_CACHE_TTL_SECONDS, AuthenticatedUser, _make_auth_request_with_retry, authenticate_request, + clear_auth_cache, ) from automation.db import get_session @@ -22,6 +25,14 @@ TEST_ORG_ID = uuid.UUID("87654321-4321-8765-4321-876543218765") +@pytest.fixture(autouse=True) +def clear_cache(): + """Clear auth cache before and after each test.""" + clear_auth_cache() + yield + clear_auth_cache() + + @pytest.fixture def mock_request(): """Create a mock FastAPI request.""" @@ -242,6 +253,125 @@ async def override_get_session(): app.dependency_overrides.clear() +class TestAuthCache: + """Tests for authentication caching functionality.""" + + async def test_cache_hit_skips_api_call(self, mock_request, mock_http_client): + """Second call with same API key uses cache and skips API call.""" + mock_request.headers.get.return_value = "Bearer cached-key" + + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.json.return_value = { + "user_id": str(TEST_USER_ID), + "org_id": str(TEST_ORG_ID), + } + mock_http_client.get = AsyncMock(return_value=mock_response) + + # First call - should hit API + result1 = await authenticate_request(mock_request, client=mock_http_client) + assert mock_http_client.get.call_count == 1 + + # Second call - should use cache + result2 = await authenticate_request(mock_request, client=mock_http_client) + assert mock_http_client.get.call_count == 1 # No additional API call + + assert result1.user_id == result2.user_id + assert result1.org_id == result2.org_id + + async def test_cache_expires_after_ttl(self, mock_request, mock_http_client): + """Cache entry expires after TTL and API is called again.""" + import asyncio + + import automation.auth as auth_module + + # Use a short TTL for testing (0.5 seconds) + test_ttl = 0.5 + original_cache = auth_module._auth_cache + auth_module._auth_cache = TTLCache(maxsize=1024, ttl=test_ttl) + + try: + mock_request.headers.get.return_value = "Bearer expiring-key" + + mock_response = MagicMock() + mock_response.status_code = 200 + mock_response.json.return_value = { + "user_id": str(TEST_USER_ID), + "org_id": str(TEST_ORG_ID), + } + mock_http_client.get = AsyncMock(return_value=mock_response) + + # First call + await authenticate_request(mock_request, client=mock_http_client) + assert mock_http_client.get.call_count == 1 + + # Wait for TTL to expire (add buffer for timing) + await asyncio.sleep(test_ttl + 0.1) + + # Second call after expiry - should hit API again + await authenticate_request(mock_request, client=mock_http_client) + assert mock_http_client.get.call_count == 2 + finally: + auth_module._auth_cache = original_cache + + async def test_different_keys_cached_separately( + self, mock_request, mock_http_client + ): + """Different API keys are cached independently.""" + user2_id = uuid.UUID("22222222-2222-2222-2222-222222222222") + org2_id = uuid.UUID("33333333-3333-3333-3333-333333333333") + + mock_response1 = MagicMock() + mock_response1.status_code = 200 + mock_response1.json.return_value = { + "user_id": str(TEST_USER_ID), + "org_id": str(TEST_ORG_ID), + } + + mock_response2 = MagicMock() + mock_response2.status_code = 200 + mock_response2.json.return_value = { + "user_id": str(user2_id), + "org_id": str(org2_id), + } + + mock_http_client.get = AsyncMock(side_effect=[mock_response1, mock_response2]) + + # First key + mock_request.headers.get.return_value = "Bearer key-1" + result1 = await authenticate_request(mock_request, client=mock_http_client) + + # Second key + mock_request.headers.get.return_value = "Bearer key-2" + result2 = await authenticate_request(mock_request, client=mock_http_client) + + assert mock_http_client.get.call_count == 2 + assert result1.user_id == TEST_USER_ID + assert result2.user_id == user2_id + + async def test_failed_auth_not_cached(self, mock_request, mock_http_client): + """Failed authentication attempts are not cached.""" + mock_request.headers.get.return_value = "Bearer bad-key" + + mock_401_response = MagicMock() + mock_401_response.status_code = 401 + mock_http_client.get = AsyncMock(return_value=mock_401_response) + + # First attempt - should fail + with pytest.raises(HTTPException): + await authenticate_request(mock_request, client=mock_http_client) + + # Second attempt - should still call API (not cached) + with pytest.raises(HTTPException): + await authenticate_request(mock_request, client=mock_http_client) + + assert mock_http_client.get.call_count == 2 + + def test_cache_ttl_is_20_seconds(self): + """Verify the cache TTL is set to 20 seconds.""" + assert AUTH_CACHE_TTL_SECONDS == 20.0 + + class TestRetryMechanism: """Tests for the retry mechanism on 429 rate limit responses using tenacity.""" diff --git a/uv.lock b/uv.lock index 145e6618..f6820b9f 100644 --- a/uv.lock +++ b/uv.lock @@ -225,6 +225,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/64/b4/17d4b0b2a2dc85a6df63d1157e028ed19f90d4cd97c36717afef2bc2f395/attrs-26.1.0-py3-none-any.whl", hash = "sha256:c647aa4a12dfbad9333ca4e71fe62ddc36f4e63b2d260a37a8b83d2f043ac309", size = 67548, upload-time = "2026-03-19T14:22:23.645Z" }, ] +[[package]] +name = "cachetools" +version = "7.0.5" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/af/dd/57fe3fdb6e65b25a5987fd2cdc7e22db0aef508b91634d2e57d22928d41b/cachetools-7.0.5.tar.gz", hash = "sha256:0cd042c24377200c1dcd225f8b7b12b0ca53cc2c961b43757e774ebe190fd990", size = 37367, upload-time = "2026-03-09T20:51:29.451Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/06/f3/39cf3367b8107baa44f861dc802cbf16263c945b62d8265d36034fc07bea/cachetools-7.0.5-py3-none-any.whl", hash = "sha256:46bc8ebefbe485407621d0a4264b23c080cedd913921bad7ac3ed2f26c183114", size = 13918, upload-time = "2026-03-09T20:51:27.33Z" }, +] + [[package]] name = "certifi" version = "2026.2.25" @@ -1168,6 +1177,7 @@ source = { editable = "." } dependencies = [ { name = "alembic" }, { name = "asyncpg" }, + { name = "cachetools" }, { name = "cloud-sql-python-connector", extra = ["asyncpg"] }, { name = "croniter" }, { name = "fastapi" }, @@ -1200,6 +1210,7 @@ dev = [ requires-dist = [ { name = "alembic", specifier = ">=1.14" }, { name = "asyncpg", specifier = ">=0.30" }, + { name = "cachetools", specifier = ">=7.0.5" }, { name = "cloud-sql-python-connector", extras = ["asyncpg"], specifier = ">=1.16" }, { name = "croniter", specifier = ">=2" }, { name = "fastapi", specifier = ">=0.115" },