Skip to content

An open-source, privacy-first, self-hosted knowledge workspace where humans and AI agents work together 开源、隐私优先、自托管的知识工作空间,让人与智能体在此协作

:lock: Harden query embed SQL in publish mode https://github.com/siyuan-note/siyuan/security/advisories/GHSA-vh22-h7hf-www7

Daniel23a17d44b5f3
diff --git a/kernel/api/search.go b/kernel/api/search.go
index d48451f31b..f829e2f6c3 100644
--- a/kernel/api/search.go
+++ b/kernel/api/search.go
@@ -17,12 +17,14 @@
package api
import (
+ "fmt"
"net/http"
"strings"
"github.com/88250/gulu"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -300,10 +302,19 @@ func getEmbedBlock(c *gin.Context) {
breadcrumb = breadcrumbArg.(bool)
}
- blocks := model.GetEmbedBlock(embedBlockID, includeIDs, headingMode, breadcrumb)
- if model.IsReadOnlyRoleContext(c) {
+ isReadOnlyRole := model.IsReadOnlyRoleContext(c)
+ var blocks []*model.EmbedBlock
+ if isReadOnlyRole {
publishAccess := model.GetPublishAccess()
+ if !model.CheckBlockIdAccessableByPublishAccess(c, publishAccess, embedBlockID) {
+ ret.Code = -1
+ ret.Msg = fmt.Sprintf(model.Conf.Language(15), embedBlockID)
+ return
+ }
+ blocks = model.GetEmbedBlockForPublish(embedBlockID, includeIDs, headingMode, breadcrumb)
blocks = model.FilterEmbedBlocksByPublishAccess(c, publishAccess, blocks)
+ } else {
+ blocks = model.GetEmbedBlock(embedBlockID, includeIDs, headingMode, breadcrumb)
}
ret.Data = map[string]any{
"blocks": blocks,
@@ -345,6 +356,7 @@ func searchEmbedBlock(c *gin.Context) {
embedBlockID := arg["embedBlockID"].(string)
stmt := arg["stmt"].(string)
+ boxID, _ := arg["notebook"].(string)
excludeIDsArg := arg["excludeIDs"].([]any)
var excludeIDs []string
for _, excludeID := range excludeIDsArg {
@@ -364,16 +376,41 @@ func searchEmbedBlock(c *gin.Context) {
breadcrumb = breadcrumbArg.(bool)
}
- // 加密笔记本的嵌入块查询走 InBox 版(查加密 content db,全局库不含加密数据)
- var blocks []*model.EmbedBlock
- if notebook, ok := arg["notebook"].(string); ok && notebook != "" && model.IsEncryptedBox(notebook) {
- blocks = model.SearchEmbedBlockInBox(embedBlockID, stmt, excludeIDs, headingMode, breadcrumb, notebook)
- } else {
- blocks = model.SearchEmbedBlock(embedBlockID, stmt, excludeIDs, headingMode, breadcrumb)
+ isReadOnlyRole := model.IsReadOnlyRoleContext(c)
+ var publishAccess model.PublishAccess
+ if isReadOnlyRole {
+ publishAccess = model.GetPublishAccess()
+ if !model.CheckBlockIdAccessableByPublishAccess(c, publishAccess, embedBlockID) {
+ ret.Code = -1
+ ret.Msg = fmt.Sprintf(model.Conf.Language(15), embedBlockID)
+ return
+ }
+ var err error
+ stmt, boxID, err = model.GetQueryEmbedStatement(embedBlockID)
+ if nil != err {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
}
- if model.IsReadOnlyRoleContext(c) {
- publishAccess := model.GetPublishAccess()
+
+ if err := sql.CheckSingleStatement(stmt); nil != err {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ if err := sql.CheckReadonlyStatementInBox(stmt, boxID); nil != err {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+
+ var blocks []*model.EmbedBlock
+ if isReadOnlyRole {
+ blocks = model.SearchEmbedBlockForPublish(embedBlockID, stmt, excludeIDs, headingMode, breadcrumb, boxID)
blocks = model.FilterEmbedBlocksByPublishAccess(c, publishAccess, blocks)
+ } else {
+ blocks = model.SearchEmbedBlockInBox(embedBlockID, stmt, excludeIDs, headingMode, breadcrumb, boxID)
}
ret.Data = map[string]any{
"blocks": blocks,
diff --git a/kernel/model/publish_access.go b/kernel/model/publish_access.go
index 02ccfe0f39..789b0cebc0 100644
--- a/kernel/model/publish_access.go
+++ b/kernel/model/publish_access.go
@@ -593,8 +593,33 @@ func FilterContentByPublishAccess(c *gin.Context, publishAccess PublishAccess, b
func FilterEmbedBlocksByPublishAccess(c *gin.Context, publishAccess PublishAccess, embedBlocks []*EmbedBlock) (ret []*EmbedBlock) {
ret = []*EmbedBlock{}
for _, embedBlock := range embedBlocks {
- embedBlock.Block.Content = FilterContentByPublishAccess(c, publishAccess, embedBlock.Block.Box, embedBlock.Block.Path, embedBlock.Block.Content, false)
- ret = append(ret, embedBlock)
+ if nil == embedBlock || nil == embedBlock.Block {
+ continue
+ }
+
+ block := embedBlock.Block
+ publishIgnore := GetDisablePublishAccess(publishAccess)
+ passwordID, password := GetPathPasswordByPublishAccess(block.Box, block.Path, publishAccess)
+ accessible := CheckPathAccessableByPublishIgnore(block.Box, block.Path, publishIgnore) &&
+ (password == "" || CheckPublishAuthCookie(c, passwordID, password))
+ if accessible {
+ ret = append(ret, &EmbedBlock{
+ Block: &Block{
+ ID: block.ID,
+ Content: block.Content,
+ },
+ BlockPaths: embedBlock.BlockPaths,
+ AllowChildOperation: embedBlock.AllowChildOperation,
+ })
+ continue
+ }
+
+ ret = append(ret, &EmbedBlock{
+ Block: &Block{
+ Content: FilterContentByPublishAccess(c, publishAccess, block.Box, block.Path, block.Content, false),
+ },
+ BlockPaths: []*BlockPath{},
+ })
}
return
}
diff --git a/kernel/model/publish_access_test.go b/kernel/model/publish_access_test.go
index 9fc6d33a20..538ec3dd34 100644
--- a/kernel/model/publish_access_test.go
+++ b/kernel/model/publish_access_test.go
@@ -62,3 +62,36 @@ func TestFilterSearchDocsByPublishAccess(t *testing.T) {
t.Fatalf("unexpected authenticated search docs: %v", filtered)
}
}
+
+func TestFilterEmbedBlocksByPublishAccessRemovesInternalFields(t *testing.T) {
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
+ embedBlocks := []*EmbedBlock{{
+ Block: &Block{
+ Box: "20260720000000-boxid01",
+ Path: "/20260720000004-public1.sy",
+ HPath: "/private/path",
+ ID: "20260720000005-block01",
+ Content: "<div>visible</div>",
+ Markdown: "sensitive markdown",
+ IAL: map[string]string{"custom-secret": "sensitive ial"},
+ },
+ BlockPaths: []*BlockPath{{ID: "20260720000004-public1", Name: "Public"}},
+ AllowChildOperation: true,
+ }}
+
+ filtered := FilterEmbedBlocksByPublishAccess(c, PublishAccess{}, embedBlocks)
+ if 1 != len(filtered) {
+ t.Fatalf("unexpected filtered embed block count: %d", len(filtered))
+ }
+ block := filtered[0].Block
+ if "20260720000005-block01" != block.ID || "<div>visible</div>" != block.Content {
+ t.Fatalf("required embed block fields were not preserved: %+v", block)
+ }
+ if "" != block.Box || "" != block.Path || "" != block.HPath || "" != block.Markdown || nil != block.IAL {
+ t.Fatalf("internal embed block fields were not removed: %+v", block)
+ }
+ if 1 != len(filtered[0].BlockPaths) || !filtered[0].AllowChildOperation {
+ t.Fatalf("embed rendering metadata was not preserved: %+v", filtered[0])
+ }
+}
diff --git a/kernel/model/search.go b/kernel/model/search.go
index 98a4f5bdf7..405a813d52 100644
--- a/kernel/model/search.go
+++ b/kernel/model/search.go
@@ -20,6 +20,7 @@ import (
"bytes"
"errors"
"fmt"
+ stdhtml "html"
"math"
"os"
"path"
@@ -43,6 +44,7 @@ import (
"github.com/jinzhu/copier"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/filesys"
"github.com/siyuan-note/siyuan/kernel/search"
"github.com/siyuan-note/siyuan/kernel/sql"
"github.com/siyuan-note/siyuan/kernel/task"
@@ -216,23 +218,75 @@ func UpdateEmbedBlock(id, content string) (err error) {
}
func GetEmbedBlock(embedBlockID string, includeIDs []string, headingMode int, breadcrumb bool) (ret []*EmbedBlock) {
- return getEmbedBlock(embedBlockID, includeIDs, headingMode, breadcrumb)
+ return getEmbedBlock(embedBlockID, includeIDs, headingMode, breadcrumb, true)
}
-func getEmbedBlock(embedBlockID string, includeIDs []string, headingMode int, breadcrumb bool) (ret []*EmbedBlock) {
- stmt := "SELECT * FROM `blocks` WHERE `id` IN ('" + strings.Join(includeIDs, "','") + "')"
- sqlBlocks := sql.SelectBlocksRawStmtNoParse(stmt, 1024)
+func GetEmbedBlockForPublish(embedBlockID string, includeIDs []string, headingMode int, breadcrumb bool) (ret []*EmbedBlock) {
+ return getEmbedBlock(embedBlockID, includeIDs, headingMode, breadcrumb, false)
+}
+
+func getEmbedBlock(embedBlockID string, includeIDs []string, headingMode int, breadcrumb, updateIndex bool) (ret []*EmbedBlock) {
+ var validIDs []string
+ for _, id := range includeIDs {
+ if ast.IsNodeIDPattern(id) {
+ validIDs = append(validIDs, id)
+ }
+ if 1024 <= len(validIDs) {
+ break
+ }
+ }
+ sqlBlocks := sql.GetBlocks(validIDs)
+ var existingBlocks []*sql.Block
+ for _, block := range sqlBlocks {
+ if nil != block {
+ existingBlocks = append(existingBlocks, block)
+ }
+ }
+ sqlBlocks = existingBlocks
// 根据 includeIDs 的顺序排序 Improve `//!js` query embed block result sorting https://github.com/siyuan-note/siyuan/issues/9977
m := map[string]int{}
- for i, id := range includeIDs {
+ for i, id := range validIDs {
m[id] = i
}
sort.Slice(sqlBlocks, func(i, j int) bool {
return m[sqlBlocks[i].ID] < m[sqlBlocks[j].ID]
})
- ret = buildEmbedBlock(embedBlockID, []string{}, headingMode, breadcrumb, "", sqlBlocks)
+ ret = buildEmbedBlock(embedBlockID, []string{}, headingMode, breadcrumb, "", sqlBlocks, updateIndex)
+ return
+}
+
+func GetQueryEmbedStatement(embedBlockID string) (stmt, boxID string, err error) {
+ bt := treenode.GetBlockTree(embedBlockID)
+ if nil == bt {
+ err = ErrBlockNotFound
+ return
+ }
+ if treenode.TypeAbbr(ast.NodeBlockQueryEmbed.String()) != bt.Type {
+ err = errors.New("not query embed block")
+ return
+ }
+
+ tree, loadErr := filesys.LoadTree(bt.BoxID, bt.Path, util.NewLute())
+ if nil != loadErr {
+ err = loadErr
+ return
+ }
+ node := treenode.GetNodeInTree(tree, embedBlockID)
+ if nil == node || ast.NodeBlockQueryEmbed != node.Type {
+ err = ErrBlockNotFound
+ return
+ }
+ scriptNode := node.ChildByType(ast.NodeBlockQueryEmbedScript)
+ if nil == scriptNode {
+ err = errors.New("query embed block statement not found")
+ return
+ }
+
+ stmt = stdhtml.UnescapeString(scriptNode.TokensStr())
+ stmt = strings.ReplaceAll(stmt, editor.IALValEscNewLine, "\n")
+ boxID = bt.BoxID
return
}
@@ -243,18 +297,28 @@ func SearchEmbedBlock(embedBlockID, stmt string, excludeIDs []string, headingMod
// SearchEmbedBlockInBox 与 SearchEmbedBlock 一致,但按 boxID 路由 SQL 到加密 content db。
// 加密笔记本的嵌入块查询走独立加密库(全局 siyuan.db 不含加密数据),boxID 为空时落回全局库。
func SearchEmbedBlockInBox(embedBlockID, stmt string, excludeIDs []string, headingMode int, breadcrumb bool, boxID string) (ret []*EmbedBlock) {
+ return searchEmbedBlockInBox(embedBlockID, stmt, excludeIDs, headingMode, breadcrumb, boxID, true)
+}
+
+func SearchEmbedBlockForPublish(embedBlockID, stmt string, excludeIDs []string, headingMode int, breadcrumb bool,
+ boxID string) (ret []*EmbedBlock) {
+ return searchEmbedBlockInBox(embedBlockID, stmt, excludeIDs, headingMode, breadcrumb, boxID, false)
+}
+
+func searchEmbedBlockInBox(embedBlockID, stmt string, excludeIDs []string, headingMode int, breadcrumb bool, boxID string,
+ updateIndex bool) (ret []*EmbedBlock) {
var sqlBlocks []*sql.Block
if "" != boxID {
sqlBlocks = sql.SelectBlocksRawStmtNoParseInBox(stmt, Conf.Search.Limit, boxID)
} else {
sqlBlocks = sql.SelectBlocksRawStmtNoParse(stmt, Conf.Search.Limit)
}
- ret = buildEmbedBlock(embedBlockID, excludeIDs, headingMode, breadcrumb, treenode.GetEmbedBlockRefID(stmt), sqlBlocks)
+ ret = buildEmbedBlock(embedBlockID, excludeIDs, headingMode, breadcrumb, treenode.GetEmbedBlockRefID(stmt), sqlBlocks, updateIndex)
return
}
func buildEmbedBlock(embedBlockID string, excludeIDs []string, headingMode int, breadcrumb bool, embedBlockRefID string,
- sqlBlocks []*sql.Block) (ret []*EmbedBlock) {
+ sqlBlocks []*sql.Block, updateIndex bool) (ret []*EmbedBlock) {
var tmp []*sql.Block
for _, b := range sqlBlocks {
if "query_embed" == b.Type { // 嵌入块不再嵌入
@@ -297,8 +361,10 @@ func buildEmbedBlock(embedBlockID string, excludeIDs []string, headingMode int,
})
}
- // 嵌入块支持搜索 https://github.com/siyuan-note/siyuan/issues/7112
- task.AppendTaskWithTimeout(task.DatabaseIndexEmbedBlock, 30*time.Second, updateEmbedBlockContent, embedBlockID, ret)
+ if updateIndex {
+ // 嵌入块支持搜索 https://github.com/siyuan-note/siyuan/issues/7112
+ task.AppendTaskWithTimeout(task.DatabaseIndexEmbedBlock, 30*time.Second, updateEmbedBlockContent, embedBlockID, ret)
+ }
// 添加笔记本名称
var boxIDs []string
diff --git a/kernel/sql/stmt_validate.go b/kernel/sql/stmt_validate.go
index a4590bc465..78283a5920 100644
--- a/kernel/sql/stmt_validate.go
+++ b/kernel/sql/stmt_validate.go
@@ -18,6 +18,7 @@ package sql
import (
"context"
+ "database/sql"
"errors"
"fmt"
"strings"
@@ -162,11 +163,29 @@ func CheckSingleStatement(stmt string) error {
// 注意:若字符串里在语法上还有第二条及以后的语句,本函数只针对「首条」对应的 stmt 做判断,
// 不会拒绝多语句。与 CheckSingleStatement 组合即可得到「单条 + 只读」策略。
func CheckReadonlyStatement(stmt string) error {
+ return checkReadonlyStatement(stmt, db)
+}
+
+// CheckReadonlyStatementInBox 在指定笔记本对应的数据库连接上检查 SQL 是否只读。
+func CheckReadonlyStatementInBox(stmt, boxID string) error {
+ targetDB := db
+ if boxDB := GetEncryptedDB(boxID); nil != boxDB {
+ targetDB = boxDB
+ } else if IsEncryptedBoxFn != nil && IsEncryptedBoxFn(boxID) {
+ return errors.New("encrypted box db not opened for box " + boxID)
+ }
+ return checkReadonlyStatement(stmt, targetDB)
+}
+
+func checkReadonlyStatement(stmt string, targetDB *sql.DB) error {
if strings.TrimSpace(stmt) == "" {
return errors.New("SQL statement is empty")
}
+ if nil == targetDB {
+ return errors.New("database is nil")
+ }
ctx := context.Background()
- conn, err := db.Conn(ctx)
+ conn, err := targetDB.Conn(ctx)
if err != nil {
return err
}