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: Secure backlink refresh API https://github.com/siyuan-note/siyuan/security/advisories/GHSA-wgwx-479j-23vq
Daniel7d273c271ce1
diff --git a/kernel/api/ref.go b/kernel/api/ref.goindex 929a265e9c..9d5cb80d28 100644--- a/kernel/api/ref.go+++ b/kernel/api/ref.go@@ -35,7 +35,10 @@ func refreshBacklink(c *gin.Context) {return}- id := arg["id"].(string)+ var id string+ if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("id", &id, true, true)) || util.InvalidIDPattern(id, ret) {+ return+ }model.RefreshBacklink(id)model.FlushTxQueue()}diff --git a/kernel/api/ref_test.go b/kernel/api/ref_test.gonew file mode 100644index 0000000000..79fa3e7793--- /dev/null+++ b/kernel/api/ref_test.go@@ -0,0 +1,118 @@+// 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 api++import (+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/model"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestRefreshBacklinkAuthorization(t *testing.T) {+ gin.SetMode(gin.TestMode)++ t.Run("reader", func(t *testing.T) {+ engine := gin.New()+ engine.Use(func(c *gin.Context) {+ c.Set(model.RoleContextKey, model.RoleReader)+ c.Next()+ })+ ServeAPI(engine)++ recorder := httptest.NewRecorder()+ request := httptest.NewRequest(http.MethodPost, "/api/ref/refreshBacklink", strings.NewReader(`{"id":"20260723000000-abcdefg"}`))+ request.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, request)++ if recorder.Code != http.StatusForbidden {+ t.Fatalf("reader request returned status %d: %s", recorder.Code, recorder.Body.String())+ }+ })++ t.Run("readonly workspace", func(t *testing.T) {+ previousReadOnly := util.ReadOnly+ previousConf := model.Conf+ util.ReadOnly = true+ model.Conf = &model.AppConf{Lang: "en"}+ defer func() {+ util.ReadOnly = previousReadOnly+ model.Conf = previousConf+ }()++ engine := gin.New()+ engine.Use(func(c *gin.Context) {+ c.Set(model.RoleContextKey, model.RoleAdministrator)+ c.Next()+ })+ ServeAPI(engine)++ recorder := httptest.NewRecorder()+ request := httptest.NewRequest(http.MethodPost, "/api/ref/refreshBacklink", strings.NewReader(`{"id":"20260723000000-abcdefg"}`))+ request.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, request)++ response := &struct {+ Code int `json:"code"`+ }{}+ if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {+ t.Fatalf("unmarshal response failed: %v", err)+ }+ if response.Code != -1 {+ t.Fatalf("readonly request returned code %d: %s", response.Code, recorder.Body.String())+ }+ })+}++func TestRefreshBacklinkRejectsInvalidRequest(t *testing.T) {+ gin.SetMode(gin.TestMode)+ engine := gin.New()+ engine.POST("/api/ref/refreshBacklink", refreshBacklink)++ tests := []struct {+ name string+ body string+ }{+ {name: "missing ID", body: `{}`},+ {name: "wrong ID type", body: `{"id":1}`},+ {name: "empty ID", body: `{"id":""}`},+ {name: "invalid ID", body: `{"id":"invalid"}`},+ }+ for _, test := range tests {+ t.Run(test.name, func(t *testing.T) {+ recorder := httptest.NewRecorder()+ request := httptest.NewRequest(http.MethodPost, "/api/ref/refreshBacklink", strings.NewReader(test.body))+ request.Header.Set("Content-Type", "application/json")+ engine.ServeHTTP(recorder, request)++ response := &struct {+ Code int `json:"code"`+ }{}+ if err := json.Unmarshal(recorder.Body.Bytes(), response); err != nil {+ t.Fatalf("unmarshal response failed: %v", err)+ }+ if response.Code != -1 {+ t.Fatalf("invalid request returned code %d: %s", response.Code, recorder.Body.String())+ }+ })+ }+}diff --git a/kernel/api/router.go b/kernel/api/router.goindex 3607da29c4..e1a71398ad 100644--- a/kernel/api/router.go+++ b/kernel/api/router.go@@ -291,7 +291,7 @@ func ServeAPI(ginServer *gin.Engine) {ginServer.Handle("POST", "/api/file/readDir", model.CheckAuth, model.CheckAdminRole, readDir)ginServer.Handle("POST", "/api/file/getUniqueFilename", model.CheckAuth, getUniqueFilename)- ginServer.Handle("POST", "/api/ref/refreshBacklink", model.CheckAuth, refreshBacklink)+ ginServer.Handle("POST", "/api/ref/refreshBacklink", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, refreshBacklink)ginServer.Handle("POST", "/api/ref/getBacklink", model.CheckAuth, getBacklink)ginServer.Handle("POST", "/api/ref/getBacklink2", model.CheckAuth, getBacklink2)ginServer.Handle("POST", "/api/ref/getBacklinkDoc", model.CheckAuth, getBacklinkDoc)diff --git a/kernel/sql/block_ref_query.go b/kernel/sql/block_ref_query.goindex 73f68970ed..6cb08d8676 100644--- a/kernel/sql/block_ref_query.go+++ b/kernel/sql/block_ref_query.go@@ -436,12 +436,7 @@ func QueryRefsByDefID(defBlockID string, containChildren bool) (ret []*Ref) {var rows *sql.Rowsvar err errorif containChildren {- blockIDs := queryBlockChildrenIDs(defBlockID)- var params []string- for _, id := range blockIDs {- params = append(params, "\""+id+"\"")- }- rows, err = query("SELECT * FROM refs WHERE def_block_id IN (" + strings.Join(params, ",") + ")")+ rows, err = query(queryRefsByDefIDWithChildren, defBlockID)} else {rows, err = query("SELECT * FROM refs WHERE def_block_id = ?", defBlockID)}@@ -457,6 +452,13 @@ func QueryRefsByDefID(defBlockID string, containChildren bool) (ret []*Ref) {return}+const queryRefsByDefIDWithChildren = `WITH RECURSIVE child_ids(id) AS (+ SELECT ?+ UNION+ SELECT blocks.id FROM blocks JOIN child_ids ON blocks.parent_id = child_ids.id+)+SELECT refs.* FROM refs JOIN child_ids ON refs.def_block_id = child_ids.id`+func QueryRefsByDefIDRefID(defBlockID, refBlockID string) (ret []*Ref) {stmt := "SELECT * FROM refs WHERE def_block_id = ? AND block_id = ?"rows, err := query(stmt, defBlockID, refBlockID)diff --git a/kernel/sql/block_ref_query_test.go b/kernel/sql/block_ref_query_test.gonew file mode 100644index 0000000000..0ab4ae726e--- /dev/null+++ b/kernel/sql/block_ref_query_test.go@@ -0,0 +1,72 @@+// 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 sql++import (+ gosql "database/sql"+ "testing"+)++func TestQueryRefsByDefIDParameterizesBlockIDs(t *testing.T) {+ testDB, err := gosql.Open("sqlite3_extended", ":memory:")+ if err != nil {+ t.Fatalf("open test database failed: %s", err)+ }+ testDB.SetMaxOpenConns(1)+ defer testDB.Close()++ if _, err = testDB.Exec("CREATE TABLE blocks (id TEXT, parent_id TEXT)"); err != nil {+ t.Fatalf("create blocks table failed: %s", err)+ }+ if _, err = testDB.Exec("CREATE TABLE refs (id TEXT, def_block_id TEXT, def_block_parent_id TEXT, def_block_root_id TEXT, def_block_path TEXT, block_id TEXT, root_id TEXT, box TEXT, path TEXT, content TEXT, markdown TEXT, type TEXT)"); err != nil {+ t.Fatalf("create refs table failed: %s", err)+ }+ if _, err = testDB.Exec("INSERT INTO refs VALUES ('sentinel', 'definition', '', '', '', '', '', '', '', '', '', '')"); err != nil {+ t.Fatalf("insert ref failed: %s", err)+ }+ if _, err = testDB.Exec("INSERT INTO blocks (id, parent_id) VALUES ('root', ''), ('child', 'root'), ('grandchild', 'child'), ('sibling', '')"); err != nil {+ t.Fatalf("insert blocks failed: %s", err)+ }+ if _, err = testDB.Exec("INSERT INTO refs VALUES ('root-ref', 'root', '', '', '', '', '', '', '', '', '', ''), ('child-ref', 'child', '', '', '', '', '', '', '', '', '', ''), ('grandchild-ref', 'grandchild', '', '', '', '', '', '', '', '', '', ''), ('sibling-ref', 'sibling', '', '', '', '', '', '', '', '', '', '')"); err != nil {+ t.Fatalf("insert child refs failed: %s", err)+ }++ previousDB := db+ db = testDB+ defer func() {+ db = previousDB+ }()++ refs := QueryRefsByDefID("root", true)+ actual := map[string]bool{}+ for _, ref := range refs {+ actual[ref.ID] = true+ }+ if len(refs) != 3 || !actual["root-ref"] || !actual["child-ref"] || !actual["grandchild-ref"] || actual["sibling-ref"] {+ t.Fatalf("unexpected refs: %#v", actual)+ }++ QueryRefsByDefID(`"); DELETE FROM refs --`, true)++ var count int+ if err = testDB.QueryRow("SELECT COUNT(*) FROM refs WHERE id = 'sentinel'").Scan(&count); err != nil {+ t.Fatalf("query ref count failed: %s", err)+ }+ if count != 1 {+ t.Fatalf("query argument changed stored refs, count: %d", count)+ }+}diff --git a/kernel/sql/encrypted_query.go b/kernel/sql/encrypted_query.goindex 06674b5f83..e66fb75740 100644--- a/kernel/sql/encrypted_query.go+++ b/kernel/sql/encrypted_query.go@@ -112,12 +112,8 @@ func QueryRefsByDefIDInBox(defBlockID string, containChildren bool, boxID stringvar sqlStmt stringvar args []anyif containChildren {- blockIDs := queryBlockChildrenIDsForBox(defBlockID, boxID)- sqlStmt = "SELECT * FROM refs WHERE def_block_id IN (" + strings.Repeat("?,", len(blockIDs)-1) + "?)"- args = make([]any, len(blockIDs))- for i, id := range blockIDs {- args[i] = id- }+ sqlStmt = queryRefsByDefIDWithChildren+ args = []any{defBlockID}} else {sqlStmt = "SELECT * FROM refs WHERE def_block_id = ?"args = []any{defBlockID}