Skip to content

🛡️ fix: prevent OOM on large/decompressed requests; skip heavy prompt… - #2452

Merged
seefs001 merged 2 commits into
mainfrom
fix/oom-request-body-limit
Dec 16, 2025
Merged

seefs001 merged 2 commits into
mainfrom
fix/oom-request-body-limit

Conversation

@t0ng7u

@t0ng7u t0ng7u commented Dec 16, 2025 •

Copy link
Copy Markdown
Collaborator

… meta when token count is disabled

Clamp request body size (including post-decompression) to avoid memory exhaustion caused by huge payloads/zip bombs, especially with large-context Claude requests. Add a configurable MAX_REQUEST_BODY_MB (default 32) and document it.

  • Enforce max request body size after gzip/br decompression via http.MaxBytesReader
  • Add a secondary size guard in common.GetRequestBody and cache-safe handling
  • Return 413 Request Entity Too Large on oversized bodies in relay entry
  • Avoid building large TokenCountMeta.CombineText when both token counting and sensitive check are disabled (use lightweight meta for pricing)
  • Update READMEs (CN/EN/FR/JA) with MAX_REQUEST_BODY_MB
  • Fix a handful of vet/formatting issues encountered during the change
  • go test ./... passes

Summary by CodeRabbit

  • New Features

    • Add configurable request body size limit (MAX_REQUEST_BODY_MB, default 32 MB) with HTTP 413 for oversized requests.
    • Enforce size limits after decompression for gzip and Brotli uploads.
  • Documentation

    • Updated docs in all languages describing the new MAX_REQUEST_BODY_MB setting and behavior.
  • Bug Fixes

    • Corrected several error/log formatting issues for clearer messages.

✏️ Tip: You can customize this high-level summary in your review settings.

… meta when token count is disabled

Clamp request body size (including post-decompression) to avoid memory exhaustion caused by huge payloads/zip bombs, especially with large-context Claude requests. Add a configurable `MAX_REQUEST_BODY_MB` (default `32`) and document it.

- Enforce max request body size after gzip/br decompression via `http.MaxBytesReader`
- Add a secondary size guard in `common.GetRequestBody` and cache-safe handling
- Return **413 Request Entity Too Large** on oversized bodies in relay entry
- Avoid building large `TokenCountMeta.CombineText` when both token counting and sensitive check are disabled (use lightweight meta for pricing)
- Update READMEs (CN/EN/FR/JA) with `MAX_REQUEST_BODY_MB`
- Fix a handful of vet/formatting issues encountered during the change
- `go test ./...` passes
@coderabbitai

coderabbitai Bot commented Dec 16, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a configurable maximum request body size (default 32 MB) enforced during decompression and when reading request bodies, introduces ErrRequestBodyTooLarge and detection helpers, updates error handling to map oversized bodies to HTTP 413, and documents the new MAX_REQUEST_BODY_MB environment variable.

Changes

Cohort / File(s) Summary
Documentation & Configuration
README.md, README.en.md, README.fr.md, README.ja.md, constant/env.go, common/init.go
Add MAX_REQUEST_BODY_MB env var documentation and a new constant.MaxRequestBodyMB with initialization defaulting to 32.
Request body enforcement & helpers
common/gin.go, middleware/gzip.go
Add ErrRequestBodyTooLarge and IsRequestBodyTooLargeError(); enforce configurable post-decompression/body read size limits, cache request body in Gin context, and ensure proper reader wrapping and cleanup.
Controller / Pricing & Retry
controller/relay.go
Detect oversized request bodies and map to HTTP 413 (skip-retry); add fastTokenCountMetaForPricing to avoid heavy allocations when token counting is disabled; adjust retry/error mapping for body-read errors.
Error type improvements
types/error.go
Add Unwrap() error to NewAPIError to expose underlying error for errors.Is / errors.As.
Logging / formatting tidy-ups
controller/task.go, relay/relay_task.go, middleware/distributor.go, relay/channel/baidu/relay-baidu.go, relay/channel/coze/relay-coze.go, relay/channel/task/jimeng/adaptor.go, relay/channel/task/kling/adaptor.go, relay/channel/task/suno/adaptor.go
Replace direct fmt.Errorf(raw) with fmt.Errorf("%s", ...) and fix a logging format string; other minor log formatting fixes.
Minor formatting/whitespace
controller/discord.go, relay/channel/aws/constants.go, setting/system_setting/discord.go, controller/topup_creem.go
Indentation, alignment and import reordering only. No behavioral change.

Sequence Diagram

sequenceDiagram
    participant Client
    participant Middleware as Gzip/Brotli Middleware
    participant Common as GetRequestBody (common/gin.go)
    participant Controller as Relay Controller
    participant Response

    Client->>Middleware: POST (possibly compressed)
    Middleware->>Middleware: Detect compression (gzip/brotli/none)
    Middleware->>Middleware: Wrap source with MaxBytesReader(limit = MaxRequestBodyMB)
    alt Decompressed size exceeds limit
        Middleware->>Response: Error (oversized body -> 413)
    else Size within limit
        Middleware->>Common: Pass wrapped reader via c.Request.Body
        Common->>Common: io.LimitReader read, enforce limit, cache body in context
        alt Body exceeds limit during read
            Common->>Controller: Return ErrRequestBodyTooLarge
            Controller->>Response: HTTP 413 (skip retry)
        else Body OK
            Common->>Controller: Return body bytes
            Controller->>Controller: Process request / pricing / token counting
            Controller->>Response: Normal response
        end
    end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

  • pay special attention to:
    • common/gin.go: correctness of size enforcement, fallback behavior, body caching, and resource closing.
    • middleware/gzip.go: post-decompression MaxBytesReader wrapping, correct closing of original and decompressor readers, and removal of Content-Encoding.
    • controller/relay.go: mapping oversized errors to 413 and ensuring retry/skip semantics; correctness of fastTokenCountMetaForPricing across request types.
    • types/error.go: Unwrap implementation and interactions with NewAPIError usages.

Possibly related PRs

  • alpha -> mian #2007 — touches NewAPIError in types/error.go; likely related to error-type changes and unwrap behavior.

Suggested reviewers

  • seefs001
  • creamlike1024

Poem

🐰
I nibbled bytes and capped the heap,
Thirty-two megabytes I safely keep,
Gzip unwrapped, Brotli unrolled,
Oversize now politely told —
Four-thirteen seals the memory's keep!

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 5.56% which is insufficient. The required threshold is 80.00%. You can run @coderabbitai generate docstrings to improve docstring coverage.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly addresses the main objective: preventing OOM on large/decompressed requests by implementing request body size limits.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/oom-request-body-limit

📜 Recent review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8e3f9b1 and 8cb56fc.

📒 Files selected for processing (4)
  • common/gin.go (1 hunks)
  • controller/relay.go (6 hunks)
  • middleware/gzip.go (1 hunks)
  • types/error.go (1 hunks)
🧰 Additional context used
🧠 Learnings (1)
📚 Learning: 2025-06-21T03:37:41.726Z
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.

Applied to files:

  • controller/relay.go
🧬 Code graph analysis (2)
common/gin.go (1)
constant/env.go (1)
  • MaxRequestBodyMB (12-12)
middleware/gzip.go (1)
constant/env.go (1)
  • MaxRequestBodyMB (12-12)
🔇 Additional comments (14)
types/error.go (1)

97-103: LGTM!

The Unwrap() implementation correctly enables errors.Is/errors.As to traverse the error chain. The nil receiver guard is consistent with other methods on this type.

controller/relay.go (6)

108-114: Minor redundancy in error check, but harmless.

IsRequestBodyTooLargeError(err) already calls errors.Is(err, common.ErrRequestBodyTooLarge) internally, so the || errors.Is(...) is redundant. However, this is defensive coding and doesn't cause issues.


123-131: LGTM!

Good optimization to avoid building large CombineText strings when token counting and sensitive checks are both disabled. This aligns with the PR objective of preventing OOM on large-context requests.


133-140: LGTM!

The added meta != nil guard prevents potential nil pointer dereference when accessing meta.CombineText.


190-199: LGTM!

Correct error handling that distinguishes between oversized bodies (413) and other body read errors (400), both with skip-retry to prevent infinite retry loops on unrecoverable errors.


244-269: LGTM!

Well-designed lightweight helper that extracts only the MaxTokens field needed for pricing, avoiding the expensive CombineText string concatenation. The special handling for ImageRequest (delegating to full GetTokenCountMeta) is appropriate since image pricing has different requirements.


485-494: LGTM!

Consistent error handling with the main Relay function, correctly using TaskErrorWrapperLocal for task relay context while maintaining the same 413/400 status code distinction.

common/gin.go (2)

21-32: LGTM!

The helper correctly detects both the custom sentinel error and http.MaxBytesError from http.MaxBytesReader, ensuring consistent error identification regardless of where the size limit is enforced.


34-62: LGTM with a note on the error flow.

The implementation correctly uses the LimitReader(maxBytes+1) pattern to detect oversized bodies by checking len(body) > maxBytes after reading. This works because io.LimitReader doesn't error on limit—it just stops reading.

The check on line 51 (IsRequestBodyTooLargeError(err)) acts as a fallback for cases where the body is already wrapped by http.MaxBytesReader (from the decompression middleware), which will return http.MaxBytesError during reading.

middleware/gzip.go (5)

13-23: LGTM!

Clean wrapper type that enables proper cleanup of both the decompressor and the underlying body through a single Close() call.


31-40: LGTM!

Consistent max size handling with common/gin.go. Using http.MaxBytesReader here is appropriate as it enforces the limit during streaming reads, which is essential for defending against zip bombs (small compressed payload expanding to huge decompressed data).


43-58: LGTM!

The gzip path correctly:

  1. Creates the decompressor from the original body
  2. Closes the original body on initialization error
  3. Wraps the decompressed stream with MaxBytesReader to enforce post-decompression size limits
  4. Uses readCloser to ensure both the gzip reader and original body are closed when the request body is closed

59-67: LGTM!

The brotli path correctly handles that brotli.NewReader doesn't return an error and the reader doesn't implement io.Closer, so only the original body needs to be closed.


68-71: LGTM!

Good addition to enforce size limits on uncompressed bodies as well, ensuring consistent protection against oversized requests regardless of content encoding.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (2)
relay/channel/coze/relay-coze.go (1)

211-211: Log formatting fix looks good; consider adding punctuation for readability.

The change correctly resolves the vet/formatting issue by using format verbs. However, the current format produces output like "stream event error: 500Internal Server Error" which concatenates the code and message with just a space.

Consider this optional improvement for better log readability:

-		common.SysLog(fmt.Sprintf("stream event error: %v %v", errorData.Code, errorData.Message))
+		common.SysLog(fmt.Sprintf("stream event error: code=%v msg=%v", errorData.Code, errorData.Message))

or

-		common.SysLog(fmt.Sprintf("stream event error: %v %v", errorData.Code, errorData.Message))
+		common.SysLog(fmt.Sprintf("stream event error: %v - %v", errorData.Code, errorData.Message))
common/gin.go (1)

41-45: Consider extracting the fallback constant.

Both this file and middleware/gzip.go use 64 as the fallback when MaxRequestBodyMB <= 0. Consider extracting this to a named constant in the constant package to ensure consistency and document the default clearly.

+// In constant/env.go
+const DefaultMaxRequestBodyMB = 64

// In common/gin.go and middleware/gzip.go
 maxMB := constant.MaxRequestBodyMB
 if maxMB <= 0 {
-    maxMB = 64
+    maxMB = constant.DefaultMaxRequestBodyMB
 }
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 11593bd and 8e3f9b1.

📒 Files selected for processing (21)
  • README.en.md (1 hunks)
  • README.fr.md (1 hunks)
  • README.ja.md (1 hunks)
  • README.md (1 hunks)
  • common/gin.go (1 hunks)
  • common/init.go (1 hunks)
  • constant/env.go (1 hunks)
  • controller/discord.go (1 hunks)
  • controller/relay.go (4 hunks)
  • controller/task.go (2 hunks)
  • controller/topup_creem.go (1 hunks)
  • middleware/distributor.go (1 hunks)
  • middleware/gzip.go (1 hunks)
  • relay/channel/aws/constants.go (1 hunks)
  • relay/channel/baidu/relay-baidu.go (2 hunks)
  • relay/channel/coze/relay-coze.go (1 hunks)
  • relay/channel/task/jimeng/adaptor.go (1 hunks)
  • relay/channel/task/kling/adaptor.go (1 hunks)
  • relay/channel/task/suno/adaptor.go (1 hunks)
  • relay/relay_task.go (1 hunks)
  • setting/system_setting/discord.go (1 hunks)
🧰 Additional context used
🧠 Learnings (3)
📚 Learning: 2025-08-08T17:12:43.157Z
Learnt from: RedwindA
Repo: QuantumNous/new-api PR: 1537
File: relay/gemini_handler.go:330-342
Timestamp: 2025-08-08T17:12:43.157Z
Learning: In the new-api repository, the `GeminiEmbeddingHandler` function in `relay/gemini_handler.go` is designed specifically for native Gemini embedding requests and therefore does not require the `ConvertGeminiRequest` step that is used in the chat handler. The embedding requests are already in the native Gemini format and don't need conversion.

Applied to files:

  • relay/channel/baidu/relay-baidu.go
📚 Learning: 2025-08-26T09:59:00.337Z
Learnt from: Sh1n3zZ
Repo: QuantumNous/new-api PR: 1659
File: relay/relay_task.go:285-305
Timestamp: 2025-08-26T09:59:00.337Z
Learning: In controller/task_video.go, the redactVideoResponseBody function sanitizes video task responses by removing bytesBase64Encoded fields and truncating base64 strings to 256 characters to prevent large binary data from being stored in task.Data.

Applied to files:

  • relay/channel/task/kling/adaptor.go
📚 Learning: 2025-06-21T03:37:41.726Z
Learnt from: 9Ninety
Repo: QuantumNous/new-api PR: 1273
File: relay/channel/gemini/relay-gemini.go:97-116
Timestamp: 2025-06-21T03:37:41.726Z
Learning: In relay/channel/gemini/relay-gemini.go, the thinking budget calculation logic (including the MaxOutputTokens multiplication) was introduced in PR #1247. PR #1273 focused specifically on decoupling the thoughts summary feature from thinking budget settings and did not modify the existing thinking budget behavior.

Applied to files:

  • controller/relay.go
🧬 Code graph analysis (11)
relay/channel/task/jimeng/adaptor.go (1)
service/error.go (1)
  • TaskErrorWrapper (142-159)
relay/relay_task.go (1)
service/error.go (1)
  • TaskErrorWrapper (142-159)
middleware/gzip.go (1)
constant/env.go (1)
  • MaxRequestBodyMB (12-12)
relay/channel/coze/relay-coze.go (1)
common/sys_log.go (1)
  • SysLog (11-14)
controller/discord.go (1)
setting/system_setting/discord.go (1)
  • GetDiscordSettings (19-21)
common/gin.go (1)
constant/env.go (1)
  • MaxRequestBodyMB (12-12)
controller/task.go (2)
logger/logger.go (1)
  • LogError (65-67)
common/sys_log.go (1)
  • SysLog (11-14)
relay/channel/task/kling/adaptor.go (1)
service/error.go (1)
  • TaskErrorWrapperLocal (136-140)
relay/channel/task/suno/adaptor.go (2)
service/error.go (1)
  • TaskErrorWrapper (142-159)
dto/openai_request.go (1)
  • Message (283-294)
common/init.go (1)
constant/env.go (1)
  • MaxRequestBodyMB (12-12)
controller/relay.go (8)
common/gin.go (2)
  • IsRequestBodyTooLargeError (23-32)
  • ErrRequestBodyTooLarge (21-21)
types/error.go (4)
  • NewErrorWithStatusCode (259-275)
  • ErrorCodeReadRequestBodyFailed (61-61)
  • ErrOptionWithSkipRetry (334-338)
  • NewError (204-224)
constant/env.go (1)
  • CountToken (8-8)
relay/common/relay_info.go (1)
  • TokenCountMeta (76-79)
types/request_meta.go (3)
  • TokenCountMeta (20-31)
  • TokenType (12-12)
  • TokenTypeTokenizer (16-16)
dto/request_common.go (1)
  • Request (8-12)
dto/openai_request.go (2)
  • GeneralOpenAIRequest (26-99)
  • OpenAIResponsesRequest (792-817)
dto/claude.go (1)
  • ClaudeRequest (192-215)
🪛 LanguageTool
README.fr.md

[grammar] ~304-~304: Il y a peut-être une erreur ici
Context: ...mes/zip bombs qui saturent la mémoire). Dépassement ⇒ 413 | 32 | | `AZURE_DEFAULT_API_V...

(QB_NEW_FR)


[grammar] ~304-~304: Il y a peut-être une erreur ici
Context: ...s qui saturent la mémoire). Dépassement ⇒ 413 | 32 | | `AZURE_DEFAULT_API_VER...

(QB_NEW_FR)


[grammar] ~304-~304: Il y a peut-être une erreur ici
Context: ...qui saturent la mémoire). Dépassement ⇒ 413 | 32 | | AZURE_DEFAULT_API_VERSION | Version...

(QB_NEW_FR)

🔇 Additional comments (28)
controller/topup_creem.go (1)

13-15: Import reordering looks good.

The standard library imports are now consistently ordered alphabetically, and all imports are actively used throughout the file. No functional changes.

controller/discord.go (1)

117-123: Formatting alignment approved.

The indentation adjustment aligns line 117 with the preceding if block, correcting the code style without affecting logic or behavior. This is consistent with the PR's goal of fixing formatting issues.

relay/relay_task.go (1)

199-199: LGTM: Safer error construction.

The explicit "%s" format specifier prevents potential panics or format string injection if responseBody contains format directives like %s or %d.

README.en.md (1)

308-308: LGTM: Clear documentation of the new limit.

The description clearly explains the post-decompression measurement, the purpose (preventing memory exhaustion from large payloads/zip bombs), and the HTTP 413 response behavior.

relay/channel/aws/constants.go (1)

21-21: LGTM: Cosmetic alignment adjustment.

Whitespace-only change for consistency; no functional impact.

README.fr.md (1)

304-304: LGTM: Consistent French documentation.

The French translation accurately documents the new MAX_REQUEST_BODY_MB variable, maintaining consistency with the English version.

setting/system_setting/discord.go (1)

6-8: LGTM: Cosmetic formatting.

Field alignment adjustments only; no functional changes.

README.md (1)

309-309: LGTM: Consistent Chinese documentation.

The Chinese documentation accurately describes the new MAX_REQUEST_BODY_MB variable, maintaining consistency with other language versions.

relay/channel/task/suno/adaptor.go (1)

108-108: LGTM: Safer error construction.

The explicit "%s" format specifier prevents potential panics if sunoResponse.Message contains format directives.

relay/channel/task/jimeng/adaptor.go (1)

199-199: LGTM: Safer error construction.

The explicit "%s" format specifier prevents potential panics if jResp.Message contains format directives. This change aligns with the consistent error-handling pattern applied across other adaptors in this PR.

relay/channel/task/kling/adaptor.go (1)

189-189: LGTM: Security improvement via explicit string formatting.

The change from fmt.Errorf(kResp.Message) to fmt.Errorf("%s", kResp.Message) prevents format string injection vulnerabilities if kResp.Message contains format specifiers like %v or %s. This is part of a consistent PR-wide pattern applied across multiple adaptors.

middleware/distributor.go (1)

165-165: LGTM: Security improvement via explicit string formatting.

Consistent with the PR-wide pattern, this prevents format string injection if mjErr.Description contains format specifiers.

controller/task.go (2)

91-91: LGTM: Fixed incorrect format verb.

Corrected from %d (integer) to %s (string) for err.Error(), which returns a string. The previous format would have printed a numeric memory address rather than the error message.


144-144: LGTM: Fixed incorrect format verb.

Corrected from %d (integer) to %s (string) for string(responseBody). The previous format would have caused incorrect log output.

relay/channel/baidu/relay-baidu.go (1)

153-153: LGTM: Security improvement via explicit string formatting.

Both changes (in baiduHandler and baiduEmbeddingHandler) prevent format string injection by explicitly formatting baiduResponse.ErrorMsg as a string, consistent with the PR-wide security hardening pattern.

Also applies to: 178-178

controller/relay.go (4)

108-113: LGTM: Proper HTTP status code for oversized requests.

The change correctly maps oversized request bodies to HTTP 413 (Request Entity Too Large) with skip-retry, allowing clients to handle the error appropriately. The dual check (IsRequestBodyTooLargeError(err) || errors.Is(err, common.ErrRequestBodyTooLarge)) ensures both wrapped and direct error cases are caught.


133-140: Good defensive guard for sensitive text checking.

The nil check needSensitiveCheck && meta != nil prevents panics if the fast path returns a meta with empty CombineText. This is correct defensive coding.


235-260: Image request pricing path verified and consistent.

The fastTokenCountMetaForPricing helper correctly delegates to r.GetTokenCountMeta() for ImageRequest, which properly calculates and returns ImagePriceRatio based on size, quality, and image count. This ratio is subsequently applied in pricing calculations. For other request types, the function extracts only MaxTokens and skips building the expensive CombineText.

The GeneralOpenAIRequest token selection logic is consistent: both the fast path and the full GetTokenCountMeta() implementation use the same comparison—preferring MaxCompletionTokens when it exceeds MaxTokens, which aligns with newer API versions.


123-131: No nil safety concerns—the optimization is sound and safe as designed.

The fast path intentionally omits CombineText to avoid large allocations, as documented in the code. ModelPriceHelper does not access CombineText at all, and the fields it does use (MaxTokens) are properly initialized in fastTokenCountMetaForPricing. EstimateRequestToken has explicit nil checks and early exits when token counting is disabled, so it never accesses fields from the fast-path meta.

Likely an incorrect or invalid review comment.

constant/env.go (1)

12-12: LGTM: New configuration variable follows existing pattern.

The addition of MaxRequestBodyMB is consistent with existing configuration variables like MaxFileDownloadMB and StreamScannerMaxBufferMB. It integrates cleanly with the environment-based initialization in common/init.go.

README.ja.md (1)

313-313: LGTM: Clear and complete documentation.

The documentation for MAX_REQUEST_BODY_MB correctly specifies:

  • Default value (32)
  • Measurement point (after decompression)
  • Purpose (prevent memory exhaustion from large requests/zip bombs)
  • Behavior on exceed (HTTP 413)

The note that the limit is measured post-decompression is particularly important for users to understand.

common/init.go (1)

120-121: LGTM: Proper initialization with sensible default.

The initialization follows the established pattern using GetEnvOrDefault, and the default of 32 MB is a reasonable balance between allowing legitimate large requests (e.g., Claude's 200K context) and preventing memory exhaustion attacks.

The Chinese comment clearly explains the purpose: preventing memory spikes from oversized requests or zip bombs.

middleware/gzip.go (4)

13-23: LGTM: Clean readCloser wrapper.

The struct correctly implements io.ReadCloser by embedding io.Reader and providing a Close() method that delegates to closeFn. The nil check in Close() is appropriate defensive coding.


31-35: Good defense in depth with size limits on all request types.

Applying the max body size limit via http.MaxBytesReader even for uncompressed bodies (default case) ensures consistent protection against oversized payloads regardless of encoding. The fallback to 64 MB when MaxRequestBodyMB <= 0 provides a safe default.

Also applies to: 68-70


43-58: LGTM: Proper resource cleanup chain for gzip.

The closeFn correctly closes both the gzipReader and the origBody in sequence. The error path at line 46 properly closes origBody before aborting, preventing resource leaks.


59-67: LGTM: Correct Brotli handling.

Unlike gzip.NewReader, brotli.NewReader doesn't require error handling as it returns a reader that will surface errors on first read. The closeFn correctly only closes origBody since the Brotli reader doesn't have an explicit Close method.

common/gin.go (2)

21-32: LGTM: Clean error type with comprehensive detection.

The sentinel error ErrRequestBodyTooLarge combined with IsRequestBodyTooLargeError provides a unified way to detect oversized bodies from both:

  1. The custom error returned by GetRequestBody
  2. The http.MaxBytesError returned by http.MaxBytesReader in the middleware

This normalization ensures consistent error handling throughout the codebase.


34-62: LGTM: Well-designed body reading with caching and size enforcement.

Key design points that work correctly:

  1. Caching (lines 35-40): Returns cached body without re-validation, which is correct since it was already validated on first read.

  2. Overflow detection (line 47): Using io.LimitReader(c.Request.Body, maxBytes+1) is the idiomatic Go pattern—reading exactly maxBytes+1 bytes indicates the body exceeded the limit.

  3. Layered protection: This provides a secondary guard after the middleware's http.MaxBytesReader, ensuring defense in depth.

  4. Error normalization (lines 51-53): Converts http.MaxBytesError from upstream MaxBytesReader to the consistent ErrRequestBodyTooLarge.

@t0ng7u
t0ng7u requested a review from seefs001 December 16, 2025 09:13
@t0ng7u t0ng7u self-assigned this Dec 16, 2025
Tighten oversized request handling across relay paths and make error matching reliable.

- Align `MAX_REQUEST_BODY_MB` fallback to `32` in request body reader and decompression middleware
- Stop ignoring `GetRequestBody` errors in relay retry paths; return consistent **413** on oversized bodies (400 for other read errors)
- Add `Unwrap()` to `types.NewAPIError` so `errors.Is/As` can match wrapped underlying errors
- `go test ./...` passes
@seefs001
seefs001 merged commit b35ae9f into main Dec 16, 2025
@seefs001
seefs001 deleted the fix/oom-request-body-limit branch December 16, 2025 10:22
ennnnny pushed a commit to ennnnny/new-api that referenced this pull request Mar 17, 2026
@coderabbitai coderabbitai Bot mentioned this pull request May 26, 2026
8 of 11 tasks
@coderabbitai coderabbitai Bot mentioned this pull request Jun 2, 2026
8 of 11 tasks
salem-2007 added a commit to salem-2007/new-api that referenced this pull request Sep 10, 2026
junjundesk pushed a commit to junjundesk/new-api that referenced this pull request Oct 3, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants