An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:bug: Make agent HTTP tools honor network proxy https://github.com/siyuan-note/siyuan/issues/18746
Danielc422a42d464d
diff --git a/kernel/util/httprequest.go b/kernel/util/httprequest.goindex 1fcd7a1f87..93d0f0b5b3 100644--- a/kernel/util/httprequest.go+++ b/kernel/util/httprequest.go@@ -17,6 +17,10 @@package utilimport (+ "bufio"+ "context"+ "crypto/tls"+ "encoding/base64""errors""fmt""io"@@ -26,9 +30,11 @@ import ("os""path/filepath""strings"+ "sync""time""github.com/siyuan-note/httpclient"+ golangProxy "golang.org/x/net/proxy")const (@@ -54,18 +60,242 @@ func CheckHostSSRF(host string) error {return nil}-// ssrfSafeClient 是智能体出站请求专用的 HTTP 客户端:保留 httpclient 的统一 UA 注入与传输配置,-// 拨号走 ssrfSafeDialContext,连接阶段无条件拦截私网地址(不依赖 SafeMode),-// 防止 CheckHostSSRF 与拨号之间的 DNS 重绑定 TOCTOU 绕过。+// ssrfSafeClient 是智能体出站请求专用的 HTTP 客户端:直连时将目标固定到已校验的公网 IP,+// 使用代理时则先与用户配置的代理建立隧道,再通过隧道连接固定后的目标 IP,同时保留原始 Host 和 TLS SNI。+// 两种方式都不会在校验后再次按目标域名解析,避免 DNS 重绑定 TOCTOU 绕过。// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-x8gv-g2g3-65fjvar ssrfSafeClient = newSSRFSafeClient()func newSSRFSafeClient() *http.Client {- transport := httpclient.NewTransport(false)- transport.DialContext = ssrfSafeDialContext(30 * time.Second)+ return newSSRFSafeClientWithResolver(net.DefaultResolver.LookupIPAddr)+}++type lookupIPAddrFunc func(context.Context, string) ([]net.IPAddr, error)++type ssrfSafeTransport struct {+ directTransport *http.Transport+ lookupIPAddr lookupIPAddrFunc+}++func newSSRFSafeClientWithResolver(lookupIPAddr lookupIPAddrFunc) *http.Client {+ directTransport := httpclient.NewTransport(false)+ directTransport.Proxy = nil+ directTransport.DialContext = ssrfSafeDialContext(30 * time.Second)+ transport := &ssrfSafeTransport{directTransport: directTransport, lookupIPAddr: lookupIPAddr}return &http.Client{Timeout: 30 * time.Second, Transport: &httpclient.UserAgentTransport{Base: transport}}}+func (t *ssrfSafeTransport) RoundTrip(req *http.Request) (*http.Response, error) {+ proxyURL, err := httpclient.ProxyFromEnvironment(req)+ if err != nil {+ return nil, err+ }+ if proxyURL == nil {+ return t.directTransport.RoundTrip(req)+ }++ targetAddr, err := t.resolvePublicTarget(req.Context(), req.URL)+ if err != nil {+ return nil, err+ }+ conn, reader, err := dialProxyTunnel(req.Context(), proxyURL, targetAddr)+ if err != nil {+ return nil, err+ }++ if req.URL.Scheme == "https" {+ if reader.Buffered() != 0 {+ conn.Close()+ return nil, errors.New("proxy returned unexpected tunnel data")+ }+ tlsConn := tls.Client(conn, &tls.Config{ServerName: req.URL.Hostname(), NextProtos: []string{"http/1.1"}})+ if err = tlsConn.HandshakeContext(req.Context()); err != nil {+ conn.Close()+ return nil, err+ }+ conn = tlsConn+ reader = bufio.NewReader(conn)+ }++ targetReq := req.Clone(req.Context())+ targetReq.URL = cloneURL(req.URL)+ targetReq.URL.Scheme = ""+ targetReq.URL.Host = ""+ targetReq.RequestURI = ""+ targetReq.Header.Del("Proxy-Authorization")+ if targetReq.Host == "" {+ targetReq.Host = req.URL.Host+ }+ if err = targetReq.Write(conn); err != nil {+ conn.Close()+ return nil, err+ }+ resp, err := http.ReadResponse(reader, targetReq)+ if err != nil {+ conn.Close()+ return nil, err+ }+ resp.Request = req+ resp.Body = newConnectionReadCloser(req.Context(), resp.Body, conn)+ return resp, nil+}++func (t *ssrfSafeTransport) resolvePublicTarget(ctx context.Context, targetURL *url.URL) (string, error) {+ host := targetURL.Hostname()+ port := targetURL.Port()+ if port == "" {+ switch targetURL.Scheme {+ case "http":+ port = "80"+ case "https":+ port = "443"+ default:+ return "", errors.New("URL must start with http:// or https://")+ }+ }++ if ip := net.ParseIP(host); ip != nil {+ if isPrivateIP(ip) {+ return "", errors.New("access to private/internal IP is prohibited")+ }+ return net.JoinHostPort(ip.String(), port), nil+ }++ ips, err := t.lookupIPAddr(ctx, host)+ if err != nil {+ return "", errors.New("failed to resolve host: " + err.Error())+ }+ if len(ips) == 0 {+ return "", errors.New("host has no IP address: " + host)+ }+ for _, ipAddr := range ips {+ if isPrivateIP(ipAddr.IP) {+ return "", errors.New("access to private/internal IP is prohibited")+ }+ }+ return net.JoinHostPort(ips[0].IP.String(), port), nil+}++func cloneURL(src *url.URL) *url.URL {+ ret := *src+ return &ret+}++func dialProxyTunnel(ctx context.Context, proxyURL *url.URL, targetAddr string) (net.Conn, *bufio.Reader, error) {+ proxyAddr, err := proxyAddress(proxyURL)+ if err != nil {+ return nil, nil, err+ }+ dialer := &net.Dialer{Timeout: 30 * time.Second, KeepAlive: 30 * time.Second}+ if strings.EqualFold(proxyURL.Scheme, "socks5") || strings.EqualFold(proxyURL.Scheme, "socks5h") {+ var auth *golangProxy.Auth+ if proxyURL.User != nil {+ password, _ := proxyURL.User.Password()+ auth = &golangProxy.Auth{User: proxyURL.User.Username(), Password: password}+ }+ socksDialer, err := golangProxy.SOCKS5("tcp", proxyAddr, auth, dialer)+ if err != nil {+ return nil, nil, err+ }+ contextDialer, ok := socksDialer.(golangProxy.ContextDialer)+ if !ok {+ return nil, nil, errors.New("SOCKS5 proxy does not support context dialing")+ }+ conn, err := contextDialer.DialContext(ctx, "tcp", targetAddr)+ if err != nil {+ return nil, nil, err+ }+ return conn, bufio.NewReader(conn), nil+ }++ conn, err := dialer.DialContext(ctx, "tcp", proxyAddr)+ if err != nil {+ return nil, nil, err+ }+ if strings.EqualFold(proxyURL.Scheme, "https") {+ tlsConn := tls.Client(conn, &tls.Config{ServerName: proxyURL.Hostname(), NextProtos: []string{"http/1.1"}})+ if err = tlsConn.HandshakeContext(ctx); err != nil {+ conn.Close()+ return nil, nil, err+ }+ conn = tlsConn+ }++ connectReq := &http.Request{+ Method: http.MethodConnect,+ URL: &url.URL{Opaque: targetAddr},+ Host: targetAddr,+ Header: make(http.Header),+ }+ if proxyURL.User != nil {+ password, _ := proxyURL.User.Password()+ credentials := proxyURL.User.Username() + ":" + password+ connectReq.Header.Set("Proxy-Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(credentials)))+ }+ if err = connectReq.Write(conn); err != nil {+ conn.Close()+ return nil, nil, err+ }+ reader := bufio.NewReader(conn)+ resp, err := http.ReadResponse(reader, connectReq)+ if err != nil {+ conn.Close()+ return nil, nil, err+ }+ if resp.StatusCode != http.StatusOK {+ resp.Body.Close()+ conn.Close()+ return nil, nil, fmt.Errorf("proxy CONNECT returned %s", resp.Status)+ }+ return conn, reader, nil+}++func proxyAddress(proxyURL *url.URL) (string, error) {+ port := proxyURL.Port()+ if port == "" {+ switch strings.ToLower(proxyURL.Scheme) {+ case "http":+ port = "80"+ case "https":+ port = "443"+ case "socks5", "socks5h":+ port = "1080"+ default:+ return "", errors.New("agent HTTP tools support HTTP, HTTPS and SOCKS5 proxies")+ }+ }+ return net.JoinHostPort(proxyURL.Hostname(), port), nil+}++type connectionReadCloser struct {+ io.ReadCloser+ conn net.Conn+ done chan struct{}+ closeOnce sync.Once+ closeErr error+}++func newConnectionReadCloser(ctx context.Context, body io.ReadCloser, conn net.Conn) *connectionReadCloser {+ ret := &connectionReadCloser{ReadCloser: body, conn: conn, done: make(chan struct{})}+ go func() {+ select {+ case <-ctx.Done():+ conn.Close()+ case <-ret.done:+ }+ }()+ return ret+}++func (c *connectionReadCloser) Close() error {+ c.closeOnce.Do(func() {+ close(c.done)+ c.closeErr = c.ReadCloser.Close()+ c.conn.Close()+ })+ return c.closeErr+}+// HTTPRequest 发起一次通用 HTTP 调用,供智能体 http_request 工具使用。// 与 WebFetch 不同:本函数不做 HTML→Markdown 转换,文本类响应(含 JSON/XML)原样返回,// 便于智能体直接消费 REST API 的 JSON 输出。method 取值:GET/POST/PUT/DELETE/PATCH。diff --git a/kernel/util/httprequest_test.go b/kernel/util/httprequest_test.gonew file mode 100644index 0000000000..63ced14085--- /dev/null+++ b/kernel/util/httprequest_test.go@@ -0,0 +1,279 @@+// SiYuan - From thought to insight, with agents+// Copyright (c) 2020-present, b3log.org+//+// This program is free software: you can redistribute it and/or modify+// it under the terms of the GNU Affero General Public License as published by+// the Free Software Foundation, either version 3 of the License, or+// (at your option) any later version.+//+// This program is distributed in the hope that it will be useful,+// but WITHOUT ANY WARRANTY; without even the implied warranty of+// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+// GNU Affero General Public License for more details.+//+// You should have received a copy of the GNU Affero General Public License+// along with this program. If not, see <https://www.gnu.org/licenses/>.++package util++import (+ "bufio"+ "context"+ "fmt"+ "io"+ "net"+ "net/http"+ "net/http/httptest"+ "strings"+ "sync/atomic"+ "testing"+)++func TestSSRFSafeClientUsesLocalProxyAndPinsTarget(t *testing.T) {+ var connectHost, requestedHost string+ proxy := testTunnelProxy(t, "proxied", func(connectReq, targetReq *http.Request) {+ connectHost = connectReq.Host+ requestedHost = targetReq.Host+ })+ setTestNetworkProxy(t, proxy.URL)++ client := newSSRFSafeClientWithResolver(testPublicResolver)+ resp, err := client.Get("http://public.test/path")+ if err != nil {+ t.Fatalf("request through local proxy failed: %v", err)+ }+ body, err := io.ReadAll(resp.Body)+ if err != nil {+ t.Fatalf("read proxy response failed: %v", err)+ }+ if err = resp.Body.Close(); err != nil {+ t.Fatalf("close proxy response failed: %v", err)+ }+ if string(body) != "proxied" {+ t.Fatalf("response body = %q, want %q", body, "proxied")+ }+ if connectHost != "203.0.113.10:80" {+ t.Fatalf("proxy target = %q, want pinned public IP", connectHost)+ }+ if requestedHost != "public.test" {+ t.Fatalf("Host = %q, want original host", requestedHost)+ }+}++func TestSSRFSafeClientRejectsPrivateTargetBeforeProxy(t *testing.T) {+ var proxyRequests atomic.Int32+ proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {+ proxyRequests.Add(1)+ w.WriteHeader(http.StatusNoContent)+ }))+ defer proxy.Close()+ setTestNetworkProxy(t, proxy.URL)++ client := newSSRFSafeClientWithResolver(func(_ context.Context, host string) ([]net.IPAddr, error) {+ return []net.IPAddr{{IP: net.ParseIP("127.0.0.1")}}, nil+ })+ _, err := client.Get("http://private.test/")+ if err == nil || !strings.Contains(err.Error(), "access to private/internal IP is prohibited") {+ t.Fatalf("private target error = %v", err)+ }+ if proxyRequests.Load() != 0 {+ t.Fatalf("proxy received %d private target requests, want 0", proxyRequests.Load())+ }+}++func TestSSRFSafeClientUsesUpdatedProxy(t *testing.T) {+ firstProxy := testResponseProxy(t, "first")+ secondProxy := testResponseProxy(t, "second")+ client := newSSRFSafeClientWithResolver(testPublicResolver)++ setTestNetworkProxy(t, firstProxy.URL)+ if body := getTestResponseBody(t, client, "http://public.test/"); body != "first" {+ t.Fatalf("first proxy response = %q, want %q", body, "first")+ }++ setTestNetworkProxy(t, secondProxy.URL)+ if body := getTestResponseBody(t, client, "http://public.test/"); body != "second" {+ t.Fatalf("second proxy response = %q, want %q", body, "second")+ }+}++func TestSSRFSafeClientUsesSOCKS5Proxy(t *testing.T) {+ listener, err := net.Listen("tcp", "127.0.0.1:0")+ if err != nil {+ t.Fatalf("listen SOCKS5 proxy failed: %v", err)+ }+ t.Cleanup(func() { listener.Close() })+ targets := make(chan string, 1)+ errs := make(chan error, 1)+ go serveTestSOCKS5Connection(listener, targets, errs)++ setTestNetworkProxy(t, "socks5://"+listener.Addr().String())+ client := newSSRFSafeClientWithResolver(testPublicResolver)+ if body := getTestResponseBody(t, client, "http://public.test/"); body != "socks5" {+ t.Fatalf("SOCKS5 proxy response = %q, want %q", body, "socks5")+ }+ select {+ case err = <-errs:+ t.Fatalf("SOCKS5 proxy failed: %v", err)+ case target := <-targets:+ if target != "203.0.113.10:80" {+ t.Fatalf("SOCKS5 target = %q, want pinned public IP", target)+ }+ }+}++func TestSSRFSafeClientUsesHTTPProxyAuthentication(t *testing.T) {+ var proxyAuthorization string+ proxy := testTunnelProxy(t, "authenticated", func(connectReq, _ *http.Request) {+ proxyAuthorization = connectReq.Header.Get("Proxy-Authorization")+ })+ authenticatedProxyURL := strings.Replace(proxy.URL, "http://", "http://user:pass@", 1)+ setTestNetworkProxy(t, authenticatedProxyURL)++ client := newSSRFSafeClientWithResolver(testPublicResolver)+ if body := getTestResponseBody(t, client, "http://public.test/"); body != "authenticated" {+ t.Fatalf("authenticated proxy response = %q, want %q", body, "authenticated")+ }+ if proxyAuthorization != "Basic dXNlcjpwYXNz" {+ t.Fatalf("Proxy-Authorization = %q", proxyAuthorization)+ }+}++func TestNetworkProxyLogValueRemovesCredentials(t *testing.T) {+ got := networkProxyLogValue("http://user:[email protected]:7890")+ if got != "http://127.0.0.1:7890" {+ t.Fatalf("network proxy log value = %q", got)+ }+}++func testPublicResolver(_ context.Context, host string) ([]net.IPAddr, error) {+ return []net.IPAddr{{IP: net.ParseIP("203.0.113.10")}}, nil+}++func setTestNetworkProxy(t *testing.T, proxyURL string) {+ t.Helper()+ t.Setenv("HTTP_PROXY", proxyURL)+ t.Setenv("HTTPS_PROXY", proxyURL)+ t.Setenv("http_proxy", proxyURL)+ t.Setenv("https_proxy", proxyURL)+ t.Setenv("NO_PROXY", "")+ t.Setenv("no_proxy", "")+}++func testResponseProxy(t *testing.T, body string) *httptest.Server {+ t.Helper()+ return testTunnelProxy(t, body, nil)+}++func getTestResponseBody(t *testing.T, client *http.Client, rawURL string) string {+ t.Helper()+ resp, err := client.Get(rawURL)+ if err != nil {+ t.Fatalf("GET %q failed: %v", rawURL, err)+ }+ body, err := io.ReadAll(resp.Body)+ if err != nil {+ t.Fatalf("read %q failed: %v", rawURL, err)+ }+ if err = resp.Body.Close(); err != nil {+ t.Fatalf("close %q failed: %v", rawURL, err)+ }+ return string(body)+}++func testTunnelProxy(t *testing.T, body string, inspect func(*http.Request, *http.Request)) *httptest.Server {+ t.Helper()+ proxy := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, connectReq *http.Request) {+ if connectReq.Method != http.MethodConnect {+ t.Errorf("proxy method = %q, want CONNECT", connectReq.Method)+ w.WriteHeader(http.StatusMethodNotAllowed)+ return+ }+ hijacker, ok := w.(http.Hijacker)+ if !ok {+ t.Error("proxy response writer does not support hijacking")+ w.WriteHeader(http.StatusInternalServerError)+ return+ }+ conn, rw, err := hijacker.Hijack()+ if err != nil {+ t.Errorf("hijack proxy connection failed: %v", err)+ return+ }+ defer conn.Close()+ if _, err = rw.WriteString("HTTP/1.1 200 Connection Established\r\n\r\n"); err != nil {+ t.Errorf("write CONNECT response failed: %v", err)+ return+ }+ if err = rw.Flush(); err != nil {+ t.Errorf("flush CONNECT response failed: %v", err)+ return+ }+ targetReq, err := http.ReadRequest(bufio.NewReader(conn))+ if err != nil {+ t.Errorf("read tunneled request failed: %v", err)+ return+ }+ if inspect != nil {+ inspect(connectReq, targetReq)+ }+ if _, err = fmt.Fprintf(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: %d\r\n\r\n%s", len(body), body); err != nil {+ t.Errorf("write tunneled response failed: %v", err)+ }+ }))+ t.Cleanup(proxy.Close)+ return proxy+}++func serveTestSOCKS5Connection(listener net.Listener, targets chan<- string, errs chan<- error) {+ conn, err := listener.Accept()+ if err != nil {+ errs <- err+ return+ }+ defer conn.Close()+ reader := bufio.NewReader(conn)+ greeting := make([]byte, 2)+ if _, err = io.ReadFull(reader, greeting); err != nil {+ errs <- err+ return+ }+ methods := make([]byte, int(greeting[1]))+ if _, err = io.ReadFull(reader, methods); err != nil {+ errs <- err+ return+ }+ if _, err = conn.Write([]byte{5, 0}); err != nil {+ errs <- err+ return+ }+ request := make([]byte, 10)+ if _, err = io.ReadFull(reader, request); err != nil {+ errs <- err+ return+ }+ if request[0] != 5 || request[1] != 1 || request[3] != 1 {+ errs <- fmt.Errorf("unexpected SOCKS5 request header %v", request[:4])+ return+ }+ targetIP := net.IP(request[4:8]).String()+ targetPort := int(request[8])<<8 | int(request[9])+ targets <- net.JoinHostPort(targetIP, fmt.Sprintf("%d", targetPort))+ if _, err = conn.Write([]byte{5, 0, 0, 1, 0, 0, 0, 0, 0, 0}); err != nil {+ errs <- err+ return+ }+ targetReq, err := http.ReadRequest(reader)+ if err != nil {+ errs <- err+ return+ }+ if targetReq.Host != "public.test" {+ errs <- fmt.Errorf("Host = %q, want original host", targetReq.Host)+ return+ }+ _, err = fmt.Fprint(conn, "HTTP/1.1 200 OK\r\nContent-Type: text/plain\r\nContent-Length: 6\r\n\r\nsocks5")+ if err != nil {+ errs <- err+ }+}diff --git a/kernel/util/openai.go b/kernel/util/openai.goindex 21ba5f6f28..bc66c356c6 100644--- a/kernel/util/openai.go+++ b/kernel/util/openai.go@@ -425,16 +425,20 @@ func IsNetworkError(err error) bool {var (embeddingHTTPClientOnce sync.OnceembeddingHTTPClient *http.Client+ embeddingHTTPTransport *http.Transport+ openAITransportMu sync.Mutex)func getEmbeddingHTTPClient() *http.Client {embeddingHTTPClientOnce.Do(func() {- transport := &http.Transport{- MaxConnsPerHost: 4, // 同一 embedding endpoint 的并发连接上限- MaxIdleConns: 8,- MaxIdleConnsPerHost: 4,- IdleConnTimeout: 90 * time.Second,- }+ transport := httpclient.NewTransport(false)+ transport.MaxConnsPerHost = 4 // 同一 embedding endpoint 的并发连接上限+ transport.MaxIdleConns = 8+ transport.MaxIdleConnsPerHost = 4+ transport.IdleConnTimeout = 90 * time.Second+ openAITransportMu.Lock()+ embeddingHTTPTransport = transport+ openAITransportMu.Unlock()embeddingHTTPClient = httpclient.NewUserAgentClient(transport)})return embeddingHTTPClient@@ -476,6 +480,7 @@ const rerankDocTextMaxRunes = 4000var (rerankHTTPClientOnce sync.OncererankHTTPClient *http.Client+ rerankHTTPTransport *http.Transport)func getRerankHTTPClient() *http.Client {@@ -485,11 +490,25 @@ func getRerankHTTPClient() *http.Client {transport.MaxIdleConns = 8transport.MaxIdleConnsPerHost = 4transport.IdleConnTimeout = 90 * time.Second+ openAITransportMu.Lock()+ rerankHTTPTransport = transport+ openAITransportMu.Unlock()rerankHTTPClient = httpclient.NewUserAgentClient(transport)})return rerankHTTPClient}+func closeOpenAIIdleConnections() {+ openAITransportMu.Lock()+ defer openAITransportMu.Unlock()+ if embeddingHTTPTransport != nil {+ embeddingHTTPTransport.CloseIdleConnections()+ }+ if rerankHTTPTransport != nil {+ rerankHTTPTransport.CloseIdleConnections()+ }+}+// rerankRequest 对应主流重排服务的 /rerank 请求体(Jina/Cohere/阿里云 compatible-api 等)。type rerankRequest struct {Model string `json:"model"`diff --git a/kernel/util/runtime.go b/kernel/util/runtime.goindex 71547b41bd..a26f12c487 100644--- a/kernel/util/runtime.go+++ b/kernel/util/runtime.go@@ -20,6 +20,7 @@ import ("bytes""crypto/rand""fmt"+ "net/url""os""path/filepath""runtime"@@ -218,12 +219,22 @@ func SetNetworkProxy(proxyURL string) {}if "" != proxyURL {- logging.LogInfof("use network proxy [%s]", proxyURL)+ logging.LogInfof("use network proxy [%s]", networkProxyLogValue(proxyURL))} else {logging.LogInfof("use network proxy [system]")}httpclient.CloseIdleConnections()+ closeOpenAIIdleConnections()+}++func networkProxyLogValue(rawURL string) string {+ proxyURL, err := url.Parse(rawURL)+ if err != nil {+ return "configured"+ }+ proxyURL.User = nil+ return proxyURL.String()}const (