Skip to content

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

:lock: Enforce publish access for export embed blocks https://github.com/siyuan-note/siyuan/security/advisories/GHSA-8wx4-fvqw-f5f8

Daniel1ac1c16da867
diff --git a/kernel/api/export.go b/kernel/api/export.go
index e2ca5e1334..f8cbb6b4a5 100644
--- a/kernel/api/export.go
+++ b/kernel/api/export.go
@@ -1129,11 +1129,19 @@ func exportPreview(c *gin.Context) {
}
}
- stdHTML := model.ExportPreview(id, fillCSSVar)
- if model.IsReadOnlyRoleContext(c) {
+ isReadOnlyRole := model.IsReadOnlyRoleContext(c)
+ var publishAccess model.PublishAccess
+ var accessChecker model.EmbedBlockAccessChecker
+ if isReadOnlyRole {
+ publishAccess = model.GetPublishAccess()
+ accessChecker = func(blockID string) bool {
+ return model.CheckBlockIdAccessableByPublishAccess(c, publishAccess, blockID)
+ }
+ }
+ stdHTML := model.ExportPreview(id, fillCSSVar, accessChecker)
+ if isReadOnlyRole {
bt := treenode.GetBlockTree(id)
if bt != nil {
- publishAccess := model.GetPublishAccess()
stdHTML = model.FilterContentByPublishAccess(c, publishAccess, bt.BoxID, bt.Path, stdHTML, true)
}
}
diff --git a/kernel/api/lute.go b/kernel/api/lute.go
index f41579d758..7515da7a58 100644
--- a/kernel/api/lute.go
+++ b/kernel/api/lute.go
@@ -69,11 +69,19 @@ func copyStdMarkdown(c *gin.Context) {
imgTag = arg["imgTag"].(bool)
}
- markdownContent := model.ExportStdMarkdown(id, assetsDestSpace2Underscore, fillCSSVar, adjustHeadingLevel, imgTag)
- if model.IsReadOnlyRoleContext(c) {
+ isReadOnlyRole := model.IsReadOnlyRoleContext(c)
+ var publishAccess model.PublishAccess
+ var accessChecker model.EmbedBlockAccessChecker
+ if isReadOnlyRole {
+ publishAccess = model.GetPublishAccess()
+ accessChecker = func(blockID string) bool {
+ return model.CheckBlockIdAccessableByPublishAccess(c, publishAccess, blockID)
+ }
+ }
+ markdownContent := model.ExportStdMarkdown(id, assetsDestSpace2Underscore, fillCSSVar, adjustHeadingLevel, imgTag, accessChecker)
+ if isReadOnlyRole {
bt := treenode.GetBlockTree(id)
if bt != nil {
- publishAccess := model.GetPublishAccess()
markdownContent = model.FilterContentByPublishAccess(c, publishAccess, bt.BoxID, bt.Path, markdownContent, true)
}
}
diff --git a/kernel/model/export.go b/kernel/model/export.go
index 9449762e50..a2cd83d8ac 100644
--- a/kernel/model/export.go
+++ b/kernel/model/export.go
@@ -973,7 +973,7 @@ func exportResourcesEncryptedBox(resourcePaths []string) (encryptedBoxID string,
return
}
-func ExportPreview(id string, fillCSSVar bool) (retStdHTML string) {
+func ExportPreview(id string, fillCSSVar bool, accessChecker ...EmbedBlockAccessChecker) (retStdHTML string) {
if exportErr := withExportReadLockByBlockID(id, func() error {
blockRefMode := Conf.Export.BlockRefMode
bt := getExportBlockTree(id)
@@ -989,7 +989,7 @@ func ExportPreview(id string, fillCSSVar bool) (retStdHTML string) {
blockRefMode, Conf.Export.BlockEmbedMode, Conf.Export.FileAnnotationRefMode,
"#", "#", // 这里固定使用 # 包裹标签,否则无法正确解析标签 https://github.com/siyuan-note/siyuan/issues/13857
Conf.Export.BlockRefTextLeft, Conf.Export.BlockRefTextRight,
- Conf.Export.AddTitle, "", Conf.Export.InlineMemo, true, true)
+ Conf.Export.AddTitle, "", Conf.Export.InlineMemo, true, true, accessChecker...)
luteEngine := NewLute()
enableLuteInlineSyntax(luteEngine)
luteEngine.SetFootnotes(true)
@@ -2056,7 +2056,8 @@ func processPDFLinkEmbedAssets(pdfCtx *model.Context, assetDests []string, boxID
}
}
-func ExportStdMarkdown(id string, assetsDestSpace2Underscore, fillCSSVar, adjustHeadingLevel, imgTag bool) string {
+func ExportStdMarkdown(id string, assetsDestSpace2Underscore, fillCSSVar, adjustHeadingLevel, imgTag bool,
+ accessChecker ...EmbedBlockAccessChecker) string {
var ret string
if exportErr := withExportReadLockByBlockID(id, func() error {
bt := getExportBlockTree(id)
@@ -2101,7 +2102,7 @@ func ExportStdMarkdown(id string, assetsDestSpace2Underscore, fillCSSVar, adjust
".md", Conf.Export.BlockRefMode, Conf.Export.BlockEmbedMode, Conf.Export.FileAnnotationRefMode,
Conf.Export.TagOpenMarker, Conf.Export.TagCloseMarker,
Conf.Export.BlockRefTextLeft, Conf.Export.BlockRefTextRight,
- Conf.Export.AddTitle, Conf.Export.InlineMemo, defBlockIDs, true, fillCSSVar, nil)
+ Conf.Export.AddTitle, Conf.Export.InlineMemo, defBlockIDs, true, fillCSSVar, nil, accessChecker...)
return nil
}); exportErr != nil {
logging.LogErrorf("export std markdown [%s] failed: %s", id, exportErr)
@@ -3084,12 +3085,13 @@ func exportMarkdownContent(rootID, ext string, exportRefMode int, defBlockIDs []
func exportMarkdownContent0(id string, tree *parse.Tree, cloudAssetsBase string, assetsDestSpace2Underscore, adjustHeadingLv, imgTag bool,
ext string, blockRefMode, blockEmbedMode, fileAnnotationRefMode int,
tagOpenMarker, tagCloseMarker string, blockRefTextLeft, blockRefTextRight string,
- addTitle, inlineMemo bool, defBlockIDs []string, singleFile, fillCSSVar bool, boxPaths map[string]string) (ret string) {
+ addTitle, inlineMemo bool, defBlockIDs []string, singleFile, fillCSSVar bool, boxPaths map[string]string,
+ accessChecker ...EmbedBlockAccessChecker) (ret string) {
tree = exportTree(tree, false, false, false,
blockRefMode, blockEmbedMode, fileAnnotationRefMode,
tagOpenMarker, tagCloseMarker,
blockRefTextLeft, blockRefTextRight,
- addTitle, "", inlineMemo, 0 < len(defBlockIDs), singleFile)
+ addTitle, "", inlineMemo, 0 < len(defBlockIDs), singleFile, accessChecker...)
if adjustHeadingLv {
bt := treenode.GetBlockTreeInBox(id, tree.Box)
adjustHeadingLevel(bt, tree, addTitle)
@@ -3237,14 +3239,15 @@ func exportTree(tree *parse.Tree, wysiwyg, keepFold, avHiddenCol bool,
blockRefMode, blockEmbedMode, fileAnnotationRefMode int,
tagOpenMarker, tagCloseMarker string,
blockRefTextLeft, blockRefTextRight string,
- addTitle bool, customTitle string, inlineMemo, addDocAnchorSpan, singleFile bool) (ret *parse.Tree) {
+ addTitle bool, customTitle string, inlineMemo, addDocAnchorSpan, singleFile bool,
+ accessChecker ...EmbedBlockAccessChecker) (ret *parse.Tree) {
luteEngine := NewLute()
ret = tree
id := tree.Root.ID
// 解析查询嵌入节点
depth := 0
- resolveEmbedR(ret.Root, blockEmbedMode, luteEngine, &[]string{}, &depth)
+ resolveEmbedR(ret.Root, blockEmbedMode, luteEngine, &[]string{}, &depth, accessChecker...)
// 将当前文档的块超链接转换为引用
blockLink2Ref(ret)
diff --git a/kernel/model/export_publish_test.go b/kernel/model/export_publish_test.go
new file mode 100644
index 0000000000..d6fb58fa06
--- /dev/null
+++ b/kernel/model/export_publish_test.go
@@ -0,0 +1,156 @@
+// SiYuan - From thought to insight, with agents
+// 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/>.
+
+//go:build fts5
+
+package model
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "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/filesys"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// TestExportEmbedFilteredByPublishAccess 验证发布读者导出公共文档时,查询嵌入块匹配到的
+// 发布禁用文档内容会被访问检查过滤,而管理员导出不受影响。
+func TestExportEmbedFilteredByPublishAccess(t *testing.T) {
+ oldConf := Conf
+ oldWorkspaceDir := util.WorkspaceDir
+ oldConfDir := util.ConfDir
+ oldDataDir := util.DataDir
+ oldTempDir := util.TempDir
+ oldQueueDir := util.QueueDir
+ oldDBPath := util.DBPath
+ oldHistoryDBPath := util.HistoryDBPath
+ oldAssetContentDBPath := util.AssetContentDBPath
+ oldBlockTreeDBPath := util.BlockTreeDBPath
+
+ tempDir := t.TempDir()
+ util.WorkspaceDir = tempDir
+ util.ConfDir = filepath.Join(tempDir, "conf")
+ util.DataDir = filepath.Join(tempDir, "data")
+ util.TempDir = filepath.Join(tempDir, "temp")
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.DBPath = filepath.Join(util.TempDir, util.DBName)
+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
+ util.BlockTreeDBPath = filepath.Join(tempDir, "blocktree.db")
+ for _, dir := range []string{util.ConfDir, util.DataDir, util.TempDir, util.QueueDir} {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatalf("create temporary directory %s: %v", dir, err)
+ }
+ }
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ Conf = NewAppConf()
+ Conf.Editor = conf.NewEditor()
+ Conf.FileTree = conf.NewFileTree()
+ Conf.Search = conf.NewSearch()
+ Conf.Export = conf.NewExport()
+ treenode.InitBlockTree(true)
+ invalidateEncryptedPublishAccessCache()
+
+ t.Cleanup(func() {
+ treenode.CloseDatabase()
+ sql.CloseDatabase()
+ Conf = oldConf
+ util.WorkspaceDir = oldWorkspaceDir
+ util.ConfDir = oldConfDir
+ util.DataDir = oldDataDir
+ util.TempDir = oldTempDir
+ util.QueueDir = oldQueueDir
+ util.DBPath = oldDBPath
+ util.HistoryDBPath = oldHistoryDBPath
+ util.AssetContentDBPath = oldAssetContentDBPath
+ util.BlockTreeDBPath = oldBlockTreeDBPath
+ invalidateEncryptedPublishAccessCache()
+ if "" != oldBlockTreeDBPath {
+ treenode.InitBlockTree(false)
+ }
+ })
+
+ const (
+ boxID = "20260826000000-box0001"
+ publicID = "20260826000001-public1"
+ privateID = "20260826000002-prv0001"
+ embedID = "20260826000003-embed01"
+ canary = "PRIVATE_EMBED_CANARY_20260826"
+ )
+
+ publicTree := treenode.NewTree(boxID, "/"+publicID+".sy", "/Public", "Public")
+ embed := &ast.Node{Type: ast.NodeBlockQueryEmbed, ID: embedID, Box: boxID, Path: publicTree.Path}
+ embed.AppendChild(&ast.Node{Type: ast.NodeBlockQueryEmbedScript,
+ Tokens: []byte("SELECT * FROM blocks WHERE id = '" + privateID + "'")})
+ publicTree.Root.AppendChild(embed)
+
+ privateTree := treenode.NewTree(boxID, "/"+privateID+".sy", "/Private", "Private")
+ privateParagraph := privateTree.Root.FirstChild
+ privateParagraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte(canary)})
+
+ for _, tree := range []*parse.Tree{publicTree, privateTree} {
+ if _, err := filesys.WriteTree(tree); err != nil {
+ t.Fatalf("write synthetic tree: %v", err)
+ }
+ treenode.UpsertBlockTree(tree)
+ sql.IndexTreeQueue(tree)
+ }
+ sql.FlushQueue()
+ t.Cleanup(func() {
+ treenode.RemoveBlockTree(boxID, publicID)
+ treenode.RemoveBlockTree(boxID, privateID)
+ })
+
+ c, _ := gin.CreateTestContext(httptest.NewRecorder())
+ c.Request = httptest.NewRequest(http.MethodGet, "/", nil)
+ publishAccess := PublishAccess{
+ {ID: publicID, Visible: true},
+ {ID: privateID, Disable: true},
+ }
+ accessChecker := func(blockID string) bool {
+ bt := treenode.GetBlockTree(blockID)
+ if nil == bt {
+ return false
+ }
+ return checkBlockTreeAccessableByPublishAccess(c, publishAccess, bt)
+ }
+
+ markdown := ExportStdMarkdown(publicID, false, false, false, false, accessChecker)
+ if strings.Contains(markdown, canary) {
+ t.Fatalf("publish reader received private embed content: %s", markdown)
+ }
+ stdHTML := ExportPreview(publicID, false, accessChecker)
+ if strings.Contains(stdHTML, canary) {
+ t.Fatalf("publish reader received private embed content in preview: %s", stdHTML)
+ }
+
+ adminMarkdown := ExportStdMarkdown(publicID, false, false, false, false)
+ if !strings.Contains(adminMarkdown, canary) {
+ t.Fatalf("administrator export should include embed content: %s", adminMarkdown)
+ }
+}
diff --git a/kernel/model/render.go b/kernel/model/render.go
index 3a506156e6..bdc31d505a 100644
--- a/kernel/model/render.go
+++ b/kernel/model/render.go
@@ -296,7 +296,7 @@ func renderBlockContentByNodes(nodes []*ast.Node) string {
return buf.String()
}
-func resolveEmbedR(n *ast.Node, blockEmbedMode int, luteEngine *lute.Lute, resolved *[]string, depth *int) {
+func resolveEmbedR(n *ast.Node, blockEmbedMode int, luteEngine *lute.Lute, resolved *[]string, depth *int, accessChecker ...EmbedBlockAccessChecker) {
var children []*ast.Node
if ast.NodeHeading == n.Type {
children = append(children, n)
@@ -343,6 +343,11 @@ func resolveEmbedR(n *ast.Node, blockEmbedMode int, luteEngine *lute.Lute, resol
stmt = html.UnescapeString(stmt)
stmt = strings.ReplaceAll(stmt, editor.IALValEscNewLine, "\n")
sqlBlocks := sql.SelectBlocksRawStmt(stmt, 1, Conf.Search.Limit)
+ var embedAccessChecker EmbedBlockAccessChecker
+ if 0 < len(accessChecker) {
+ embedAccessChecker = accessChecker[0]
+ }
+ sqlBlocks = filterEmbedBlocksByAccess(sqlBlocks, embedAccessChecker)
for _, sqlBlock := range sqlBlocks {
if "query_embed" == sqlBlock.Type {
continue
@@ -485,7 +490,7 @@ func resolveEmbedR(n *ast.Node, blockEmbedMode int, luteEngine *lute.Lute, resol
return ast.WalkContinue
}
- resolveEmbedR(insert, blockEmbedMode, luteEngine, resolved, depth)
+ resolveEmbedR(insert, blockEmbedMode, luteEngine, resolved, depth, accessChecker...)
*depth--
}
}