From 48f9df96ea7c68eae04a0f3687869f232f48929f Mon Sep 17 00:00:00 2001 From: Sky Date: Fri, 20 Nov 2026 16:42:10 +0800 Subject: [PATCH] =?UTF-8?q?fix(task):=20=E4=BF=AE=E5=A4=8D=E7=A7=81?= =?UTF-8?q?=E6=9C=89=E6=B8=A0=E9=81=93=E7=9A=84=E4=BB=BB=E5=8A=A1=E5=AA=92?= =?UTF-8?q?=E4=BD=93=E4=B8=8B=E8=BD=BD=20(#8199)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(task): allow media downloads from the task channel origin * fix(task): recognize default ports on IPv6 media origins --- controller/video_proxy.go | 42 ++-- controller/video_proxy_channel_test.go | 264 +++++++++++++++++++++++++ docs/plugin-api/v1.md | 8 + 3 files changed, 303 insertions(+), 11 deletions(-) create mode 100644 controller/video_proxy_channel_test.go diff --git a/controller/video_proxy.go b/controller/video_proxy.go index 88e9efea12..d851a4d254 100644 --- a/controller/video_proxy.go +++ b/controller/video_proxy.go @@ -219,15 +219,30 @@ func proxyTaskMedia(c *gin.Context, task *model.Task, descriptor *relaychannel.T } setting := channel.GetSetting() proxy := strings.TrimSpace(setting.Proxy) - if err := validateTaskMediaURL(rawURL, proxy); err != nil { - return &taskMediaProxyError{ - status: http.StatusBadGateway, code: "artifact_request_rejected", - message: "Artifact request was rejected", err: err, + var trustedOrigin *url.URL + if taskHasPluginExecution(task) && !descriptor.Credentialless { + baseURL := channel.GetBaseURL() + if baseURL == "" { + baseURL = constant.GetChannelBaseURL(channel.Type) + } + channelURL, parseErr := url.Parse(baseURL) + if parseErr == nil && channelURL.User == nil && channelURL.Fragment == "" && sameTaskMediaOrigin(channelURL, parsedURL) { + // A validated plugin request to the operator-configured channel uses + // the same private upstream transport as submission and polling. + trustedOrigin = channelURL + } + } + if trustedOrigin == nil { + if err := validateTaskMediaURL(rawURL, proxy); err != nil { + return &taskMediaProxyError{ + status: http.StatusBadGateway, code: "artifact_request_rejected", + message: "Artifact request was rejected", err: err, + } } } client := service.GetSSRFProtectedHTTPClient() - if proxy != "" { + if trustedOrigin != nil || proxy != "" { client, err = service.GetHttpClientWithProxySettings(proxy, setting) if err != nil { return &taskMediaProxyError{ @@ -262,7 +277,7 @@ func proxyTaskMedia(c *gin.Context, task *model.Task, descriptor *relaychannel.T req.Header.Set(name, value) } - client = taskMediaRedirectClient(client, proxy, c, clientHeaders, descriptor.Credentialless) + client = taskMediaRedirectClient(client, proxy, c, clientHeaders, descriptor.Credentialless, trustedOrigin) clientWithoutBodyTimeout := *client clientWithoutBodyTimeout.Timeout = 0 resp, err := doTaskMediaRequest(&clientWithoutBodyTimeout, req, taskMediaResponseHeaderTimeout) @@ -491,7 +506,7 @@ func applyTaskMediaRequestHeaders(destination http.Header, headers map[string]st return nil } -func taskMediaRedirectClient(base *http.Client, proxy string, c *gin.Context, clientHeaders map[string]string, credentialless bool) *http.Client { +func taskMediaRedirectClient(base *http.Client, proxy string, c *gin.Context, clientHeaders map[string]string, credentialless bool, trustedOrigin *url.URL) *http.Client { cloned := *base cloned.CheckRedirect = func(req *http.Request, via []*http.Request) error { if len(via) >= 10 { @@ -501,7 +516,11 @@ func taskMediaRedirectClient(base *http.Client, proxy string, c *gin.Context, cl req.URL.Host == "" || req.URL.User != nil || req.URL.Fragment != "" { return fmt.Errorf("%w: invalid redirect URL", errTaskMediaRequestRejected) } - if err := validateTaskMediaURL(req.URL.String(), proxy); err != nil { + if trustedOrigin != nil { + if !sameTaskMediaOrigin(trustedOrigin, req.URL) { + return fmt.Errorf("%w: redirect outside channel origin", errTaskMediaRequestRejected) + } + } else if err := validateTaskMediaURL(req.URL.String(), proxy); err != nil { return fmt.Errorf("%w: %v", errTaskMediaRequestRejected, err) } if isSelfTaskMediaURL(c, req.URL) { @@ -558,11 +577,12 @@ func normalizeTaskMediaHost(scheme, host string) string { if err != nil { return strings.TrimSuffix(host, ".") } - hostname = strings.TrimSuffix(strings.ToLower(hostname), ".") if (strings.EqualFold(scheme, "http") && port == "80") || (strings.EqualFold(scheme, "https") && port == "443") { - return hostname + // Keep an IPv6 literal bracketed, as it is when the port is omitted. + host = strings.TrimSuffix(host, ":"+port) + return strings.TrimSuffix(host, ".") } - return net.JoinHostPort(hostname, port) + return net.JoinHostPort(strings.TrimSuffix(hostname, "."), port) } func isSelfTaskMediaURL(c *gin.Context, target *url.URL) bool { diff --git a/controller/video_proxy_channel_test.go b/controller/video_proxy_channel_test.go new file mode 100644 index 0000000000..05fed9fb77 --- /dev/null +++ b/controller/video_proxy_channel_test.go @@ -0,0 +1,264 @@ +package controller + +import ( + "net/http" + "net/http/httptest" + "net/url" + "strings" + "sync/atomic" + "testing" + + "github.com/QuantumNous/new-api/common" + "github.com/QuantumNous/new-api/constant" + "github.com/QuantumNous/new-api/model" + relaychannel "github.com/QuantumNous/new-api/relay/channel" + "github.com/QuantumNous/new-api/relaykit/dto" + "github.com/QuantumNous/new-api/service" + "github.com/QuantumNous/new-api/setting/system_setting" + "github.com/gin-gonic/gin" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func setupPrivateChannelMediaTest(t *testing.T) *model.Task { + t.Helper() + task := setupGenericTaskTest(t) + previousFetch := *system_setting.GetFetchSetting() + previousCache := common.MemoryCacheEnabled + common.MemoryCacheEnabled = false + *system_setting.GetFetchSetting() = system_setting.FetchSetting{ + EnableSSRFProtection: true, ApplyIPFilterForDomain: true, + AllowedPorts: []string{"443"}, + } + service.InitHttpClient() + t.Cleanup(func() { + common.MemoryCacheEnabled = previousCache + *system_setting.GetFetchSetting() = previousFetch + service.InitHttpClient() + }) + task.Platform = constant.TaskPlatform("google") + task.PrivateData.Execution = &model.TaskExecutionSnapshot{TaskPlugin: &model.TaskPluginSnapshot{ + Key: "google", Name: "Google Veo (Gemini API)", Version: "1.2.0", APIVersion: 1, + }} + return task +} + +func TestPrivateChannelMediaDownloadEndpoints(t *testing.T) { + for _, endpoint := range []string{"video", "artifact"} { + for _, method := range []string{http.MethodGet, http.MethodHead} { + t.Run(endpoint+"/"+method, func(t *testing.T) { + task := setupPrivateChannelMediaTest(t) + var requests atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + assert.Equal(t, method, r.Method) + assert.Equal(t, "provider-key", r.Header.Get("x-goog-api-key")) + assert.Equal(t, "bytes=0-3", r.Header.Get("Range")) + assert.Equal(t, `"video-etag"`, r.Header.Get("If-Range")) + assert.Empty(t, r.Header.Get("Authorization"), "the caller's token must stay at the gateway") + if r.URL.Path == "/start" { + http.Redirect(w, r, "/video", http.StatusTemporaryRedirect) + return + } + w.Header().Set("Content-Type", "video/mp4") + w.Header().Set("Content-Length", "4") + w.Header().Set("Content-Range", "bytes 0-3/10") + w.WriteHeader(http.StatusPartialContent) + if r.Method != http.MethodHead { + _, _ = w.Write([]byte("data")) + } + })) + defer upstream.Close() + require.NoError(t, model.DB.Model(&model.Channel{}).Where("id = ?", task.ChannelId).Updates(map[string]any{ + "type": constant.ChannelTypeGemini, "base_url": upstream.URL, "key": "provider-key", + }).Error) + task.SetData(map[string]any{"response": map[string]any{ + "generateVideoResponse": map[string]any{ + "generatedSamples": []any{map[string]any{"video": map[string]any{"uri": upstream.URL + "/start"}}}, + }, + }}) + require.NoError(t, model.DB.Save(task).Error) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Set("id", task.UserId) + c.Set("token_id", 1) + path := "/v1/videos/" + task.TaskID + "/content" + handler := VideoProxy + c.Params = gin.Params{{Key: "task_id", Value: task.TaskID}} + if endpoint == "artifact" { + path = "/v1/tasks/" + task.TaskID + "/artifacts/video/content" + handler = TaskArtifactContent + c.Params = gin.Params{{Key: "key", Value: task.TaskID}, {Key: "artifact_key", Value: "video"}} + } + c.Request = httptest.NewRequest(method, path, nil) + c.Request.Header.Set("Authorization", "Bearer caller-token") + c.Request.Header.Set("Range", "bytes=0-3") + c.Request.Header.Set("If-Range", `"video-etag"`) + handler(c) + + assert.Equal(t, http.StatusPartialContent, recorder.Code, recorder.Body.String()) + assert.Equal(t, int32(2), requests.Load(), "same-origin redirects must work without relaxing global SSRF settings") + assert.Equal(t, "video/mp4", recorder.Header().Get("Content-Type")) + assert.Equal(t, "4", recorder.Header().Get("Content-Length")) + assert.Equal(t, "bytes 0-3/10", recorder.Header().Get("Content-Range")) + assert.Equal(t, "private, no-store", recorder.Header().Get("Cache-Control")) + if method == http.MethodHead { + assert.Empty(t, recorder.Body.String()) + } else { + assert.Equal(t, "data", recorder.Body.String()) + } + assert.False(t, system_setting.GetFetchSetting().AllowPrivateIp) + }) + } + } +} + +func TestPrivateChannelMediaDoesNotTrustOtherURLs(t *testing.T) { + for _, name := range []string{"credentialless", "legacy", "other-channel", "other-scheme", "userinfo", "fragment"} { + t.Run(name, func(t *testing.T) { + task := setupPrivateChannelMediaTest(t) + var requests atomic.Int32 + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + })) + defer upstream.Close() + baseURL := upstream.URL + descriptor := &relaychannel.TaskContentRequest{URL: upstream.URL + "/video", Method: http.MethodGet} + switch name { + case "credentialless": + descriptor.Credentialless = true + case "legacy": + task.PrivateData.Execution = nil + case "other-channel": + baseURL = "http://127.0.0.1:1" + case "other-scheme": + baseURL = strings.Replace(baseURL, "http:", "https:", 1) + case "userinfo": + descriptor.URL = strings.Replace(descriptor.URL, "http://", "http://user:password@", 1) + case "fragment": + descriptor.URL += "#fragment" + } + require.NoError(t, model.DB.Model(&model.Channel{}).Where("id = ?", task.ChannelId).Update("base_url", baseURL).Error) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodGet, "/content", nil) + err := proxyTaskMedia(c, task, descriptor) + var proxyErr *taskMediaProxyError + require.ErrorAs(t, err, &proxyErr) + assert.Equal(t, "artifact_request_rejected", proxyErr.code) + assert.Zero(t, requests.Load()) + }) + } +} + +func TestPrivateChannelMediaRejectsCrossOriginRedirect(t *testing.T) { + task := setupPrivateChannelMediaTest(t) + // Even a globally permitted destination must not inherit the channel's trust. + system_setting.GetFetchSetting().AllowPrivateIp = true + system_setting.GetFetchSetting().AllowedPorts = []string{"1-65535"} + var destinationRequests, sourceRequests atomic.Int32 + destination := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + destinationRequests.Add(1) + })) + defer destination.Close() + source := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + sourceRequests.Add(1) + http.Redirect(w, r, destination.URL, http.StatusFound) + })) + defer source.Close() + require.NoError(t, model.DB.Model(&model.Channel{}).Where("id = ?", task.ChannelId).Update("base_url", source.URL).Error) + c, _ := gin.CreateTestContext(httptest.NewRecorder()) + c.Request = httptest.NewRequest(http.MethodGet, "/content", nil) + err := proxyTaskMedia(c, task, &relaychannel.TaskContentRequest{ + URL: source.URL, Method: http.MethodGet, Headers: map[string]string{"Authorization": "Bearer provider-key"}, + }) + var proxyErr *taskMediaProxyError + require.ErrorAs(t, err, &proxyErr) + assert.Equal(t, "artifact_request_rejected", proxyErr.code) + assert.Equal(t, int32(1), sourceRequests.Load()) + assert.Zero(t, destinationRequests.Load(), "no request or credentials may reach the redirect target") +} + +func TestPrivateChannelMediaUsesChannelProxy(t *testing.T) { + task := setupPrivateChannelMediaTest(t) + var requests atomic.Int32 + proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + assert.Equal(t, "http://private-upstream.invalid:8080/video", r.URL.String()) + assert.Equal(t, "Bearer provider-key", r.Header.Get("Authorization")) + _, _ = w.Write([]byte("data")) + })) + defer proxy.Close() + channel, err := model.CacheGetChannel(task.ChannelId) + require.NoError(t, err) + channel.SetSetting(dto.ChannelSettings{Proxy: proxy.URL}) + require.NoError(t, model.DB.Model(channel).Updates(map[string]any{ + "base_url": "http://private-upstream.invalid:8080", "setting": channel.Setting, + }).Error) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodGet, "/content", nil) + require.NoError(t, proxyTaskMedia(c, task, &relaychannel.TaskContentRequest{ + URL: "http://private-upstream.invalid:8080/video", Headers: map[string]string{"Authorization": "Bearer provider-key"}, + })) + assert.Equal(t, http.StatusOK, recorder.Code) + assert.Equal(t, "data", recorder.Body.String()) + assert.Equal(t, int32(1), requests.Load()) +} + +func TestPrivateChannelMediaUsesChannelTLSSettings(t *testing.T) { + for _, skipVerify := range []bool{false, true} { + t.Run(map[bool]string{false: "verify", true: "channel-opt-out"}[skipVerify], func(t *testing.T) { + task := setupPrivateChannelMediaTest(t) + var requests atomic.Int32 + upstream := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + _, _ = w.Write([]byte("data")) + })) + defer upstream.Close() + channel, err := model.CacheGetChannel(task.ChannelId) + require.NoError(t, err) + channel.SetSetting(dto.ChannelSettings{TLSInsecureSkipVerify: skipVerify}) + require.NoError(t, model.DB.Model(channel).Updates(map[string]any{ + "base_url": upstream.URL, "setting": channel.Setting, + }).Error) + recorder := httptest.NewRecorder() + c, _ := gin.CreateTestContext(recorder) + c.Request = httptest.NewRequest(http.MethodGet, "/content", nil) + err = proxyTaskMedia(c, task, &relaychannel.TaskContentRequest{URL: upstream.URL + "/video"}) + if !skipVerify { + var proxyErr *taskMediaProxyError + require.ErrorAs(t, err, &proxyErr) + assert.Equal(t, "artifact_upstream_error", proxyErr.code) + assert.Zero(t, requests.Load(), "private upstream trust must not disable certificate validation") + return + } + require.NoError(t, err) + assert.Equal(t, http.StatusOK, recorder.Code) + assert.Equal(t, "data", recorder.Body.String()) + assert.Equal(t, int32(1), requests.Load()) + }) + } +} + +func TestTaskMediaChannelOriginComparison(t *testing.T) { + for _, tc := range []struct { + base, target string + allowed bool + }{ + {"https://provider.example/v1", "https://PROVIDER.example:443/video", true}, + {"http://provider.example/v1", "http://provider.example:80/video", true}, + {"http://[::1]:80", "http://[::1]/video", true}, + {"http://[::1]:8080", "http://[::1]:8080/video", true}, + {"https://provider.example", "http://provider.example/video", false}, + {"http://provider.example:8080", "http://provider.example:8081/video", false}, + {"http://provider.example", "http://provider.example.evil.test/video", false}, + } { + t.Run(tc.target, func(t *testing.T) { + base, err := url.Parse(tc.base) + require.NoError(t, err) + target, err := url.Parse(tc.target) + require.NoError(t, err) + assert.Equal(t, tc.allowed, sameTaskMediaOrigin(base, target)) + }) + } +} diff --git a/docs/plugin-api/v1.md b/docs/plugin-api/v1.md index 5698bf99aa..110c0bba1d 100644 --- a/docs/plugin-api/v1.md +++ b/docs/plugin-api/v1.md @@ -728,6 +728,14 @@ submission. Content requests keep the host of their URL; credentialless content requests and `utils.fetch` are sent as the plugin builds them. An invalid header value fails the request. +Credentialed `buildContentRequest` URLs on the task channel's base URL origin +(same scheme, hostname and effective port) use that channel's HTTP client and +transport settings, including private upstreams. Redirects must stay on that +origin. This trust applies only to plugin tasks, not to credentialless requests +or legacy result URLs. Other content URLs, including extra `meta.allowedHosts`, +keep the global fetch SSRF checks; an allowed credential recipient does not +grant private-network access. + `buildSubmitRequest` returns a request descriptor. JSON bodies (the default) may embed a file placeholder at any object or array depth. The host replaces each placeholder with an encoded string before the request is sent; JavaScript never sees file bytes. ```js