| 1 |
from pathlib import Path |
| 2 |
|
| 3 |
from fastapi import APIRouter, FastAPI, File, UploadFile |
| 4 |
from fastapi.exceptions import HTTPException |
| 5 |
from fastapi.testclient import TestClient |
| 6 |
from starlette.types import ASGIApp |
| 7 |
|
| 8 |
app = FastAPI() |
| 9 |
|
| 10 |
router = APIRouter() |
| 11 |
|
| 12 |
|
| 13 |
class ContentSizeLimitMiddleware: |
| 14 |
"""Content size limiting middleware for ASGI applications |
| 15 |
Args: |
| 16 |
app (ASGI application): ASGI application |
| 17 |
max_content_size (optional): the maximum content size allowed in bytes, None for no limit |
| 18 |
""" |
| 19 |
|
| 20 |
def __init__(self, app: ASGIApp, max_content_size: int | None = None): |
| 21 |
self.app = app |
| 22 |
self.max_content_size = max_content_size |
| 23 |
|
| 24 |
def receive_wrapper(self, receive): |
| 25 |
received = 0 |
| 26 |
|
| 27 |
async def inner(): |
| 28 |
nonlocal received |
| 29 |
message = await receive() |
| 30 |
if message["type"] != "http.request": |
| 31 |
return message # pragma: no cover |
| 32 |
|
| 33 |
body_len = len(message.get("body", b"")) |
| 34 |
received += body_len |
| 35 |
assert self.max_content_size is not None |
| 36 |
if received > self.max_content_size: |
| 37 |
raise HTTPException( |
| 38 |
422, |
| 39 |
detail={ |
| 40 |
"name": "ContentSizeLimitExceeded", |
| 41 |
"code": 999, |
| 42 |
"message": "File limit exceeded", |
| 43 |
}, |
| 44 |
) |
| 45 |
return message |
| 46 |
|
| 47 |
return inner |
| 48 |
|
| 49 |
async def __call__(self, scope, receive, send): |
| 50 |
if scope["type"] != "http" or self.max_content_size is None: |
| 51 |
await self.app(scope, receive, send) |
| 52 |
return |
| 53 |
|
| 54 |
wrapper = self.receive_wrapper(receive) |
| 55 |
await self.app(scope, wrapper, send) |
| 56 |
|
| 57 |
|
| 58 |
@router.post("/middleware") |
| 59 |
def run_middleware(file: UploadFile = File(..., description="Big File")): |
| 60 |
return {"message": "OK"} |
| 61 |
|
| 62 |
|
| 63 |
app.include_router(router) |
| 64 |
app.add_middleware(ContentSizeLimitMiddleware, max_content_size=2**8) |
| 65 |
|
| 66 |
|
| 67 |
client = TestClient(app) |
| 68 |
|
| 69 |
|
| 70 |
def test_custom_middleware_exception(tmp_path: Path): |
| 71 |
default_pydantic_max_size = 2**16 |
| 72 |
path = tmp_path / "test.txt" |
| 73 |
path.write_bytes(b"x" * (default_pydantic_max_size + 1)) |
| 74 |
|
| 75 |
with client: |
| 76 |
with open(path, "rb") as file: |
| 77 |
response = client.post("/middleware", files={"file": file}) |
| 78 |
assert response.status_code == 422, response.text |
| 79 |
assert response.json() == { |
| 80 |
"detail": { |
| 81 |
"name": "ContentSizeLimitExceeded", |
| 82 |
"code": 999, |
| 83 |
"message": "File limit exceeded", |
| 84 |
} |
| 85 |
} |
| 86 |
|
| 87 |
|
| 88 |
def test_custom_middleware_exception_not_raised(tmp_path: Path): |
| 89 |
path = tmp_path / "test.txt" |
| 90 |
path.write_bytes(b"<file content>") |
| 91 |
|
| 92 |
with client: |
| 93 |
with open(path, "rb") as file: |
| 94 |
response = client.post("/middleware", files={"file": file}) |
| 95 |
assert response.status_code == 200, response.text |
| 96 |
assert response.json() == {"message": "OK"} |