feat: search engine adds proxy addresses and adds SSRF verification.

This commit is contained in:
hjz
2026-04-15 08:53:09 +08:00
committed by lyingbug
parent 092044b68f
commit 7bd36bf954
16 changed files with 228 additions and 14 deletions
+3 -2
View File
@@ -54,8 +54,9 @@ func NewBingProvider(params types.WebSearchProviderParameters) (interfaces.WebSe
if params.APIKey == "" {
return nil, fmt.Errorf("API key is required for Bing provider")
}
client := &http.Client{
Timeout: defaultBingTimeout,
client, err := NewSearchHTTPClient(defaultBingTimeout, params.ProxyURL)
if err != nil {
return nil, err
}
return &BingProvider{
client: client,
@@ -23,13 +23,13 @@ type DuckDuckGoProvider struct {
}
// NewDuckDuckGoProvider creates a new DuckDuckGo provider.
// DuckDuckGo is free and requires no API key or configuration.
// DuckDuckGo is free and requires no API key; optional ProxyURL tunnels requests via an HTTP/HTTPS proxy.
func NewDuckDuckGoProvider(params types.WebSearchProviderParameters) (interfaces.WebSearchProvider, error) {
return &DuckDuckGoProvider{
client: &http.Client{
Timeout: 30 * time.Second,
},
}, nil
client, err := NewSearchHTTPClient(30*time.Second, params.ProxyURL)
if err != nil {
return nil, err
}
return &DuckDuckGoProvider{client: client}, nil
}
// Name returns the provider name
@@ -3,6 +3,7 @@ package web_search
import (
"context"
"fmt"
"time"
"google.golang.org/api/customsearch/v1"
"google.golang.org/api/option"
@@ -29,8 +30,13 @@ func NewGoogleProvider(params types.WebSearchProviderParameters) (interfaces.Web
return nil, fmt.Errorf("engine ID is required for Google provider")
}
httpClient, err := NewSearchHTTPClient(30*time.Second, params.ProxyURL)
if err != nil {
return nil, err
}
clientOpts := []option.ClientOption{
option.WithAPIKey(params.APIKey),
option.WithHTTPClient(httpClient),
}
srv, err := customsearch.NewService(context.Background(), clientOpts...)
if err != nil {
@@ -0,0 +1,68 @@
package web_search
import (
"fmt"
"net/http"
"net/url"
"strings"
"time"
"github.com/Tencent/WeKnora/internal/utils"
)
// ValidateProxyURL delegates to utils.ValidateURLForSSRF (only http/https pass that check).
func ValidateProxyURL(proxyURL string) error {
proxyURL = strings.TrimSpace(proxyURL)
if proxyURL == "" {
return nil
}
return utils.ValidateURLForSSRF(proxyURL)
}
func ssrfSafeRedirect(maxRedirects int) func(*http.Request, []*http.Request) error {
return func(req *http.Request, via []*http.Request) error {
if len(via) >= maxRedirects {
return fmt.Errorf("stopped after %d redirects", maxRedirects)
}
if err := utils.ValidateURLForSSRF(req.URL.String()); err != nil {
return fmt.Errorf("%w: %v", utils.ErrSSRFRedirectBlocked, err)
}
return nil
}
}
// NewSearchHTTPClient builds an http.Client for outbound web search requests.
// It uses utils.SSRFSafeDialContext, optional explicit or environment proxy, and
// redirect validation consistent with utils.NewSSRFSafeHTTPClient.
func NewSearchHTTPClient(timeout time.Duration, proxyURL string) (*http.Client, error) {
proxyURL = strings.TrimSpace(proxyURL)
def, ok := http.DefaultTransport.(*http.Transport)
if !ok {
return nil, fmt.Errorf("default HTTP transport is not *http.Transport")
}
t := def.Clone()
t.DialContext = utils.SSRFSafeDialContext
if proxyURL != "" {
if err := ValidateProxyURL(proxyURL); err != nil {
return nil, err
}
u, err := url.Parse(proxyURL)
if err != nil {
return nil, fmt.Errorf("invalid proxy_url: %w", err)
}
if u.Scheme == "" || u.Host == "" {
return nil, fmt.Errorf("invalid proxy_url: scheme and host are required")
}
t.Proxy = http.ProxyURL(u)
} else {
t.Proxy = http.ProxyFromEnvironment
}
cfg := utils.DefaultSSRFSafeHTTPClientConfig()
return &http.Client{
Timeout: timeout,
Transport: t,
CheckRedirect: ssrfSafeRedirect(cfg.MaxRedirects),
}, nil
}
@@ -0,0 +1,78 @@
package web_search
import (
"net/http"
"net/url"
"strings"
"testing"
)
func TestValidateProxyURL(t *testing.T) {
tests := []struct {
name string
raw string
wantErr bool
}{
{"empty", "", false},
{"whitespace only", " ", false},
{"no scheme private IP bare host:port", "192.168.0.1:3128", true},
{"localhost http", "http://localhost:3128", true},
{"direct IPv4 http", "http://192.168.1.1:3128", true},
{"socks5 to IP blocked", "socks5://10.0.0.1:1080", true},
{"bad scheme", "ftp://proxy.example:21", true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := ValidateProxyURL(tt.raw)
if tt.wantErr && err == nil {
t.Fatalf("expected error, got nil")
}
if !tt.wantErr && err != nil {
t.Fatalf("unexpected error: %v", err)
}
})
}
}
func TestNewSearchHTTPClient_RejectsUnsafeProxy(t *testing.T) {
_, err := NewSearchHTTPClient(0, "http://127.0.0.1:3128")
if err == nil {
t.Fatal("expected error for disallowed proxy URL (127.0.0.1)")
}
if !strings.Contains(err.Error(), "SSRF") {
t.Fatalf("expected SSRF-related error, got: %v", err)
}
}
func TestNewSearchHTTPClient_AcceptsEmptyProxy(t *testing.T) {
c, err := NewSearchHTTPClient(0, "")
if err != nil {
t.Fatal(err)
}
if c.Transport == nil {
t.Fatal("expected transport")
}
if c.CheckRedirect == nil {
t.Fatal("expected CheckRedirect for SSRF-safe redirects")
}
}
func TestSsrfSafeRedirect_BlocksNonHTTPSScheme(t *testing.T) {
h := ssrfSafeRedirect(10)
req := &http.Request{URL: mustParse(t, "ftp://evil.com/")}
// len(via)==0 so first redirect
err := h(req, nil)
if err == nil {
t.Fatal("expected error for ftp redirect")
}
}
func mustParse(t *testing.T, s string) *url.URL {
t.Helper()
u, err := url.Parse(s)
if err != nil {
t.Fatal(err)
}
return u
}
+3 -2
View File
@@ -36,8 +36,9 @@ func NewTavilyProvider(params types.WebSearchProviderParameters) (interfaces.Web
if params.APIKey == "" {
return nil, fmt.Errorf("API key is required for Tavily provider")
}
client := &http.Client{
Timeout: defaultTavilyTimeout,
client, err := NewSearchHTTPClient(defaultTavilyTimeout, params.ProxyURL)
if err != nil {
return nil, err
}
return &TavilyProvider{
client: client,