Repository navigation
🛡️ fix: prevent OOM on large/decompressed requests; skip heavy prompt… - #2452
Conversation
… 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
WalkthroughAdds 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
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes
Possibly related PRs
Suggested reviewers
Poem
Pre-merge checks and finishing touches❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✨ Finishing touches
🧪 Generate unit tests (beta)
📜 Recent review detailsConfiguration used: CodeRabbit UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (4)
🧰 Additional context used🧠 Learnings (1)📚 Learning: 2025-06-21T03:37:41.726ZApplied to files:
🧬 Code graph analysis (2)common/gin.go (1)
middleware/gzip.go (1)
🔇 Additional comments (14)
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. Comment |
There was a problem hiding this comment.
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.gouse64as the fallback whenMaxRequestBodyMB <= 0. Consider extracting this to a named constant in theconstantpackage 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
📒 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 ifresponseBodycontains format directives like%sor%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_MBvariable, 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_MBvariable, 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 ifsunoResponse.Messagecontains format directives.relay/channel/task/jimeng/adaptor.go (1)
199-199: LGTM: Safer error construction.The explicit
"%s"format specifier prevents potential panics ifjResp.Messagecontains 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)tofmt.Errorf("%s", kResp.Message)prevents format string injection vulnerabilities ifkResp.Messagecontains format specifiers like%vor%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.Descriptioncontains format specifiers.controller/task.go (2)
91-91: LGTM: Fixed incorrect format verb.Corrected from
%d(integer) to%s(string) forerr.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) forstring(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
baiduHandlerandbaiduEmbeddingHandler) prevent format string injection by explicitly formattingbaiduResponse.ErrorMsgas 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 != nilprevents panics if the fast path returns a meta with emptyCombineText. This is correct defensive coding.
235-260: Image request pricing path verified and consistent.The
fastTokenCountMetaForPricinghelper correctly delegates tor.GetTokenCountMeta()forImageRequest, which properly calculates and returnsImagePriceRatiobased on size, quality, and image count. This ratio is subsequently applied in pricing calculations. For other request types, the function extracts onlyMaxTokensand skips building the expensiveCombineText.The
GeneralOpenAIRequesttoken selection logic is consistent: both the fast path and the fullGetTokenCountMeta()implementation use the same comparison—preferringMaxCompletionTokenswhen it exceedsMaxTokens, 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
CombineTextto avoid large allocations, as documented in the code.ModelPriceHelperdoes not accessCombineTextat all, and the fields it does use (MaxTokens) are properly initialized infastTokenCountMetaForPricing.EstimateRequestTokenhas 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
MaxRequestBodyMBis consistent with existing configuration variables likeMaxFileDownloadMBandStreamScannerMaxBufferMB. It integrates cleanly with the environment-based initialization incommon/init.go.README.ja.md (1)
313-313: LGTM: Clear and complete documentation.The documentation for
MAX_REQUEST_BODY_MBcorrectly 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: CleanreadCloserwrapper.The struct correctly implements
io.ReadCloserby embeddingio.Readerand providing aClose()method that delegates tocloseFn. The nil check inClose()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.MaxBytesReadereven for uncompressed bodies (default case) ensures consistent protection against oversized payloads regardless of encoding. The fallback to 64 MB whenMaxRequestBodyMB <= 0provides a safe default.Also applies to: 68-70
43-58: LGTM: Proper resource cleanup chain for gzip.The
closeFncorrectly closes both thegzipReaderand theorigBodyin sequence. The error path at line 46 properly closesorigBodybefore aborting, preventing resource leaks.
59-67: LGTM: Correct Brotli handling.Unlike
gzip.NewReader,brotli.NewReaderdoesn't require error handling as it returns a reader that will surface errors on first read. ThecloseFncorrectly only closesorigBodysince the Brotli reader doesn't have an explicitClosemethod.common/gin.go (2)
21-32: LGTM: Clean error type with comprehensive detection.The sentinel error
ErrRequestBodyTooLargecombined withIsRequestBodyTooLargeErrorprovides a unified way to detect oversized bodies from both:
- The custom error returned by
GetRequestBody- The
http.MaxBytesErrorreturned byhttp.MaxBytesReaderin the middlewareThis 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:
Caching (lines 35-40): Returns cached body without re-validation, which is correct since it was already validated on first read.
Overflow detection (line 47): Using
io.LimitReader(c.Request.Body, maxBytes+1)is the idiomatic Go pattern—reading exactlymaxBytes+1bytes indicates the body exceeded the limit.Layered protection: This provides a secondary guard after the middleware's
http.MaxBytesReader, ensuring defense in depth.Error normalization (lines 51-53): Converts
http.MaxBytesErrorfrom upstreamMaxBytesReaderto the consistentErrRequestBodyTooLarge.
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
… 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(default32) and document it.http.MaxBytesReadercommon.GetRequestBodyand cache-safe handlingTokenCountMeta.CombineTextwhen both token counting and sensitive check are disabled (use lightweight meta for pricing)MAX_REQUEST_BODY_MBgo test ./...passesSummary by CodeRabbit
New Features
Documentation
Bug Fixes
✏️ Tip: You can customize this high-level summary in your review settings.