Skip to content

feat: add pass-through headers control for channels 渠道透传请求头开关 - #2302

Closed
w3ng-git wants to merge 7 commits into
QuantumNous:mainfrom
w3ng-git:dev
Closed

w3ng-git wants to merge 7 commits into
QuantumNous:mainfrom
w3ng-git:dev

Conversation

@w3ng-git

@w3ng-git w3ng-git commented Nov 25, 2025 •

Copy link
Copy Markdown

在渠道添加和管理页面,新增开关:用于透传用户其他的全部请求头给上游

目的:避免因上游可能的客户端限制等其他head部分限制导致客户无法通过中转使用目标服务

----------以下内容为ai总结⬇️
PR 描述

问题描述 / Problem

部分上游供应商(如 Anthropic Claude)会对客户端请求头进行检查,当发现缺少关键请求头(如
User-Agent、Origin、Referer)时,会返回 403 错误。目前 New-API 默认只转发 Content-Type 和 Accept
请求头,导致这些供应商的客户端限制无法通过。

Some upstream providers (e.g., Anthropic Claude) check client request headers and return 403 errors when key
headers (User-Agent, Origin, Referer) are missing. Currently, New-API only forwards Content-Type and Accept
headers by default, causing issues with providers that have client restrictions.

解决方案 / Solution

在渠道管理界面的"渠道额外设置"区块中新增"透传全部请求头"开关,启用后会转发所有客户端请求头(排除敏感头如
Authorization、Host、X-Forwarded-* 等),帮助解决上游供应商的客户端限制问题。

Added a "pass-through all request headers" toggle in the channel management interface. When enabled, it
forwards all client request headers (excluding sensitive ones like Authorization, Host, X-Forwarded-*) to
resolve upstream provider client restrictions.

主要改动 / Changes

后端 Backend

  • dto/channel_settings.go: 在 ChannelOtherSettings 中新增 PassThroughHeaders 字段
  • relay/channel/api_request.go:
    • 修改 SetupApiRequestHeader() 函数,增加条件判断逻辑
    • 添加敏感请求头过滤(Authorization、Host、Connection、X-API-Key、X-Forwarded-*)
    • 新增调试日志记录(在 DEBUG 模式下记录客户端请求头和上游请求头)

前端 Frontend

  • web/src/components/table/channels/modals/EditChannelModal.jsx:
    • 在"渠道额外设置"区块新增"透传全部请求头"开关
    • 实现状态加载、保存和更新逻辑
    • 所有渠道类型均可使用该功能

设计考虑 / Design Considerations

  1. 安全性:自动过滤敏感请求头(Authorization、Host、X-Forwarded-*、X-API-Key 等)
  2. 向后兼容:默认关闭,不影响现有渠道行为
  3. 通用性:适用于所有渠道类型,而非特定供应商
  4. 调试友好:在 DEBUG 模式下记录客户端和上游请求头,便于排查问题

测试 / Testing

  • 功能测试:开关正常工作,请求头正确转发
  • 安全测试:敏感请求头被正确过滤
  • 编辑测试:编辑渠道时正确加载之前的配置
  • 兼容性测试:默认关闭时与现有行为一致

Summary by CodeRabbit

  • New Features

    • Option to pass through all client request headers (off by default).
    • New toggle in Channel Extra Settings to enable header pass-through.
  • Security

    • When passthrough is enabled, only a safe whitelist of headers (e.g., those starting with anthropic-, plus x-app and user-agent) are forwarded; other sensitive headers remain excluded.
  • Diagnostics

    • Enhanced debug logging to show client and upstream request headers when debugging is enabled.
  • Chores

    • CI image metadata and tags updated.

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

w3ng-git and others added 4 commits November 26, 2025 00:31
- Add PassThroughHeaders field to ChannelOtherSettings
- Implement selective header forwarding in SetupApiRequestHeader
- Add UI switch in channel edit modal for Claude (type 14)
- Add debug logging to compare client vs upstream headers

This feature allows forwarding all client headers to upstream providers
to resolve 403 errors caused by client restrictions. By default, only
Content-Type and Accept headers are forwarded. When enabled, all headers
except sensitive ones (Authorization, Host, X-Forwarded-*, etc.) are
passed through.
Move the pass_through_headers UI switch from Claude-specific section
to the general Channel Extra Settings section, making it available
for all channel types.

This change aligns with the backend implementation which already
supports header pass-through for all channels. Now users can enable
this feature for any upstream provider that has client restrictions.

Location: Placed next to pass_through_body_enabled for better UX.
修复编辑渠道时未正确加载 pass_through_headers 字段状态的问题。
现在编辑渠道时,"透传全部请求头"开关会正确显示之前保存的状态。

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Nov 25, 2025 •

Copy link
Copy Markdown
Contributor

Walkthrough

Adds a boolean PassThroughHeaders to channel settings, forwards a whitelist of client headers to upstream when enabled, surfaces a UI toggle to control it, adds debug logging of client/upstream headers, and updates a CI workflow image repository name.

Changes

Cohort / File(s) Change Summary
Channel Configuration
dto/channel_settings.go
Added public PassThroughHeaders bool to ChannelOtherSettings with JSON tag pass_through_headers,omitempty.
Header passthrough & logging
relay/channel/api_request.go
When PassThroughHeaders is true, SetupApiRequestHeader forwards client headers whose lowercase names start with anthropic-, or equal x-app, or equal user-agent; preserves header values. Continues forwarding Content-Type and Accept by default and sets Accept: text/event-stream for streaming if missing. Added debug logs (gated by DebugEnabled) to log client request headers and upstream request headers.
UI Settings Control
web/src/components/table/channels/modals/EditChannelModal.jsx
Reads, initializes, and persists pass_through_headers from/to channel settings JSON. Adds a Form.Switch labeled "透传全部请求头" wired to component state and submit handling.
CI workflow image names
.github/workflows/docker-image-alpha.yml
Replaced Docker image repository references from calciumion/new-api to w3ng/new-api across metadata tags and manifest targets (string substitutions only).

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant Channel
    participant ReqHandler as Request Handler
    participant Upstream

    Client->>Channel: HTTP request (with headers)
    Channel->>ReqHandler: SetupApiRequestHeader(info, req)
    Note right of ReqHandler: Debug log client headers (if DebugEnabled)

    alt PassThroughHeaders = true
        ReqHandler->>ReqHandler: Select headers where name starts with "anthropic-" or name == "x-app" or name == "user-agent"
        ReqHandler->>ReqHandler: Copy selected headers to upstream request (preserve values)
    else
        ReqHandler->>ReqHandler: Forward default headers (Content-Type, Accept)
    end

    alt Streaming and Accept missing
        ReqHandler->>ReqHandler: Set Accept: text/event-stream
    end

    Note right of ReqHandler: Debug log upstream headers (if DebugEnabled)
    ReqHandler->>Upstream: Execute request
    Upstream-->>Channel: Response
    Channel-->>Client: Return response
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

  • Check header whitelist correctness and ensure no sensitive headers are accidentally forwarded.
  • Verify debug logging is gated and does not leak secrets in production.
  • Confirm UI reads/writes pass_through_headers across legacy/missing settings and persists JSON shape.
  • Validate CI workflow tag substitutions don't break manifest creation.

Possibly related PRs

Suggested reviewers

  • seefs001
  • Calcium-Ion

Poem

🐰 I hop through bits and headers bright,
I carry what is safe in flight.
A tiny switch, a careful tread,
Upstream greets the headers spread.
Hooray — those packets find their bed! 🥕

Pre-merge checks and finishing touches

❌ 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%. 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 clearly and specifically describes the main feature addition: a pass-through headers control for channels, with bilingual clarity (English and Chinese).
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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: 1

🧹 Nitpick comments (1)
web/src/components/table/channels/modals/EditChannelModal.jsx (1)

130-166: Consider adding explicit initialization and cleanup for consistency.

For consistency with other channelOtherSettings fields like allow_service_tier:

  1. Add pass_through_headers: false to originInputs (around line 166)
  2. Add delete localInputs.pass_through_headers in the submit cleanup section (around line 1223)

While the feature works correctly via implicit preservation in the settings JSON, explicit handling improves code maintainability and follows the established pattern for similar fields.

Suggested additions:

In originInputs (around line 166):

     allow_service_tier: false,
     disable_store: false, // false = 允许透传(默认开启)
     allow_safety_identifier: false,
+    pass_through_headers: false,
   };

In submit cleanup (around line 1223):

     delete localInputs.allow_service_tier;
     delete localInputs.disable_store;
     delete localInputs.allow_safety_identifier;
+    delete localInputs.pass_through_headers;

Also applies to: 1208-1223

📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between a6a20a2 and dbf91e2.

📒 Files selected for processing (3)
  • dto/channel_settings.go (1 hunks)
  • relay/channel/api_request.go (3 hunks)
  • web/src/components/table/channels/modals/EditChannelModal.jsx (4 hunks)
🧰 Additional context used
🧠 Learnings (2)
📚 Learning: 2025-08-27T02:15:25.448Z
Learnt from: AAEE86
Repo: QuantumNous/new-api PR: 1658
File: web/src/components/table/channels/modals/EditChannelModal.jsx:555-569
Timestamp: 2025-08-27T02:15:25.448Z
Learning: In EditChannelModal.jsx, the database stores mapped keys (display names) in the models field after applying model mapping transformations. When loading a channel, data.models contains the mapped keys, not the original model names. The filtering logic if (data.models.includes(key)) in the initialization is correct.

Applied to files:

  • web/src/components/table/channels/modals/EditChannelModal.jsx
📚 Learning: 2025-08-27T02:15:25.448Z
Learnt from: AAEE86
Repo: QuantumNous/new-api PR: 1658
File: web/src/components/table/channels/modals/EditChannelModal.jsx:555-569
Timestamp: 2025-08-27T02:15:25.448Z
Learning: In EditChannelModal.jsx, the applyModelMapping function transforms the models list by replacing original model names (mapping values) with display names (mapping keys). The database stores this transformed list containing mapped keys. On channel load, data.models contains these mapped display names, making the initialization filter if (data.models.includes(key)) correct.

Applied to files:

  • web/src/components/table/channels/modals/EditChannelModal.jsx
🧬 Code graph analysis (1)
relay/channel/api_request.go (3)
dto/channel_settings.go (1)
  • ChannelOtherSettings (26-35)
common/constants.go (1)
  • DebugEnabled (71-71)
logger/logger.go (1)
  • LogDebug (69-76)
🔇 Additional comments (4)
dto/channel_settings.go (1)

34-34: LGTM! Field addition follows Go conventions.

The new PassThroughHeaders field is correctly structured with proper json tags and clear documentation explaining the default behavior.

relay/channel/api_request.go (1)

97-101: Debug logging appropriately placed.

The debug logging hooks at both ends of the request pipeline (client headers and final upstream headers) will aid troubleshooting when the passthrough feature is enabled.

Also applies to: 115-118

web/src/components/table/channels/modals/EditChannelModal.jsx (2)

574-575: LGTM! Settings load logic correctly handles the new field.

The code properly reads pass_through_headers from the parsed settings and provides sensible defaults (false) for error cases and legacy data, consistent with the backend default.

Also applies to: 586-586, 596-596


2964-2978: UI switch implementation is correct.

The Form.Switch is properly wired using handleChannelOtherSettingsChange, which correctly updates the settings JSON, form state, and inputs. The help text clearly explains the feature behavior.

Comment thread relay/channel/api_request.go Resolved
w3ng-git and others added 3 commits November 26, 2025 02:14
Replace the website logo with a Hatsune Miku themed icon (120x120px).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
Change the PassThroughHeaders feature from blacklist mode (passing all headers except excluded ones) to whitelist mode (only passing specific extension headers).

Now when PassThroughHeaders is enabled, only these headers are passed through:
- anthropic-* prefix headers (anthropic-version, anthropic-beta, etc.)
- x-app header (application identifier)
- User-Agent header (for statistics)

This change prevents performance issues caused by passing unnecessary headers (like Accept-Encoding, Cache-Control, etc.) to upstream APIs.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>

@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: 1

🧹 Nitpick comments (1)
relay/channel/api_request.go (1)

33-70: Whitelist-based passthrough is safer but diverges from the “pass all headers” semantics and omits Origin/Referer.

The new whitelist (anthropic-*, x-app, user-agent) in SetupApiRequestHeader is a good move from a security standpoint and avoids leaking things like Cookie and Authorization. However:

  • The field ChannelOtherSettings.PassThroughHeaders is still documented as “透传全部客户端请求头(默认false,仅透传Content-Type和Accept)`, while the actual behavior now only passes a small subset of headers. This mismatch can confuse operators configuring channels.
  • The PR description mentions upstreams needing Origin and Referer, but those headers are not included in the whitelist, so they still won’t be forwarded even when PassThroughHeaders is true.

Please double-check the intended behavior:

  • If the goal is truly “all headers except a sensitive blocklist”, consider implementing that (with a strong denylist) instead of the current whitelist; or
  • If the intended behavior is “only specific extensions needed for Anthropic and friends”, consider updating the DTO comment / UI label to reflect that narrower scope and decide explicitly whether Origin/Referer should be included.
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fa1d3f8 and 2bbe46b.

⛔ Files ignored due to path filters (1)
  • web/public/logo.png is excluded by !**/*.png
📒 Files selected for processing (1)
  • relay/channel/api_request.go (3 hunks)
🧰 Additional context used
🧬 Code graph analysis (1)
relay/channel/api_request.go (4)
dto/request_common.go (1)
  • Request (8-12)
dto/channel_settings.go (1)
  • ChannelOtherSettings (26-35)
common/constants.go (1)
  • DebugEnabled (71-71)
logger/logger.go (1)
  • LogDebug (69-76)

Comment on lines +108 to +112
// 记录客户端原始请求头(用于调试)
if common2.DebugEnabled {
logger.LogDebug(c.Request.Context(), fmt.Sprintf("Client headers: %v", c.Request.Header))
}

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.

⚠️ Potential issue | 🟠 Major

Avoid logging full client/upstream headers; redact sensitive values before logging.

These debug logs will include sensitive headers such as Authorization, X-API-Key, Cookie / Set-Cookie, and X-Forwarded-*. Even behind DebugEnabled, that’s risky for log storage, incident exports, and multi-tenant environments.

Recommend logging a sanitized copy of headers with sensitive keys redacted, e.g.:

-	if common2.DebugEnabled {
-		logger.LogDebug(c.Request.Context(), fmt.Sprintf("Client headers: %v", c.Request.Header))
-	}
+	if common2.DebugEnabled {
+		logger.LogDebug(c.Request.Context(), fmt.Sprintf("Client headers: %v", sanitizeHeadersForLog(c.Request.Header)))
+	}
…
-	if common2.DebugEnabled {
-		logger.LogDebug(c.Request.Context(), fmt.Sprintf("Upstream headers: %v", headers))
-	}
+	if common2.DebugEnabled {
+		logger.LogDebug(c.Request.Context(), fmt.Sprintf("Upstream headers: %v", sanitizeHeadersForLog(headers)))
+	}

And add a helper like:

func sanitizeHeadersForLog(h http.Header) http.Header {
	sanitized := http.Header{}
	for k, values := range h {
		lower := strings.ToLower(k)
		if lower == "authorization" ||
			lower == "proxy-authorization" ||
			lower == "x-api-key" ||
			lower == "cookie" ||
			lower == "set-cookie" ||
			strings.HasPrefix(lower, "x-forwarded-") {
			sanitized[k] = []string{"***REDACTED***"}
		} else {
			sanitized[k] = append([]string(nil), values...)
		}
	}
	return sanitized
}

This keeps the debugging value while avoiding leaking raw secrets into logs.

Also applies to: 125-128

🤖 Prompt for AI Agents
In relay/channel/api_request.go around lines 108-112 (and similarly 125-128),
the debug logging prints full client/upstream headers which can leak sensitive
values; create a helper function sanitizeHeadersForLog(h http.Header) that
returns a copy with sensitive keys redacted (at minimum: authorization,
proxy-authorization, x-api-key, cookie, set-cookie and any header with prefix
x-forwarded-) and then replace direct logging of c.Request.Header (and upstream
headers) with logging of the sanitized copy so headers remain visible for
debugging but secrets are replaced with a constant like "***REDACTED***".

@w3ng-git w3ng-git closed this Nov 26, 2025
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