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: Block sensitive package files in publish reader paths https://github.com/siyuan-note/siyuan/security/advisories/GHSA-3pm7-cc76-7j2p
Daniel1e5a5a2c3498
diff --git a/kernel/api/plugin_publish_test.go b/kernel/api/plugin_publish_test.goindex f24a1fa9a5..2c3fda5f9a 100644--- a/kernel/api/plugin_publish_test.go+++ b/kernel/api/plugin_publish_test.go@@ -27,10 +27,11 @@ func TestAPIContractPluginPublish(t *testing.T) {util.WorkspaceDir, util.DataDir, util.ConfDir, model.Conf = oldWorkspace, oldData, oldConfDir, oldConf})files := map[string]string{- "data/plugins/example/plugin.json": `{"name":"example","version":"1.0.0","minAppVersion":"0.0.1","publish":{"resources":["logo.txt"],"data":["theme"]}}`,+ "data/plugins/example/plugin.json": `{"name":"example","version":"1.0.0","minAppVersion":"0.0.1","publish":{"resources":["logo.txt","credentials.json"],"data":["theme"]}}`,"data/plugins/example/index.js": "frontend","data/plugins/example/kernel.js": "kernel secret","data/plugins/example/logo.txt": "logo",+ "data/plugins/example/credentials.json": "API_TOKEN=secret","data/plugins/example/private.json": "secret","data/storage/petal/example/private.json": "private token","data/public/file.txt": "public",@@ -109,7 +110,7 @@ func TestAPIContractPluginPublish(t *testing.T) {t.Fatalf("allowed %s: %d %s", path, response.Code, response.Body)}}- for _, path := range []string{"data/plugins/example/kernel.js", "data/plugins/example/private.json", "data/storage/petal/example/private.json", "data/private.json", "conf/private.json", "temp/private.json", "repo/private.json", "history/private.json", "conf/plugin-publish/example.json", "data/public/../storage/petal/example/private.json", "data/plugins/example/%2e%2e/private.json"} {+ for _, path := range []string{"data/plugins/example/kernel.js", "data/plugins/example/private.json", "data/plugins/example/credentials.json", "data/storage/petal/example/private.json", "data/private.json", "conf/private.json", "temp/private.json", "repo/private.json", "history/private.json", "conf/plugin-publish/example.json", "data/public/../storage/petal/example/private.json", "data/plugins/example/%2e%2e/private.json"} {body, _ := json.Marshal(map[string]string{"path": path})response := request(model.RoleReader, "/api/file/getFile", string(body))if response.Code != 202 || code(response) != 403 {diff --git a/kernel/model/plugin_publish.go b/kernel/model/plugin_publish.goindex 04717e746c..900454b7be 100644--- a/kernel/model/plugin_publish.go+++ b/kernel/model/plugin_publish.go@@ -116,7 +116,7 @@ func OpenPluginPublishResource(name, resource string) (*os.File, error) {if err != nil || !isPluginPublishResource(declaration, resource) {return nil, ErrPluginPublishDenied}- return util.OpenPublishFile(util.DataDir, "plugins/"+name+"/"+resource)+ return util.OpenPublishReaderFile(util.DataDir, "plugins/"+name+"/"+resource)}func loadPluginPublishCode(petal *Petal) bool {@@ -169,7 +169,7 @@ func OpenPublishPackageFile(c *gin.Context, requestPath string) (file *os.File,if !ok || !CheckWidgetAccessableByPublishAccess(c, name, GetPublishAccess()) {return nil, true, ErrPluginPublishDenied}- file, err = util.OpenPublishFile(util.DataDir, "widgets/"+resource)+ file, err = util.OpenPublishReaderFile(util.DataDir, "widgets/"+resource)}return file, true, err}diff --git a/kernel/model/publish_package_file_test.go b/kernel/model/publish_package_file_test.gonew file mode 100644index 0000000000..051db8454a--- /dev/null+++ b/kernel/model/publish_package_file_test.go@@ -0,0 +1,140 @@+package model++import (+ "errors"+ "io"+ "io/fs"+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/88250/lute/parse"+ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// TestOpenPublishPackageFileRejectsSensitiveWidgetResource 验证发布读者经文件接口读取挂件包时先拒绝敏感文件名。+func TestOpenPublishPackageFileRejectsSensitiveWidgetResource(t *testing.T) {+ const boxID, rootID = "20261026000000-sensbx1", "20261026000000-sensdoc"+ previousDataDir, previousWorkspace, previousDBPath := util.DataDir, util.WorkspaceDir, util.BlockTreeDBPath+ root := t.TempDir()+ util.DataDir = filepath.Join(root, "data")+ util.WorkspaceDir = root+ util.BlockTreeDBPath = filepath.Join(root, "blocktree.db")+ if err := os.MkdirAll(util.DataDir, 0755); err != nil {+ t.Fatal(err)+ }+ treenode.InitBlockTree(true)+ cacheKey := boxID + "/" + rootID+ t.Cleanup(func() {+ publishResourceRefsCache.Delete(cacheKey)+ treenode.CloseDatabase()+ util.DataDir, util.WorkspaceDir, util.BlockTreeDBPath = previousDataDir, previousWorkspace, previousDBPath+ })++ doc := &ast.Node{Type: ast.NodeDocument, ID: rootID}+ doc.SetIALAttr("updated", "20261026000001")+ tree := &parse.Tree{ID: rootID, Box: boxID, Path: "/" + rootID + ".sy", Root: doc}+ treenode.IndexBlockTree(tree)+ bt := treenode.GetBlockTreeInBox(rootID, boxID)+ if bt == nil {+ t.Fatal("block tree missing")+ }++ widgetDir := filepath.Join(util.DataDir, "widgets", "example")+ if err := os.MkdirAll(widgetDir, 0755); err != nil {+ t.Fatal(err)+ }+ files := map[string]string{+ "widget.json": `{"name":"example","version":"1.0.0","minAppVersion":"0.0.1","disabledInPublish":false}`,+ "index.html": "<html>ok</html>",+ "credentials.json": "API_TOKEN=secret",+ "id_token": "token-secret",+ }+ for name, content := range files {+ if err := os.WriteFile(filepath.Join(widgetDir, name), []byte(content), 0644); err != nil {+ t.Fatal(err)+ }+ }+ publishResourceRefsCache.Store(cacheKey, &publishResourceRefs{+ updated: bt.Updated,+ widgets: map[string]struct{}{"example": {}},+ })++ c, _ := gin.CreateTestContext(httptest.NewRecorder())+ c.Request = httptest.NewRequest(http.MethodPost, "/api/file/getFile", nil)+ for _, requestPath := range []string{"/data/widgets/example/credentials.json", "/data/widgets/example/id_token"} {+ file, handled, err := OpenPublishPackageFile(c, requestPath)+ if file != nil {+ file.Close()+ }+ if !handled || !errors.Is(err, fs.ErrPermission) {+ t.Fatalf("sensitive %s: handled = %v, err = %v, want permission denied", requestPath, handled, err)+ }+ }++ file, handled, err := OpenPublishPackageFile(c, "/data/widgets/example/index.html")+ if err != nil || !handled {+ t.Fatalf("ordinary widget file rejected: handled = %v, err = %v", handled, err)+ }+ defer file.Close()+ data, readErr := io.ReadAll(file)+ if readErr != nil || string(data) != files["index.html"] {+ t.Fatalf("unexpected ordinary widget content: %q, %v", data, readErr)+ }+}++// TestOpenPublishPackageFileRejectsSensitivePluginResource 验证发布读者经文件接口读取插件包时先拒绝敏感文件名。+func TestOpenPublishPackageFileRejectsSensitivePluginResource(t *testing.T) {+ originalDataDir, originalConf := util.DataDir, Conf+ util.DataDir = t.TempDir()+ Conf = NewAppConf()+ Conf.Sync.Store(conf.NewSync())+ Conf.Bazaar.Store(&conf.Bazaar{Trust: true})+ Conf.Lang = "en"+ t.Cleanup(func() { util.DataDir, Conf = originalDataDir, originalConf })++ pluginDir := filepath.Join(util.DataDir, "plugins", "example")+ if err := os.MkdirAll(pluginDir, 0755); err != nil {+ t.Fatal(err)+ }+ files := map[string]string{+ "plugin.json": `{"name":"example","version":"1.0.0","minAppVersion":"0.0.1","publish":{"resources":["logo.txt","credentials.json"]}}`,+ "index.js": "frontend",+ "logo.txt": "logo",+ "credentials.json": "API_TOKEN=secret",+ }+ for name, content := range files {+ if err := os.WriteFile(filepath.Join(pluginDir, name), []byte(content), 0644); err != nil {+ t.Fatal(err)+ }+ }+ if _, err := SetPetalEnabled("example", true); err != nil {+ t.Fatal(err)+ }++ c, _ := gin.CreateTestContext(httptest.NewRecorder())+ c.Request = httptest.NewRequest(http.MethodPost, "/api/file/getFile", nil)+ file, handled, err := OpenPublishPackageFile(c, "/data/plugins/example/credentials.json")+ if file != nil {+ file.Close()+ }+ if !handled || !errors.Is(err, fs.ErrPermission) {+ t.Fatalf("sensitive plugin resource: handled = %v, err = %v, want permission denied", handled, err)+ }++ file, handled, err = OpenPublishPackageFile(c, "/data/plugins/example/logo.txt")+ if err != nil || !handled {+ t.Fatalf("ordinary plugin resource rejected: handled = %v, err = %v", handled, err)+ }+ defer file.Close()+ data, readErr := io.ReadAll(file)+ if readErr != nil || string(data) != files["logo.txt"] {+ t.Fatalf("unexpected ordinary plugin content: %q, %v", data, readErr)+ }+}diff --git a/kernel/server/serve.go b/kernel/server/serve.goindex 3a03519282..36f2ff4f70 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -474,7 +474,7 @@ func serveWidgets(ginServer *gin.Engine) {if !model.CheckWidgetAccessableByPublishAccess(c, name, model.GetPublishAccess()) {return false}- file, err := util.OpenPublishFile(util.DataDir, "widgets/"+resource)+ file, err := util.OpenPublishReaderFile(util.DataDir, "widgets/"+resource)if err != nil {return false}diff --git a/kernel/server/serve_publish_package_test.go b/kernel/server/serve_publish_package_test.gonew file mode 100644index 0000000000..d38419da72--- /dev/null+++ b/kernel/server/serve_publish_package_test.go@@ -0,0 +1,148 @@+package server++import (+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"++ "github.com/88250/lute/ast"+ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/conf"+ "github.com/siyuan-note/siyuan/kernel/filesys"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// TestWidgetPublishReaderRefusesSensitiveFile 验证发布读者不能经静态路由读取挂件包中的敏感文件。+func TestWidgetPublishReaderRefusesSensitiveFile(t *testing.T) {+ gin.SetMode(gin.TestMode)+ const boxID, docID = "20261026000000-sensbx1", "20261026000000-sensdoc"+ previousWorkspace, previousData, previousConfDir := util.WorkspaceDir, util.DataDir, util.ConfDir+ previousDBPath, previousConf := util.BlockTreeDBPath, model.Conf+ root := t.TempDir()+ util.WorkspaceDir = root+ util.DataDir, util.ConfDir = filepath.Join(root, "data"), filepath.Join(root, "conf")+ util.BlockTreeDBPath = filepath.Join(root, "blocktree.db")+ for _, dir := range []string{util.DataDir, util.ConfDir, filepath.Join(util.DataDir, boxID)} {+ if err := os.MkdirAll(dir, 0755); err != nil {+ t.Fatal(err)+ }+ }+ model.Conf = model.NewAppConf()+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.FileTree.Store(conf.NewFileTree())+ model.Conf.Editor.Store(conf.NewEditor())+ model.Conf.Lang = "en"+ treenode.InitBlockTree(true)+ t.Cleanup(func() {+ model.SetPublishAccess(model.PublishAccess{})+ treenode.CloseDatabase()+ util.WorkspaceDir, util.DataDir, util.ConfDir = previousWorkspace, previousData, previousConfDir+ util.BlockTreeDBPath, model.Conf = previousDBPath, previousConf+ })++ widgetDir := filepath.Join(util.DataDir, "widgets", "example")+ if err := os.MkdirAll(widgetDir, 0755); err != nil {+ t.Fatal(err)+ }+ files := map[string]string{+ "widget.json": `{"name":"example","version":"1.0.0","minAppVersion":"0.0.1","disabledInPublish":false}`,+ "index.html": "<html>ok</html>",+ "credentials.json": "API_TOKEN=secret",+ "id_token": "token-secret",+ }+ for name, content := range files {+ if err := os.WriteFile(filepath.Join(widgetDir, name), []byte(content), 0644); err != nil {+ t.Fatal(err)+ }+ }++ tree := treenode.NewTree(boxID, "/"+docID+".sy", "/Widget proof", "Widget proof")+ tree.Root.AppendChild(&ast.Node{Type: ast.NodeIFrame, Tokens: []byte(`<iframe src="/widgets/example/"></iframe>`)})+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ treenode.IndexBlockTree(tree)+ if err := model.SetPublishAccess(model.PublishAccess{{ID: docID, Visible: true, Password: "", Disable: false}}); err != nil {+ t.Fatal(err)+ }++ request := func(role model.Role, requestPath string) *httptest.ResponseRecorder {+ engine := gin.New()+ engine.Use(func(c *gin.Context) {+ c.Set(model.RoleContextKey, role)+ c.Next()+ })+ serveWidgets(engine)+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, requestPath, nil))+ return recorder+ }++ for _, role := range []model.Role{model.RoleReader, model.RoleAdministrator} {+ for _, requestPath := range []string{"/widgets/example/credentials.json", "/widgets/example/id_token"} {+ recorder := request(role, requestPath)+ if recorder.Code != http.StatusForbidden || recorder.Body.Len() != 0 {+ t.Fatalf("%v %s: status = %d, body = %q", role, requestPath, recorder.Code, recorder.Body.String())+ }+ }+ if recorder := request(role, "/widgets/example/"); recorder.Code != http.StatusOK || recorder.Body.String() != files["index.html"] {+ t.Fatalf("%v ordinary widget file: status = %d, body = %q", role, recorder.Code, recorder.Body.String())+ }+ }+}++// TestPluginPublishReaderRefusesSensitiveFile 验证发布读者不能经静态路由读取插件包中的敏感文件。+func TestPluginPublishReaderRefusesSensitiveFile(t *testing.T) {+ gin.SetMode(gin.TestMode)+ previousData, previousConf := util.DataDir, model.Conf+ util.DataDir = t.TempDir()+ model.Conf = model.NewAppConf()+ model.Conf.Sync.Store(conf.NewSync())+ model.Conf.Bazaar.Store(&conf.Bazaar{Trust: true})+ model.Conf.Lang = "en"+ t.Cleanup(func() { util.DataDir, model.Conf = previousData, previousConf })++ pluginDir := filepath.Join(util.DataDir, "plugins", "example")+ if err := os.MkdirAll(pluginDir, 0755); err != nil {+ t.Fatal(err)+ }+ files := map[string]string{+ "plugin.json": `{"name":"example","version":"1.0.0","minAppVersion":"0.0.1","publish":{"resources":["logo.txt","credentials.json"]}}`,+ "index.js": "frontend",+ "logo.txt": "logo",+ "credentials.json": "API_TOKEN=secret",+ }+ for name, content := range files {+ if err := os.WriteFile(filepath.Join(pluginDir, name), []byte(content), 0644); err != nil {+ t.Fatal(err)+ }+ }+ if _, err := model.SetPetalEnabled("example", true); err != nil {+ t.Fatal(err)+ }++ request := func(role model.Role, requestPath string) *httptest.ResponseRecorder {+ engine := gin.New()+ engine.Use(func(c *gin.Context) {+ c.Set(model.RoleContextKey, role)+ c.Next()+ })+ servePlugins(engine)+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, requestPath, nil))+ return recorder+ }++ for _, role := range []model.Role{model.RoleReader, model.RoleAdministrator} {+ if recorder := request(role, "/plugins/example/credentials.json"); recorder.Code != http.StatusForbidden || recorder.Body.Len() != 0 {+ t.Fatalf("%v sensitive plugin resource: status = %d, body = %q", role, recorder.Code, recorder.Body.String())+ }+ if recorder := request(role, "/plugins/example/logo.txt"); recorder.Code != http.StatusOK || recorder.Body.String() != files["logo.txt"] {+ t.Fatalf("%v ordinary plugin resource: status = %d, body = %q", role, recorder.Code, recorder.Body.String())+ }+ }+}diff --git a/kernel/util/publish_file.go b/kernel/util/publish_file.goindex 914cd96eca..c601a5a5dc 100644--- a/kernel/util/publish_file.go+++ b/kernel/util/publish_file.go@@ -3,6 +3,7 @@ package utilimport ("io/fs""os"+ "path/filepath""strings")@@ -70,3 +71,15 @@ func OpenPublishFile(rootPath, name string) (*os.File, error) {}return file, nil}++// OpenPublishReaderFile 打开读者可见的包资源:先执行敏感文件名策略,再进入包内约束读取。+// data/public 按设计公开,仍直接使用 OpenPublishFile,不经过本函数。+func OpenPublishReaderFile(rootPath, name string) (*os.File, error) {+ if !IsPublishRelativePath(name) {+ return nil, fs.ErrPermission+ }+ if IsSensitivePath(filepath.Join(rootPath, filepath.FromSlash(name))) {+ return nil, fs.ErrPermission+ }+ return OpenPublishFile(rootPath, name)+}diff --git a/kernel/util/publish_file_test.go b/kernel/util/publish_file_test.goindex f1a456b389..72bea3a9f5 100644--- a/kernel/util/publish_file_test.go+++ b/kernel/util/publish_file_test.go@@ -1,7 +1,9 @@package utilimport (+ "errors""io"+ "io/fs""os""path/filepath""testing"@@ -50,3 +52,43 @@ func TestPublishFileBoundary(t *testing.T) {}})}++// TestOpenPublishReaderFileSensitiveNames 验证读者可见的包资源在打开前按文件名策略拒绝敏感文件。+func TestOpenPublishReaderFileSensitiveNames(t *testing.T) {+ root := t.TempDir()+ previousWorkspace := WorkspaceDir+ WorkspaceDir = root+ t.Cleanup(func() { WorkspaceDir = previousWorkspace })++ dir := filepath.Join(root, "widgets", "example")+ if err := os.MkdirAll(filepath.Join(dir, "sub"), 0755); err != nil {+ t.Fatal(err)+ }+ for name, content := range map[string]string{+ "index.html": "ok",+ "my-credentials.json": "ok",+ "credentials.json": "secret",+ "id_rsa": "secret",+ "sub/id_token": "secret",+ } {+ if err := os.WriteFile(filepath.Join(dir, filepath.FromSlash(name)), []byte(content), 0644); err != nil {+ t.Fatal(err)+ }+ }++ for _, name := range []string{"widgets/example/credentials.json", "widgets/example/id_rsa", "widgets/example/sub/id_token"} {+ if file, err := OpenPublishReaderFile(root, name); !errors.Is(err, fs.ErrPermission) {+ if file != nil {+ file.Close()+ }+ t.Fatalf("sensitive file %q: err = %v, want permission denied", name, err)+ }+ }+ for _, name := range []string{"widgets/example/index.html", "widgets/example/my-credentials.json"} {+ file, err := OpenPublishReaderFile(root, name)+ if err != nil {+ t.Fatalf("ordinary file %q rejected: %v", name, err)+ }+ file.Close()+ }+}