RAGFlow is an agent-native database: a Retrieval-Augmented Generation (RAG) engine that grew into context infrastructure.
Go agent-harnessagent-native-databaseagentic-aiagentic-retrievalagentic-searchaiai-agentscontext-enginecontext-engineeringcontext-managementharness-engineeringknowledge-compilationragretrieval-augmented-generationretrieval-harnesssearch-harness
fix(agent): runtime fixes for tool naming, legacy sessions, tenant scoping and MCP SSRF (#20558)
Andrej Kratkyaffbc9777063
diff --git a/internal/agent/component/agent.go b/internal/agent/component/agent.goindex 9a2a0e23de..fd079a5b6f 100644--- a/internal/agent/component/agent.go+++ b/internal/agent/component/agent.go@@ -2037,13 +2037,39 @@ func agentToolObject(item map[string]any) (string, map[string]any, bool) {rawParams, _ := item["params"].(map[string]any)toolParams := cloneMap(rawParams)- if fn, ok := stringFrom(item, "function_name"); ok && strings.TrimSpace(fn) != "" {- if toolParams == nil {- toolParams = make(map[string]any)- }- toolParams["function_name"] = strings.TrimSpace(fn)+ if toolParams == nil {+ toolParams = make(map[string]any)+ }+ toolParams["component_name"] = toolName++ // Some Canvas DSLs store function_name/description inside params rather+ // than as top-level tool object fields.+ functionName, _ := stringFrom(item, "function_name")+ functionName = strings.TrimSpace(functionName)+ if functionName == "" {+ functionName, _ = stringFrom(toolParams, "function_name")+ functionName = strings.TrimSpace(functionName)+ }+ // Only forward a DSL-provided function_name; without one the tool+ // factory keeps its registered default (e.g. retrieval stays+ // search_my_dateset), which is what the model calls.+ if functionName == "" {+ functionName = toolName+ } else {+ toolParams["function_name"] = functionName}- return toolName, toolParams, true++ description, _ := stringFrom(item, "description")+ description = strings.TrimSpace(description)+ if description == "" {+ description, _ = stringFrom(toolParams, "description")+ description = strings.TrimSpace(description)+ }+ if description != "" {+ toolParams["description"] = description+ }++ return functionName, toolParams, true}func cloneMap(in map[string]any) map[string]any {diff --git a/internal/agent/component/agent_mcp_test.go b/internal/agent/component/agent_mcp_test.goindex 65db719a79..952cbb693c 100644--- a/internal/agent/component/agent_mcp_test.go+++ b/internal/agent/component/agent_mcp_test.go@@ -45,7 +45,8 @@ func TestAgentMCPModelDispatch(t *testing.T) {t.Cleanup(func() { common.LookupHost = lookup })var dispatched atomic.Boolconst authToken = "ragflow-secret"- mcp := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ // TLS server: CallTool refuses to send credential headers over http.+ mcp := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if r.URL.RawQuery != "" {t.Error("MCP authentication unexpectedly appeared in the URL")}diff --git a/internal/agent/component/agent_test.go b/internal/agent/component/agent_test.goindex 154c81613f..e9ca18c2d9 100644--- a/internal/agent/component/agent_test.go+++ b/internal/agent/component/agent_test.go@@ -1669,6 +1669,47 @@ func TestAgentDisabledTemperatureAndTopP(t *testing.T) {}}+func TestAgent_MultipleRetrievalToolsUseFunctionName(t *testing.T) {+ p := AgentParam{+ Tools: []string{"search_archa_metodika", "search_archa_data"},+ ToolParams: map[string]map[string]any{+ "search_archa_metodika": {+ "component_name": "Retrieval",+ "function_name": "search_archa_metodika",+ "description": "Vyhľadávanie v metodike.",+ "kb_ids": []any{"kb-metodika"},+ "top_n": float64(10),+ },+ "search_archa_data": {+ "component_name": "Retrieval",+ "function_name": "search_archa_data",+ "description": "Vyhľadávanie v projektovej dokumentácii.",+ "kb_ids": []any{"kb-data"},+ "top_n": float64(25),+ },+ },+ MaxRounds: 1,+ }+ tools, err := buildAgentTools(t.Context(), p)+ if err != nil {+ t.Fatalf("buildAgentTools: %v", err)+ }+ if len(tools) != 2 {+ t.Fatalf("len(tools) = %d, want 2", len(tools))+ }+ names := make(map[string]bool)+ for _, tool := range tools {+ info, err := tool.Info(t.Context())+ if err != nil {+ t.Fatalf("tool.Info: %v", err)+ }+ names[info.Name] = true+ }+ if !names["search_archa_metodika"] || !names["search_archa_data"] {+ t.Fatalf("expected distinct retrieval tool names, got %v", names)+ }+}+type fakeAgentRetrievalService struct {chunks []agenttool.RetrievalChunk}diff --git a/internal/agent/tool/registry.go b/internal/agent/tool/registry.goindex 92eacd2a4b..12410e9d15 100644--- a/internal/agent/tool/registry.go+++ b/internal/agent/tool/registry.go@@ -106,6 +106,15 @@ func noConfig(name string, fn func() einotool.BaseTool) Factory {}}+// retrievalRegistryKeys lists every registry key whose factory is+// buildRetrievalTool, so DSL metadata handling does not depend on which+// alias the canvas used.+var retrievalRegistryKeys = map[string]struct{}{+ "retrieval": {},+ "search_my_dataset": {},+ "search_my_dateset": {},+}+// BuildByName resolves a tool name into an Eino BaseTool.func BuildByName(name string, params map[string]any) (einotool.BaseTool, error) {key := normalizeToolName(name)@@ -113,8 +122,36 @@ func BuildByName(name string, params map[string]any) (einotool.BaseTool, error)return nil, fmt.Errorf("agent tool: empty tool name")}factory, ok := registry[key]++ var componentKey string+ if params != nil {+ if componentName, _ := params["component_name"].(string); componentName != "" {+ componentKey = normalizeToolName(componentName)+ }+ }+if !ok {- return nil, fmt.Errorf("agent tool: unsupported tool %q", name)+ // Canvas DSLs often give each retrieval instance a unique+ // function_name while keeping the component_name as "Retrieval".+ // Fall back to the component_name when the agent-visible name is+ // not itself a registered tool.+ if componentKey != "" {+ factory, ok = registry[componentKey]+ key = componentKey+ }+ if !ok {+ return nil, fmt.Errorf("agent tool: unsupported tool %q", name)+ }+ } else if componentKey != "" && componentKey != key {+ // The agent-visible name matches a registered tool, but the DSL+ // says this node is a different component (e.g., a Retrieval+ // instance whose function_name collides with "wikipedia"). Trust+ // the component_name so we build the intended tool, not the+ // registered one the function_name happens to match.+ if altFactory, altOk := registry[componentKey]; altOk {+ factory = altFactory+ key = componentKey+ }}if factory == nil {return nil, fmt.Errorf("agent tool: nil factory for %q", name)@@ -122,7 +159,30 @@ func BuildByName(name string, params map[string]any) (einotool.BaseTool, error)if err := ValidateSearchFilters(params, false); err != nil {return nil, runtime.NewUserFacingError(fmt.Sprintf("agent tool %s: %s", name, err))}- return factory(params)+ // component_name, function_name and description are DSL metadata, not+ // constructor arguments for most tools. Strip them before handing the+ // params to the factory; keep function_name/description only for+ // retrieval so each instance can advertise its DSL-defined name. All+ // registered retrieval aliases count — a DSL using function_name+ // "search_my_dataset" resolves to that registry key, not "retrieval".+ cleanParams := params+ if cleanParams != nil {+ cleanParams = cloneToolParams(cleanParams)+ delete(cleanParams, "component_name")+ if _, isRetrieval := retrievalRegistryKeys[key]; !isRetrieval {+ delete(cleanParams, "function_name")+ delete(cleanParams, "description")+ }+ }+ return factory(cleanParams)+}++func cloneToolParams(in map[string]any) map[string]any {+ out := make(map[string]any, len(in))+ for k, v := range in {+ out[k] = v+ }+ return out}// BuildAll resolves a list of tool names into Eino BaseTool instances.@@ -419,6 +479,13 @@ func buildRetrievalTool(params map[string]any) (einotool.BaseTool, error) {}}+ if v, ok := stringParam(params, "function_name"); ok {+ defaults.FunctionName = v+ }+ if v, ok := stringParam(params, "description"); ok {+ defaults.Description = v+ }+if ids, ok, err := stringSliceParam(params, "dataset_ids"); err != nil {return nil, fmt.Errorf("agent tool: retrieval config: %w", err)} else if ok {diff --git a/internal/agent/tool/registry_test.go b/internal/agent/tool/registry_test.goindex cc12b4ceba..36c04d24e9 100644--- a/internal/agent/tool/registry_test.go+++ b/internal/agent/tool/registry_test.go@@ -109,6 +109,27 @@ func TestBuildAll_CanvasComponentNameUsesCanonicalParams(t *testing.T) {}}+// TestBuildByName_FunctionNameCollisionPrefersComponentName asserts that a+// Retrieval node whose DSL function_name happens to match a registered tool+// (e.g., "wikipedia") still builds the retrieval tool, not the registered one.+// The retrieval tool advertises the DSL function_name as its agent-visible name.+func TestBuildByName_FunctionNameCollisionPrefersComponentName(t *testing.T) {+ built, err := BuildByName("wikipedia", map[string]any{+ "component_name": "Retrieval",+ "function_name": "wikipedia",+ })+ if err != nil {+ t.Fatalf("BuildByName: %v", err)+ }+ info, err := built.Info(t.Context())+ if err != nil {+ t.Fatalf("Info: %v", err)+ }+ if info.Name != "wikipedia" {+ t.Errorf("tool name = %q, want retrieval advertised as the DSL function_name (collision must not build Wikipedia)", info.Name)+ }+}+func TestBuildByName_QueritAliases(t *testing.T) {for _, name := range []string{"querit", "querit_search", "queritsearch", "QueritSearch"} {built, err := BuildByName(name, map[string]any{diff --git a/internal/agent/tool/retrieval.go b/internal/agent/tool/retrieval.goindex fdaf087b88..7bf440757e 100644--- a/internal/agent/tool/retrieval.go+++ b/internal/agent/tool/retrieval.go@@ -64,6 +64,12 @@ type retrievalArgs struct {MetaDataFilter map[string]any `json:"meta_data_filter,omitempty"`RetrievalFrom string `json:"retrieval_from,omitempty"`EmptyResponse string `json:"empty_response,omitempty"`+ // FunctionName is the agent-visible tool name from the DSL. It is not+ // exposed to the model as part of the tool arguments.+ FunctionName string `json:"-"`+ // Description is the agent-visible tool description from the DSL. It is+ // not exposed to the model as part of the tool arguments.+ Description string `json:"-"`}// retrievalResult is the JSON shape returned to the model. The `_ERROR`@@ -93,6 +99,8 @@ type chunkPayload struct {// surfaces ErrRetrievalServiceMissing.type RetrievalTool struct {defaults retrievalArgs+ name string+ desc string}// NewRetrievalTool returns a RetrievalTool implementing eino's@@ -107,15 +115,23 @@ func NewRetrievalToolWithDefaults(defaults retrievalArgs) *RetrievalTool {if len(defaults.DatasetIDs) == 0 && len(defaults.KBIDs) != 0 {defaults.DatasetIDs = append([]string(nil), defaults.KBIDs...)}- return &RetrievalTool{defaults: defaults}+ name := defaults.FunctionName+ if strings.TrimSpace(name) == "" {+ name = retrievalToolName+ }+ desc := defaults.Description+ if strings.TrimSpace(desc) == "" {+ desc = retrievalToolDescription+ }+ return &RetrievalTool{defaults: defaults, name: name, desc: desc}}// Info returns the tool's metadata for the chat model. The schema mirrors// the Python RetrievalParam ToolMeta (plan, field alignment).func (r *RetrievalTool) Info(_ context.Context) (*schema.ToolInfo, error) {return &schema.ToolInfo{- Name: retrievalToolName,- Desc: retrievalToolDescription,+ Name: r.name,+ Desc: r.desc,ParamsOneOf: schema.NewParamsOneOfByParams(map[string]*schema.ParameterInfo{"query": {Type: schema.String,diff --git a/internal/entity/base.go b/internal/entity/base.goindex 1b3b3568f0..1aa3fe0311 100644--- a/internal/entity/base.go+++ b/internal/entity/base.go@@ -19,6 +19,8 @@ package entityimport ("database/sql/driver""encoding/json"+ "fmt"+ "strings""time""gorm.io/gorm"@@ -150,11 +152,38 @@ func (j *JSONMap) Scan(value interface{}) error {*j = nilreturn nil}- b, ok := value.([]byte)- if !ok {- return json.Unmarshal([]byte(value.(string)), j)+ var raw string+ switch v := value.(type) {+ case []byte:+ raw = string(v)+ case string:+ raw = v+ default:+ raw = fmt.Sprint(value)}- return json.Unmarshal(b, j)+ if strings.TrimSpace(raw) == "" {+ *j = nil+ return nil+ }+ // Python/legacy rows sometimes stored a JSON object as a JSON-encoded+ // string ("{...}"). Try parsing directly first, then unwrap one level.+ // Decode into fresh maps: Unmarshal into a reused non-nil map keeps+ // stale keys from a previous Scan.+ var fresh JSONMap+ if err := json.Unmarshal([]byte(raw), &fresh); err == nil {+ *j = fresh+ return nil+ }+ var quoted string+ if err := json.Unmarshal([]byte(raw), "ed); err != nil {+ return json.Unmarshal([]byte(raw), j)+ }+ var unwrapped JSONMap+ if err := json.Unmarshal([]byte(quoted), &unwrapped); err != nil {+ return err+ }+ *j = unwrapped+ return nil}func (j *JSONMap) GormDataType() string {diff --git a/internal/entity/base_test.go b/internal/entity/base_test.gonew file mode 100644index 0000000000..fc7208ae8c--- /dev/null+++ b/internal/entity/base_test.go@@ -0,0 +1,35 @@+package entity++import (+ "testing"+)++func TestJSONMapScan(t *testing.T) {+ for _, tt := range []struct {+ name string+ input any+ want map[string]any+ }{+ {"nil", nil, nil},+ {"empty string", "", nil},+ {"object bytes", []byte(`{"k":"v"}`), map[string]any{"k": "v"}},+ {"object string", `{"k":"v"}`, map[string]any{"k": "v"}},+ {"quoted object string", `"{\"k\":\"v\"}"`, map[string]any{"k": "v"}},+ {"quoted object bytes", []byte(`"{\"k\":\"v\"}"`), map[string]any{"k": "v"}},+ } {+ t.Run(tt.name, func(t *testing.T) {+ var j JSONMap+ if err := j.Scan(tt.input); err != nil {+ t.Fatalf("Scan: %v", err)+ }+ if len(j) != len(tt.want) {+ t.Fatalf("got %v, want %v", j, tt.want)+ }+ for k, v := range tt.want {+ if j[k] != v {+ t.Fatalf("key %q got %v want %v", k, j[k], v)+ }+ }+ })+ }+}diff --git a/internal/mcp/client/mcp_call.go b/internal/mcp/client/mcp_call.goindex 1fc4a9b9bd..784c272026 100644--- a/internal/mcp/client/mcp_call.go+++ b/internal/mcp/client/mcp_call.go@@ -22,6 +22,7 @@ import ("errors""fmt""net/http"+ "net/url""ragflow/internal/utility""time")@@ -84,11 +85,20 @@ func CallTool(ctx context.Context, opts CallOptions) (*CallResult, error) {}if opts.HTTPClient == nil {opts.HTTPClient = utility.PinnedHTTPClient(hostname, resolvedIP, opts.Timeout)+ } else {+ opts.HTTPClient = restrictClientRedirects(opts.HTTPClient, opts.AllowPrivateHosts)}headers, headerErr := renderHeaders(opts.Headers, opts.Variables)if headerErr != nil {return nil, headerErr}+ // The private-host allowlist also permits http:// endpoints; never send+ // configured credential headers in cleartext.+ if len(headers) > 0 {+ if u, perr := url.Parse(opts.URL); perr == nil && u.Scheme == "http" {+ return nil, errors.New("MCP refuses to send credential headers over cleartext http")+ }+ }connectCtx, cancel := context.WithTimeout(ctx, opts.Timeout)defer cancel()diff --git a/internal/mcp/client/mcp_call_test.go b/internal/mcp/client/mcp_call_test.goindex 0c21046ae1..864af0343a 100644--- a/internal/mcp/client/mcp_call_test.go+++ b/internal/mcp/client/mcp_call_test.go@@ -125,7 +125,8 @@ func TestCallTool_StreamableHTTP(t *testing.T) {defer mu.Unlock()requestOrder = append(requestOrder, method)}- srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ // TLS server: CallTool refuses to send credential headers over http.+ srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {if got := r.Header.Get("Authorization"); got != "Bearer test-token" {t.Errorf("Authorization=%q, want rendered header", got)}@@ -617,3 +618,38 @@ func TestCallToolSSE(t *testing.T) {t.Fatalf("called=%v result=%+v", called.Load(), result)}}++// TestCallTool_SuppliedClientRejectsCrossOriginRedirect covers the+// caller-supplied HTTPClient path: even without the pinned transport,+// a redirect to a different port/origin must not be followed.+func TestCallTool_SuppliedClientRejectsCrossOriginRedirect(t *testing.T) {+ defer allowLoopbackForTests(t)()++ var targetHits int32+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ atomic.AddInt32(&targetHits, 1)+ w.WriteHeader(http.StatusOK)+ }))+ defer target.Close()++ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ w.Header().Set("Location", target.URL)+ w.WriteHeader(http.StatusTemporaryRedirect)+ }))+ defer srv.Close()++ _, err := CallTool(t.Context(), CallOptions{+ URL: srv.URL,+ ServerType: TransportStreamableHTTP,+ ToolName: "echo",+ Arguments: json.RawMessage(`{}`),+ HTTPClient: srv.Client(),+ Timeout: 2 * time.Second,+ })+ if err == nil {+ t.Fatal("CallTool should fail when the supplied client is redirected to a different origin")+ }+ if got := atomic.LoadInt32(&targetHits); got != 0 {+ t.Errorf("redirect target hits=%d, want 0", got)+ }+}diff --git a/internal/mcp/client/mcp_client.go b/internal/mcp/client/mcp_client.goindex baade2d04f..50d9be2679 100644--- a/internal/mcp/client/mcp_client.go+++ b/internal/mcp/client/mcp_client.go@@ -106,6 +106,8 @@ func FetchTools(ctx context.Context, opts FetchOptions) ([]Tool, error) {opts.pinIP = resolvedIPif opts.HTTPClient == nil {opts.HTTPClient = utility.PinnedHTTPClient(hostname, resolvedIP, opts.Timeout)+ } else {+ opts.HTTPClient = restrictClientRedirects(opts.HTTPClient, opts.AllowPrivateHosts)}headers, headerErr := renderHeaders(opts.Headers, opts.Variables)diff --git a/internal/mcp/client/mcp_ssrf.go b/internal/mcp/client/mcp_ssrf.goindex ef8ac399ae..37c4fad629 100644--- a/internal/mcp/client/mcp_ssrf.go+++ b/internal/mcp/client/mcp_ssrf.go@@ -17,6 +17,8 @@package mcpclientimport (+ "fmt"+ "net/http""net/url""ragflow/internal/common""strings"@@ -82,28 +84,57 @@ func AssertMCPURLSafe(rawURL string, allowPrivateHosts bool) (hostname, resolved}// AssertMCPURLSafeSameOrigin validates a server-advertised URL (e.g., the POST-// URL from an SSE endpoint event). Public URLs are accepted. Private URLs are-// accepted only when allowPrivateHosts is true AND the advertised URL shares the-// same origin (scheme, port, and host) as originURL, so the server cannot bounce-// POSTs to another service on the same host but a different port or scheme.+// URL from an SSE endpoint event). The URL must share the origin (scheme,+// port, and host) with originURL — checked before any success path — and+// private URLs additionally require allowPrivateHosts, so the server cannot+// bounce POSTs to a cleartext downgrade or an unrelated target.func AssertMCPURLSafeSameOrigin(rawURL, originURL string, allowPrivateHosts bool) (hostname, resolvedIP string, err error) {- hostname, resolvedIP, err = common.AssertURLSafe(rawURL)- if err == nil {- return hostname, resolvedIP, nil- }- if !allowPrivateHosts {- return "", "", err- }+ // The advertised URL must keep the full origin — scheme, host and+ // effective port — before any success path, so a server cannot bounce+ // POSTs to a cleartext downgrade or a different public/internal target.origin, perr := url.Parse(strings.TrimSpace(originURL))if perr != nil || origin.Hostname() == "" {- return "", "", err+ return "", "", fmt.Errorf("invalid MCP origin URL %q", originURL)}parsed, perr := url.Parse(strings.TrimSpace(rawURL))if perr != nil {- return "", "", err+ return "", "", perr}if !sameOrigin(parsed, origin) {+ return "", "", fmt.Errorf("MCP advertised URL %q does not match origin %q", rawURL, originURL)+ }+ hostname, resolvedIP, err = common.AssertURLSafe(rawURL)+ if err == nil {+ return hostname, resolvedIP, nil+ }+ if !allowPrivateHosts {return "", "", err}return AssertMCPURLSafe(rawURL, allowPrivateHosts)}++// restrictClientRedirects returns a copy of a caller-supplied HTTP client+// whose redirect policy keeps credential headers on the validated origin:+// it rejects HTTPS downgrades and any redirect target that is not the same+// origin as the first request. The default PinnedHTTPClient applies the same+// rules; a supplied client must not quietly bypass them.+func restrictClientRedirects(client *http.Client, allowPrivateHosts bool) *http.Client {+ restricted := *client+ inner := restricted.CheckRedirect+ restricted.CheckRedirect = func(req *http.Request, via []*http.Request) error {+ if len(via) >= 10 {+ return fmt.Errorf("stopped after 10 redirects")+ }+ if via[0].URL.Scheme == "https" && req.URL.Scheme == "http" {+ return fmt.Errorf("refusing HTTPS to HTTP redirect to %q", req.URL)+ }+ if _, _, err := AssertMCPURLSafeSameOrigin(req.URL.String(), via[0].URL.String(), allowPrivateHosts); err != nil {+ return err+ }+ if inner != nil {+ return inner(req, via)+ }+ return nil+ }+ return &restricted+}diff --git a/internal/service/agent.go b/internal/service/agent.goindex 794defd059..728d88f9c8 100644--- a/internal/service/agent.go+++ b/internal/service/agent.go@@ -1945,8 +1945,9 @@ func (s *AgentService) RunAgent(ctx context.Context, canvasID, sessionID, versio// authenticated runner for caller-scoped permission checks and conversation data.root["tenant_id"] = agentTenantID- // Preserve the historical RunTracker tenant dimension separately from- // the canvas tenant used by runtime components.+ // Preserve the historical RunTracker tenant dimension separately.+ // Existing tests and log filters expect the caller's joined tenant id+ // in the run hash.if tenantIDs, terr := s.userTenantDAO.GetTenantIDsByUserID(ctx, dao.DB, userID); terr == nil && len(tenantIDs) > 0 {root["run_tenant_id"] = tenantIDs[0]} else if terr != nil {diff --git a/internal/service/agent_deferred_failure_test.go b/internal/service/agent_deferred_failure_test.goindex 6b7ef02291..cf52e7bb6f 100644--- a/internal/service/agent_deferred_failure_test.go+++ b/internal/service/agent_deferred_failure_test.go@@ -106,6 +106,9 @@ func TestRunAgent_DeferredAgentModelFailureStaysInChatStream(t *testing.T) {},"path": []any{"begin_0", "Agent:fail_0", "Message:fail_0"},}+ // Model validation runs against the canvas tenant and resolves the+ // tenant owner's model configuration (provider TenantID == canvas tenant,+ // provider UserID == tenant owner).dao.DB.Create(&entity.TenantModelProvider{ID: "prov-deferred-fail", UserID: "user-1", ProviderName: "OpenAI-API-Compatible", TenantID: "tenant-1"})dao.DB.Create(&entity.TenantModelInstance{ID: "inst-deferred-fail", InstanceName: "unreachable", ProviderID: "prov-deferred-fail", APIKey: "test-key", Extra: `{"base_url": "http://127.0.0.1:59999/v1"}`})dao.DB.Create(&entity.TenantModel{ID: "unavailable-model", ModelName: "unavailable-model", ProviderID: "prov-deferred-fail", InstanceID: "inst-deferred-fail", ModelType: int(entity.ModelTypeChat), Status: "active", Extra: "{}"})diff --git a/internal/utility/ssrf.go b/internal/utility/ssrf.goindex bca40959eb..ea956681a3 100644--- a/internal/utility/ssrf.go+++ b/internal/utility/ssrf.go@@ -21,6 +21,7 @@ import ("fmt""net""net/http"+ "net/url""strings""time"@@ -60,5 +61,41 @@ var PinnedHTTPClient = func(hostname, resolvedIP string, timeout time.Duration)return &http.Client{Transport: transport,Timeout: timeout,+ CheckRedirect: func(req *http.Request, via []*http.Request) error {+ if len(via) >= 10 {+ return fmt.Errorf("stopped after 10 redirects")+ }+ // The pinned dialer only guarantees the host, not the scheme:+ // a same-host HTTPS -> HTTP redirect would carry credential+ // headers in cleartext.+ if via[0].URL.Scheme == "https" && req.URL.Scheme == "http" {+ return fmt.Errorf("refusing HTTPS to HTTP redirect to %q", req.URL)+ }+ // The pinned dialer also leaves the port to the redirect target:+ // a same-host redirect to another port would reach a different+ // service while Go still forwards sensitive headers for the host.+ if !sameRequestOrigin(via[0].URL, req.URL) {+ return fmt.Errorf("refusing redirect to different origin %q", req.URL)+ }+ return nil+ },+ }+}++// sameRequestOrigin reports whether two URLs share scheme, host, and effective+// port (default 443/80 when the URL omits it).+func sameRequestOrigin(a, b *url.URL) bool {+ return a.Scheme == b.Scheme &&+ strings.EqualFold(a.Hostname(), b.Hostname()) &&+ effectiveURLPort(a) == effectiveURLPort(b)+}++func effectiveURLPort(u *url.URL) string {+ if p := u.Port(); p != "" {+ return p+ }+ if u.Scheme == "https" {+ return "443"}+ return "80"}