-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat: Add HTTP request body size limit to OpenAI frontend #8787
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
pskiran1
merged 16 commits into
main
from
spolisetty/tri-1015-psirt-triton-openai-frontend-accepts-a-single-64-mib-json
May 29, 2026
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
1dc81c2
Update
pskiran1 9b470a9
Update
pskiran1 c34879a
Potential fix for pull request finding 'CodeQL / Unused local variable'
pskiran1 f225956
Fix pre-commit error
pskiran1 2f558e2
Merge branch 'spolisetty/tri-1015-psirt-triton-openai-frontend-accept…
pskiran1 dbdf2a1
Update
pskiran1 9a4e237
Merge branch 'main' into spolisetty/tri-1015-psirt-triton-openai-fron…
pskiran1 52db716
Update python/openai/openai_frontend/utils/utils.py
pskiran1 a3c228c
Merge branch 'main' into spolisetty/tri-1015-psirt-triton-openai-fron…
pskiran1 1790771
Update
pskiran1 ef53123
Merge branch 'main' into spolisetty/tri-1015-psirt-triton-openai-fron…
pskiran1 269ce01
Merge branch 'main' into spolisetty/tri-1015-psirt-triton-openai-fron…
pskiran1 51bef11
Update
pskiran1 cb20fff
Merge branch 'spolisetty/tri-1015-psirt-triton-openai-frontend-accept…
pskiran1 8caf3ef
Update
pskiran1 3532616
Merge branch 'main' into spolisetty/tri-1015-psirt-triton-openai-fron…
pskiran1 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
163 changes: 163 additions & 0 deletions
163
python/openai/openai_frontend/frontend/fastapi/middleware/request_size.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| # Copyright 2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # | ||
| # Redistribution and use in source and binary forms, with or without | ||
| # modification, are permitted provided that the following conditions | ||
| # are met: | ||
| # * Redistributions of source code must retain the above copyright | ||
| # notice, this list of conditions and the following disclaimer. | ||
| # * Redistributions in binary form must reproduce the above copyright | ||
| # notice, this list of conditions and the following disclaimer in the | ||
| # documentation and/or other materials provided with the distribution. | ||
| # * Neither the name of NVIDIA CORPORATION nor the names of its | ||
| # contributors may be used to endorse or promote products derived | ||
| # from this software without specific prior written permission. | ||
| # | ||
| # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY | ||
| # EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE | ||
| # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR | ||
| # PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR | ||
| # CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, | ||
| # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, | ||
| # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR | ||
| # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY | ||
| # OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT | ||
| # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE | ||
| # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | ||
|
|
||
| from fastapi.responses import JSONResponse | ||
| from starlette.types import ASGIApp, Message, Receive, Scope, Send | ||
| from utils.utils import StatusCode, validate_positive_int | ||
|
|
||
|
|
||
| async def _disconnect_receive() -> Message: | ||
| return {"type": "http.disconnect"} | ||
|
|
||
|
|
||
| class RequestSizeLimitMiddleware: | ||
| """ | ||
| Reject HTTP requests whose body exceeds ``http_max_input_size`` bytes. | ||
| First validation rejects on the Content-Length header before any body bytes are | ||
| read. Second validation streams the body chunks, counting bytes as they arrive, | ||
| and rejects as soon as the running total crosses the limit. Driving | ||
| receive() from the middleware protects every endpoint, including | ||
| handlers that never read the body. The buffered body is released the | ||
| moment the application consumes it, so the middleware contributes no | ||
| sustained memory overhead. | ||
| """ | ||
|
|
||
| def __init__(self, app: ASGIApp, http_max_input_size: int) -> None: | ||
| self.app = app | ||
| self.http_max_input_size = validate_positive_int(http_max_input_size) | ||
|
|
||
| async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None: | ||
| if scope["type"] != "http": | ||
| await self.app(scope, receive, send) | ||
| return | ||
|
|
||
| # Stage 1: reject on Content-Length before reading any body bytes. | ||
| for name, value in scope["headers"]: | ||
|
pskiran1 marked this conversation as resolved.
|
||
| if name != b"content-length": | ||
| continue | ||
| try: | ||
| content_length = int(value) | ||
| except ValueError: | ||
| await self._send_error( | ||
| scope, | ||
| send, | ||
| StatusCode.CLIENT_ERROR, | ||
| "invalid_content_length", | ||
| "Invalid Content-Length header: not an integer.", | ||
| ) | ||
| return | ||
| if content_length < 0: | ||
| await self._send_error( | ||
| scope, | ||
| send, | ||
| StatusCode.CLIENT_ERROR, | ||
| "invalid_content_length", | ||
| "Invalid Content-Length header: must be non-negative.", | ||
| ) | ||
| return | ||
| if content_length > self.http_max_input_size: | ||
| await self._send_error( | ||
| scope, | ||
| send, | ||
| StatusCode.CONTENT_TOO_LARGE, | ||
| "content_too_large", | ||
| self._oversized_request_message( | ||
| content_length, self.http_max_input_size | ||
| ), | ||
| ) | ||
| return | ||
| break | ||
|
|
||
| # Stage 2: count chunks as they arrive, reject if total exceeds limit. | ||
| body_chunks: list[bytes] = [] | ||
| total = 0 | ||
| while True: | ||
| message = await receive() | ||
| if message["type"] != "http.request": | ||
| return | ||
| chunk = message.get("body", b"") | ||
| total += len(chunk) | ||
| if total > self.http_max_input_size: | ||
| await self._send_error( | ||
| scope, | ||
| send, | ||
| StatusCode.CONTENT_TOO_LARGE, | ||
| "content_too_large", | ||
| self._oversized_request_message(total, self.http_max_input_size), | ||
| ) | ||
| return | ||
| body_chunks.append(chunk) | ||
| if not message.get("more_body", False): | ||
| break | ||
|
|
||
| # Assemble the buffered body and replay it to the app. | ||
| body_message: Message = { | ||
| "type": "http.request", | ||
| "body": b"".join(body_chunks), | ||
| "more_body": False, | ||
| } | ||
| del body_chunks | ||
|
|
||
| async def replay_receive() -> Message: | ||
|
pskiran1 marked this conversation as resolved.
|
||
| nonlocal body_message | ||
| if body_message is not None: | ||
| # Drop the reference on hand-off so the body is freed while | ||
| # the app processes it, instead of being held by this closure. | ||
| message, body_message = body_message, None | ||
| return message | ||
| # Body already delivered — delegate to the original receive() so | ||
| # streaming responses can wait for the real client disconnect. | ||
| return await receive() | ||
|
|
||
| await self.app(scope, replay_receive, send) | ||
|
|
||
| @staticmethod | ||
| def _oversized_request_message(actual_bytes: int, max_bytes: int) -> str: | ||
| return ( | ||
| f"Request size of {actual_bytes} bytes exceeds the maximum allowed " | ||
| f"input size of {max_bytes} bytes. " | ||
| f"Use --http-max-input-size to increase the limit." | ||
| ) | ||
|
|
||
| async def _send_error( | ||
| self, | ||
| scope: Scope, | ||
| send: Send, | ||
| status_code: int, | ||
| code: str, | ||
| message: str, | ||
| ) -> None: | ||
| response = JSONResponse( | ||
| status_code=status_code, | ||
| content={ | ||
| "error": { | ||
| "message": message, | ||
| "type": "invalid_request_error", | ||
| "code": code, | ||
| } | ||
| }, | ||
| ) | ||
| await response(scope, _disconnect_receive, send) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.