File size: 3,737 Bytes
e11f3d2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
"""Optional API-key auth and per-client rate limiting."""

from fastapi import FastAPI
from fastapi.testclient import TestClient

from core.security import RateLimiter, install_security


def _client(**security_kwargs) -> TestClient:
    app = FastAPI()
    install_security(app, **security_kwargs)

    @app.get("/ping")
    def ping():
        return {"ok": True}

    @app.get("/health")
    def health():
        return {"status": "ok"}

    return TestClient(app)


def test_auth_is_disabled_without_a_key():
    client = _client(api_key="", rate_limit_per_minute=0)
    assert client.get("/ping").status_code == 200


def test_bearer_and_x_api_key_are_accepted():
    client = _client(api_key="secret", rate_limit_per_minute=0)

    assert client.get("/ping").status_code == 401
    assert client.get(
        "/ping", headers={"Authorization": "Bearer wrong"}
    ).status_code == 401
    assert client.get(
        "/ping", headers={"Authorization": "Bearer secret"}
    ).status_code == 200
    assert client.get(
        "/ping", headers={"X-API-Key": "secret"}
    ).status_code == 200


def test_health_and_options_stay_open():
    client = _client(api_key="secret", rate_limit_per_minute=0)

    assert client.get("/health").status_code == 200
    # No CORS middleware in this test app, so OPTIONS may be 405 — the point is
    # that authentication did not intercept it.
    assert client.options("/ping").status_code != 401


def test_auth_error_is_a_json_401_with_www_authenticate():
    client = _client(api_key="secret", rate_limit_per_minute=0)
    response = client.get("/ping")

    assert response.status_code == 401
    assert response.json()["detail"] == "Invalid or missing API key."
    assert response.headers["www-authenticate"] == "Bearer"


def test_security_headers_are_added():
    client = _client(api_key="", rate_limit_per_minute=0)
    response = client.get("/health")

    assert response.headers["x-content-type-options"] == "nosniff"
    assert response.headers["x-frame-options"] == "DENY"


def test_rate_limit_rejects_after_burst_and_sets_retry_after():
    client = _client(api_key="", rate_limit_per_minute=60, rate_limit_burst=2)

    assert client.get("/ping").status_code == 200
    assert client.get("/ping").status_code == 200

    response = client.get("/ping")
    assert response.status_code == 429
    assert int(response.headers["retry-after"]) >= 1


def test_health_is_exempt_from_rate_limiting():
    client = _client(api_key="", rate_limit_per_minute=60, rate_limit_burst=1)

    for _ in range(5):
        assert client.get("/health").status_code == 200


def test_anonymous_key_headers_do_not_bypass_rate_limit():
    client = _client(api_key="", rate_limit_per_minute=60, rate_limit_burst=1)

    assert client.get("/ping", headers={"X-API-Key": "one"}).status_code == 200
    # A different fake key must not get a fresh bucket while auth is disabled.
    assert client.get("/ping", headers={"X-API-Key": "two"}).status_code == 429


def test_install_security_reads_env_key(monkeypatch):
    monkeypatch.setenv("SENTINEL_API_KEY", "env-secret")
    client = _client(rate_limit_per_minute=0)

    assert client.get("/ping").status_code == 401
    assert client.get(
        "/ping", headers={"Authorization": "Bearer env-secret"}
    ).status_code == 200


def test_token_bucket_reports_when_disabled():
    limiter = RateLimiter(per_minute=0)
    assert limiter.enabled is False
    assert limiter.check("any") == (True, 0)


def test_token_bucket_blocks_after_burst():
    limiter = RateLimiter(per_minute=60, burst=1)

    assert limiter.check("client")[0] is True
    allowed, retry_after = limiter.check("client")
    assert allowed is False
    assert retry_after >= 1