Skip to content

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

:lock: Enforce publish access for static resources https://github.com/siyuan-note/siyuan/security/advisories/GHSA-fgmr-7w36-9qfq

Daniel34be6c0bb073
diff --git a/kernel/model/publish_resource_access.go b/kernel/model/publish_resource_access.go
new file mode 100644
index 0000000000..15d9af237d
--- /dev/null
+++ b/kernel/model/publish_resource_access.go
@@ -0,0 +1,202 @@
+// 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 model
+
+import (
+ "bytes"
+ stdhtml "html"
+ "net/url"
+ "path"
+ "path/filepath"
+ "strings"
+ "sync"
+
+ "github.com/88250/lute/ast"
+ lutehtml "github.com/88250/lute/html"
+ "github.com/88250/lute/parse"
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/bazaar"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+type publishResourceRefs struct {
+ updated string
+ widgets map[string]struct{}
+ emojis map[string]struct{}
+}
+
+var publishResourceRefsCache sync.Map
+
+func CheckSnippetAccessableInPublish(name, typ string) (found, accessable bool) {
+ snippets, err := LoadSnippets()
+ if err != nil {
+ return
+ }
+ for _, snippet := range snippets {
+ if snippet.Name == name && snippet.Type == typ {
+ return true, !snippet.DisabledInPublish
+ }
+ }
+ return
+}
+
+func CheckPluginAccessableInPublish(name string) bool {
+ if name == "" || !IsPetalsEnabled() {
+ return false
+ }
+
+ petal := getPetalByName(name, getPetals())
+ if petal == nil || !petal.Enabled {
+ return false
+ }
+
+ found, _, _, _, disabledInPublish, disallowInstall, _ := bazaar.ParseInstalledPlugin(name, "")
+ return found && !disabledInPublish && !disallowInstall
+}
+
+func CheckWidgetAccessableInPublish(name string) bool {
+ if name == "" {
+ return false
+ }
+ widget, err := bazaar.ParsePackageJSON(filepath.Join(util.DataDir, "widgets", name, "widget.json"))
+ return err == nil && widget != nil && !widget.DisabledInPublish
+}
+
+func CheckWidgetAccessableByPublishAccess(c *gin.Context, name string, publishAccess PublishAccess) bool {
+ if !CheckWidgetAccessableInPublish(name) {
+ return false
+ }
+ return checkResourceAccessableByPublishAccess(c, name, publishAccess, true)
+}
+
+func CheckEmojiAccessableByPublishAccess(c *gin.Context, relativePath string, publishAccess PublishAccess) bool {
+ relativePath = normalizePublishResourcePath(relativePath)
+ if relativePath == "" {
+ return false
+ }
+ return checkResourceAccessableByPublishAccess(c, relativePath, publishAccess, false)
+}
+
+func checkResourceAccessableByPublishAccess(c *gin.Context, resource string, publishAccess PublishAccess, widget bool) bool {
+ for _, bt := range treenode.GetBlockTreesByType("d") {
+ if !checkBlockTreeAccessableByPublishAccess(c, publishAccess, bt) {
+ continue
+ }
+
+ refs := getPublishResourceRefs(bt)
+ if widget {
+ if _, ok := refs.widgets[resource]; ok {
+ return true
+ }
+ } else if _, ok := refs.emojis[resource]; ok {
+ return true
+ }
+ }
+ return false
+}
+
+func getPublishResourceRefs(bt *treenode.BlockTree) *publishResourceRefs {
+ cacheKey := bt.BoxID + "/" + bt.RootID
+ if cached, ok := publishResourceRefsCache.Load(cacheKey); ok {
+ refs := cached.(*publishResourceRefs)
+ if refs.updated == bt.Updated {
+ return refs
+ }
+ }
+
+ refs := &publishResourceRefs{
+ updated: bt.Updated,
+ widgets: map[string]struct{}{},
+ emojis: map[string]struct{}{},
+ }
+ tree, err := loadTreeByBlockIDInBox(bt.RootID, bt.BoxID)
+ if err != nil || tree == nil {
+ return refs
+ }
+
+ refs.widgets = widgetPackagesInTree(tree)
+ for _, emoji := range emojisInTree(tree) {
+ if relativePath := publishResourceURLPath(emoji, "/emojis/"); relativePath != "" {
+ refs.emojis[relativePath] = struct{}{}
+ }
+ }
+ publishResourceRefsCache.Store(cacheKey, refs)
+ return refs
+}
+
+func widgetPackagesInTree(tree *parse.Tree) map[string]struct{} {
+ ret := map[string]struct{}{}
+ ast.Walk(tree.Root, func(n *ast.Node, entering bool) ast.WalkStatus {
+ if !entering || (n.Type != ast.NodeWidget && n.Type != ast.NodeIFrame &&
+ n.Type != ast.NodeHTMLBlock && n.Type != ast.NodeInlineHTML) {
+ return ast.WalkContinue
+ }
+
+ nodes, err := lutehtml.ParseFragment(bytes.NewReader(n.Tokens), &lutehtml.Node{Type: lutehtml.ElementNode})
+ if err != nil {
+ return ast.WalkContinue
+ }
+ for _, node := range nodes {
+ walkPublishResourceHTML(node, func(value string) {
+ relativePath := publishResourceURLPath(value, "/widgets/")
+ if relativePath == "" {
+ return
+ }
+ name, _, _ := strings.Cut(relativePath, "/")
+ if name != "" {
+ ret[name] = struct{}{}
+ }
+ })
+ }
+ return ast.WalkContinue
+ })
+ return ret
+}
+
+func walkPublishResourceHTML(node *lutehtml.Node, visit func(string)) {
+ for _, attr := range node.Attr {
+ visit(attr.Val)
+ }
+ for child := node.FirstChild; child != nil; child = child.NextSibling {
+ walkPublishResourceHTML(child, visit)
+ }
+}
+
+func publishResourceURLPath(value, prefix string) string {
+ value = strings.TrimSpace(stdhtml.UnescapeString(value))
+ parsed, err := url.Parse(value)
+ if err != nil {
+ return ""
+ }
+ if parsed.Host != "" && !util.IsLocalHostname(parsed.Hostname()) {
+ return ""
+ }
+ cleanPath := path.Clean(parsed.Path)
+ if !strings.HasPrefix(cleanPath, prefix) {
+ return ""
+ }
+ return normalizePublishResourcePath(strings.TrimPrefix(cleanPath, prefix))
+}
+
+func normalizePublishResourcePath(relativePath string) string {
+ relativePath = filepath.ToSlash(filepath.Clean(filepath.FromSlash(strings.TrimPrefix(relativePath, "/"))))
+ if relativePath == "." || relativePath == ".." || strings.HasPrefix(relativePath, "../") {
+ return ""
+ }
+ return relativePath
+}
diff --git a/kernel/model/publish_resource_access_test.go b/kernel/model/publish_resource_access_test.go
new file mode 100644
index 0000000000..8f798cfd65
--- /dev/null
+++ b/kernel/model/publish_resource_access_test.go
@@ -0,0 +1,181 @@
+// 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 model
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/88250/lute/ast"
+ "github.com/88250/lute/parse"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestPublishResourceURLPath(t *testing.T) {
+ tests := []struct {
+ value string
+ prefix string
+ expected string
+ }{
+ {"/widgets/example/", "/widgets/", "example"},
+ {"http://127.0.0.1:6806/emojis/icon.png?v=1", "/emojis/", "icon.png"},
+ {"https://example.com/widgets/external/", "/widgets/", ""},
+ {"/assets/icon.png", "/emojis/", ""},
+ {"/widgets/../templates/private.md", "/widgets/", ""},
+ }
+ for _, test := range tests {
+ if actual := publishResourceURLPath(test.value, test.prefix); actual != test.expected {
+ t.Fatalf("publishResourceURLPath(%q, %q) = %q, expected %q", test.value, test.prefix, actual, test.expected)
+ }
+ }
+}
+
+func TestWidgetPackagesInTree(t *testing.T) {
+ root := &ast.Node{Type: ast.NodeDocument}
+ root.AppendChild(&ast.Node{
+ Type: ast.NodeWidget,
+ Tokens: []byte(`<iframe src="/widgets/example/"></iframe>`),
+ })
+ root.AppendChild(&ast.Node{
+ Type: ast.NodeHTMLBlock,
+ Tokens: []byte(`<img data-resource="/widgets/from-html/image.png">`),
+ })
+ root.AppendChild(&ast.Node{
+ Type: ast.NodeIFrame,
+ Tokens: []byte(`<iframe src="https://example.com/widgets/external/"></iframe>`),
+ })
+
+ widgets := widgetPackagesInTree(&parse.Tree{Root: root})
+ for _, name := range []string{"example", "from-html"} {
+ if _, ok := widgets[name]; !ok {
+ t.Fatalf("widget package [%s] was not extracted", name)
+ }
+ }
+ if _, ok := widgets["external"]; ok {
+ t.Fatal("external widget URL should not authorize a local widget package")
+ }
+}
+
+func TestCheckSnippetAccessableInPublish(t *testing.T) {
+ originalSnippetsPath := util.SnippetsPath
+ util.SnippetsPath = t.TempDir()
+ t.Cleanup(func() {
+ util.SnippetsPath = originalSnippetsPath
+ })
+
+ if err := SetSnippet([]*conf.Snippet{
+ {Name: "allowed", Type: "css"},
+ {Name: "disabled", Type: "js", DisabledInPublish: true},
+ }); err != nil {
+ t.Fatal(err)
+ }
+
+ if found, accessable := CheckSnippetAccessableInPublish("allowed", "css"); !found || !accessable {
+ t.Fatal("publish-enabled snippet should be accessable")
+ }
+ if found, accessable := CheckSnippetAccessableInPublish("disabled", "js"); !found || accessable {
+ t.Fatal("publish-disabled snippet should not be accessable")
+ }
+ if found, _ := CheckSnippetAccessableInPublish("missing", "js"); found {
+ t.Fatal("missing snippet should not be found")
+ }
+}
+
+func TestCheckPluginAccessableInPublish(t *testing.T) {
+ originalDataDir := util.DataDir
+ originalConf := Conf
+ util.DataDir = t.TempDir()
+ Conf = NewAppConf()
+ Conf.Bazaar = &conf.Bazaar{Trust: true}
+ t.Cleanup(func() {
+ util.DataDir = originalDataDir
+ Conf = originalConf
+ })
+
+ writePlugin := func(name string, disabledInPublish bool) {
+ dir := filepath.Join(util.DataDir, "plugins", name)
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ disabled := "false"
+ if disabledInPublish {
+ disabled = "true"
+ }
+ data := []byte(`{"name":"` + name + `","version":"1.0.0","minAppVersion":"0.0.1","disabledInPublish":` + disabled + `}`)
+ if err := os.WriteFile(filepath.Join(dir, "plugin.json"), data, 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ writePlugin("allowed", false)
+ writePlugin("publish-disabled", true)
+ writePlugin("disabled", false)
+ if err := os.MkdirAll(filepath.Join(util.DataDir, "storage", "petal"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ savePetals([]*Petal{
+ {Name: "allowed", Enabled: true},
+ {Name: "publish-disabled", Enabled: true},
+ {Name: "disabled", Enabled: false},
+ })
+
+ if !CheckPluginAccessableInPublish("allowed") {
+ t.Fatal("enabled plugin should be accessable in publish")
+ }
+ if CheckPluginAccessableInPublish("publish-disabled") {
+ t.Fatal("publish-disabled plugin should not be accessable")
+ }
+ if CheckPluginAccessableInPublish("disabled") {
+ t.Fatal("disabled plugin should not be accessable")
+ }
+}
+
+func TestCheckWidgetAccessableInPublish(t *testing.T) {
+ originalDataDir := util.DataDir
+ util.DataDir = t.TempDir()
+ t.Cleanup(func() {
+ util.DataDir = originalDataDir
+ })
+
+ writeWidget := func(name string, disabledInPublish bool) {
+ dir := filepath.Join(util.DataDir, "widgets", name)
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ disabled := "false"
+ if disabledInPublish {
+ disabled = "true"
+ }
+ data := []byte(`{"name":"` + name + `","disabledInPublish":` + disabled + `}`)
+ if err := os.WriteFile(filepath.Join(dir, "widget.json"), data, 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ writeWidget("allowed", false)
+ writeWidget("disabled", true)
+
+ if !CheckWidgetAccessableInPublish("allowed") {
+ t.Fatal("publish-enabled widget should be accessable")
+ }
+ if CheckWidgetAccessableInPublish("disabled") {
+ t.Fatal("publish-disabled widget should not be accessable")
+ }
+ if CheckWidgetAccessableInPublish("missing") {
+ t.Fatal("missing widget should not be accessable")
+ }
+}
diff --git a/kernel/server/serve.go b/kernel/server/serve.go
index 1b3a7ebc2b..1f45b812f1 100644
--- a/kernel/server/serve.go
+++ b/kernel/server/serve.go
@@ -322,7 +322,7 @@ func rewritePortJSON(pid, port string) {
func serveExport(ginServer *gin.Engine) {
// Potential data export disclosure security vulnerability https://github.com/siyuan-note/siyuan/issues/12213
- exportGroup := ginServer.Group("/export/", model.CheckAuth)
+ exportGroup := ginServer.Group("/export/", model.CheckAuth, model.CheckAdminRole)
exportBaseDir := filepath.Join(util.TempDir, "export")
exportGroup.GET("/*filepath", func(c *gin.Context) {
@@ -412,22 +412,39 @@ func serveExport(ginServer *gin.Engine) {
func serveWidgets(ginServer *gin.Engine) {
widgets := ginServer.Group("/widgets/", model.CheckAuth)
- widgets.Static("", filepath.Join(util.DataDir, "widgets"))
+ registerStaticFileHandlers(widgets, filepath.Join(util.DataDir, "widgets"), true, func(c *gin.Context, relativePath string) bool {
+ if !model.IsReadOnlyRoleContext(c) {
+ return true
+ }
+ name, _, _ := strings.Cut(filepath.ToSlash(relativePath), "/")
+ return model.CheckWidgetAccessableByPublishAccess(c, name, model.GetPublishAccess())
+ })
}
func servePlugins(ginServer *gin.Engine) {
plugins := ginServer.Group("/plugins/", model.CheckAuth)
- plugins.Static("", filepath.Join(util.DataDir, "plugins"))
+ registerStaticFileHandlers(plugins, filepath.Join(util.DataDir, "plugins"), true, func(c *gin.Context, relativePath string) bool {
+ if !model.IsReadOnlyRoleContext(c) {
+ return true
+ }
+ name, _, _ := strings.Cut(filepath.ToSlash(relativePath), "/")
+ return model.CheckPluginAccessableInPublish(name)
+ })
}
func serveEmojis(ginServer *gin.Engine) {
emojis := ginServer.Group("/emojis/", model.CheckAuth)
- emojis.Static("", filepath.Join(util.DataDir, "emojis"))
+ registerStaticFileHandlers(emojis, filepath.Join(util.DataDir, "emojis"), false, func(c *gin.Context, relativePath string) bool {
+ if !model.IsReadOnlyRoleContext(c) {
+ return true
+ }
+ return model.CheckEmojiAccessableByPublishAccess(c, filepath.ToSlash(relativePath), model.GetPublishAccess())
+ })
}
func serveTemplates(ginServer *gin.Engine) {
- templates := ginServer.Group("/templates/", model.CheckAuth)
- templates.Static("", filepath.Join(util.DataDir, "templates"))
+ templates := ginServer.Group("/templates/", model.CheckAuth, model.CheckAdminRole)
+ registerStaticFileHandlers(templates, filepath.Join(util.DataDir, "templates"), true, nil)
}
func servePublic(ginServer *gin.Engine) {
@@ -437,7 +454,12 @@ func servePublic(ginServer *gin.Engine) {
func serveSnippets(ginServer *gin.Engine) {
ginServer.Handle("GET", "/snippets/*filepath", model.CheckAuth, func(c *gin.Context) {
- filePath := strings.TrimPrefix(c.Request.URL.Path, "/snippets/")
+ filePath, ok := cleanStaticRelativePath(c.Param("filepath"))
+ if !ok {
+ c.Status(http.StatusForbidden)
+ return
+ }
+ filePath = filepath.ToSlash(filePath)
if !model.IsAdminRoleContext(c) {
if "conf.json" == filePath {
c.Status(http.StatusUnauthorized)
@@ -447,6 +469,18 @@ func serveSnippets(ginServer *gin.Engine) {
ext := filepath.Ext(filePath)
name := strings.TrimSuffix(filePath, ext)
+ if model.IsReadOnlyRoleContext(c) {
+ found, accessable := model.CheckSnippetAccessableInPublish(name, strings.TrimPrefix(ext, "."))
+ if !found {
+ c.Status(http.StatusNotFound)
+ return
+ }
+ if !accessable {
+ c.Status(http.StatusForbidden)
+ return
+ }
+ }
+
confSnippets, err := model.LoadSnippets()
if err != nil {
logging.LogErrorf("load snippets failed: %s", err)
@@ -463,21 +497,97 @@ func serveSnippets(ginServer *gin.Engine) {
}
// 没有在配置文件中命中时在文件系统上查找
- filePath = filepath.Join(util.SnippetsPath, filePath)
+ serveStaticFile(c, util.SnippetsPath, filePath, false)
+ })
+}
- // 限制只能访问 snippets 目录内的文件,并拦截敏感路径,避免通过路径穿越读取工作空间内的敏感文件
- if !gulu.File.IsSubPath(util.SnippetsPath, filePath) {
- c.Status(http.StatusUnauthorized)
+type staticFileAccessCheck func(c *gin.Context, relativePath string) bool
+
+func registerStaticFileHandlers(group *gin.RouterGroup, root string, packageScoped bool, accessCheck staticFileAccessCheck) {
+ handler := func(c *gin.Context) {
+ relativePath, ok := cleanStaticRelativePath(c.Param("filepath"))
+ if !ok {
+ c.Status(http.StatusForbidden)
return
}
- if util.IsSensitivePath(filePath) {
- logging.LogErrorf("refuse to serve sensitive snippet file [%s]", c.Request.URL.Path)
+ if accessCheck != nil && !accessCheck(c, relativePath) {
c.Status(http.StatusForbidden)
return
}
+ serveStaticFile(c, root, relativePath, packageScoped)
+ }
+ group.GET("/*filepath", handler)
+ group.HEAD("/*filepath", handler)
+}
- c.File(filePath)
- })
+func cleanStaticRelativePath(requestPath string) (string, bool) {
+ requestPath = strings.TrimPrefix(requestPath, "/")
+ relativePath := filepath.Clean(filepath.FromSlash(requestPath))
+ if filepath.IsAbs(relativePath) || filepath.VolumeName(relativePath) != "" ||
+ relativePath == ".." || strings.HasPrefix(relativePath, ".."+string(os.PathSeparator)) {
+ return "", false
+ }
+ return relativePath, true
+}
+
+func serveStaticFile(c *gin.Context, root, relativePath string, packageScoped bool) {
+ rootAbsPath, err := filepath.Abs(root)
+ if err != nil {
+ c.Status(http.StatusInternalServerError)
+ return
+ }
+ rootRealPath, err := filepath.EvalSymlinks(rootAbsPath)
+ if err != nil {
+ c.Status(http.StatusNotFound)
+ return
+ }
+
+ targetPath := filepath.Join(rootAbsPath, relativePath)
+ targetInfo, err := os.Stat(targetPath)
+ if err != nil {
+ if os.IsNotExist(err) {
+ c.Status(http.StatusNotFound)
+ } else {
+ c.Status(http.StatusForbidden)
+ }
+ return
+ }
+ if targetInfo.IsDir() {
+ targetPath = filepath.Join(targetPath, "index.html")
+ }
+
+ targetRealPath, err := filepath.EvalSymlinks(targetPath)
+ if err != nil {
+ c.Status(http.StatusNotFound)
+ return
+ }
+ allowedRoot := rootRealPath
+ if packageScoped && relativePath != "." {
+ // 插件、挂件等支持将一级包目录作为符号链接,包内符号链接仍不得越出该包的实际目录。
+ firstSegment, _, _ := strings.Cut(filepath.ToSlash(relativePath), "/")
+ if firstSegment != "" {
+ packageRoot := filepath.Join(rootAbsPath, filepath.FromSlash(firstSegment))
+ if resolvedPackageRoot, resolveErr := filepath.EvalSymlinks(packageRoot); resolveErr == nil {
+ allowedRoot = resolvedPackageRoot
+ }
+ }
+ }
+ if targetRealPath != allowedRoot && !gulu.File.IsSubPath(allowedRoot, targetRealPath) {
+ c.Status(http.StatusForbidden)
+ return
+ }
+ if util.IsSensitivePath(targetRealPath) {
+ logging.LogErrorf("refuse to serve sensitive static file [%s]", c.Request.URL.Path)
+ c.Status(http.StatusForbidden)
+ return
+ }
+
+ targetInfo, err = os.Stat(targetRealPath)
+ if err != nil || !targetInfo.Mode().IsRegular() {
+ c.Status(http.StatusNotFound)
+ return
+ }
+ http.ServeFile(c.Writer, c.Request, targetRealPath)
}
func serveAppearance(ginServer *gin.Engine) {
diff --git a/kernel/server/serve_static_test.go b/kernel/server/serve_static_test.go
new file mode 100644
index 0000000000..fd28985c5e
--- /dev/null
+++ b/kernel/server/serve_static_test.go
@@ -0,0 +1,193 @@
+// 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 server
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestCleanStaticRelativePath(t *testing.T) {
+ if relativePath, ok := cleanStaticRelativePath("/package/index.js"); !ok ||
+ filepath.ToSlash(relativePath) != "package/index.js" {
+ t.Fatalf("unexpected clean path [%s], ok=%v", relativePath, ok)
+ }
+ for _, requestPath := range []string{"/../secret", "../secret", "/package/../../secret"} {
+ if _, ok := cleanStaticRelativePath(requestPath); ok {
+ t.Fatalf("path traversal should be rejected [%s]", requestPath)
+ }
+ }
+}
+
+func TestRegisterStaticFileHandlers(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ root := t.TempDir()
+ if err := os.MkdirAll(filepath.Join(root, "package"), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(root, "package", "index.html"), []byte("content"), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ engine := gin.New()
+ group := engine.Group("/files/")
+ registerStaticFileHandlers(group, root, true, func(_ *gin.Context, relativePath string) bool {
+ return filepath.ToSlash(relativePath) == "package"
+ })
+
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/files/package/", nil))
+ if recorder.Code != http.StatusOK || recorder.Body.String() != "content" {
+ t.Fatalf("unexpected allowed response: status=%d body=%q", recorder.Code, recorder.Body.String())
+ }
+
+ recorder = httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/files/package/index.html", nil))
+ if recorder.Code != http.StatusForbidden {
+ t.Fatalf("access callback should deny the request, got %d", recorder.Code)
+ }
+}
+
+func TestStaticFileNestedSymlinkEscape(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ root, outside := t.TempDir(), t.TempDir()
+ packagePath := filepath.Join(root, "package")
+ if err := os.MkdirAll(packagePath, 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(outside, "secret.txt"), []byte("secret"), 0644); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.Symlink(outside, filepath.Join(packagePath, "escape")); err != nil {
+ t.Skipf("create directory symlink failed: %s", err)
+ }
+
+ engine := gin.New()
+ group := engine.Group("/files/")
+ registerStaticFileHandlers(group, root, true, func(_ *gin.Context, _ string) bool {
+ return true
+ })
+
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/files/package/escape/secret.txt", nil))
+ if recorder.Code != http.StatusForbidden {
+ t.Fatalf("nested symlink escape should be forbidden, got %d", recorder.Code)
+ }
+}
+
+func TestTemplatesAndExportRequireAdministrator(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ originalDataDir, originalTempDir := util.DataDir, util.TempDir
+ util.DataDir, util.TempDir = t.TempDir(), t.TempDir()
+ t.Cleanup(func() {
+ util.DataDir, util.TempDir = originalDataDir, originalTempDir
+ })
+
+ templatePath := filepath.Join(util.DataDir, "templates", "private.md")
+ exportPath := filepath.Join(util.TempDir, "export", "private.txt")
+ for path, content := range map[string]string{templatePath: "template", exportPath: "export"} {
+ if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(path, []byte(content), 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+
+ request := func(role model.Role, register func(*gin.Engine), requestPath string) *httptest.ResponseRecorder {
+ engine := gin.New()
+ engine.Use(func(c *gin.Context) {
+ c.Set(model.RoleContextKey, role)
+ c.Next()
+ })
+ register(engine)
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, requestPath, nil))
+ return recorder
+ }
+ for _, test := range []struct {
+ register func(*gin.Engine)
+ requestPath string
+ content string
+ }{
+ {serveTemplates, "/templates/private.md", "template"},
+ {serveExport, "/export/private.txt", "export"},
+ } {
+ if recorder := request(model.RoleReader, test.register, test.requestPath); recorder.Code != http.StatusForbidden {
+ t.Fatalf("reader request [%s] should be forbidden, got %d", test.requestPath, recorder.Code)
+ }
+ recorder := request(model.RoleAdministrator, test.register, test.requestPath)
+ if recorder.Code != http.StatusOK || recorder.Body.String() != test.content {
+ t.Fatalf("unexpected administrator response [%s]: status=%d body=%q",
+ test.requestPath, recorder.Code, recorder.Body.String())
+ }
+ }
+}
+
+func TestSnippetPublishAccess(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+ originalSnippetsPath := util.SnippetsPath
+ util.SnippetsPath = t.TempDir()
+ t.Cleanup(func() {
+ util.SnippetsPath = originalSnippetsPath
+ })
+
+ if err := model.SetSnippet([]*conf.Snippet{
+ {Name: "allowed", Type: "css", Content: "allowed"},
+ {Name: "disabled", Type: "js", Content: "disabled", DisabledInPublish: true},
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(util.SnippetsPath, "fallback.css"), []byte("fallback"), 0644); err != nil {
+ t.Fatal(err)
+ }
+
+ request := func(role model.Role, requestPath string) *httptest.ResponseRecorder {
+ engine := gin.New()
+ engine.Use(func(c *gin.Context) {
+ c.Set(model.RoleContextKey, role)
+ c.Next()
+ })
+ serveSnippets(engine)
+ recorder := httptest.NewRecorder()
+ engine.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, requestPath, nil))
+ return recorder
+ }
+ if recorder := request(model.RoleReader, "/snippets/allowed.css"); recorder.Code != http.StatusOK ||
+ strings.TrimSpace(recorder.Body.String()) != "allowed" {
+ t.Fatalf("unexpected publish-enabled snippet response: status=%d body=%q", recorder.Code, recorder.Body.String())
+ }
+ if recorder := request(model.RoleReader, "/snippets/disabled.js"); recorder.Code != http.StatusForbidden {
+ t.Fatalf("publish-disabled snippet should be forbidden, got %d", recorder.Code)
+ }
+ if recorder := request(model.RoleReader, "/snippets/fallback.css"); recorder.Code != http.StatusNotFound {
+ t.Fatalf("filesystem fallback should be hidden from readers, got %d", recorder.Code)
+ }
+ if recorder := request(model.RoleAdministrator, "/snippets/fallback.css"); recorder.Code != http.StatusOK ||
+ recorder.Body.String() != "fallback" {
+ t.Fatalf("unexpected administrator fallback response: status=%d body=%q", recorder.Code, recorder.Body.String())
+ }
+}