File size: 2,490 Bytes
f6fdf6a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
import pytest
from unittest.mock import AsyncMock, patch

from app.middleware import api_key_guard
from app.config import settings


@pytest.mark.asyncio
async def test_api_key_guard_no_key_configured():
    """Test middleware allows requests when no API key is configured."""
    request = AsyncMock()
    request.headers = {}
    call_next = AsyncMock()
    
    with patch.object(settings, 'service_api_key', None):
        response = await api_key_guard(request, call_next)
        call_next.assert_called_once_with(request)
        assert response == call_next.return_value


@pytest.mark.asyncio
async def test_api_key_guard_valid_x_api_key():
    """Test middleware allows requests with valid x-api-key header."""
    request = AsyncMock()
    request.headers = {"x-api-key": "secret-key"}
    call_next = AsyncMock()
    
    with patch.object(settings, 'service_api_key', 'secret-key'):
        response = await api_key_guard(request, call_next)
        call_next.assert_called_once_with(request)
        assert response == call_next.return_value


@pytest.mark.asyncio
async def test_api_key_guard_valid_authorization():
    """Test middleware allows requests with valid Authorization header."""
    request = AsyncMock()
    request.headers = {"authorization": "Bearer secret-key"}
    call_next = AsyncMock()
    
    with patch.object(settings, 'service_api_key', 'secret-key'):
        response = await api_key_guard(request, call_next)
        call_next.assert_called_once_with(request)
        assert response == call_next.return_value


@pytest.mark.asyncio
async def test_api_key_guard_invalid_key():
    """Test middleware rejects requests with invalid API key."""
    request = AsyncMock()
    request.headers = {"x-api-key": "wrong-key"}
    call_next = AsyncMock()
    
    with patch.object(settings, 'service_api_key', 'secret-key'):
        response = await api_key_guard(request, call_next)
        call_next.assert_not_called()
        assert response.status_code == 401
        assert response.body.decode() == '{"error":"unauthorized"}'


@pytest.mark.asyncio
async def test_api_key_guard_no_headers():
    """Test middleware rejects requests with no API key headers."""
    request = AsyncMock()
    request.headers = {}
    call_next = AsyncMock()
    
    with patch.object(settings, 'service_api_key', 'secret-key'):
        response = await api_key_guard(request, call_next)
        call_next.assert_not_called()
        assert response.status_code == 401