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
27 changes: 26 additions & 1 deletion automation/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -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
)

Comment thread
malhotra5 marked this conversation as resolved.
Resolved
# Default timeout for HTTP client
HTTP_CLIENT_TIMEOUT = 10.0

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 "):
Expand All @@ -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

Comment thread
malhotra5 marked this conversation as resolved.
Resolved
logger.debug("Auth cache miss, validating with OpenHands API")

settings = get_settings()
try:
resp = await _make_auth_request_with_retry(
Expand Down Expand Up @@ -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
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
130 changes: 130 additions & 0 deletions tests/test_auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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."""
Expand Down Expand Up @@ -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
Comment thread
malhotra5 marked this conversation as resolved.
Resolved


class TestRetryMechanism:
"""Tests for the retry mechanism on 429 rate limit responses using tenacity."""

Expand Down
11 changes: 11 additions & 0 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading