Files
TJWaterServerBinary/tests/api/test_audit_middleware.py
T

52 lines
1.6 KiB
Python

from io import BytesIO
from unittest.mock import AsyncMock
from fastapi import FastAPI
from fastapi.responses import StreamingResponse
from fastapi.testclient import TestClient
from app.infra.audit import middleware as audit_middleware
from app.infra.audit.middleware import AuditMiddleware
from app.core.audit import sanitize_sensitive_data
def test_sanitize_sensitive_data_redacts_database_dsn() -> None:
raw_dsn = "postgresql://alice:supersecret@db.internal/project"
sanitized = sanitize_sensitive_data(
{"dsn": raw_dsn, "database": {"readonly_dsn": raw_dsn}}
)
assert sanitized == {
"dsn": "***REDACTED***",
"database": {"readonly_dsn": "***REDACTED***"},
}
assert raw_dsn not in str(sanitized)
def test_post_streaming_response_survives_audit_body_capture(monkeypatch):
log_audit_event = AsyncMock()
monkeypatch.setattr(audit_middleware, "log_audit_event", log_audit_event)
app = FastAPI()
app.add_middleware(AuditMiddleware)
@app.post("/exports")
async def export(payload: dict[str, str]) -> StreamingResponse:
assert payload == {"format": "xlsx"}
return StreamingResponse(
BytesIO(b"xlsx"),
media_type=(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
),
)
response = TestClient(app, raise_server_exceptions=False).post(
"/exports",
json={"format": "xlsx"},
)
assert response.status_code == 200
assert response.content == b"xlsx"
log_audit_event.assert_awaited_once()