Skip to content

fix(task-plugin): set multipart content type for upstream requests - #7655

Merged
Calcium-Ion merged 2 commits into
QuantumNous:mainfrom
LauZzL:fix/task-plugin-multipart-content-type
Oct 8, 2026
Merged

Calcium-Ion merged 2 commits into
QuantumNous:mainfrom
LauZzL:fix/task-plugin-multipart-content-type

Conversation

@LauZzL

@LauZzL LauZzL commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ 提交说明 / PR Notice

English template: .github/PULL_REQUEST_TEMPLATE/en.md

Important

  • 描述可用 AI 辅助。提交前请审阅并精炼全文,仅保留维护者需要复核的要点,并声明对其负责。PR 正文及后续评论均不得直接粘贴未经人工过滤的大段 AI 文本;多次提交此类内容可能会被 block。
  • 开启透传请勿反馈问题;透传会直接发送内容,不会经过 new-api 的逻辑处理。
  • 请按本模板填写后再提交。

🔗 关联任务 / Related Issue

  • 新功能请填写下方 Issue 编号;若还没有对应 Issue,请先自行创建。功能讨论请放在 Issue 中进行。

  • 改动较大或方向性变更,请先在关联 Issue 中与维护者达成一致,再提交 PR。

  • Bug 修复请关联对应 Issue。设计取舍、理解偏差或预期不一致,更适合作为讨论或功能请求。

  • Closes #

🚀 变更类型 / Type of change

  • 🐛 Bug 修复 (Bug fix)
  • ✨ 新功能 (New feature)
  • ⚡ 性能优化 / 重构 (Refactor)
  • 📝 文档更新 (Documentation)

📝 变更描述 / Description

任务插件中,当构造钩子返回的 bodyType 为 multipart 时,宿主会重新构造请求体:

writer := multipart.NewWriter(&body)
...
writer.Close()
c.Request.Header.Set("Content-Type", writer.FormDataContentType()) // Content-Type: multipart/form-data; boundary=cf34b....

此时会生成一个新的boundary,宿主在 DoTaskApiRequest 重新构建了一个上游请求:

req, err := newTaskAPIRequest(c, fullRequestURL, requestBody)
...
a.BuildRequestHeader(c, req, info)

新的 req.Header 并不会自动继承 c.Request.Header,而 BuildRequestHeader 只复制插件声明的 Header:

for name, value := range a.submit.Headers {
    req.Header.Set(name, value)
}

这就导致了实际发往上游的请求中缺少了由宿主重新生成的 Content-Type,虽然插件允许在构造钩子返回 Header,但由于 Content-Type boundary 由宿主构建请求体时动态生成,无法在插件中动态获取或使用 ctx.requestHeaders["Content-Type"] 解决这个问题 (boundary不一致会导致 multipart: NextPart: EOF 。

修复方案:

在 BuildRequestHeader 中为 BodyType 为 multipart 类型的请求设置由宿主生成的 Content-Type:

func (a *TaskAdaptor) BuildRequestHeader(c *gin.Context, req *http.Request, _ *relaycommon.RelayInfo) error {
	if a.submit == nil {
		return fmt.Errorf("plugin submit request was not built")
	}

	for name, value := range a.submit.Headers {
		req.Header.Set(name, value)
	}

	if a.submit.BodyType == "multipart" && c != nil && c.Request != nil {
		contentType := c.Request.Header.Get("Content-Type")
		mediaType, params, err := mime.ParseMediaType(contentType)
		if err == nil &&
			strings.EqualFold(mediaType, "multipart/form-data") &&
			params["boundary"] != "" {
			req.Header.Set("Content-Type", contentType)
		}
	}

	return nil
}

📸 运行证明 / Proof of Work

测试使用了 Sora 官方插件(图生视频)以及 自行构建的 OpenAI Image 插件(edits)。

未修复前:

  1. 向newapi发起请求
POST /v1/images/edits HTTP/1.1
Authorization: Bearer ...
Connection: keep-alive
Content-Length: 58854
Content-Type: multipart/form-data; boundary=----WebKitFormBoundarygy551Cs9AbewJGsq
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/154.0.0.0 Safari/537.36

------WebKitFormBoundarygy551Cs9AbewJGsq
Content-Disposition: form-data; name="model"

gpt-image-2.5
------WebKitFormBoundarygy551Cs9AbewJGsq
Content-Disposition: form-data; name="prompt"

参考图片编号:图片1。请按这些编号理解提示词中的图片引用。

给人物换个发型
------WebKitFormBoundarygy551Cs9AbewJGsq
Content-Disposition: form-data; name="n"

1
------WebKitFormBoundarygy551Cs9AbewJGsq
Content-Disposition: form-data; name="output_format"

png
------WebKitFormBoundarygy551Cs9AbewJGsq
Content-Disposition: form-data; name="size"

1024x1024
------WebKitFormBoundarygy551Cs9AbewJGsq
Content-Disposition: form-data; name="image"; filename="头像.jpg"
Content-Type: image/jpeg
  1. 宿主重新构建请求后发送上游:
POST upstream/v1/images/edits HTTP/1.1
Authorization: Bearer ...
Content-Length: 59139
Host: upstream
User-Agent: Go-http-client/1.1

--02e3670bb0cfb7cec8e340b42a3d7d517f09a20c33d840171fabd396a7e0
Content-Disposition: form-data; name=model

gpt-image-2.5
--02e3670bb0cfb7cec8e340b42a3d7d517f09a20c33d840171fabd396a7e0
Content-Disposition: form-data; name=response_format

url
--02e3670bb0cfb7cec8e340b42a3d7d517f09a20c33d840171fabd396a7e0
Content-Disposition: form-data; name=n

1
--02e3670bb0cfb7cec8e340b42a3d7d517f09a20c33d840171fabd396a7e0
Content-Disposition: form-data; name=output_format

png
--02e3670bb0cfb7cec8e340b42a3d7d517f09a20c33d840171fabd396a7e0
Content-Disposition: form-data; name=prompt

参考图片编号:图片1。请按这些编号理解提示词中的图片引用。

给人物换个发型
--02e3670bb0cfb7cec8e340b42a3d7d517f09a20c33d840171fabd396a7e0
Content-Disposition: form-data; name=size

1024x1024
--02e3670bb0cfb7cec8e340b42a3d7d517f09a20c33d840171fabd396a7e0
Content-Disposition: form-data; filename*=utf-8''%E5%A4%B4%E5%83%8F.jpg; name=image
Content-Type: image/jpeg

由于缺少 Content-Type,所以上游无法正常解析body内容:

{"error":{"code":"","message":"未指定模型名称,模型名称不能为空 (request id: ...)","type":"new_api_error"}}
{"error":{"message":"failed to parse request body","type":"invalid_request_error"}}

当在插件中的构造钩子声明 "Content-Type": ctx.requestHeaders["Content-Type"], 则会因为 boundary 不一致导致无法正常解析请求体:

{"error":{"message":"read multipart body: multipart: NextPart: EOF","type":"invalid_request_error"}}

修复后:

POST upstream/v1/images/edits HTTP/1.1
Authorization: Bearer ...
Content-Length: 59139
Content-Type: multipart/form-data; boundary=d2751c249f7a116ea810d68484d66f57c5dec5fc4f79da3b1b864ed790d4
Host: upstream
User-Agent: Go-http-client/1.1

--d2751c249f7a116ea810d68484d66f57c5dec5fc4f79da3b1b864ed790d4
Content-Disposition: form-data; name=model

gpt-image-2.5
--d2751c249f7a116ea810d68484d66f57c5dec5fc4f79da3b1b864ed790d4
Content-Disposition: form-data; name=response_format

url
--d2751c249f7a116ea810d68484d66f57c5dec5fc4f79da3b1b864ed790d4
Content-Disposition: form-data; name=n

1
--d2751c249f7a116ea810d68484d66f57c5dec5fc4f79da3b1b864ed790d4
Content-Disposition: form-data; name=output_format

png
--d2751c249f7a116ea810d68484d66f57c5dec5fc4f79da3b1b864ed790d4
Content-Disposition: form-data; name=prompt

参考图片编号:图片1。请按这些编号理解提示词中的图片引用。

给人物换个发型
--d2751c249f7a116ea810d68484d66f57c5dec5fc4f79da3b1b864ed790d4
Content-Disposition: form-data; name=size

1024x1024
--d2751c249f7a116ea810d68484d66f57c5dec5fc4f79da3b1b864ed790d4
Content-Disposition: form-data; filename*=utf-8''%E5%A4%B4%E5%83%8F.jpg; name=image
Content-Type: image/jpeg

修正后构建的上游请求正常携带由宿主生成的 Content-Type。

Test:

go test ./relay/channel/task/jsplugin: ok github.com/QuantumNous/new-api/relay/channel/task/jsplugin 2.775s

✅ 提交前检查项 / Checklist

  • 人工确认: 无论描述是否由 AI 生成,我已审阅并精炼全文,仅保留可复核的要点,并声明对其准确性与完整性负责。PR 正文及后续评论均未直接粘贴未经人工过滤的大段 AI 文本。
  • 非重复提交: 我已搜索现有的 Issues 与 PRs,确认不是重复提交。
  • 新功能关联 Issue: 若此 PR 标记为 New feature,我已关联对应 Issue;若尚无 Issue,我已先自行创建。
  • 事前沟通: 若改动较大或涉及方向性变更,已在关联 Issue 中与维护者沟通并达成一致。
  • 功能范围: 本 PR 不是 Coding Plan、逆向渠道、第三方封装接口,也不是对 Codex 渠道类型的改动。
  • 非透传: 本 PR 不是针对开启透传后的转发行为;透传会直接发送内容,不会经过 new-api 的逻辑处理。
  • 范围聚焦: 本 PR 为一项聚焦改动,未包含无关代码。
  • 本地验证: 已按变更路径实际验证,并写明命令与观察结果。仅声明 go build 通过或测试通过,不视为有效证明。
  • 安全合规: 代码中无敏感凭据,且符合项目代码规范。

Summary by CodeRabbit

  • Bug Fixes
    • Multipart submissions now use the incoming request’s Content-Type header, preserving its boundary so multipart data can be parsed correctly. Non-multipart submissions continue to use the plugin-provided Content-Type.

@coderabbitai

coderabbitai Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Organization UI
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 08e6552d-7e1e-4673-9a8e-86afbcdec9b1
📥 Commits

Reviewing files that changed from the base of the PR and between 1facdef and d494f4d.

📒 Files selected for processing (2)
  • relay/channel/task/jsplugin/adaptor.go
  • relay/channel/task/jsplugin/adaptor_test.go

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 9 remain after this review.


Walkthrough

BuildRequestHeader uses the client request’s Content-Type for multipart submissions. The test parses the generated request header and uses its boundary to read the rebuilt multipart body.

Changes

Multipart request headers

Layer / File(s) Summary
Apply and verify multipart content type
relay/channel/task/jsplugin/adaptor.go, relay/channel/task/jsplugin/adaptor_test.go
For multipart submissions, the adaptor uses the client request’s Content-Type after applying plugin-provided headers. The test parses the generated request header and uses its boundary to read the rebuilt body.

Priority: ⬇️ Low

Estimated code review effort: 2 (Simple) | ~8 minutes

Change: Bug fix

Suggested reviewers: calcium-ion

Merge Risk: ⚪ Minimal · up to d494f

The rebuilt multipart body and upstream header use the same boundary, and the test checks that pairing. No actionable merge-blocking risk remains in the reviewed changes.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 1facd

The change aligns multipart headers with the generated request body without changing destinations or access privileges. No introduced security concern was established, but exceptional execution paths have only partial validation.

Retained concerns
No architecture-level concerns identified.

Security review details

Security Blast Radius

  • inferred — The demonstrated effect is confined to framing individual multipart upstream submissions. The normal factory creates a fresh adaptor for each request, providing separation for cached submit state; broader cross-tenant or privilege expansion was not established.

Trust Boundaries and Controls

  • observed — In the normal body-building path, the client’s original top-level Content-Type is replaced by the host-generated framing value before header construction. That value takes precedence over plugin Content-Type configuration. Media-type validation alone would not prove host ownership for a standalone caller that skipped body construction; no such production caller was established.

Resilience and Maintainability Implications

  • observed — Multipart construction errors return before publishing a new boundary. Temporary form cleanup is deferred, and opened input files are closed. Reusable parsing saves the original Content-Type separately, avoiding reparsing original bytes with a subsequently generated boundary.
  • observed — The generated multipart body is returned as a bytes.Reader. The existing dispatch path supports snapshot-based replay for this body type and avoids installing a replay closure that would reuse a consumed reader. The PR does not introduce a new retry or recovery mechanism.
🚥 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%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 2 files. 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 clearly and concisely describes the main change: fixing the multipart Content-Type for upstream requests generated by the task plugin.
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.
  • Fix all pre-merge checks with AI
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

A rabbit checks the headers with care,
A boundary travels from here to there.
The multipart pages find their way,
The rebuilt form is read today.
Soft paws tap; the tests pass along,
Then hop away with a header song.

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

BuildRequestBody stores writer.FormDataContentType() on the client
request right before BuildRequestHeader runs, so the media type and
boundary checks could never fail. Copy the value directly, as the sora
adaptor did before task plugins.

The test plugin now forwards the client's Content-Type, whose boundary
differs from the rebuilt body, so the test also fails if a plugin header
wins over the host value.
@Calcium-Ion
Calcium-Ion merged commit 7aa3531 into QuantumNous:main Oct 8, 2026
3 checks passed
@LauZzL
LauZzL deleted the fix/task-plugin-multipart-content-type branch October 19, 2026 03:28
timwenx pushed a commit to timwenx/new-api that referenced this pull request Nov 18, 2026
…uantumNous#7655)

* fix(task-plugin): set multipart content type for upstream requests

* refactor(task-plugin): copy the rebuilt multipart Content-Type as is

BuildRequestBody stores writer.FormDataContentType() on the client
request right before BuildRequestHeader runs, so the media type and
boundary checks could never fail. Copy the value directly, as the sora
adaptor did before task plugins.

The test plugin now forwards the client's Content-Type, whose boundary
differs from the rebuilt body, so the test also fails if a plugin header
wins over the host value.

---------

Co-authored-by: CaIon <[email protected]>
xiaolanawaqaq pushed a commit to xiaolanawaqaq/new-apiaaa that referenced this pull request Nov 26, 2026
…uantumNous#7655)

* fix(task-plugin): set multipart content type for upstream requests

* refactor(task-plugin): copy the rebuilt multipart Content-Type as is

BuildRequestBody stores writer.FormDataContentType() on the client
request right before BuildRequestHeader runs, so the media type and
boundary checks could never fail. Copy the value directly, as the sora
adaptor did before task plugins.

The test plugin now forwards the client's Content-Type, whose boundary
differs from the rebuilt body, so the test also fails if a plugin header
wins over the host value.

---------

Co-authored-by: CaIon <[email protected]>
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