Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:art: Add Generic Streamed Proxy Responses for Kernel Plugins (#17748)

mm-odda0fb91367a
diff --git a/kernel/api/network.go b/kernel/api/network.go
index 2e3a00a98f..68aac744df 100644
--- a/kernel/api/network.go
+++ b/kernel/api/network.go
@@ -23,12 +23,10 @@ import (
"encoding/json"
"fmt"
"io"
- "net"
"net/http"
"net/textproto"
"net/url"
"strings"
- "syscall"
"time"
"github.com/88250/gulu"
@@ -188,6 +186,9 @@ func forwardProxy(c *gin.Context) {
}
client := getSafeClient(time.Duration(timeout) * time.Millisecond)
+ if redirectArg, ok := arg["redirect"].(bool); ok && !redirectArg {
+ client.SetRedirectPolicy(req.NoRedirectPolicy())
+ }
request := client.R()
if headers, ok := arg["headers"].([]any); ok {
for _, pair := range headers {
@@ -327,31 +328,9 @@ func forwardProxy(c *gin.Context) {
// elapsed.Seconds(), len(bodyData), data["url"], headers, contentType, arg["payload"], data["status"], shortBody)
}
-// ssrfSafeDialer returns a net.Dialer whose Control hook blocks private IPs.
-func ssrfSafeDialer(timeout time.Duration) *net.Dialer {
- return &net.Dialer{
- Timeout: timeout,
- Control: func(network, address string, _ syscall.RawConn) error {
- host, _, err := net.SplitHostPort(address)
- if err != nil {
- return err
- }
- if ip := net.ParseIP(host); ip != nil && isPrivateIP(ip) {
- return fmt.Errorf("ip address [%s] is prohibited", host)
- }
- return nil
- },
- }
-}
-
-// 校验 IP 是否为私有内网地址
-func isPrivateIP(ip net.IP) bool {
- return ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsPrivate() || ip.IsUnspecified()
-}
-
// 创建安全的 HTTP Client,防止 SSRF 和 DNS 重绑定
func getSafeClient(timeout time.Duration) *req.Client {
- dialer := ssrfSafeDialer(timeout)
+ dialer := util.SSRFSafeDialer(timeout)
client := req.C()
client.SetTimeout(timeout)
@@ -436,7 +415,7 @@ func httpProxy(c *gin.Context) {
}
transport := &http.Transport{
- DialContext: ssrfSafeDialer(30 * time.Second).DialContext,
+ DialContext: util.SSRFSafeDialer(30 * time.Second).DialContext,
}
httpClient := &http.Client{Transport: transport}
@@ -491,7 +470,7 @@ func wsProxy(c *gin.Context) {
}
wsDialer := &websocket.Dialer{
- NetDialContext: ssrfSafeDialer(30 * time.Second).DialContext,
+ NetDialContext: util.SSRFSafeDialer(30 * time.Second).DialContext,
HandshakeTimeout: 30 * time.Second,
}
@@ -584,7 +563,7 @@ func esProxy(c *gin.Context) {
}
transport := &http.Transport{
- DialContext: ssrfSafeDialer(30 * time.Second).DialContext,
+ DialContext: util.SSRFSafeDialer(30 * time.Second).DialContext,
}
httpClient := &http.Client{Transport: transport}
diff --git a/kernel/plugin/server.go b/kernel/plugin/server.go
index 56190f7d08..086d696b56 100644
--- a/kernel/plugin/server.go
+++ b/kernel/plugin/server.go
@@ -18,11 +18,16 @@ package plugin
import (
"fmt"
+ "io"
"net/http"
+ "net/url"
+ "strings"
+ "time"
"github.com/dop251/goja"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/logging"
+ "github.com/siyuan-note/siyuan/kernel/util"
)
const (
@@ -144,6 +149,7 @@ type ResponseBody struct {
String *ResponseString `json:"string"` // if the response is a formatted string, String will be non-nil.
Raw *ResponseRawData `json:"raw"` // if the response is raw data, Raw will be non-nil.
Redirect *ResponseRedirect `json:"redirect"` // if the response is a redirect, Redirect will be non-nil.
+ Proxy *ResponseProxy `json:"proxy"` // if the response is a streaming proxy, Proxy will be non-nil.
}
type ResponseSerializedData struct {
@@ -170,11 +176,130 @@ type ResponseRedirect struct {
Location string `json:"location"` // the URL to redirect to
}
+type ResponseProxy struct {
+ URL string `json:"url"` // target http/https URL
+ Method string `json:"method"` // optional, defaults to the incoming request method, only GET/HEAD are supported
+ Headers map[string][]string `json:"headers"` // request headers forwarded to the target
+}
+
// isSseRequest checks if the incoming HTTP request is a Server-Sent Events (SSE) request by inspecting the "Accept" header for the "text/event-stream" value.
func isSseRequest(c *gin.Context) bool {
return c.GetHeader(SseHeaderAcceptName) == SseHeaderAcceptValue
}
+func isHopByHopHeader(header string) bool {
+ switch strings.ToLower(header) {
+ case "connection", "keep-alive", "proxy-authenticate", "proxy-authorization", "proxy-connection", "te", "trailer", "transfer-encoding", "upgrade":
+ return true
+ default:
+ return false
+ }
+}
+
+func connectionHopByHopHeaders(header http.Header) map[string]bool {
+ result := map[string]bool{}
+ for _, value := range header.Values("Connection") {
+ for _, part := range strings.Split(value, ",") {
+ if name := strings.ToLower(strings.TrimSpace(part)); name != "" {
+ result[name] = true
+ }
+ }
+ }
+ return result
+}
+
+func shouldProxyHeader(name string, connectionHeaders map[string]bool) bool {
+ lower := strings.ToLower(name)
+ return lower != "set-cookie" && !isHopByHopHeader(lower) && !connectionHeaders[lower]
+}
+
+func copyProxyHeaders(dst http.Header, src http.Header) {
+ connectionHeaders := connectionHopByHopHeaders(src)
+ for key, values := range src {
+ if !shouldProxyHeader(key, connectionHeaders) {
+ continue
+ }
+ dst.Del(key)
+ for _, value := range values {
+ dst.Add(key, value)
+ }
+ }
+}
+
+func newProxyHTTPClient() *http.Client {
+ return &http.Client{
+ Transport: &http.Transport{
+ DialContext: util.SSRFSafeDialer(30 * time.Second).DialContext,
+ DisableCompression: true,
+ },
+ CheckRedirect: func(req *http.Request, via []*http.Request) error {
+ if len(via) >= 10 {
+ return fmt.Errorf("stopped after 10 redirects")
+ }
+ req.Header.Del("Referer")
+ return nil
+ },
+ Timeout: 0,
+ }
+}
+
+func writeProxyResponse(c *gin.Context, proxy *ResponseProxy) {
+ if proxy.URL == "" {
+ c.String(http.StatusBadRequest, "missing proxy url")
+ return
+ }
+ targetURL, err := url.ParseRequestURI(proxy.URL)
+ if err != nil {
+ c.String(http.StatusBadRequest, "parse proxy url failed: %s", err.Error())
+ return
+ }
+ if targetURL.Scheme != "http" && targetURL.Scheme != "https" {
+ c.String(http.StatusBadRequest, "only http/https proxy url is allowed")
+ return
+ }
+
+ method := proxy.Method
+ if method == "" {
+ method = c.Request.Method
+ }
+ method = strings.ToUpper(method)
+ if method != http.MethodGet && method != http.MethodHead {
+ c.String(http.StatusBadRequest, "only GET/HEAD proxy method is allowed")
+ return
+ }
+ req, err := http.NewRequestWithContext(c.Request.Context(), method, targetURL.String(), nil)
+ if err != nil {
+ c.String(http.StatusBadRequest, "create proxy request failed: %s", err.Error())
+ return
+ }
+ requestConnectionHeaders := connectionHopByHopHeaders(http.Header(proxy.Headers))
+ for key, values := range proxy.Headers {
+ if !shouldProxyHeader(key, requestConnectionHeaders) {
+ continue
+ }
+ for _, value := range values {
+ req.Header.Add(key, value)
+ }
+ }
+
+ client := newProxyHTTPClient()
+ resp, err := client.Do(req)
+ if err != nil {
+ c.String(http.StatusBadGateway, "proxy request failed: %s", err.Error())
+ return
+ }
+ defer resp.Body.Close()
+
+ copyProxyHeaders(c.Writer.Header(), resp.Header)
+ c.Writer.WriteHeader(resp.StatusCode)
+ if method == http.MethodHead {
+ return
+ }
+ if _, err = io.Copy(c.Writer, resp.Body); err != nil {
+ logging.LogWarnf("plugin proxy copy response failed: %s", err.Error())
+ }
+}
+
func parseRequest(c *gin.Context) (request *Request, err error) {
var form *RequestForm
var data *[]byte
@@ -411,6 +536,10 @@ func HandleHttpRequest(c *gin.Context, scope AccessScope) {
// Redirect
c.Redirect(response.StatusCode, response.Body.Redirect.Location)
return
+ } else if response.Body.Proxy != nil {
+ // Streaming proxy
+ writeProxyResponse(c, response.Body.Proxy)
+ return
} else {
// No body
}
diff --git a/kernel/plugin/server_test.go b/kernel/plugin/server_test.go
new file mode 100644
index 0000000000..43cefcab85
--- /dev/null
+++ b/kernel/plugin/server_test.go
@@ -0,0 +1,129 @@
+// SiYuan - Refactor your thinking
+// 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 plugin
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+)
+
+func TestConnectionHopByHopHeaders(t *testing.T) {
+ header := http.Header{}
+ header.Add("Connection", "X-Request-Id, keep-alive")
+ header.Add("Connection", "X-Trace")
+
+ got := connectionHopByHopHeaders(header)
+ for _, name := range []string{"x-request-id", "keep-alive", "x-trace"} {
+ if !got[name] {
+ t.Fatalf("expected %q to be treated as hop-by-hop", name)
+ }
+ }
+}
+
+func TestCopyProxyHeadersFiltersAndOverwrites(t *testing.T) {
+ dst := http.Header{}
+ dst.Add("Content-Type", "application/json")
+ dst.Add("Accept-Ranges", "old")
+ dst.Add("X-Keep", "plugin")
+
+ src := http.Header{}
+ src.Add("Content-Type", "video/mp4")
+ src.Add("Accept-Ranges", "bytes")
+ src.Add("Connection", "X-Hop")
+ src.Add("X-Hop", "drop")
+ src.Add("Proxy-Connection", "close")
+ src.Add("Set-Cookie", "cloud=session")
+ src.Add("Transfer-Encoding", "chunked")
+
+ copyProxyHeaders(dst, src)
+
+ if got := dst.Values("Content-Type"); len(got) != 1 || got[0] != "video/mp4" {
+ t.Fatalf("expected upstream content type to overwrite plugin header, got %v", got)
+ }
+ if got := dst.Values("Accept-Ranges"); len(got) != 1 || got[0] != "bytes" {
+ t.Fatalf("expected upstream accept-ranges to overwrite plugin header, got %v", got)
+ }
+ for _, name := range []string{"Connection", "X-Hop", "Proxy-Connection", "Set-Cookie", "Transfer-Encoding"} {
+ if got := dst.Values(name); len(got) != 0 {
+ t.Fatalf("expected %q to be filtered, got %v", name, got)
+ }
+ }
+ if got := dst.Values("X-Keep"); len(got) != 1 || got[0] != "plugin" {
+ t.Fatalf("expected unrelated plugin header to remain, got %v", got)
+ }
+}
+
+func TestNewProxyHTTPClientStreamsRedirectsWithProxyHeaders(t *testing.T) {
+ client := newProxyHTTPClient()
+ if client.CheckRedirect == nil {
+ t.Fatal("expected redirect policy to be set")
+ }
+
+ final := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if got := r.Header.Get("Range"); got != "bytes=0-" {
+ t.Fatalf("expected Range to reach redirected request, got %q", got)
+ }
+ if got := r.Header.Get("User-Agent"); got != "pan.baidu.com" {
+ t.Fatalf("expected User-Agent to reach redirected request, got %q", got)
+ }
+ if got := r.Header.Get("Referer"); got != "" {
+ t.Fatalf("expected Referer to be dropped on redirected request, got %q", got)
+ }
+ w.WriteHeader(http.StatusPartialContent)
+ }))
+ defer final.Close()
+
+ start := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, final.URL, http.StatusFound)
+ }))
+ defer start.Close()
+
+ savedTransport := client.Transport
+ client.Transport = http.DefaultTransport
+ req, err := http.NewRequest(http.MethodGet, start.URL, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ req.Header.Set("Range", "bytes=0-")
+ req.Header.Set("User-Agent", "pan.baidu.com")
+ req.Header.Set("Referer", "https://drop.example.test/")
+ resp, err := client.Do(req)
+ if err != nil {
+ t.Fatalf("expected redirect to be followed, got %v", err)
+ }
+ defer resp.Body.Close()
+ if resp.StatusCode != http.StatusPartialContent {
+ t.Fatalf("expected final response status, got %d", resp.StatusCode)
+ }
+ client.Transport = savedTransport
+
+ tooMany := make([]*http.Request, 10)
+ for i := range tooMany {
+ tooMany[i] = &http.Request{Header: http.Header{}}
+ }
+ if err := client.CheckRedirect(&http.Request{Header: http.Header{}}, tooMany); err == nil {
+ t.Fatal("expected redirect limit error")
+ }
+ transport, ok := client.Transport.(*http.Transport)
+ if !ok {
+ t.Fatalf("expected *http.Transport, got %T", client.Transport)
+ }
+ if !transport.DisableCompression {
+ t.Fatal("expected automatic compression handling to be disabled")
+ }
+}
diff --git a/kernel/util/net.go b/kernel/util/net.go
index 43e914b2a2..08f1d23e57 100644
--- a/kernel/util/net.go
+++ b/kernel/util/net.go
@@ -26,6 +26,7 @@ import (
"os"
"strconv"
"strings"
+ "syscall"
"time"
"github.com/88250/gulu"
@@ -119,6 +120,27 @@ func IsLocalOrigin(origin string) bool {
return false
}
+// SSRFSafeDialer returns a net.Dialer whose Control hook blocks private, loopback, link-local and unspecified IPs.
+func SSRFSafeDialer(timeout time.Duration) *net.Dialer {
+ return &net.Dialer{
+ Timeout: timeout,
+ Control: func(network, address string, _ syscall.RawConn) error {
+ host, _, err := net.SplitHostPort(address)
+ if err != nil {
+ return err
+ }
+ if ip := net.ParseIP(host); ip != nil && isPrivateIP(ip) {
+ return fmt.Errorf("ip address [%s] is prohibited", host)
+ }
+ return nil
+ },
+ }
+}
+
+func isPrivateIP(ip net.IP) bool {
+ return ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsPrivate() || ip.IsUnspecified()
+}
+
func IsOnline(checkURL string, skipTlsVerify bool, timeout int) bool {
if "" == checkURL {
return false