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: Enforce publish access control on dynamic icon templates https://github.com/siyuan-note/siyuan/security/advisories/GHSA-whcx-xxqh-c838
Danielc38031c2defe
diff --git a/kernel/api/icon.go b/kernel/api/icon.goindex 136e1b35aa..b402e7cfdf 100644--- a/kernel/api/icon.go+++ b/kernel/api/icon.go@@ -161,7 +161,16 @@ var getDynamicIcon = contractHandler(apicontract.GetDynamicIcon, func(c *gin.Con// Type 8: 文字图标content := c.Query("content")id := c.Query("id")- svg = generateTypeEightSVG(color, content, id)+ if strings.Contains(content, ".action{") {+ // 模板内容会按 id 读取工作区数据,只读角色必须通过发布访问控制后才能执行 https://github.com/siyuan-note/siyuan/security/advisories/GHSA-whcx-xxqh-c838+ if !dynamicIconContentAccessable(c, id) {+ // 空内容保持与 id 不存在时一致的响应结构,避免泄露文档的可访问状态+ svg = generateTypeEightSVG(color, "")+ break+ }+ content = model.RenderDynamicIconContentTemplate(c, content, id)+ }+ svg = generateTypeEightSVG(color, content)default:// 默认为Type 1svg = generateTypeOneSVG(color, dateInfo)@@ -178,11 +187,22 @@ var getDynamicIcon = contractHandler(apicontract.GetDynamicIcon, func(c *gin.Conc.Header("Content-Type", "image/svg+xml")c.Header("Content-Security-Policy", "script-src 'none'; object-src 'none'; base-uri 'none'")c.Header("X-Content-Type-Options", "nosniff")+ // 响应内容随角色与发布密码 Cookie 变化,避免中间缓存跨调用方回放+ c.Header("Vary", "Cookie")c.Header("Cache-Control", "no-cache")c.Header("Pragma", "no-cache")return apicontract.SuccessBinary("image/svg+xml", []byte(svg))})+// dynamicIconContentAccessable 判断调用方是否可读取动态图标模板内容所引用的块。+// 管理员与编辑者拥有工作区读权限,只读角色则需要通过发布访问控制(禁用、密码与加密笔记本门禁)。+func dynamicIconContentAccessable(c *gin.Context, id string) bool {+ if !model.IsReadOnlyRoleContext(c) {+ return true+ }+ return model.CheckBlockIdMetadataAccessableByPublishAccess(c, model.GetPublishAccess(), id)+}+func getDateInfo(dateStr string, lang string, weekdayType string) map[string]any {// 设置默认值var date time.Time@@ -543,38 +563,44 @@ func generateTypeSevenSVG(color string, lang string, dateInfo map[string]any) st}// Type 8: 文字图标-func generateTypeEightSVG(color, content, id string) string {- if strings.Contains(content, ".action{") {- content = model.RenderDynamicIconContentTemplate(content, id)- }-+func generateTypeEightSVG(color, content string) string {colorScheme := getColorScheme(color)+ contentLen := len([]rune(content))+ if 0 == contentLen {+ // 内容为空时不输出文本,避免字号按零长度计算得到无效值+ return fmt.Sprintf(`+ <svg id="dynamic_icon_type8" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512">+ <path d="M39,0h434c20.97,0,38,17.03,38,38v412c0,33.11-26.89,60-60,60H60c-32.56,0-59-26.44-59-59V38C1,17.03,18.03,0,39,0Z" style="fill: %s;"/>+ </svg>+ `, colorScheme.Primary)+ }+// 动态变化字体大小isChinese := regexp.MustCompile(`[\p{Han}]`).MatchString(content)var fontSize float64if isChinese {switch {- case len([]rune(content)) == 1:+ case contentLen == 1:fontSize = 320default:- fontSize = 480 / float64(len([]rune(content)))+ fontSize = 480 / float64(contentLen)}} else {switch {- case len([]rune(content)) == 1:+ case contentLen == 1:fontSize = 480- case len([]rune(content)) == 2:+ case contentLen == 2:fontSize = 300- case len([]rune(content)) == 3:+ case contentLen == 3:fontSize = 240default:- fontSize = 750 / float64(len([]rune(content)))+ fontSize = 750 / float64(contentLen)}}// 当内容为单个字符时,一些小写字母需要调整文字位置(暂时没法批量解决)dy := "0%"- if len([]rune(content)) == 1 {+ if contentLen == 1 {switch content {case "g", "p", "y", "q":dy = "-10%"diff --git a/kernel/api/icon_publish_access_test.go b/kernel/api/icon_publish_access_test.gonew file mode 100644index 0000000000..b0c660c113--- /dev/null+++ b/kernel/api/icon_publish_access_test.go@@ -0,0 +1,190 @@+// 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/>.++package api++import (+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "strings"+ "testing"++ "github.com/88250/lute/ast"+ "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/treenode"+ "github.com/siyuan-note/siyuan/kernel/util"+)++// TestGetDynamicIconEnforcesPublishAccess 覆盖动态图标模板的发布访问控制。+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-whcx-xxqh-c838+func TestGetDynamicIconEnforcesPublishAccess(t *testing.T) {+ gin.SetMode(gin.TestMode)++ const (+ boxID = "20260918000000-ic0nb0x"+ publicID = "20260918000001-ic0n001"+ hiddenID = "20260918000002-ic0n002"+ disabledID = "20260918000003-ic0n003"+ passwordID = "20260918000004-ic0n004"+ password = "secret123"+ )++ oldWorkspaceDir, oldConfDir, oldDataDir := util.WorkspaceDir, util.ConfDir, util.DataDir+ oldHistoryDir, oldTempDir, oldQueueDir := util.HistoryDir, util.TempDir, util.QueueDir+ oldBlockTreeDBPath := util.BlockTreeDBPath+ oldConf := model.Conf++ root := t.TempDir()+ t.Cleanup(func() {+ treenode.CloseDatabase()+ model.Conf = oldConf+ util.WorkspaceDir, util.ConfDir, util.DataDir = oldWorkspaceDir, oldConfDir, oldDataDir+ util.HistoryDir, util.TempDir, util.QueueDir = oldHistoryDir, oldTempDir, oldQueueDir+ util.BlockTreeDBPath = oldBlockTreeDBPath+ })++ util.WorkspaceDir = root+ util.ConfDir = filepath.Join(root, "conf")+ util.DataDir = filepath.Join(root, "data")+ util.HistoryDir = filepath.Join(root, "history")+ util.TempDir = filepath.Join(root, "temp")+ util.QueueDir = filepath.Join(util.TempDir, "queue")+ util.BlockTreeDBPath = filepath.Join(util.TempDir, "blocktree.db")+ for _, dir := range []string{util.ConfDir, util.DataDir, util.HistoryDir, util.TempDir, util.QueueDir} {+ if err := os.MkdirAll(dir, 0755); err != nil {+ t.Fatal(err)+ }+ }++ model.Conf = model.NewAppConf()+ model.Conf.Lang = "en"+ model.Conf.Editor = conf.NewEditor()++ boxConf := conf.NewBoxConf()+ boxConf.Name = "Dynamic icon publish access"+ boxConf.Closed = false+ if err := (&model.Box{ID: boxID}).SaveConf(boxConf); err != nil {+ t.Fatal(err)+ }+ if err := os.MkdirAll(filepath.Join(util.DataDir, boxID, ".siyuan"), 0755); err != nil {+ t.Fatal(err)+ }++ treenode.InitBlockTree(true)++ addDoc := func(id, title string) {+ tree := treenode.NewTree(boxID, "/"+id+".sy", "/"+title, title)+ tree.Root.FirstChild.Unlink()+ node := &ast.Node{Type: ast.NodeParagraph, ID: id[:21] + "c"}+ node.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("body")})+ tree.Root.AppendChild(node)+ treenode.IndexBlockTree(tree)+ if _, err := filesys.WriteTree(tree); err != nil {+ t.Fatal(err)+ }+ }+ addDoc(publicID, "Public Doc")+ addDoc(hiddenID, "Hidden Doc")+ addDoc(disabledID, "Disabled Doc")+ addDoc(passwordID, "Password Doc")++ if err := model.SetPublishAccess(model.PublishAccess{+ {ID: hiddenID, Visible: false},+ {ID: disabledID, Disable: true},+ {ID: passwordID, Password: password},+ }); err != nil {+ t.Fatal(err)+ }++ // requestIcon 以指定角色请求动态图标,返回原始 SVG 响应+ requestIcon := func(role model.Role, id, content string, cookies ...*http.Cookie) string {+ recorder := httptest.NewRecorder()+ context, _ := gin.CreateTestContext(recorder)+ context.Request = httptest.NewRequest(http.MethodGet, "/api/icon/getDynamicIcon", nil)+ context.Request.URL.RawQuery = "type=8&color=%23d23f31&id=" + id + "&content=" + content+ for _, cookie := range cookies {+ context.Request.AddCookie(cookie)+ }+ context.Set(model.RoleContextKey, role)+ getDynamicIcon(context)++ requireAPIContract(t, http.MethodGet, "/api/icon/getDynamicIcon", recorder)+ if http.StatusOK != recorder.Code {+ t.Fatalf("unexpected status code %d: %s", recorder.Code, recorder.Body.String())+ }+ if "Cookie" != recorder.Header().Get("Vary") {+ t.Fatalf("response varies by caller but Vary header is %q", recorder.Header().Get("Vary"))+ }+ return recorder.Body.String()+ }++ // 模板分隔符为 .action{ 与 },动作只写一层花括号+ const titleContent = ".action%7B.title%7D"++ if svg := requestIcon(model.RoleReader, publicID, titleContent); !strings.Contains(svg, "Public Doc") {+ t.Fatalf("publish reader cannot render an accessible template icon: %s", svg)+ }+ if svg := requestIcon(model.RoleAdministrator, publicID, titleContent); !strings.Contains(svg, "Public Doc") {+ t.Fatalf("administrator cannot render a template icon: %s", svg)+ }++ // 隐藏(不列出)与禁止发布、密码保护不同:发布访问控制按设计仍允许按 ID 读取隐藏文档,+ // 仅禁止其被枚举,因此这里只断言禁止与密码保护两类+ for _, id := range []string{disabledID, passwordID} {+ if svg := requestIcon(model.RoleReader, id, titleContent); strings.Contains(svg, " Doc") {+ t.Fatalf("publish reader read a protected doc title through the dynamic icon: %s", svg)+ }+ }++ // 通过发布密码认证的读者必须仍能渲染+ authCookie := &http.Cookie{+ Name: "publish-auth-" + passwordID,+ Value: util.SHA256Hash([]byte(passwordID + password)),+ }+ if svg := requestIcon(model.RoleReader, passwordID, titleContent, authCookie); !strings.Contains(svg, "Password Doc") {+ t.Fatalf("authenticated publish reader cannot render the template icon: %s", svg)+ }++ hPathContent := ".action%7BgetHPathByID%20%22" + disabledID + "%22%7D"+ statContent := ".action%7BstatBlock%20%22" + disabledID + "%22%7D"++ // 通用模板函数不得成为绕过发布访问控制的第二条通路+ if svg := requestIcon(model.RoleReader, publicID, hPathContent); strings.Contains(svg, "Disabled Doc") {+ t.Fatalf("publish reader read a protected doc path through getHPathByID: %s", svg)+ }+ // statBlock 返回结构体,模板渲染为 {runeCount wordCount linkCount imageCount refCount blockCount}+ if svg := requestIcon(model.RoleReader, publicID, statContent); strings.Contains(svg, "{4 1 0 0 0 1}") {+ t.Fatalf("publish reader read protected block stats through statBlock: %s", svg)+ }++ // 可写角色不受影响+ if svg := requestIcon(model.RoleAdministrator, publicID, hPathContent); !strings.Contains(svg, "Disabled Doc") {+ t.Fatalf("administrator cannot use getHPathByID in a template icon: %s", svg)+ }+ if svg := requestIcon(model.RoleAdministrator, publicID, statContent); !strings.Contains(svg, "{4 1 0 0 0 1}") {+ t.Fatalf("administrator cannot use statBlock in a template icon: %s", svg)+ }++ // 模板解析失败时不应回显模板原文+ if svg := requestIcon(model.RoleReader, publicID, ".action%7B%7B.title%7D%7D"); strings.Contains(svg, ".title") {+ t.Fatalf("dynamic icon echoed the raw template content: %s", svg)+ }+}diff --git a/kernel/api/icon_test.go b/kernel/api/icon_test.goindex 838fd8da53..e63d5cb5fd 100644--- a/kernel/api/icon_test.go+++ b/kernel/api/icon_test.go@@ -21,7 +21,7 @@ import (func TestGenerateTypeEightSVGEscapesContent(t *testing.T) {content := `</text><desc><style><script>alert(1)</script></style></desc><text>`- output := generateTypeEightSVG("red", content, "")+ output := generateTypeEightSVG("red", content)if strings.Contains(output, `<script>`) || strings.Contains(output, `</text><desc>`) {t.Fatalf("dynamic icon contains injected SVG markup: %s", output)}@@ -31,12 +31,22 @@ func TestGenerateTypeEightSVGEscapesContent(t *testing.T) {}func TestGenerateTypeEightSVGCalculatesFontSizeBeforeEscaping(t *testing.T) {- output := generateTypeEightSVG("red", "<", "")+ output := generateTypeEightSVG("red", "<")if !strings.Contains(output, `font-size: 480.00px`) || !strings.Contains(output, `<`) {t.Fatalf("escaped content changed the dynamic icon font size: %s", output)}}+func TestGenerateTypeEightSVGHandlesEmptyContent(t *testing.T) {+ output := generateTypeEightSVG("red", "")+ if strings.Contains(output, "font-size") || strings.Contains(output, "Inf") || strings.Contains(output, "NaN") {+ t.Fatalf("empty dynamic icon content produced an invalid font size: %s", output)+ }+ if !strings.Contains(output, `id="dynamic_icon_type8"`) {+ t.Fatalf("empty dynamic icon content lost the icon frame: %s", output)+ }+}+func TestGetDynamicIconSetsSecurityHeaders(t *testing.T) {oldConf := model.Confmodel.Conf = model.NewAppConf()diff --git a/kernel/model/template.go b/kernel/model/template.goindex bfac569a04..bb99fff569 100644--- a/kernel/model/template.go+++ b/kernel/model/template.go@@ -33,6 +33,7 @@ import ("github.com/88250/lute/ast""github.com/88250/lute/parse""github.com/88250/lute/render"+ "github.com/gin-gonic/gin""github.com/siyuan-note/filelock""github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/av"@@ -482,7 +483,9 @@ func markTemplateAttributeViewModes(root *ast.Node, databaseMode TemplateDatabas})}-func RenderDynamicIconContentTemplate(content, id string) (ret string) {+// RenderDynamicIconContentTemplate 渲染动态图标中的模板内容。+// 调用方必须自行完成授权:只读角色会失去按块 ID 读取工作区数据的模板函数,避免绕过发布访问控制。+func RenderDynamicIconContentTemplate(c *gin.Context, content, id string) (ret string) {tree, err := LoadTreeByBlockID(id)if err != nil {return@@ -508,7 +511,7 @@ func RenderDynamicIconContentTemplate(content, id string) (ret string) {dataModel["alias"] = block.AliasgoTpl := template.New("").Delims(".action{", "}")- tplFuncMap := dynamicIconTemplateFuncs()+ tplFuncMap := dynamicIconTemplateFuncs(c)goTpl = goTpl.Funcs(tplFuncMap)tpl, err := goTpl.Funcs(tplFuncMap).Parse(content)if err != nil {@@ -526,8 +529,17 @@ func RenderDynamicIconContentTemplate(content, id string) (ret string) {return}-func dynamicIconTemplateFuncs() template.FuncMap {- return filesys.BuiltInTemplateFuncs()+// dynamicIconTemplateFuncs 返回动态图标模板可用的函数表。+// 通用模板函数会按块 ID 直接读取工作区数据,与动态图标模板自身的授权无关,+// 因此只读角色(发布读者与匿名访问者)必须剔除这些函数,防止其绕过发布访问控制读取被禁用、+// 受密码保护或加密笔记本中的文档元数据与块统计。+func dynamicIconTemplateFuncs(c *gin.Context) (ret template.FuncMap) {+ ret = filesys.BuiltInTemplateFuncs()+ if IsReadOnlyRoleContext(c) {+ delete(ret, "getHPathByID")+ delete(ret, "statBlock")+ }+ return}func RenderTemplate(p, id string, preview bool) (tree *parse.Tree, dom string, err error) {diff --git a/kernel/model/template_security_test.go b/kernel/model/template_security_test.goindex fadfe13302..3af310a18e 100644--- a/kernel/model/template_security_test.go+++ b/kernel/model/template_security_test.go@@ -16,10 +16,21 @@package model-import "testing"+import (+ "net/http/httptest"+ "testing"++ "github.com/gin-gonic/gin"+)++func testRoleContext(role Role) *gin.Context {+ context, _ := gin.CreateTestContext(httptest.NewRecorder())+ context.Set(RoleContextKey, role)+ return context+}func TestDynamicIconTemplateFuncsExcludeSQL(t *testing.T) {- funcs := dynamicIconTemplateFuncs()+ funcs := dynamicIconTemplateFuncs(nil)for _, name := range []string{"queryBlocks", "querySpans", "querySQL", "getBlock"} {if _, ok := funcs[name]; ok {t.Fatalf("动态图标模板不应包含 SQL 函数 [%s]", name)@@ -29,3 +40,31 @@ func TestDynamicIconTemplateFuncsExcludeSQL(t *testing.T) {t.Fatal("动态图标模板应保留内置模板函数")}}++// TestDynamicIconTemplateFuncsDenyWorkspaceReadsForReadOnlyRole 防止只读角色通过模板函数绕过发布访问控制。+// https://github.com/siyuan-note/siyuan/security/advisories/GHSA-whcx-xxqh-c838+func TestDynamicIconTemplateFuncsDenyWorkspaceReadsForReadOnlyRole(t *testing.T) {+ gin.SetMode(gin.TestMode)+ for _, role := range []Role{RoleReader, RoleVisitor} {+ funcs := dynamicIconTemplateFuncs(testRoleContext(role))+ for _, name := range []string{"getHPathByID", "statBlock"} {+ if _, ok := funcs[name]; ok {+ t.Fatalf("只读角色 [%d] 的动态图标模板不应包含按块 ID 读取数据的函数 [%s]", role, name)+ }+ }+ for _, name := range []string{"date", "now"} {+ if _, ok := funcs[name]; !ok {+ t.Fatalf("只读角色 [%d] 的动态图标模板应保留 [%s]", role, name)+ }+ }+ }++ for _, role := range []Role{RoleAdministrator, RoleEditor} {+ funcs := dynamicIconTemplateFuncs(testRoleContext(role))+ for _, name := range []string{"getHPathByID", "statBlock"} {+ if _, ok := funcs[name]; !ok {+ t.Fatalf("可写角色 [%d] 的动态图标模板应保留 [%s]", role, name)+ }+ }+ }+}