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: Resolve Windows junctions across workspace file operations https://github.com/siyuan-note/siyuan/issues/20651
Danielff4b867586e7
diff --git a/kernel/api/archive.go b/kernel/api/archive.goindex 2a281bd22c..9a835e1d24 100644--- a/kernel/api/archive.go+++ b/kernel/api/archive.go@@ -75,7 +75,7 @@ func resolveArchivePath(path string) (string, error) {}parent = filepath.Dir(parent)}- resolved, err := model.ResolveRealPath(parent)+ resolved, err := util.ResolveRealPath(parent)if err != nil {return "", err}diff --git a/kernel/api/template.go b/kernel/api/template.goindex 71e46ce534..908923a7e5 100644--- a/kernel/api/template.go+++ b/kernel/api/template.go@@ -164,11 +164,11 @@ func isPathInTemplatesDir(p string) bool {if !gulu.File.IsSubPath(templatesRoot, abs) {return false}- realRoot, err := filepath.EvalSymlinks(templatesRoot)+ realRoot, err := util.ResolveRealPath(templatesRoot)if nil != err {return false}- realPath, err := filepath.EvalSymlinks(abs)+ realPath, err := util.ResolveRealPath(abs)if nil != err {return false}diff --git a/kernel/api/template_junction_windows_test.go b/kernel/api/template_junction_windows_test.gonew file mode 100644index 0000000000..b39ecacb4e--- /dev/null+++ b/kernel/api/template_junction_windows_test.go@@ -0,0 +1,40 @@+package api++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/internal/testutil"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestIsPathInTemplatesDirJunctionWorkspace(t *testing.T) {+ for _, atWorkspace := range []bool{false, true} {+ t.Run(map[bool]string{false: "ancestor", true: "workspace"}[atWorkspace], func(t *testing.T) {+ alias, _ := testutil.JunctionWorkspace(t, t.TempDir(), atWorkspace)+ previous := util.DataDir+ util.DataDir = filepath.Join(alias, "data")+ t.Cleanup(func() { util.DataDir = previous })+ root := filepath.Join(util.DataDir, "templates")+ if err := os.MkdirAll(root, 0755); err != nil {+ t.Fatal(err)+ }+ file := filepath.Join(root, "test.md")+ if err := os.WriteFile(file, []byte("template"), 0644); err != nil {+ t.Fatal(err)+ }+ if !isPathInTemplatesDir(file) {+ t.Error("valid template below a junction was rejected")+ }+ outside := t.TempDir()+ if err := os.WriteFile(filepath.Join(outside, "test.md"), []byte("outside"), 0644); err != nil {+ t.Fatal(err)+ }+ testutil.Junction(t, filepath.Join(root, "escape"), outside)+ if isPathInTemplatesDir(filepath.Join(root, "escape", "test.md")) {+ t.Error("template escaped its real root")+ }+ })+ }+}diff --git a/kernel/internal/testutil/junction_windows.go b/kernel/internal/testutil/junction_windows.gonew file mode 100644index 0000000000..c35fab2f16--- /dev/null+++ b/kernel/internal/testutil/junction_windows.go@@ -0,0 +1,34 @@+package testutil++import (+ "os"+ "os/exec"+ "path/filepath"+ "testing"+)++// Junction 创建不需要管理员权限的真实目录联接。+func Junction(t testing.TB, link, target string) {+ t.Helper()+ if output, err := exec.Command("cmd", "/d", "/c", "mklink", "/J", link, target).CombinedOutput(); err != nil {+ t.Fatalf("create junction %q to %q: %v, %s", link, target, err, output)+ }+}++// JunctionWorkspace 分别构造工作空间本身或其祖先为联接的夹具。+func JunctionWorkspace(t testing.TB, root string, atWorkspace bool) (alias, physical string) {+ t.Helper()+ physical = filepath.Join(root, "physical target")+ alias = filepath.Join(root, "linked path")+ if err := os.Mkdir(physical, 0755); err != nil {+ t.Fatal(err)+ }+ Junction(t, alias, physical)+ if !atWorkspace {+ alias, physical = filepath.Join(alias, "workspace"), filepath.Join(physical, "workspace")+ if err := os.Mkdir(physical, 0755); err != nil {+ t.Fatal(err)+ }+ }+ return+}diff --git a/kernel/model/appearance_export.go b/kernel/model/appearance_export.goindex bc0bb14d94..3a8f46cfe9 100644--- a/kernel/model/appearance_export.go+++ b/kernel/model/appearance_export.go@@ -41,7 +41,7 @@ func copyExportAppearance(savePath, theme, icon string) error {return fmt.Errorf("invalid appearance package [%s/%s]", kind, name)}// 解析包目录本身的符号链接,使导出保留完整资源而不携带本机路径。- from, err := filepath.EvalSymlinks(from)+ from, err := util.ResolveRealPath(from)if err != nil {return err}diff --git a/kernel/model/asset_download_read.go b/kernel/model/asset_download_read.goindex be8c9162b7..e476cbaa71 100644--- a/kernel/model/asset_download_read.go+++ b/kernel/model/asset_download_read.go@@ -33,7 +33,7 @@ func ResolveAssetPathWithMissingLeaf(absPath string) (string, error) {current := filepath.Clean(absPath)var missing []stringfor {- resolved, err := ResolveRealPath(current)+ resolved, err := util.ResolveRealPath(current)if err == nil {for _, m := range slices.Backward(missing) {resolved = filepath.Join(resolved, m)@@ -105,8 +105,8 @@ func deferredAssetPathFromFiles(relativePath, boxID string, includeEncrypted boo}root, rootErr := ResolveAssetPathWithMissingLeaf(filepath.Join(util.DataDir, resolvedBoxID, "assets"))resolved, resolveErr := ResolveAssetPathWithMissingLeaf(absPath)- notebookRoot, notebookErr := ResolveRealPath(filepath.Join(util.DataDir, resolvedBoxID))- dataRoot, dataErr := ResolveRealPath(util.DataDir)+ notebookRoot, notebookErr := util.ResolveRealPath(filepath.Join(util.DataDir, resolvedBoxID))+ dataRoot, dataErr := util.ResolveRealPath(util.DataDir)if rootErr != nil || resolveErr != nil || notebookErr != nil || dataErr != nil ||!gulu.File.IsSubPath(dataRoot, notebookRoot) ||!gulu.File.IsSubPath(notebookRoot, root) || !gulu.File.IsSubPath(root, resolved) {diff --git a/kernel/model/assets.go b/kernel/model/assets.goindex 8f24947a2c..dde9e8ab3b 100644--- a/kernel/model/assets.go+++ b/kernel/model/assets.go@@ -1167,8 +1167,8 @@ func ResolveDataAssetPath(assetPath string) (relativePath, absPath string, err e}if assetDirIndex > 0 {notebookRoot := filepath.Join(util.DataDir, parts[0])- resolvedDataDir, dataEvalErr := ResolveRealPath(util.DataDir)- resolvedNotebookRoot, notebookEvalErr := ResolveRealPath(notebookRoot)+ resolvedDataDir, dataEvalErr := util.ResolveRealPath(util.DataDir)+ resolvedNotebookRoot, notebookEvalErr := util.ResolveRealPath(notebookRoot)if dataEvalErr != nil || notebookEvalErr != nil ||!gulu.File.IsSubPath(resolvedDataDir, resolvedNotebookRoot) ||!gulu.File.IsSubPath(resolvedNotebookRoot, resolvedRoot) {diff --git a/kernel/model/junction_workspace_windows_test.go b/kernel/model/junction_workspace_windows_test.gonew file mode 100644index 0000000000..d1ec4a5249--- /dev/null+++ b/kernel/model/junction_workspace_windows_test.go@@ -0,0 +1,56 @@+package model++import (+ "os"+ "path/filepath"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/internal/testutil"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestJunctionWorkspaceTemplatesAndAppearanceExport(t *testing.T) {+ for _, atWorkspace := range []bool{false, true} {+ t.Run(map[bool]string{false: "ancestor", true: "workspace"}[atWorkspace], func(t *testing.T) {+ alias, _ := testutil.JunctionWorkspace(t, t.TempDir(), atWorkspace)+ previousData, previousAppearance, previousThemes, previousIcons, previousMode :=+ util.DataDir, util.AppearancePath, util.ThemesPath, util.IconsPath, util.Mode+ util.DataDir, util.AppearancePath = filepath.Join(alias, "data"), filepath.Join(alias, "conf", "appearance")+ util.ThemesPath, util.IconsPath, util.Mode = filepath.Join(util.DataDir, "themes"), filepath.Join(util.DataDir, "icons"), "prod"+ t.Cleanup(func() {+ util.DataDir, util.AppearancePath, util.ThemesPath, util.IconsPath, util.Mode =+ previousData, previousAppearance, previousThemes, previousIcons, previousMode+ })+ root := filepath.Join(util.DataDir, "templates", "package", "root.md")+ writeAppearanceTestFile(t, root, "root template")+ writeAppearanceTestFile(t, filepath.Join(filepath.Dir(root), "children", "child.md"), "child template")+ if _, err := resolveDocContentTemplatePath("package/root.md"); err != nil {+ t.Errorf("content template below junction: %v", err)+ }+ if _, err := resolveTemplatePackageFile(root, "children/child.md"); err != nil {+ t.Errorf("child template below junction: %v", err)+ }+ outside := t.TempDir()+ writeAppearanceTestFile(t, filepath.Join(outside, "child.md"), "outside")+ testutil.Junction(t, filepath.Join(filepath.Dir(root), "escape"), outside)+ if _, err := resolveDocContentTemplatePath("package/escape/child.md"); err == nil {+ t.Error("content template escaped templates root")+ }+ if _, err := resolveTemplatePackageFile(root, "escape/child.md"); err == nil {+ t.Error("child template escaped package root")+ }+ for _, relative := range []string{"themes/daylight/theme.css", "themes/midnight/theme.css", "icons/litheness/icon.js",+ "fonts/Noto-COLRv1-2.051/Noto-COLRv1.woff2", "fonts/Noto-COLRv1-2.051/LICENSE"} {+ writeAppearanceTestFile(t, filepath.Join(util.AppearancePath, filepath.FromSlash(relative)), "built-in resource")+ }+ writeAppearanceTestFile(t, filepath.Join(util.ThemesPath, "custom", "theme.css"), "custom theme")+ writeAppearanceTestFile(t, filepath.Join(util.IconsPath, "custom", "icon.js"), "custom icons")+ export := t.TempDir()+ if err := copyExportAppearance(export, "custom", "custom"); err != nil {+ t.Errorf("export appearance below junction: %v", err)+ } else if data, err := os.ReadFile(filepath.Join(export, "appearance", "themes", "custom", "theme.css")); err != nil || string(data) != "custom theme" {+ t.Errorf("exported custom theme: %q, %v", data, err)+ }+ })+ }+}diff --git a/kernel/model/template.go b/kernel/model/template.goindex 8c0c873e10..28abf1ec13 100644--- a/kernel/model/template.go+++ b/kernel/model/template.go@@ -1367,11 +1367,11 @@ func resolveDocContentTemplatePath(templatePath string) (string, error) {if !filelock.IsExist(absPath) {return "", fmt.Errorf("content template [%s] not found", templatePath)}- realRoot, err := filepath.EvalSymlinks(templateRoot)+ realRoot, err := util.ResolveRealPath(templateRoot)if nil != err {return "", err}- realPath, err := filepath.EvalSymlinks(absPath)+ realPath, err := util.ResolveRealPath(absPath)if nil != err {return "", err}diff --git a/kernel/model/template_doc_tree.go b/kernel/model/template_doc_tree.goindex eef2230567..d5a3d1d016 100644--- a/kernel/model/template_doc_tree.go+++ b/kernel/model/template_doc_tree.go@@ -417,11 +417,11 @@ func resolveTemplatePackageFile(rootTemplatePath, relativePath string) (string,if !gulu.File.IsSubPath(packageRoot, absPath) || !filelock.IsExist(absPath) {return "", fmt.Errorf("child template [%s] not found in the current template package", relativePath)}- realRoot, err := filepath.EvalSymlinks(packageRoot)+ realRoot, err := util.ResolveRealPath(packageRoot)if nil != err {return "", err}- realPath, err := filepath.EvalSymlinks(absPath)+ realPath, err := util.ResolveRealPath(absPath)if nil != err {return "", err}diff --git a/kernel/server/appearance_symlink_windows.go b/kernel/server/appearance_symlink_windows.goindex 46a67e044c..539b5c9f21 100644--- a/kernel/server/appearance_symlink_windows.go+++ b/kernel/server/appearance_symlink_windows.go@@ -18,9 +18,9 @@package server-import "github.com/siyuan-note/siyuan/kernel/model"+import "github.com/siyuan-note/siyuan/kernel/util"func evalAppearanceSymlinks(name string) (string, error) {// 通过句柄解析完整链路,兼容可打开但无法逐级解析的目录联接。- return model.ResolveRealPath(name)+ return util.ResolveRealPath(name)}diff --git a/kernel/server/serve.go b/kernel/server/serve.goindex 84615d8b20..cf02a15654 100644--- a/kernel/server/serve.go+++ b/kernel/server/serve.go@@ -678,7 +678,7 @@ func serveStaticFile(c *gin.Context, root, relativePath string, packageScoped boc.Status(http.StatusInternalServerError)return}- rootRealPath, err := filepath.EvalSymlinks(rootAbsPath)+ rootRealPath, err := util.ResolveRealPath(rootAbsPath)if err != nil {c.Status(http.StatusNotFound)return@@ -698,7 +698,7 @@ func serveStaticFile(c *gin.Context, root, relativePath string, packageScoped botargetPath = filepath.Join(targetPath, "index.html")}- targetRealPath, err := filepath.EvalSymlinks(targetPath)+ targetRealPath, err := util.ResolveRealPath(targetPath)if err != nil {c.Status(http.StatusNotFound)return@@ -709,7 +709,7 @@ func serveStaticFile(c *gin.Context, root, relativePath string, packageScoped bofirstSegment, _, _ := strings.Cut(filepath.ToSlash(relativePath), "/")if firstSegment != "" {packageRoot := filepath.Join(rootAbsPath, filepath.FromSlash(firstSegment))- if resolvedPackageRoot, resolveErr := filepath.EvalSymlinks(packageRoot); resolveErr == nil {+ if resolvedPackageRoot, resolveErr := util.ResolveRealPath(packageRoot); resolveErr == nil {allowedRoot = resolvedPackageRoot}}diff --git a/kernel/server/serve_static_junction_windows_test.go b/kernel/server/serve_static_junction_windows_test.gonew file mode 100644index 0000000000..352d07d35b--- /dev/null+++ b/kernel/server/serve_static_junction_windows_test.go@@ -0,0 +1,81 @@+package server++import (+ "net/http"+ "net/http/httptest"+ "os"+ "path/filepath"+ "testing"++ "github.com/gin-gonic/gin"+ "github.com/siyuan-note/siyuan/kernel/internal/testutil"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestStaticFileJunctionWorkspace(t *testing.T) {+ for _, atWorkspace := range []bool{false, true} {+ t.Run(map[bool]string{false: "ancestor", true: "workspace"}[atWorkspace], func(t *testing.T) {+ alias, _ := testutil.JunctionWorkspace(t, testutil.PublicDataDir(t), atWorkspace)+ previousWorkspace, previousData := util.WorkspaceDir, util.DataDir+ util.WorkspaceDir, util.DataDir = alias, filepath.Join(alias, "data")+ t.Cleanup(func() { util.WorkspaceDir, util.DataDir = previousWorkspace, previousData })+ write := func(name string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(name, []byte("resource"), 0644); err != nil {+ t.Fatal(err)+ }+ }+ gin.SetMode(gin.TestMode)+ engine := gin.New()+ for _, kind := range []string{"plugins", "widgets", "templates", "emojis", "snippets"} {+ root := filepath.Join(util.DataDir, kind)+ write(filepath.Join(root, "demo", "icon.png"))+ registerStaticFileHandlers(engine.Group("/"+kind), root, kind != "emojis" && kind != "snippets", nil)+ }+ outside := testutil.PublicDataDir(t)+ write(filepath.Join(outside, "icon.png"))+ write(filepath.Join(alias, "conf", "conf.json"))+ write(filepath.Join(alias, "temp", "private.txt"))+ write(filepath.Join(alias, "temp", "export", "doc.html"))+ plugins := filepath.Join(util.DataDir, "plugins")+ write(filepath.Join(plugins, "demo", "credentials.json"))+ testutil.Junction(t, filepath.Join(plugins, "linked"), outside)+ testutil.Junction(t, filepath.Join(plugins, "demo", "escape"), outside)+ testutil.Junction(t, filepath.Join(plugins, "private"), filepath.Join(alias, "conf"))+ registerStaticFileHandlers(engine.Group("/files"), alias, false, nil)+ for _, item := range []struct {+ path string+ code int+ }{+ {"/plugins/demo/icon.png?v=123", http.StatusOK},+ {"/widgets/demo/icon.png", http.StatusOK},+ {"/templates/demo/icon.png", http.StatusOK},+ {"/emojis/demo/icon.png", http.StatusOK},+ {"/snippets/demo/icon.png", http.StatusOK},+ {"/plugins/linked/icon.png", http.StatusOK},+ {"/plugins/demo/escape/icon.png", http.StatusForbidden},+ {"/plugins/private/conf.json", http.StatusForbidden},+ {"/files/conf/conf.json", http.StatusForbidden},+ {"/files/temp/private.txt", http.StatusForbidden},+ {"/files/temp/export/doc.html", http.StatusOK},+ {"/plugins/demo/credentials.json", http.StatusForbidden},+ {"/files/data/plugins/demo/icon.png", http.StatusOK},+ {"/plugins/demo/missing.png", http.StatusNotFound},+ } {+ for _, method := range []string{http.MethodGet, http.MethodHead} {+ recorder := httptest.NewRecorder()+ engine.ServeHTTP(recorder, httptest.NewRequest(method, item.path, nil))+ if recorder.Code != item.code {+ t.Errorf("%s %s = %d, want %d", method, item.path, recorder.Code, item.code)+ }+ if method == http.MethodGet && item.code == http.StatusOK && recorder.Body.String() != "resource" {+ t.Errorf("%s returned %q", item.path, recorder.Body.String())+ }+ }+ }+ })+ }+}diff --git a/kernel/util/file.go b/kernel/util/file.goindex 8afd52f4d1..2390c61475 100644--- a/kernel/util/file.go+++ b/kernel/util/file.go@@ -111,12 +111,13 @@ func GetMimeTypeByPath(filePath string) (m *mimetype.MIME, ok bool) {return}+// IsSymlinkPath 判断现有路径是否为符号链接或目录联接。func IsSymlinkPath(absPath string) bool {fi, err := os.Lstat(absPath)if err != nil {return false}- return 0 != fi.Mode()&os.ModeSymlink+ return isLinkFileInfo(fi)}// IsSystemMetadataFile 判断是否为操作系统自动生成的元数据文件(如 macOS 的 .DS_Store),@@ -179,8 +180,16 @@ func RemoveEmptyDir(p string) (err error) {return}+// IsSymlink 判断目录条目是否为符号链接或目录联接。func IsSymlink(dir fs.DirEntry) bool {- return dir.Type() == fs.ModeSymlink+ if dir.Type()&fs.ModeSymlink != 0 {+ return true+ }+ if dir.Type()&fs.ModeIrregular == 0 {+ return false+ }+ info, err := dir.Info()+ return err == nil && isLinkFileInfo(info)}func IsDirRegularOrSymlink(dir fs.DirEntry) bool {diff --git a/kernel/util/junction_windows_test.go b/kernel/util/junction_windows_test.gonew file mode 100644index 0000000000..d52fc1b582--- /dev/null+++ b/kernel/util/junction_windows_test.go@@ -0,0 +1,101 @@+package util_test++import (+ "context"+ "os"+ "path/filepath"+ "reflect"+ "strings"+ "testing"++ "github.com/siyuan-note/siyuan/kernel/internal/testutil"+ "github.com/siyuan-note/siyuan/kernel/util"+)++func TestJunctionWorkspaceUtilities(t *testing.T) {+ for _, atWorkspace := range []bool{false, true} {+ t.Run(map[bool]string{false: "ancestor", true: "workspace"}[atWorkspace], func(t *testing.T) {+ alias, physical := testutil.JunctionWorkspace(t, t.TempDir(), atWorkspace)+ previousData, previousHome := util.DataDir, util.HomeDir+ util.DataDir, util.HomeDir = filepath.Join(alias, "data"), t.TempDir()+ t.Cleanup(func() { util.DataDir, util.HomeDir = previousData, previousHome })+ write := func(name, content string) {+ t.Helper()+ if err := os.MkdirAll(filepath.Dir(name), 0755); err != nil {+ t.Fatal(err)+ }+ if err := os.WriteFile(name, []byte(content), 0644); err != nil {+ t.Fatal(err)+ }+ }+ skill := filepath.Join(util.SkillsDir(), "sample")+ const skillSource = "---\nname: sample\ndescription: test\n---\nbody"+ write(filepath.Join(skill, "SKILL.md"), skillSource)+ write(filepath.Join(skill, "refs", "note.txt"), "reference")+ loaded, err := util.LoadSkill("sample", nil)+ if err != nil || !reflect.DeepEqual(loaded.Resources, []string{"refs/note.txt"}) {+ t.Errorf("skill manifest below junction: %+v, %v", loaded, err)+ }+ loaded, err = util.LoadSkill("sample/refs/note.txt", nil)+ if err != nil || loaded.Content != "reference" {+ t.Errorf("skill resource below junction: %+v, %v", loaded, err)+ }+ outside := t.TempDir()+ write(filepath.Join(outside, "note.txt"), "must not be read or counted")+ testutil.Junction(t, filepath.Join(skill, "escape"), outside)+ if _, err := util.LoadSkill("sample/escape/note.txt", nil); err == nil {+ t.Error("skill resource escaped its real root")+ }+ write(filepath.Join(outside, "SKILL.md"), "---\nname: linked\n---\nlinked body")+ testutil.Junction(t, filepath.Join(util.SkillsDir(), "linked"), outside)+ if linked, err := util.LoadSkill("linked", nil); err != nil || linked.Content != "linked body" ||+ !reflect.DeepEqual(linked.Resources, []string{"note.txt"}) {+ t.Errorf("skill directory junction was not discovered: %+v, %v", linked, err)+ }+ if util.NormalizeAndResolve(alias) != util.NormalizeAndResolve(physical) {+ t.Error("workspace aliases have different canonical paths")+ }+ missing := filepath.Join("data", "new", "document.sy")+ if resolved := util.ResolveLongestExistingParent(filepath.Join(alias, missing)); !strings.EqualFold(resolved, filepath.Join(physical, missing)) {+ t.Errorf("nonexistent child below junction was not resolved: %q", resolved)+ }+ realStorage, err := util.GetWorkspaceStorage(context.Background(), physical)+ if err != nil {+ t.Fatal(err)+ }+ if want := int64(len(skillSource) + len("reference")); realStorage.TotalSize != want {+ t.Errorf("storage counted files outside the workspace: got %d, want %d", realStorage.TotalSize, want)+ }+ aliasStorage, err := util.GetWorkspaceStorage(context.Background(), alias)+ if err != nil || aliasStorage.TotalSize != realStorage.TotalSize ||+ !reflect.DeepEqual(aliasStorage.Directories, realStorage.Directories) {+ t.Errorf("storage below junction: %+v, %v; physical: %+v", aliasStorage, err, realStorage)+ }+ if atWorkspace && !util.IsSymlinkPath(alias) {+ t.Error("junction path was not identified as a link")+ }+ entries, err := os.ReadDir(skill)+ if err != nil {+ t.Fatal(err)+ }+ for _, entry := range entries {+ if entry.Name() == "escape" && (!util.IsSymlink(entry) || !util.IsDirRegularOrSymlink(entry)) {+ t.Error("junction directory entry was not identified as a directory link")+ }+ if entry.Name() == "refs" && (util.IsSymlink(entry) || !util.IsDirRegularOrSymlink(entry)) {+ t.Error("ordinary directory was misidentified")+ }+ if entry.Name() == "SKILL.md" && (util.IsSymlink(entry) || util.IsDirRegularOrSymlink(entry)) {+ t.Error("ordinary file was identified as a directory link")+ }+ }+ testutil.Junction(t, filepath.Join(util.DataDir, "assets"), outside)+ assets := util.GetDataAssetsAbsPath()+ assetInfo, err := os.Stat(assets)+ outsideInfo, outsideErr := os.Stat(outside)+ if err != nil || outsideErr != nil || !os.SameFile(assetInfo, outsideInfo) || assets == filepath.Join(util.DataDir, "assets") {+ t.Errorf("asset junction was not resolved: %q, %v", assets, err)+ }+ })+ }+}diff --git a/kernel/util/path.go b/kernel/util/path.goindex bdf7427d5d..e4cc044b22 100644--- a/kernel/util/path.go+++ b/kernel/util/path.go@@ -640,7 +640,7 @@ func isSensitivePath(p string, htmlAsset bool) bool {if !inWorkspace && workspaceDir != "" {// 静态资源使用解析后的真实路径,工作空间也需采用相同形式判断归属及 conf、temp 目录。// 仅解析工作空间根目录,不能将指向外部敏感文件的资源符号链接视为工作空间内文件。- if resolved, err := filepath.EvalSymlinks(workspaceDir); err == nil && gulu.File.IsSubPath(resolved, p) {+ if resolved, err := ResolveRealPath(workspaceDir); err == nil && gulu.File.IsSubPath(resolved, p) {workspaceDir = resolvedinWorkspace = true}@@ -718,21 +718,21 @@ func isSensitivePath(p string, htmlAsset bool) bool {// 自定义配置主目录不能使系统用户主目录中的凭据失去保护。if homeDirOverridden && systemHomeDir != "" && systemHomeDir != HomeDir {homeDirs = append(homeDirs, systemHomeDir)- if resolved, err := filepath.EvalSymlinks(systemHomeDir); err == nil && resolved != systemHomeDir {+ if resolved, err := ResolveRealPath(systemHomeDir); err == nil && resolved != systemHomeDir {homeDirs = append(homeDirs, resolved)}}homeCheckPaths := []string{toCheckPathLower}if HomeDir != "" {// 主目录自身也可能是别名,工作空间规范路径必须同时匹配其真实目录中的敏感位置。- if resolved, err := filepath.EvalSymlinks(HomeDir); err == nil && resolved != HomeDir {+ if resolved, err := ResolveRealPath(HomeDir); err == nil && resolved != HomeDir {homeDirs = append(homeDirs, resolved)}}// 工作空间别名可能位于自定义主目录中,但指向系统主目录中的敏感位置。// 只映射工作空间根目录,保留对尚未创建的目标及工作空间内路径的检查。if inWorkspace && workspaceDir == WorkspaceDir {- if resolved, err := filepath.EvalSymlinks(workspaceDir); err == nil && resolved != workspaceDir {+ if resolved, err := ResolveRealPath(workspaceDir); err == nil && resolved != workspaceDir {if rel, err := filepath.Rel(workspaceDir, p); err == nil {homeCheckPaths = append(homeCheckPaths, strings.ToLower(filepath.Join(resolved, rel)))}@@ -777,7 +777,7 @@ func isSensitivePath(p string, htmlAsset bool) bool {return false}-// ResolveLongestExistingParent 解析 absPath 中最长已存在部分的 symlink,拼回剩余路径。+// ResolveLongestExistingParent 解析 absPath 中最长已存在部分的符号链接或目录联接,拼回剩余路径。// 例如 absPath = /workspace/data/link/newdir/file,其中 /workspace/data/link 是指向// /workspace/data/<encBoxID>/ 的 symlink,newdir/file 尚不存在:// 返回 /workspace/data/<encBoxID>/newdir/file。@@ -795,7 +795,7 @@ func ResolveLongestExistingParent(absPath string) string {dir = parent}if dir == cleaned {- if resolved, err := filepath.EvalSymlinks(cleaned); err == nil {+ if resolved, err := ResolveRealPath(cleaned); err == nil {return resolved}return cleaned@@ -803,7 +803,7 @@ func ResolveLongestExistingParent(absPath string) string {if dir == "/" || dir == "." {return cleaned}- resolvedDir, err := filepath.EvalSymlinks(dir)+ resolvedDir, err := ResolveRealPath(dir)if err != nil {return cleaned}diff --git a/kernel/util/path_guard.go b/kernel/util/path_guard.goindex 53f4824ad5..773b081a40 100644--- a/kernel/util/path_guard.go+++ b/kernel/util/path_guard.go@@ -126,12 +126,12 @@ func IsForbiddenDataRelPath(rel string) bool {return false}-// NormalizeAndResolve 将路径转为绝对、解析符号链接并清理;在需要时转为小写以实现不区分大小写比较+// NormalizeAndResolve 将路径转为绝对、解析符号链接和目录联接并清理;在需要时转为小写以实现不区分大小写比较。func NormalizeAndResolve(p string) string {if abs, err := filepath.Abs(p); err == nil {p = abs}- if eval, err := filepath.EvalSymlinks(p); err == nil {+ if eval, err := ResolveRealPath(p); err == nil {p = eval}p = filepath.Clean(p)diff --git a/kernel/model/asset_path_resolver_other.go b/kernel/util/real_path_other.gosimilarity index 85%rename from kernel/model/asset_path_resolver_other.gorename to kernel/util/real_path_other.goindex c60f02ff26..921e946cbd 100644--- a/kernel/model/asset_path_resolver_other.go+++ b/kernel/util/real_path_other.go@@ -16,9 +16,17 @@//go:build !windows-package model+package util-import "path/filepath"+import (+ "io/fs"+ "os"+ "path/filepath"+)++func isLinkFileInfo(info fs.FileInfo) bool {+ return info.Mode()&os.ModeSymlink != 0+}func ResolveRealPath(path string) (string, error) {return filepath.EvalSymlinks(path)diff --git a/kernel/model/asset_path_resolver_windows.go b/kernel/util/real_path_windows.gosimilarity index 79%rename from kernel/model/asset_path_resolver_windows.gorename to kernel/util/real_path_windows.goindex 9713200db4..5990b81741 100644--- a/kernel/model/asset_path_resolver_windows.go+++ b/kernel/util/real_path_windows.go@@ -16,15 +16,31 @@//go:build windows-package model+package utilimport (+ "io/fs"+ "os""path/filepath""strings"+ "syscall""golang.org/x/sys/windows")+// isLinkFileInfo 识别符号链接和 Windows 的目录名称替代重解析点。+func isLinkFileInfo(info fs.FileInfo) bool {+ if info.Mode()&os.ModeSymlink != 0 {+ return true+ }+ if info.Mode()&os.ModeIrregular == 0 || info.IsDir() {+ return false+ }+ attributes, ok := info.Sys().(*syscall.Win32FileAttributeData)+ const directoryLink = syscall.FILE_ATTRIBUTE_DIRECTORY | syscall.FILE_ATTRIBUTE_REPARSE_POINT+ return ok && attributes.FileAttributes&directoryLink == directoryLink+}+// ResolveRealPath 使用文件句柄解析符号链接和目录联接,返回现有文件的最终绝对路径。func ResolveRealPath(path string) (string, error) {absPath, err := filepath.Abs(path)diff --git a/kernel/util/skill.go b/kernel/util/skill.goindex b49a960aad..4b049c6a0d 100644--- a/kernel/util/skill.go+++ b/kernel/util/skill.go@@ -96,7 +96,7 @@ func readSkillRecords(root string) []skillRecord {var records []skillRecordfor _, e := range entries {isDir := e.IsDir()- if !isDir && e.Type()&os.ModeSymlink != 0 {+ if !isDir && IsSymlink(e) {if info, statErr := os.Stat(filepath.Join(root, e.Name())); statErr == nil {isDir = info.IsDir()}@@ -303,7 +303,7 @@ func hasWindowsDrivePrefix(resource string) bool {}func listSkillResources(skillDir string) (resources []string, truncated bool) {- realRoot, err := filepath.EvalSymlinks(skillDir)+ realRoot, err := ResolveRealPath(skillDir)if err != nil {return nil, false}@@ -356,13 +356,13 @@ func listSkillResources(skillDir string) (resources []string, truncated bool) {}func readSkillResource(skillDir, skillName, resource string) (string, error) {- realRoot, err := filepath.EvalSymlinks(skillDir)+ realRoot, err := ResolveRealPath(skillDir)if err != nil {return "", fmt.Errorf("skill not found: %s", skillName)}target := filepath.Join(realRoot, filepath.FromSlash(resource))- realTarget, err := filepath.EvalSymlinks(target)+ realTarget, err := ResolveRealPath(target)if err != nil {return "", fmt.Errorf("skill resource not found: %s/%s", skillName, resource)}diff --git a/kernel/util/working.go b/kernel/util/working.goindex 378ab55928..7f15d3871c 100644--- a/kernel/util/working.go+++ b/kernel/util/working.go@@ -594,9 +594,9 @@ func initMime() {func GetDataAssetsAbsPath() (ret string) {ret = filepath.Join(DataDir, "assets")if IsSymlinkPath(ret) {- // 跟随符号链接 https://github.com/siyuan-note/siyuan/issues/5480+ // 跟随资源目录的符号链接和目录联接。var err error- ret, err = filepath.EvalSymlinks(ret)+ ret, err = ResolveRealPath(ret)if err != nil {logging.LogErrorf("read assets link failed: %s", err)}diff --git a/kernel/util/workspace_storage.go b/kernel/util/workspace_storage.goindex ea72478a89..4a63fbb845 100644--- a/kernel/util/workspace_storage.go+++ b/kernel/util/workspace_storage.go@@ -73,7 +73,7 @@ func measureWorkspaceStorage(ctx context.Context, workspacePath string, walk fun}}()ret = WorkspaceStorage{Directories: map[string]int64{"data": 0, "repo": 0, "history": 0, "temp": 0, "conf": 0, "other": 0}}- root, err := filepath.EvalSymlinks(workspacePath)+ root, err := ResolveRealPath(workspacePath)if err != nil {return WorkspaceStorage{}, err}@@ -107,7 +107,7 @@ func measureWorkspaceStorage(ctx context.Context, workspacePath string, walk fun}return err}- if info.Mode()&fs.ModeSymlink != 0 {+ if isLinkFileInfo(info) {if entry.IsDir() {return fs.SkipDir}