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: Filter publish-inaccessible sub-document counts on reader endpoints https://github.com/siyuan-note/siyuan/security/advisories/GHSA-ccxp-q3vg-jvgj
Danielaba413342804
diff --git a/kernel/api/filetree.go b/kernel/api/filetree.goindex 88ccc9884d..c1d996a6bb 100644--- a/kernel/api/filetree.go+++ b/kernel/api/filetree.go@@ -1176,6 +1176,10 @@ func listDocsByPathContract(c *gin.Context, request apicontract.FileTreeListRequfor _, file := range files {if model.CheckPathAccessableByPublishIgnore(notebook, file.Path, publishInvisible) &&model.CheckPathAccessableByPublishIgnore(notebook, file.Path, publishDisable) {+ // 下级文档数同样只统计发布可见的文档,避免读者据此推断被排除文档的数量+ if 0 < file.SubFileCount {+ file.SubFileCount = model.BoxDocSubFileCountForPublishAt(notebook, file.Path, publishAccess)+ }tempFiles = append(tempFiles, file)}}diff --git a/kernel/api/filetree_test.go b/kernel/api/filetree_test.goindex 407fc66459..f12030995b 100644--- a/kernel/api/filetree_test.go+++ b/kernel/api/filetree_test.go@@ -764,3 +764,112 @@ func TestFilterFileTreePublishAccess(t *testing.T) {t.Fatalf("administrator IDs should remain unchanged: %v", filtered)}}++// TestListDocsByPathFiltersSubFileCountForPublishReader 验证发布读者看到的文档树+// 下级文档数只统计发布可见的文档,避免据此推断被排除文档的数量。+func TestListDocsByPathFiltersSubFileCountForPublishReader(t *testing.T) {+ gin.SetMode(gin.TestMode)++ const (+ boxID = "20260726000000-boxid01"+ parentID = "20260726000001-parent1"+ publicID = "20260726000002-public1"+ hiddenID = "20260726000003-hidden1"+ forbiddenID = "20260726000004-forbid1"+ )+ oldDataDir, oldConf := util.DataDir, model.Conf+ oldPublishAccess := model.GetPublishAccess()+ util.DataDir = t.TempDir()+ model.Conf = model.NewAppConf()+ model.Conf.FileTree = conf.NewFileTree()+ const testLang = "filetree-subfile-count-test"+ installAPITestTimeLangs(t, testLang)+ model.Conf.Lang = testLang+ t.Cleanup(func() {+ if err := model.SetPublishAccess(oldPublishAccess); err != nil {+ t.Errorf("restore publish access failed: %v", err)+ }+ util.DataDir, model.Conf = oldDataDir, oldConf+ })+ if err := model.SetPublishAccess(model.PublishAccess{}); err != nil {+ t.Fatal(err)+ }++ boxConf := conf.NewBoxConf()+ boxConf.Closed = false+ if err := (&model.Box{ID: boxID}).SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ boxDir := filepath.Join(util.DataDir, boxID)+ if err := os.MkdirAll(filepath.Join(boxDir, parentID), 0755); err != nil {+ t.Fatal(err)+ }+ // 文档属性必须非空,否则会被当作损坏数据移出笔记本+ writeDoc := func(dir, id string) {+ t.Helper()+ content := `{"Properties":{"id":"` + id + `","title":"` + id + `"}}`+ if err := os.WriteFile(filepath.Join(boxDir, dir, id+".sy"), []byte(content), 0644); err != nil {+ t.Fatal(err)+ }+ }+ writeDoc(".", parentID)+ writeDoc(parentID, publicID)+ writeDoc(parentID, hiddenID)+ writeDoc(parentID, forbiddenID)++ requestSubFileCount := func(role model.Role) int {+ t.Helper()++ engine := gin.New()+ engine.Use(func(c *gin.Context) {+ c.Set(model.RoleContextKey, role)+ c.Next()+ })+ engine.POST("/api/filetree/listDocsByPath", listDocsByPath)++ recorder := httptest.NewRecorder()+ httpRequest := httptest.NewRequest(+ http.MethodPost,+ "/api/filetree/listDocsByPath",+ strings.NewReader(`{"notebook":"`+boxID+`","path":"/"}`),+ )+ httpRequest.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, httpRequest)+ requireAPIContract(t, http.MethodPost, "/api/filetree/listDocsByPath", recorder)++ response := &struct {+ Code int `json:"code"`+ Msg string `json:"msg"`+ Data struct {+ Files []*model.File `json:"files"`+ } `json:"data"`+ }{}+ if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {+ t.Fatalf("unmarshal list response failed: %v", err)+ }+ if 0 != response.Code {+ t.Fatalf("list docs by path failed: %s", recorder.Body.String())+ }+ for _, file := range response.Data.Files {+ if file.ID == parentID {+ return file.SubFileCount+ }+ }+ t.Fatalf("parent document not found: %s", recorder.Body.String())+ return -1+ }++ if actual := requestSubFileCount(model.RoleAdministrator); 3 != actual {+ t.Fatalf("administrator subfile count = %d, want 3", actual)+ }++ if err := model.SetPublishAccess(model.PublishAccess{+ {ID: hiddenID, Visible: false},+ {ID: forbiddenID, Visible: false, Disable: true},+ }); err != nil {+ t.Fatal(err)+ }+ if actual := requestSubFileCount(model.RoleReader); 1 != actual {+ t.Fatalf("reader subfile count = %d, want only the published one", actual)+ }+}diff --git a/kernel/api/notebook_security_test.go b/kernel/api/notebook_security_test.goindex 294df09366..fa320901a3 100644--- a/kernel/api/notebook_security_test.go+++ b/kernel/api/notebook_security_test.go@@ -190,8 +190,8 @@ func TestGetNotebookInfoHidesInvisibleNotebookFromReader(t *testing.T) {}}-// installNotebookSecurityTimeLangs 为指定语言安装时间本地化标签,避免聚合信息渲染相对时间失败。-func installNotebookSecurityTimeLangs(t *testing.T, lang string) {+// installAPITestTimeLangs 为指定语言安装时间本地化标签,避免聚合信息渲染相对时间失败。+func installAPITestTimeLangs(t *testing.T, lang string) {t.Helper()oldLang, hadLang := util.TimeLangs[lang]@@ -219,7 +219,7 @@ func TestGetNotebookInfoExcludesPublishExcludedDocumentsForReader(t *testing.T)model.Conf = model.NewAppConf()model.Conf.FileTree = conf.NewFileTree()const testLang = "notebook-info-publish-test"- installNotebookSecurityTimeLangs(t, testLang)+ installAPITestTimeLangs(t, testLang)model.Conf.Lang = testLangt.Cleanup(func() {if err := model.SetPublishAccess(oldPublishAccess); err != nil {diff --git a/kernel/model/box_doc.go b/kernel/model/box_doc.goindex f8e861ba9b..935b3e6a11 100644--- a/kernel/model/box_doc.go+++ b/kernel/model/box_doc.go@@ -274,16 +274,21 @@ func reconcileBoxDoc(box *Box, boxDocID string) error {// BoxDocSubFileCount 返回笔记本顶层文档的可见下级文档数。func BoxDocSubFileCount(boxID string) int {- return boxDocSubFileCount(boxID, nil)+ return boxDocSubFileCount(boxID, "/", nil)}// BoxDocSubFileCountForPublish 返回发布访问控制下笔记本顶层文档的可见下级文档数。func BoxDocSubFileCountForPublish(boxID string, publishAccess PublishAccess) int {- return boxDocSubFileCount(boxID, PublishVisibleDocPathFilter(boxID, publishAccess))+ return boxDocSubFileCount(boxID, "/", PublishVisibleDocPathFilter(boxID, publishAccess))}-func boxDocSubFileCount(boxID string, include func(string) bool) int {- ret, _ := visibleDocCount(boxID, "/", func(p string) map[string]string {+// BoxDocSubFileCountForPublishAt 返回发布访问控制下指定文档的可见直接子文档数,docPath 为该文档的 .sy 路径。+func BoxDocSubFileCountForPublishAt(boxID, docPath string, publishAccess PublishAccess) int {+ return boxDocSubFileCount(boxID, strings.TrimSuffix(docPath, ".sy"), PublishVisibleDocPathFilter(boxID, publishAccess))+}++func boxDocSubFileCount(boxID, parentPath string, include func(docPath string) bool) int {+ ret, _ := visibleDocCount(boxID, parentPath, func(p string) map[string]string {return filesys.DocIAL(filepath.Join(util.DataDir, boxID, p))}, include)return retdiff --git a/kernel/model/box_doc_test.go b/kernel/model/box_doc_test.goindex a7ef71e5e2..f3772044d8 100644--- a/kernel/model/box_doc_test.go+++ b/kernel/model/box_doc_test.go@@ -177,3 +177,47 @@ func TestBoxDocSubFileCount(t *testing.T) {t.Fatalf("unexpected visible published box document subfile count [%d]", actual)}}++// TestBoxDocSubFileCountForPublishAt 验证发布访问控制下指定文档的可见直接子文档数。+func TestBoxDocSubFileCountForPublishAt(t *testing.T) {+ originalDataDir := util.DataDir+ util.DataDir = t.TempDir()+ t.Cleanup(func() {+ util.DataDir = originalDataDir+ })++ const (+ boxID = "20260716130000-abcdefg"+ parentID = "20260716130001-abcdefg"+ publicID = "20260716130002-abcdefg"+ hiddenID = "20260716130003-abcdefg"+ forbiddenID = "20260716130004-abcdefg"+ )+ boxDir := filepath.Join(util.DataDir, boxID)+ if err := os.MkdirAll(filepath.Join(boxDir, parentID), 0755); err != nil {+ t.Fatal(err)+ }+ writeDoc := func(dir, id string) {+ t.Helper()+ if err := os.WriteFile(filepath.Join(boxDir, dir, id+".sy"), []byte(`{"Properties":{}}`), 0644); err != nil {+ t.Fatal(err)+ }+ }+ writeDoc(".", parentID)+ writeDoc(parentID, publicID)+ writeDoc(parentID, hiddenID)+ writeDoc(parentID, forbiddenID)++ parentPath := "/" + parentID + ".sy"+ if actual := BoxDocSubFileCountForPublishAt(boxID, parentPath, PublishAccess{}); actual != 3 {+ t.Fatalf("unexpected subfile count [%d]", actual)+ }++ publishAccess := PublishAccess{+ {ID: hiddenID, Visible: false},+ {ID: forbiddenID, Visible: false, Disable: true},+ }+ if actual := BoxDocSubFileCountForPublishAt(boxID, parentPath, publishAccess); actual != 1 {+ t.Fatalf("unexpected published subfile count [%d]", actual)+ }+}diff --git a/kernel/model/publish_access.go b/kernel/model/publish_access.goindex 9071c0f053..ed8d3a76a7 100644--- a/kernel/model/publish_access.go+++ b/kernel/model/publish_access.go@@ -1300,18 +1300,31 @@ func FilterBlockInfoByPublishAccess(c *gin.Context, publishAccess PublishAccess,ret.IAL[av.NodeAttrNameAvs] = strings.Join(avIDs, ",")bt := treenode.GetBlockTree(info.RootID)- if bt != nil {- passwordID, password := GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)- if (password != "" && !CheckPublishAuthCookie(c, passwordID, password)) || !CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {- ret.IAL["name"] = ""- ret.IAL["alias"] = ""- ret.IAL["memo"] = ""- ret.IAL["bookmark"] = ""- ret.IAL["tags"] = ""- ret.RefCount = 0- ret.RefIDs = []string{}+ if nil == bt {+ // 无法定位文档路径时不给出下级文档数,避免泄漏发布排除文档的数量+ ret.SubFileCount = 0+ return+ }++ // 下级文档数只统计发布可见的文档,与读者可见的文档树口径一致+ if 0 < ret.SubFileCount {+ if IsBoxDoc(bt.BoxID, bt.ID) {+ ret.SubFileCount = BoxDocSubFileCountForPublish(bt.BoxID, publishAccess)+ } else {+ ret.SubFileCount = BoxDocSubFileCountForPublishAt(bt.BoxID, bt.Path, publishAccess)}}++ passwordID, password := GetPathPasswordByPublishAccess(bt.BoxID, bt.Path, publishAccess)+ if (password != "" && !CheckPublishAuthCookie(c, passwordID, password)) || !CheckPathAccessableByPublishIgnore(bt.BoxID, bt.Path, publishIgnore) {+ ret.IAL["name"] = ""+ ret.IAL["alias"] = ""+ ret.IAL["memo"] = ""+ ret.IAL["bookmark"] = ""+ ret.IAL["tags"] = ""+ ret.RefCount = 0+ ret.RefIDs = []string{}+ }return}diff --git a/kernel/model/publish_access_test.go b/kernel/model/publish_access_test.goindex fd33a5a77e..ab7d17743d 100644--- a/kernel/model/publish_access_test.go+++ b/kernel/model/publish_access_test.go@@ -26,6 +26,7 @@ import ("testing""github.com/88250/lute/ast"+ "github.com/88250/lute/parse""github.com/gin-gonic/gin""github.com/siyuan-note/siyuan/kernel/av""github.com/siyuan-note/siyuan/kernel/conf"@@ -1868,3 +1869,67 @@ func TestCheckAbsPathAccessableByPublishAccessKeepsHiddenNotebookAccessible(t *tt.Fatal("password protected notebook should be accessible after authorization")}}++// TestFilterBlockInfoByPublishAccessFiltersSubFileCount 验证读者拿到的下级文档数+// 只统计发布可见的文档,避免据此推断被排除文档的数量。+func TestFilterBlockInfoByPublishAccessFiltersSubFileCount(t *testing.T) {+ const (+ boxID = "20260726000000-boxid01"+ parentID = "20260726000001-parent1"+ publicID = "20260726000002-public1"+ hiddenID = "20260726000003-hidden1"+ forbiddenID = "20260726000004-forbid1"+ )++ previousDataDir, previousBlockTreeDBPath, previousConf := util.DataDir, util.BlockTreeDBPath, Conf+ util.DataDir = t.TempDir()+ util.BlockTreeDBPath = filepath.Join(util.DataDir, "blocktree.db")+ Conf = NewAppConf()+ Conf.FileTree = conf.NewFileTree()+ treenode.InitBlockTree(true)+ t.Cleanup(func() {+ treenode.CloseDatabase()+ util.DataDir, util.BlockTreeDBPath, Conf = previousDataDir, previousBlockTreeDBPath, previousConf+ })++ boxDir := filepath.Join(util.DataDir, boxID)+ if err := os.MkdirAll(filepath.Join(boxDir, parentID), 0755); err != nil {+ t.Fatal(err)+ }+ for _, target := range []struct{ dir, id string }{+ {".", parentID}, {parentID, publicID}, {parentID, hiddenID}, {parentID, forbiddenID},+ } {+ if err := os.WriteFile(filepath.Join(boxDir, target.dir, target.id+".sy"), []byte(`{"Properties":{}}`), 0644); err != nil {+ t.Fatal(err)+ }+ }++ parentPath := "/" + parentID + ".sy"+ treenode.IndexBlockTree(&parse.Tree{+ ID: parentID,+ Box: boxID,+ Path: parentPath,+ HPath: "/" + parentID,+ Root: &ast.Node{ID: parentID, Type: ast.NodeDocument},+ })++ publishAccess := PublishAccess{+ {ID: hiddenID, Visible: false},+ {ID: forbiddenID, Visible: false, Disable: true},+ }+ c, _ := gin.CreateTestContext(httptest.NewRecorder())+ c.Request = httptest.NewRequest(http.MethodPost, "/", nil)+ c.Set(RoleContextKey, RoleReader)++ // SubFileCount 模拟 blockinfo 已按未过滤口径统计出的下级文档数+ filtered := FilterBlockInfoByPublishAccess(c, publishAccess, &BlockInfo{RootID: parentID, SubFileCount: 3, IAL: map[string]string{}})+ if 1 != filtered.SubFileCount {+ t.Fatalf("reader subfile count = %d, want only the published one", filtered.SubFileCount)+ }++ // 无法定位文档路径时不下发下级文档数+ missing := FilterBlockInfoByPublishAccess(c, publishAccess, &BlockInfo{RootID: "20260726000005-missing", SubFileCount: 5, IAL: map[string]string{}})+ if 0 != missing.SubFileCount {+ t.Fatalf("missing document subfile count = %d, want 0", missing.SubFileCount)+ }+}