diff --git a/tests/test_auth.py b/tests/test_auth.py new file mode 100644 index 0000000..b714537 --- /dev/null +++ b/tests/test_auth.py @@ -0,0 +1,64 @@ +import pytest +from fastapi import FastAPI +from fastapi.testclient import TestClient + + +def _make_app(): + app = FastAPI() + + @app.get("/data") + async def data(): + return {"ok": True} + + @app.get("/health") + async def health(): + return {"status": "ok"} + + return app + + +def test_auth_skipped_when_no_keys_configured(monkeypatch): + monkeypatch.setattr("axon.middleware.auth.settings.api_keys", None) + from axon.middleware.auth import APIKeyMiddleware + app = _make_app() + app.add_middleware(APIKeyMiddleware) + client = TestClient(app, raise_server_exceptions=True) + assert client.get("/data").status_code == 200 + + +def test_auth_valid_key_accepted(monkeypatch): + monkeypatch.setattr("axon.middleware.auth.settings.api_keys", "secret") + from axon.middleware.auth import APIKeyMiddleware + app = _make_app() + app.add_middleware(APIKeyMiddleware) + client = TestClient(app) + assert client.get("/data", headers={"X-API-Key": "secret"}).status_code == 200 + + +def test_auth_wrong_key_rejected(monkeypatch): + monkeypatch.setattr("axon.middleware.auth.settings.api_keys", "secret") + from axon.middleware.auth import APIKeyMiddleware + app = _make_app() + app.add_middleware(APIKeyMiddleware) + client = TestClient(app) + resp = client.get("/data", headers={"X-API-Key": "wrong"}) + assert resp.status_code == 401 + assert "detail" in resp.json() + + +def test_auth_missing_key_rejected(monkeypatch): + monkeypatch.setattr("axon.middleware.auth.settings.api_keys", "secret") + from axon.middleware.auth import APIKeyMiddleware + app = _make_app() + app.add_middleware(APIKeyMiddleware) + client = TestClient(app) + assert client.get("/data").status_code == 401 + + +def test_health_exempt_from_auth(monkeypatch): + monkeypatch.setattr("axon.middleware.auth.settings.api_keys", "secret") + from axon.middleware.auth import APIKeyMiddleware + app = _make_app() + app.add_middleware(APIKeyMiddleware) + client = TestClient(app) + assert client.get("/health").status_code == 200