An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作
TypeScript agentic-aiai-agentknowledge-baselocal-firstmarkdownmcpmindmapnote-takingself-hostedsiyuanworkspace
:lock: Confine plugin private service file responses to the workspace https://github.com/siyuan-note/siyuan/security/advisories/GHSA-phmw-4rgv-r4xv
Danielc6494375ea40
diff --git a/kernel/plugin/server.go b/kernel/plugin/server.goindex 6ce225c41b..542503b031 100644--- a/kernel/plugin/server.go+++ b/kernel/plugin/server.go@@ -159,7 +159,7 @@ type ResponseSerializedData struct {type ResponseFile struct {Name string `json:"name"` // e.g. "index.html". If Name is not empty, the file will be sent with Content-Disposition header.- Path string `json:"path"` // e.g. "/data/plugins/<plugin-name>/app/index.html"+ Path string `json:"path"` // e.g. "/data/plugins/<plugin-name>/app/index.html"; must resolve inside the workspace, otherwise the kernel answers 404}type ResponseString struct {diff --git a/kernel/plugin/service_contract.go b/kernel/plugin/service_contract.goindex 6ee9d88981..291715816a 100644--- a/kernel/plugin/service_contract.go+++ b/kernel/plugin/service_contract.go@@ -1,12 +1,19 @@package pluginimport (+ "errors""fmt""net/http"+ "os"+ "path/filepath"+ "strings"+ "github.com/88250/gulu""github.com/gin-gonic/gin""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/apicontract"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util")func PreparePrivateService(c *gin.Context, _ apicontract.EmptyRequest) apicontract.Response[apicontract.PluginServiceContent] {@@ -116,10 +123,18 @@ func pluginServiceHTTPResponse(c *gin.Context, name string, response *HttpRespon}} else if response.Body.File != nil {// 文件由 HTTP 文件服务处理范围请求和条件读取,不预先加载文件内容。+ fileAbsPath, pathErr := pluginServiceFileAbsPath(response.Body.File.Path)+ if nil != pathErr {+ if errors.Is(pathErr, errPluginServiceFilePathOutsideWorkspace) {+ logging.LogWarnf("[plugin:%s] Rejected file response path [%s] outside the workspace", name, response.Body.File.Path)+ }+ // 越界与文件缺失返回同样的响应,插件无法借状态差异探测工作空间外的文件+ return pluginServiceError(c, http.StatusNotFound, fmt.Sprintf("[plugin:%s] file not found", name))+ }if response.Body.File.Name != "" {- return pluginServiceStream(apicontract.PluginServiceFile, 200, func() { c.FileAttachment(response.Body.File.Path, response.Body.File.Name) })+ return pluginServiceStream(apicontract.PluginServiceFile, 200, func() { c.FileAttachment(fileAbsPath, response.Body.File.Name) })} else {- return pluginServiceStream(apicontract.PluginServiceFile, 200, func() { c.File(response.Body.File.Path) })+ return pluginServiceStream(apicontract.PluginServiceFile, 200, func() { c.File(fileAbsPath) })}} else if response.Body.String != nil {return pluginServiceStream(apicontract.PluginServiceString, response.StatusCode, func() { c.String(response.StatusCode, response.Body.String.Format, response.Body.String.Values...) })@@ -133,3 +148,48 @@ func pluginServiceHTTPResponse(c *gin.Context, name string, response *HttpRespon}return pluginServiceStream(apicontract.PluginServiceEmpty, response.StatusCode, func() { c.Status(response.StatusCode) })}++// errPluginServiceFilePathOutsideWorkspace 表示插件响应请求的文件落在工作空间之外。+var errPluginServiceFilePathOutsideWorkspace = errors.New("plugin service file path is outside the workspace")++// pluginServiceFileAbsPath 校验插件私有服务返回的文件路径,只允许服务工作空间内的文件。+// 插件与管理员 API 的能力边界必须一致:/api/file/getFile 依赖工作空间边界阻挡工作空间外的读取,+// 插件私有服务若不做同样的限制,插件就能借内核读取宿主机上的任意文件+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-phmw-4rgv-r4xv+func pluginServiceFileAbsPath(p string) (ret string, err error) {+ p = strings.TrimSpace(p)+ if "" == p {+ return "", os.ErrNotExist+ }+ if "" == util.WorkspaceDir {+ return "", errPluginServiceFilePathOutsideWorkspace+ }++ // 插件可以传工作空间内的绝对路径,也可以传工作空间相对路径(相对路径允许带前导斜杠,+ // 与 ResponseFile.Path 的文档示例 "/data/plugins/<plugin-name>/app/index.html" 一致)。+ // 工作空间外的绝对路径按相对路径解释,落到工作空间内不存在的文件上,与文件不存在不可区分+ cleanPath := filepath.Clean(p)+ candidates := []string{cleanPath}+ if !util.IsAbsPathInWorkspace(cleanPath) {+ candidates = append(candidates, filepath.Join(util.WorkspaceDir, cleanPath))+ }++ for _, candidate := range candidates {+ if !util.IsAbsPathInWorkspace(candidate) {+ continue+ }++ // 符号链接与目录联接可能指向工作空间外,解析后必须仍在工作空间内。这里不沿用+ // /api/file/getFile 对管理员的豁免,因为插件私有服务的调用方还包括浏览器发起的请求+ // https://github.com/siyuan-note/siyuan/security/advisories/GHSA-g7gf-v79m-jwrm+ resolved, resolveErr := model.ResolveAssetPathWithMissingLeaf(candidate)+ if nil != resolveErr {+ continue+ }+ if !gulu.File.IsSubPath(util.NormalizeAndResolve(util.WorkspaceDir), util.NormalizeAndResolve(resolved)) {+ continue+ }+ return resolved, nil+ }+ return "", errPluginServiceFilePathOutsideWorkspace+}diff --git a/kernel/plugin/service_contract_test.go b/kernel/plugin/service_contract_test.goindex 411c4a58d5..8f681d818d 100644--- a/kernel/plugin/service_contract_test.go+++ b/kernel/plugin/service_contract_test.go@@ -19,6 +19,7 @@ import ("github.com/gorilla/websocket""github.com/siyuan-note/siyuan/kernel/apicontract""github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util""google.golang.org/protobuf/types/known/wrapperspb")@@ -30,6 +31,16 @@ func serviceTestHandler(c *gin.Context) {serviceTestWrite(c, PreparePrivateService(c, apicontract.EmptyRequest{}))}+// newPluginServiceWorkspace 把工作空间指向临时目录,插件私有服务的文件响应以此为边界。+func newPluginServiceWorkspace(t *testing.T) (ret string) {+ t.Helper()+ oldWorkspaceDir := util.WorkspaceDir+ ret = t.TempDir()+ util.WorkspaceDir = ret+ t.Cleanup(func() { util.WorkspaceDir = oldWorkspaceDir })+ return+}+func newServiceTestPlugin(t *testing.T, script string) (*KernelPlugin, context.CancelFunc) {t.Helper()ctx, cancel := context.WithCancel(context.Background())@@ -57,7 +68,7 @@ func TestPluginServiceHTTPBranches(t *testing.T) {if err != nil {t.Fatal(err)}- file := filepath.Join(t.TempDir(), "content.txt")+ file := filepath.Join(newPluginServiceWorkspace(t), "content.txt")if err = os.WriteFile(file, []byte("file content"), 0600); err != nil {t.Fatal(err)}@@ -191,7 +202,7 @@ func TestPluginServiceProxyAndFiles(t *testing.T) {}func TestPluginServiceFileRangesRedirectAndPriority(t *testing.T) {- file := filepath.Join(t.TempDir(), "range.txt")+ file := filepath.Join(newPluginServiceWorkspace(t), "range.txt")if err := os.WriteFile(file, []byte("0123456789"), 0600); err != nil {t.Fatal(err)}@@ -282,3 +293,87 @@ func TestPluginServiceStreamingLifecycle(t *testing.T) {t.Fatal("plugin cancellation did not close SSE")}}++// TestPluginServiceFileConfinedToWorkspace 校验插件私有服务只能服务工作空间内的文件。+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-phmw-4rgv-r4xv+func TestPluginServiceFileConfinedToWorkspace(t *testing.T) {+ root := newPluginServiceWorkspace(t)+ const secret = "PLUGIN-FILE-DISCLOSURE-SECRET"++ outsideDir := t.TempDir()+ outside := filepath.Join(outsideDir, "secret.txt")+ if err := os.WriteFile(outside, []byte(secret), 0600); err != nil {+ t.Fatal(err)+ }+ inside := filepath.Join(root, "inside.txt")+ if err := os.WriteFile(inside, []byte("inside content"), 0600); err != nil {+ t.Fatal(err)+ }++ request := func(path string) *httptest.ResponseRecorder {+ engine := gin.New()+ engine.Any("/plugin/private/:name/*path", func(c *gin.Context) {+ serviceTestWrite(c, pluginServiceHTTPResponse(c, "test", &HttpResponse{+ StatusCode: 200,+ Body: &ResponseBody{File: &ResponseFile{Path: path}},+ }))+ })+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest("GET", "/plugin/private/test/file", nil))+ return recorder+ }++ // 控制组:工作空间内的文件照常服务+ recorder := request(inside)+ if "inside content" != recorder.Body.String() || http.StatusOK != recorder.Code {+ t.Fatalf("in-workspace file was not served: %d %q", recorder.Code, recorder.Body.String())+ }++ // 控制组:ResponseFile.Path 的文档示例形式(以工作空间根为基准、带前导斜杠)照常服务+ example := filepath.Join(root, "data", "plugins", "sample", "app", "index.html")+ if err := os.MkdirAll(filepath.Dir(example), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(example, []byte("plugin page"), 0600); err != nil {+ t.Fatal(err)+ }+ recorder = request("/data/plugins/sample/app/index.html")+ if "plugin page" != recorder.Body.String() || http.StatusOK != recorder.Code {+ t.Fatalf("documented leading-slash path was not served: %d %q", recorder.Code, recorder.Body.String())+ }++ for _, tt := range []struct {+ name string+ path string+ }{+ {"absolute path outside the workspace", outside},+ {"relative traversal outside the workspace", strings.Repeat("../", 16) + "etc/hosts"},+ {"workspace escaped by ..", filepath.Join(root, "..", "..", filepath.Base(outsideDir), "secret.txt")},+ } {+ t.Run(tt.name, func(t *testing.T) {+ recorder := request(tt.path)+ if strings.Contains(recorder.Body.String(), secret) {+ t.Fatalf("plugin service served a file outside the workspace: %q", recorder.Body.String())+ }+ if http.StatusNotFound != recorder.Code {+ t.Fatalf("unexpected status %d: %q", recorder.Code, recorder.Body.String())+ }+ })+ }++ // 工作空间内的符号链接指向工作空间外时同样拒绝+ t.Run("symlink pointing outside the workspace", func(t *testing.T) {+ link := filepath.Join(root, "link.txt")+ if err := os.Symlink(outside, link); err != nil {+ // Windows 未开启开发者模式时创建符号链接需要特权,链接解析本身由 model 的用例覆盖+ t.Skipf("symlink is unavailable: %s", err)+ }+ recorder := request(link)+ if strings.Contains(recorder.Body.String(), secret) {+ t.Fatalf("plugin service followed a symlink outside the workspace: %q", recorder.Body.String())+ }+ if http.StatusNotFound != recorder.Code {+ t.Fatalf("unexpected status %d: %q", recorder.Code, recorder.Body.String())+ }+ })+}