diff --git a/archipy/configs/sections/fastapi.py b/archipy/configs/sections/fastapi.py index 8beb59420..9c910ec28 100644 --- a/archipy/configs/sections/fastapi.py +++ b/archipy/configs/sections/fastapi.py @@ -3,7 +3,7 @@ import warnings from typing import Self -from pydantic import BaseModel, Field, model_validator +from pydantic import BaseModel, ConfigDict, Field, NonNegativeInt, model_validator from archipy.configs.sections.uvicorn import UVICORN_FIELDS_ON_FASTAPI @@ -13,6 +13,16 @@ def _moved(name: str) -> str: return f"Use UVICORN.{name} instead; FASTAPI.{name} will be removed in 6.0.0" +class FastAPIFormLimits(BaseModel): + """Overrides for the number of fields and files and the size of each text field in bytes.""" + + model_config = ConfigDict(extra="forbid") + + max_fields: NonNegativeInt | None = None + max_files: NonNegativeInt | None = None + max_part_size: NonNegativeInt | None = None + + class FastAPIConfig(BaseModel): """Configuration settings for FastAPI applications. @@ -22,6 +32,14 @@ class FastAPIConfig(BaseModel): PROJECT_NAME: str = Field(default="project_name", description="Name of the FastAPI project") API_PREFIX: str = Field(default="/api", description="URL prefix for API endpoints") + MAX_BODY_SIZE: NonNegativeInt | None = Field( + default=None, + description="Maximum total request body size in bytes, including files and multipart overhead", + ) + FORM_LIMITS: FastAPIFormLimits | None = Field( + default=None, + description="Limits for automatic form parsing, with FastAPI defaults for omitted keys", + ) ACCESS_LOG: bool = Field( default=True, diff --git a/archipy/helpers/utils/app_utils.py b/archipy/helpers/utils/app_utils.py index eb5c9515e..9164233a2 100644 --- a/archipy/helpers/utils/app_utils.py +++ b/archipy/helpers/utils/app_utils.py @@ -7,7 +7,7 @@ import warnings from concurrent import futures from pathlib import Path -from typing import TYPE_CHECKING, Any +from typing import TYPE_CHECKING, Any, cast from archipy.configs.base_config import BaseConfig from archipy.models.errors import ( @@ -22,6 +22,7 @@ from collections.abc import AsyncGenerator, Awaitable, Callable, Sequence, Set as AbstractSet from contextlib import AbstractAsyncContextManager + from fastapi._form_limits import _FormLimits from fastapi.routing import APIRoute from fastapi.telemetry import TelemetryConfig from grpc.aio import Server as GrpcAioServer @@ -567,6 +568,7 @@ def create_fastapi_app( responses_dict = dict(common_responses.items()) resolved_lifespan = cls._compose_otel_lifespan(config, lifespan) + form_limits = config.FASTAPI.FORM_LIMITS app = FastAPI( title=config.FASTAPI.PROJECT_NAME, openapi_url=config.FASTAPI.OPENAPI_URL, @@ -577,6 +579,8 @@ def create_fastapi_app( responses=responses_dict, lifespan=resolved_lifespan, telemetry=FastAPIUtils.build_otel_telemetry_config(config), + max_body_size=config.FASTAPI.MAX_BODY_SIZE, + form_limits=cast("_FormLimits", form_limits.model_dump(exclude_none=True)) if form_limits else None, ) FastAPIUtils.setup_cors(app, config) diff --git a/docs/api_reference/configs.md b/docs/api_reference/configs.md index 469d73d33..53a5b1dd6 100644 --- a/docs/api_reference/configs.md +++ b/docs/api_reference/configs.md @@ -133,6 +133,16 @@ heading_level: 3 ### Web Framework Configs +Set `FASTAPI__MAX_BODY_SIZE` to cap the total request in bytes, including files and multipart overhead. +Set `FASTAPI__FORM_LIMITS` to a JSON object with any of `max_fields`, `max_files`, and `max_part_size`. +`max_part_size` limits individual text fields. FastAPI supplies its defaults for omitted settings. +FastAPI returns HTTP 413 for an oversized body and HTTP 400 for a form parsing limit. + +```bash +FASTAPI__MAX_BODY_SIZE=10485760 +FASTAPI__FORM_LIMITS='{"max_fields": 20, "max_files": 4, "max_part_size": 65536}' +``` + ::: archipy.configs.config_template.FastAPIConfig options: show_root_toc_entry: false diff --git a/features/app_utils.feature b/features/app_utils.feature index 90e7d7a42..749b3eaaa 100644 --- a/features/app_utils.feature +++ b/features/app_utils.feature @@ -5,6 +5,23 @@ Feature: App Utilities Then the app should have the correct title And exception handlers should be registered + Scenario: FastAPI rejects a request body above the configured limit + Given a FastAPI form endpoint with request body limit 32 and form field limit 1 + When I submit the URL-encoded form "name=abcdefghijklmnopqrstuvwxyz0123456789" + Then the response should return status code 413 + And the response media type should be "text/plain" + + Scenario Outline: FastAPI applies the configured form field count limit + Given a FastAPI form endpoint with request body limit 32 and form field limit 1 + When I submit the URL-encoded form "" + Then the response should return status code + And the response media type should be "application/json" + + Examples: + | body | status | + | name=ArchiPy | 200 | + | name=ArchiPy&extra=1 | 400 | + Scenario: Handle a common custom exception Given a FastAPI app When an endpoint raises a "BaseError" diff --git a/features/steps/app_utils_steps.py b/features/steps/app_utils_steps.py index 242251748..d54d16269 100644 --- a/features/steps/app_utils_steps.py +++ b/features/steps/app_utils_steps.py @@ -12,13 +12,14 @@ from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec from cryptography.x509.oid import NameOID -from fastapi import Depends, FastAPI, WebSocket +from fastapi import Depends, FastAPI, Form, WebSocket from fastapi.routing import APIRoute from pydantic import BaseModel, ValidationError from starlette.testclient import TestClient from archipy.configs.base_config import BaseConfig from archipy.configs.config_template import FastAPIConfig, RedisMode +from archipy.configs.sections.fastapi import FastAPIFormLimits from archipy.configs.sections.grpc import GrpcConfig from archipy.helpers.utils.app_utils import ( AppUtils, @@ -83,6 +84,38 @@ def step_then_check_exception_handlers(context): assert ValidationError in app.exception_handlers +@given("a FastAPI form endpoint with request body limit {body_limit:d} and form field limit {field_limit:d}") +def step_given_fastapi_form_limits(context, body_limit, field_limit): + scenario_context = get_current_scenario_context(context) + config = BaseConfig.global_config().model_copy() + config.FASTAPI = FastAPIConfig(MAX_BODY_SIZE=body_limit, FORM_LIMITS=FastAPIFormLimits(max_fields=field_limit)) + app = AppUtils.create_fastapi_app(config) + + @app.post("/form") + def accept_form(name: str = Form()): + return {"name": name} + + scenario_context.store("app", app) + + +@when('I submit the URL-encoded form "{body}"') +def step_when_submit_fastapi_form(context, body): + scenario_context = get_current_scenario_context(context) + with TestClient(scenario_context.get("app")) as client: + response = client.post( + "/form", + content=body.encode(), + headers={"Content-Type": "application/x-www-form-urlencoded"}, + ) + scenario_context.store("response", response) + + +@then('the response media type should be "{media_type}"') +def step_then_response_media_type(context, media_type): + response = get_current_scenario_context(context).get("response") + assert response.headers["Content-Type"].split(";", 1)[0] == media_type + + @given('a FastAPI route with tag "{tag}" and name "{route_name}"') def step_given_fastapi_route(context, tag, route_name): scenario_context = get_current_scenario_context(context)