d5c645bf17
- Settings con Pydantic Settings, validazione env obbligatori - Shared models: TemplateVariable/Frontmatter, ImageVariable, TokenUsage, GenerationResult, TemplateSummary, TemplateAsset - ApiKeyAuthMiddleware Bearer token con exempt paths 19 test, tutti passed. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
58 lines
1.7 KiB
Python
58 lines
1.7 KiB
Python
import pytest
|
|
from fastapi import FastAPI
|
|
from fastapi.testclient import TestClient
|
|
|
|
from mcp_docugen.auth import ApiKeyAuthMiddleware
|
|
|
|
|
|
@pytest.fixture
|
|
def app_with_auth():
|
|
app = FastAPI()
|
|
app.add_middleware(
|
|
ApiKeyAuthMiddleware, api_key="secret", exempt_paths={"/health"}
|
|
)
|
|
|
|
@app.get("/protected")
|
|
async def protected():
|
|
return {"ok": True}
|
|
|
|
@app.get("/health")
|
|
async def health():
|
|
return {"status": "ok"}
|
|
|
|
return app
|
|
|
|
|
|
def test_protected_without_header_returns_401(app_with_auth):
|
|
client = TestClient(app_with_auth)
|
|
response = client.get("/protected")
|
|
assert response.status_code == 401
|
|
assert response.json() == {"error": "invalid_api_key"}
|
|
|
|
|
|
def test_protected_with_wrong_key_returns_401(app_with_auth):
|
|
client = TestClient(app_with_auth)
|
|
response = client.get("/protected", headers={"Authorization": "Bearer wrong"})
|
|
assert response.status_code == 401
|
|
|
|
|
|
def test_protected_with_correct_key_passes(app_with_auth):
|
|
client = TestClient(app_with_auth)
|
|
response = client.get("/protected", headers={"Authorization": "Bearer secret"})
|
|
assert response.status_code == 200
|
|
assert response.json() == {"ok": True}
|
|
|
|
|
|
def test_health_bypasses_auth(app_with_auth):
|
|
client = TestClient(app_with_auth)
|
|
response = client.get("/health")
|
|
assert response.status_code == 200
|
|
|
|
|
|
def test_malformed_auth_header_returns_401(app_with_auth):
|
|
client = TestClient(app_with_auth)
|
|
response = client.get("/protected", headers={"Authorization": "secret"})
|
|
assert response.status_code == 401
|
|
response = client.get("/protected", headers={"Authorization": "Basic secret"})
|
|
assert response.status_code == 401
|