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: Restore missing document indexes before encrypted access checks https://github.com/siyuan-note/siyuan/issues/19238
Daniel0613acae1cce
diff --git a/kernel/api/block.go b/kernel/api/block.goindex 9a6afd7bfa..e425ac193c 100644--- a/kernel/api/block.go+++ b/kernel/api/block.go@@ -1198,6 +1198,12 @@ func getBlockInfo(c *gin.Context) {return}boxID := encryptedNotebookFromArg(arg)+ // 普通文档的索引可能尚未就绪,先恢复索引,再按实际归属取得响应租约。+ if boxID == "" && !model.IsReadOnlyRoleContext(c) && treenode.GetBlockTree(id) == nil {+ if err := model.ReindexMissingNormalBlock(id); setGetBlockInfoError(ret, id, err) {+ return+ }+ }if !holdBlockRequest(c, ret, boxID, arg) {return}@@ -1226,29 +1232,7 @@ func getBlockInfo(c *gin.Context) {} else {tree, err = model.LoadTreeByBlockIDWithReindex(id)}- if err != nil {- if errors.Is(err, model.ErrIndexing) {- ret.Code = 3- ret.Msg = model.Conf.Language(56)- return- }- if errors.Is(err, treenode.ErrSpecTooNew) {- ret.Code = -1- ret.Msg = model.Conf.Language(275)- return- }- if errors.Is(err, model.ErrBoxUnindexed) {- ret.Code = -1- ret.Msg = "" // 加载的时候已经推送过提示了,这里不需要再提示- return- }- if errors.Is(err, model.ErrTreeNotFound) {- ret.Code = -1- ret.Msg = fmt.Sprintf(model.Conf.Language(15), id)- return- }- ret.Code = -1- ret.Msg = err.Error()+ if setGetBlockInfoError(ret, id, err) {return}@@ -1304,6 +1288,27 @@ func getBlockInfo(c *gin.Context) {}}+func setGetBlockInfoError(ret *gulu.Result, id string, err error) bool {+ if err == nil {+ return false+ }+ ret.Code = -1+ switch {+ case errors.Is(err, model.ErrIndexing):+ ret.Code = 3+ ret.Msg = model.Conf.Language(56)+ case errors.Is(err, treenode.ErrSpecTooNew):+ ret.Msg = model.Conf.Language(275)+ case errors.Is(err, model.ErrBoxUnindexed):+ ret.Msg = "" // 加载时已经推送提示。+ case errors.Is(err, model.ErrTreeNotFound):+ ret.Msg = fmt.Sprintf(model.Conf.Language(15), id)+ default:+ ret.Msg = err.Error()+ }+ return true+}+func getBlockInfoPublishAccess(c *gin.Context, id, boxID string) (blockTree *treenode.BlockTree, passwordRequired, metadataVisible, accessible bool) {if !model.IsReadOnlyRoleContext(c) {return nil, false, true, truediff --git a/kernel/api/block_test.go b/kernel/api/block_test.goindex 6ea300bd44..8684df1e56 100644--- a/kernel/api/block_test.go+++ b/kernel/api/block_test.go@@ -17,23 +17,147 @@package apiimport (+ "context""encoding/json""net/http""net/http/httptest"+ "os"+ "os/exec""path/filepath""slices""strings""testing"+ "time""github.com/88250/gulu""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/filesys""github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/sql"+ "github.com/siyuan-note/siyuan/kernel/task""github.com/siyuan-note/siyuan/kernel/treenode""github.com/siyuan-note/siyuan/kernel/util")+func TestGetBlockInfoRecovery(t *testing.T) {+ for _, name := range []string{"document", "child", "explicit", "missing", "indexing", "reader", "encrypted"} {+ t.Run(name, func(t *testing.T) {+ if os.Getenv("SIYUAN_TEST_BLOCK_INFO_RECOVERY") == t.Name() {+ testGetBlockInfoRecovery(t, name)+ return+ }+ ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)+ defer cancel()+ command := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestGetBlockInfoRecovery$/^"+name+"$", "-test.v")+ command.Env = append(os.Environ(), "SIYUAN_TEST_BLOCK_INFO_RECOVERY="+t.Name())+ if output, err := command.CombinedOutput(); err != nil {+ t.Fatalf("recovery subprocess failed: %v\n%s", err, output)+ }+ })+ }+}++func testGetBlockInfoRecovery(t *testing.T, name string) {+ root := t.TempDir()+ util.DataDir = filepath.Join(root, "data")+ util.TempDir = root+ util.ConfDir = root+ util.QueueDir = filepath.Join(root, "queue")+ util.DBPath = filepath.Join(root, "siyuan.db")+ util.HistoryDBPath = filepath.Join(root, "history.db")+ util.AssetContentDBPath = filepath.Join(root, "asset_content.db")+ util.BlockTreeDBPath = filepath.Join(root, "blocktree.db")+ model.Conf = model.NewAppConf()+ model.Conf.FileTree, model.Conf.Sync = conf.NewFileTree(), conf.NewSync()+ model.Conf.NotebookCrypto = conf.NewNotebookCrypto()+ model.Conf.Search, model.Conf.Editor, model.Conf.Export = conf.NewSearch(), conf.NewEditor(), conf.NewExport()+ box := &model.Box{ID: ast.NewNodeID()}+ boxConf := conf.NewBoxConf()+ boxConf.Name, boxConf.Closed = "Recovery", false+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ sql.InitDatabase(true)+ sql.InitHistoryDatabase(true)+ sql.InitAssetContentDatabase(true)+ defer sql.CloseDatabase()+ docID := ast.NewNodeID()+ tree := treenode.NewTree(box.ID, "/"+docID+".sy", "/Recovered", "Recovered")+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ if name == "encrypted" {+ // 加密候选即使带有可解析的明文,也不能由普通笔记本恢复路径读取或索引。+ boxConf.Encrypted = true+ if err := box.SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ }+ id := docID+ if name == "child" {+ id = tree.Root.FirstChild.ID+ } else if name == "missing" {+ id = ast.NewNodeID()+ }+ if name == "indexing" {+ task.AppendTask(task.DatabaseIndexFull, func() {})+ }+ gin.SetMode(gin.TestMode)+ engine := gin.New()+ engine.Use(boxLeaseMiddleware)+ engine.Use(func(c *gin.Context) {+ role := model.RoleAdministrator+ if name == "reader" {+ role = model.RoleReader+ }+ c.Set(model.RoleContextKey, role)+ c.Next()+ })+ engine.POST("/api/block/getBlockInfo", getBlockInfo)+ args := map[string]any{"id": id}+ if name == "explicit" {+ args["notebook"] = box.ID+ }+ body, err := json.Marshal(args)+ if err != nil {+ t.Fatal(err)+ }+ recorder := httptest.NewRecorder()+ request := httptest.NewRequest(http.MethodPost, "/api/block/getBlockInfo", strings.NewReader(string(body)))+ request.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, request)+ var response struct {+ Code int `json:"code"`+ Data struct {+ RootID string `json:"rootID"`+ RootTitle string `json:"rootTitle"`+ } `json:"data"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ switch name {+ case "document", "child", "explicit":+ if response.Code != 0 || response.Data.RootID != docID || response.Data.RootTitle != "Recovered" {+ t.Fatalf("document did not recover: %s", recorder.Body.String())+ }+ if treenode.GetBlockTree(id) == nil {+ t.Fatal("requested block was not indexed")+ }+ default:+ wantCode := -1+ if name == "indexing" {+ wantCode = 3+ }+ if response.Code != wantCode || response.Data.RootID != "" || treenode.GetBlockTree(docID) != nil {+ t.Fatalf("unexpected recovery or response: %s", recorder.Body.String())+ }+ }+}+func TestParseBlockRefStringArrayEmptyHandling(t *testing.T) {arg := map[string]any{"ids": []any{}}diff --git a/kernel/api/box_lease_test.go b/kernel/api/box_lease_test.goindex daad4bef09..e26e110fef 100644--- a/kernel/api/box_lease_test.go+++ b/kernel/api/box_lease_test.go@@ -65,6 +65,10 @@ func TestBatchNotebookResponseLease(t *testing.T) {runNotebookResponseLease(t, false, true)}+func TestGetBlockInfoNotebookResponseLease(t *testing.T) {+ runNotebookResponseLease(t, false, false)+}+func runNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {t.Helper()if os.Getenv("SIYUAN_TEST_NOTEBOOK_RESPONSE_LEASE") == t.Name() {@@ -128,6 +132,9 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {paragraph := &ast.Node{Type: ast.NodeParagraph, ID: ast.NewNodeID()}paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("REVIEW-SECRET-CONTENT")})tree.Root.AppendChild(paragraph)+ if t.Name() == "TestGetBlockInfoNotebookResponseLease" {+ tree.Root.SetIALAttr("title", "REVIEW-SECRET-CONTENT")+ }if _, err = filesys.WriteTree(tree); err != nil {t.Fatal(err)}@@ -139,6 +146,7 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleAdministrator); c.Next() })engine.POST("/api/block/getBlockKramdown", getBlockKramdown)engine.POST("/api/block/getBlockKramdowns", getBlockKramdowns)+ engine.POST("/api/block/getBlockInfo", getBlockInfo)writer := &blockedBlockResponseWriter{ResponseRecorder: httptest.NewRecorder(), ready: make(chan []byte, 1), proceed: make(chan struct{})}var releaseWriter sync.Oncedefer releaseWriter.Do(func() { close(writer.proceed) })@@ -147,6 +155,9 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {args["notebook"] = boxIDs[0]}endpoint := "/api/block/getBlockKramdown"+ if t.Name() == "TestGetBlockInfoNotebookResponseLease" {+ endpoint = "/api/block/getBlockInfo"+ }if batch {delete(args, "id")args["ids"] = boxIDs@@ -197,4 +208,29 @@ func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {if lockedBeforeResponse {t.Fatalf("lock completed before plaintext response was sent: %s", writer.Body.String())}+ if t.Name() == "TestGetBlockInfoNotebookResponseLease" {+ for _, explicit := range []bool{false, true} {+ args := map[string]any{"id": boxIDs[0]}+ if explicit {+ args["notebook"] = boxIDs[0]+ }+ body, err := json.Marshal(args)+ if err != nil {+ t.Fatal(err)+ }+ recorder := httptest.NewRecorder()+ request := httptest.NewRequest(http.MethodPost, endpoint, strings.NewReader(string(body)))+ request.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, request)+ var response struct {+ Code int `json:"code"`+ }+ if err := json.Unmarshal(recorder.Body.Bytes(), &response); err != nil {+ t.Fatal(err)+ }+ if response.Code == 0 || strings.Contains(recorder.Body.String(), "REVIEW-SECRET-CONTENT") {+ t.Fatalf("locked notebook metadata escaped: %s", recorder.Body.String())+ }+ }+ }}diff --git a/kernel/model/tree.go b/kernel/model/tree.goindex e6f32e75c3..c71d603627 100644--- a/kernel/model/tree.go+++ b/kernel/model/tree.go@@ -336,6 +336,21 @@ func loadTreeByBlockIDInBox0(id, boxID string, logNotFound bool) (ret *parse.Trevar searchTreeLimiter = rate.NewLimiter(rate.Every(3*time.Second), 1)func indexTreeInFilesystem(blockID string) error {+ return indexTreeInFilesystem0(blockID, false)+}++// ReindexMissingNormalBlock 在请求取得加密笔记本租约前,仅恢复普通笔记本中缺失的块索引。+func ReindexMissingNormalBlock(blockID string) error {+ if !ast.IsNodeIDPattern(blockID) {+ return ErrInvalidID+ }+ if task.ContainIndexTask() {+ return ErrIndexing+ }+ return indexTreeInFilesystem0(blockID, true)+}++func indexTreeInFilesystem0(blockID string, normalOnly bool) error {if !searchTreeLimiter.Allow() {return ErrIndexing}@@ -345,7 +360,7 @@ func indexTreeInFilesystem(blockID string) error {logging.LogWarnf("searching tree on filesystem [id=%s]", blockID)- unindexedTreePath := findUnindexedTreePathInAllBoxes(blockID)+ unindexedTreePath := findUnindexedTreePath(blockID, normalOnly)if "" == unindexedTreePath {logging.LogInfof("tree not found on filesystem [id=%s]", blockID)return ErrTreeNotFound@@ -402,9 +417,16 @@ func loadParentTree(tree *parse.Tree) (ret *parse.Tree) {}func findUnindexedTreePathInAllBoxes(id string) (ret string) {+ return findUnindexedTreePath(id, false)+}++func findUnindexedTreePath(id string, normalOnly bool) (ret string) {boxes := Conf.GetBoxes()luteEngine := util.NewLute()for _, box := range boxes {+ if normalOnly && IsEncryptedBox(box.ID) {+ continue+ }root := filepath.Join(util.DataDir, box.ID)paths := search.FindAllMatchedPaths(root, []string{id})var rootIDs []string