Skip to content

fix: limit anonymous request body - #5244

Merged
seefs001 merged 2 commits into
QuantumNous:mainfrom
seefs001:fix/webhook
Jun 5, 2026
Merged

fix: limit anonymous request body#5244
seefs001 merged 2 commits into
QuantumNous:mainfrom
seefs001:fix/webhook

Conversation

@seefs001

@seefs001 seefs001 commented Jun 2, 2026

Copy link
Copy Markdown
Collaborator

⚠️ 提交说明 / PR Notice

Important

  • 请提供人工撰写的简洁摘要,避免直接粘贴未经整理的 AI 输出。

📝 变更描述 / Description

(简述:做了什么?为什么这样改能生效?请基于你对代码逻辑的理解来写,避免粘贴未经整理的内容)

对一些接口增加body limit,环境变量 ANONYMOUS_REQUEST_BODY_LIMIT_KB,默认为 512 (512KB)

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix) - 请关联对应 Issue,避免将设计取舍、理解偏差或预期不一致直接归类为 bug
  • ✨ 新功能 (New feature) - 重大特性建议先通过 Issue 沟通
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

🔗 关联任务 / Related Issue

  • Closes # (如有)

✅ 提交前检查项 / Checklist

  • 人工确认: 我已亲自整理并撰写此描述,没有直接粘贴未经处理的 AI 输出。
  • 非重复提交: 我已搜索现有的 IssuesPRs,确认不是重复提交。
  • Bug fix 说明: 若此 PR 标记为 Bug fix,我已提交或关联对应 Issue,且不会将设计取舍、预期不一致或理解偏差直接归类为 bug。
  • 变更理解: 我已理解这些更改的工作原理及可能影响。
  • 范围聚焦: 本 PR 未包含任何与当前任务无关的代码改动。
  • 本地验证: 已在本地运行并通过测试或手动验证,维护者可以据此复核结果。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

📸 运行证明 / Proof of Work

(请在此粘贴截图、关键日志或测试报告,以证明变更生效)

Summary by CodeRabbit

  • New Features
    • Anonymous requests now enforce a configurable maximum body size (default 512 KB) via an environment variable.
    • Oversized anonymous requests are rejected with HTTP 413; malformed reads return HTTP 400.
    • Limit is applied to unauthenticated endpoints such as registration/login flows, webhook callbacks, and payment notification routes.

@coderabbitai

coderabbitai Bot commented Jun 2, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 2aa793bd-24b5-4d34-9528-016e7bfd6014

📥 Commits

Reviewing files that changed from the base of the PR and between e2d647e and 7eefc77.

📒 Files selected for processing (2)
  • common/request_body_limit.go
  • middleware/request_body_limit.go
🚧 Files skipped from review as they are similar to previous changes (2)
  • common/request_body_limit.go
  • middleware/request_body_limit.go

Walkthrough

Adds a configurable anonymous request-body size limit: new env-backed AnonymousRequestBodyLimitKB, a KB→bytes helper, a Gin middleware that enforces the limit (HTTP 413/400), and wiring into anonymous POST endpoints (registrations, logins, OAuth, webhooks, payment callbacks).

Changes

Anonymous Request Body Limit

Layer / File(s) Summary
Configuration and limit helper
constant/env.go, common/init.go, common/request_body_limit.go
Adds exported AnonymousRequestBodyLimitKB, initializes it from ANONYMOUS_REQUEST_BODY_LIMIT_KB (default 512), and provides GetAnonymousRequestBodyLimitBytes() converting KB to bytes.
Request body limit middleware
middleware/request_body_limit.go
Adds AnonymousRequestBodyLimit() middleware that reads up to the configured byte limit, responds HTTP 413 on oversized bodies, HTTP 400 on read errors, and replaces c.Request.Body with a buffered reader for handlers.
Router integration
router/api-router.go
Applies the middleware to anonymous POST endpoints under /api (e.g., /setup, /user/register, /user/login, password reset, OAuth binding POSTs, webhook callbacks, and payment notification POSTs).

Sequence Diagram

sequenceDiagram
  participant Client
  participant AnonymousRequestBodyLimit
  participant Handler
  Client->>AnonymousRequestBodyLimit: POST request with body
  AnonymousRequestBodyLimit->>AnonymousRequestBodyLimit: Read body up to limit + 1
  alt Body exceeds limit
    AnonymousRequestBodyLimit-->>Client: HTTP 413 Payload Too Large
  else Body within limit
    AnonymousRequestBodyLimit->>Handler: Pass request with buffered body
    Handler-->>Client: Response
  else Read error
    AnonymousRequestBodyLimit-->>Client: HTTP 400 Bad Request
  end
Loading

Possibly related PRs

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I nibble bytes with tidy care,
KB to bytes, a guarded snare,
POSTs now checked at the burrow gate,
413 keeps payloads straight,
A small, safe hop—no data scare. 🥕

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title 'fix: limit anonymous request body' accurately summarizes the main change—adding request body size limits for anonymous endpoints via a new environment variable and middleware.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

🧹 Nitpick comments (1)
middleware/request_body_limit.go (1)

19-29: ⚡ Quick win

Short-circuit obvious oversize requests before reading the body.

When Content-Length is already greater than maxBytes, we can return 413 immediately instead of reading and buffering maxBytes+1 bytes first. That avoids unnecessary I/O on the exact path this middleware is protecting.

Proposed change
 		originalBody := c.Request.Body
 		maxBytes := common.GetAnonymousRequestBodyLimitBytes()
+		if c.Request.ContentLength > maxBytes {
+			_ = originalBody.Close()
+			c.AbortWithStatus(http.StatusRequestEntityTooLarge)
+			return
+		}
 		limitedBody, err := readAnonymousRequestBody(originalBody, maxBytes)
 		_ = originalBody.Close()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@middleware/request_body_limit.go` around lines 19 - 29, The middleware
currently reads and buffers the request body even when Content-Length already
exceeds maxBytes; modify the handler (around where originalBody :=
c.Request.Body and maxBytes := common.GetAnonymousRequestBodyLimitBytes() are
used) to first check c.Request.ContentLength (and fall back to parsing the
"Content-Length" header if needed) and if that length > maxBytes call
c.AbortWithStatus(http.StatusRequestEntityTooLarge) and return without calling
readAnonymousRequestBody or reading the body; preserve the existing error-path
behavior that uses common.IsRequestBodyTooLargeError and ensure the originalBody
is not consumed/closed when you early-return.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@middleware/request_body_limit.go`:
- Around line 19-29: The middleware currently reads and buffers the request body
even when Content-Length already exceeds maxBytes; modify the handler (around
where originalBody := c.Request.Body and maxBytes :=
common.GetAnonymousRequestBodyLimitBytes() are used) to first check
c.Request.ContentLength (and fall back to parsing the "Content-Length" header if
needed) and if that length > maxBytes call
c.AbortWithStatus(http.StatusRequestEntityTooLarge) and return without calling
readAnonymousRequestBody or reading the body; preserve the existing error-path
behavior that uses common.IsRequestBodyTooLargeError and ensure the originalBody
is not consumed/closed when you early-return.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

Run ID: 8f8bed39-525d-4379-8f2a-43584a6231c0

📥 Commits

Reviewing files that changed from the base of the PR and between 0ff9c35 and e2d647e.

📒 Files selected for processing (5)
  • common/init.go
  • common/request_body_limit.go
  • constant/env.go
  • middleware/request_body_limit.go
  • router/api-router.go

@seefs001
seefs001 merged commit d2f7f9e into QuantumNous:main Jun 5, 2026
1 check passed
Soein added a commit to Soein/new-api that referenced this pull request Jun 6, 2026
… id 等)

主要变更(QuantumNous/new-api → adc390c):
- feat: 渠道被禁用后可配置是否清空渠道粘性 (QuantumNous#5306)
- feat(web): profile 页显示 user id (QuantumNous#5317)
- fix: 复用 channel handler 的 stream scanner buffer (QuantumNous#5225)
- fix: 收窄 OpenAI o 系列模型适配范围 (QuantumNous#5293)
- fix(relay): GLM Anthropic 兼容避免 chunked encoding (QuantumNous#5307)
- fix: 新增 relay idle 连接超时配置 (QuantumNous#5309)
- fix: 限制匿名请求体大小 (QuantumNous#5244)
- fix(distributor): 修复 video generations task_id 模型解析 (QuantumNous#5133)
- fix(dify): 远程图片字段赋值前初始化 file pointer (QuantumNous#5134)
- fix(i18n): 优化 thinking adapter 文案 (QuantumNous#5242)

去合规一致性:上游未触及任何合规文件,合并完整保留本地去合规状态
(payment_setting.go / payment-settings-section.tsx / recharge-form-card.tsx /
risk-acknowledgement-dialog.tsx 均未被改动)。

i18n:web/default 6 语言(en/zh/fr/ja/ru/vi)key 并集三路合并 + i18n:sync
规范化,4584 keys/语言,missing/extras/untranslated 全为 0。

验证:go build ./... ✅ + bun run typecheck ✅
Ember-Moth pushed a commit to Ember-Moth/new-api that referenced this pull request Jun 7, 2026
* fix: limit anonymous request body (env ANONYMOUS_REQUEST_BODY_LIMIT_KB = 512)

* fix: allow disabling anonymous request body limit
szxufan pushed a commit to szxufan/new-api that referenced this pull request Jun 9, 2026
* fix: limit anonymous request body (env ANONYMOUS_REQUEST_BODY_LIMIT_KB = 512)

* fix: allow disabling anonymous request body limit
52assert added a commit to 52assert/new-api that referenced this pull request Jun 10, 2026
…codes

* origin/main: (45 commits)
  fix(openai): support streaming image relay and image edit for images API  (QuantumNous#4608)
  perf(web): improve dialog sizing and footer layout
  feat(web): add shared dialog wrapper
  perf(web): simplify public page hero copy
  perf(model-pricing): move pricing tabs into page title
  feat(json-editor): add reusable JSON code editor
  perf(model-pricing): improve JSON pricing editor layout
  perf(model-pricing): reduce duplicate model name display
  fix: support six-decimal steps in model pricing editor
  fix: respect theme for multiselect combobox popover
  fix: reuse stream scanner buffer in channel handlers (QuantumNous#5225)
  fix: 收窄 OpenAI o 系列模型适配范围 (QuantumNous#5293)
  fix(i18n): clarify thinking adapter copy (QuantumNous#5242)
  fix: limit anonymous request body (QuantumNous#5244)
  fix(relay): fix Anthropic-compatible compatibility for GLM (avoid chunked encoding) (QuantumNous#5307)
  feat: 支持配置渠道被禁用后是否清空渠道粘性 (QuantumNous#5306)
  fix: add relay idle connection timeout config (QuantumNous#5309)
  feat(web): show user id on profile page
  perf(model-pricing): refine visual editor actions
  refactor(model-pricing): split visual pricing editor modules
  ...

# Conflicts:
#	router/api-router.go
#	web/default/src/features/usage-logs/components/usage-logs-mobile-card.tsx
endercat-alu pushed a commit to endercat-alu/new-api that referenced this pull request Jun 10, 2026
* fix: limit anonymous request body (env ANONYMOUS_REQUEST_BODY_LIMIT_KB = 512)

* fix: allow disabling anonymous request body limit

(cherry picked from commit d2f7f9e)
OuYang-HX pushed a commit to OuYang-HX/new-api that referenced this pull request Jun 13, 2026
* fix: limit anonymous request body (env ANONYMOUS_REQUEST_BODY_LIMIT_KB = 512)

* fix: allow disabling anonymous request body limit
yangshare added a commit to yangshare/new-api that referenced this pull request Jun 16, 2026
合并上游 QuantumNous/new-api v1.0.0-rc.11,主要新增 Claude Opus 4.8、
OpenAI 图片流式中继、渠道粘性清空选项、安全审计日志、模型定价双栏重构、
Dialog prop-based API 重构。

冲突解决(20 文件):
- 13 个 dialog 采用上游新结构,保留 dev sm: 响应式前缀与 ESLint 注释
- common-logs-columns / details-dialog 的 multikey 徽章功能完整保留
- channels-table 采用上游 useDebouncedColumnFilter
- model-pricing-sheet / model-ratio-visual-editor 采用 upstream 版本
- codex-oauth-dialog 删除(跟随上游 QuantumNous#5461)

撞车修复核对通过:视频任务 GET 验证(QuantumNous#4834/QuantumNous#5133)、匿名请求体限制(QuantumNous#5244)
逻辑均正确保留,无重复。

验证:前端 typecheck + 生产 build 通过,后端 go build 通过,i18n 全语言对齐。
ruanhangjian pushed a commit to ruanhangjian/new-api that referenced this pull request Jul 11, 2026
* fix: limit anonymous request body (env ANONYMOUS_REQUEST_BODY_LIMIT_KB = 512)

* fix: allow disabling anonymous request body limit
zhaodechao2008 pushed a commit to zhaodechao2008/new-api that referenced this pull request Jul 27, 2026
* fix: limit anonymous request body (env ANONYMOUS_REQUEST_BODY_LIMIT_KB = 512)

* fix: allow disabling anonymous request body limit
330079598 pushed a commit to 330079598/new-api that referenced this pull request Aug 19, 2026
* fix: limit anonymous request body (env ANONYMOUS_REQUEST_BODY_LIMIT_KB = 512)

* fix: allow disabling anonymous request body limit
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.

1 participant