"""Request body-size measurement and a leak-free 413 handler. Werkzeug enforces the byte ceiling itself from ``app.config['MAX_CONTENT_LENGTH']`` (lazily, when the body is read), so this module only adds the two things around it: a passive ``before_request`` that records the observed ``Content-Length`` of every request carrying a body, and a 413 handler that renders a fixed message so the configured limit never reaches the client. The measurement is what lets the limit be right-sized from real traffic, which APM cannot otherwise observe. """ from flask import Flask, Response, request from owsresponse import response from owsresponse.adaptors.flask import flaskify from werkzeug.exceptions import RequestEntityTooLarge from core.config import Config from core.hardening import observability as obs def setup_body_limit(app: Flask, config: type[Config]) -> None: """Install body-size measurement and the generic 413 handler on ``app``. The ceiling itself comes from ``MAX_CONTENT_LENGTH`` in the app config; this only observes and renders. Both are always on (no enable flag). """ @app.before_request def _measure_body() -> None: size = request.content_length if size: obs.request_body_bytes(size, request.endpoint or '') @app.errorhandler(RequestEntityTooLarge) def _body_too_large(_e: RequestEntityTooLarge) -> Response: obs.body_too_large() return flaskify( response.create_error_response( message='request body too large', status=413, code='error', ) )