Skip to content

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

:white_check_mark: Make kernel path fixtures independent of temporary directory settings https://github.com/siyuan-note/siyuan/issues/19480

Danielca2df7086eca
diff --git a/.github/workflows/api-contracts.yml b/.github/workflows/api-contracts.yml
index 28403fb92a..e3c8f12a0f 100644
--- a/.github/workflows/api-contracts.yml
+++ b/.github/workflows/api-contracts.yml
@@ -42,8 +42,12 @@ jobs:
- name: Test all kernel packages
run: go test -tags "fts5 sqlcipher" ./... -count=1
working-directory: kernel
+ - name: Test path fixtures with custom temporary directories
+ run: go test -tags "fts5 sqlcipher" ./internal/testutil ./util ./model ./server -run 'Test(PublicDataDir|IsSensitivePath|.*Obsidian|RegisterStaticFileHandlers|StaticFile|WidgetResponseCacheControl|TemplatesAndExportRequireAdministrator|SnippetPublishAccess|PluginPublishAccess)' -count=1
+ working-directory: kernel
env:
- TMPDIR: ${{ runner.temp }}
+ TMPDIR: /tmp
+ GOTMPDIR: ${{ runner.temp }}
frontend-tests:
runs-on: windows-latest
diff --git a/docs/API-CONTRACTS.md b/docs/API-CONTRACTS.md
index 337784a628..05bd49dc8c 100644
--- a/docs/API-CONTRACTS.md
+++ b/docs/API-CONTRACTS.md
@@ -163,6 +163,6 @@ go test -tags "fts5 sqlcipher" ./... -count=1
`tsconfig.api.json` separately enables strict checks and declaration-file checking for invalid parameters, misspelled fields, required bodies, success and failure branches, nullability, and method mismatches. The main application retains its existing configuration; do not assume strict null checks apply to every call. Handler tests use temporary workspaces and isolated test processes without starting or restarting the running kernel.
-On Linux, set `TMPDIR` to an existing directory under your home directory before running the full kernel suite. Import and static-file fixtures represent ordinary user data, while `/tmp` outside the workspace is intentionally rejected by the sensitive-path guard. CI uses `${{ runner.temp }}` for this purpose.
+Import and static-file fixtures use `internal/testutil.PublicDataDir` to create and clean up explicitly validated non-sensitive directories independently of `TMPDIR` and `GOTMPDIR`. The helper tries the user home, current directory, and filesystem root, and reports a fixture setup failure if none is safe and writable. CI also reruns the affected path tests with `/tmp` as `TMPDIR` and a separate `GOTMPDIR` to cover environment overrides.
CI runs all kernel packages on Linux and all frontend, Electron, and packaging-script tests on Windows. Frontend discovery is restricted to `src/**/*.test.ts`, `tests/**/*.test.js`, `electron/**/*.test.js`, and `scripts/**/*.test.js`, so packaged copies under `app/build` are excluded. Test files run serially to avoid Electron process startup contention. New regression tests in these locations are included automatically; update the test command and this document when adding a new test location or filename convention. Keep `Contract` in Go contract regression test names so they remain easy to run separately.
diff --git a/kernel/internal/testutil/path.go b/kernel/internal/testutil/path.go
new file mode 100644
index 0000000000..a37db32e5b
--- /dev/null
+++ b/kernel/internal/testutil/path.go
@@ -0,0 +1,50 @@
+// 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.
+
+package testutil
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+// PublicDataDir 创建不受系统敏感目录限制的独立夹具,并在测试结束后清理。
+// 显式选择父目录,避免 TMPDIR 和 GOTMPDIR 改变普通用户数据的安全属性。
+func PublicDataDir(t testing.TB) string {
+ t.Helper()
+ home, _ := os.UserHomeDir()
+ cwd, _ := os.Getwd()
+ parents := []string{home, cwd, filepath.VolumeName(cwd) + string(filepath.Separator)}
+ for _, parent := range parents {
+ if parent == "" {
+ continue
+ }
+ resolved, err := filepath.EvalSymlinks(parent)
+ if err != nil || util.IsSensitivePath(filepath.Join(resolved, "siyuan-test-data")) {
+ continue
+ }
+ dir, err := os.MkdirTemp(resolved, "siyuan-test-data-")
+ if err != nil {
+ continue
+ }
+ t.Cleanup(func() {
+ if err := os.RemoveAll(dir); err != nil {
+ t.Errorf("remove public data fixture %q: %v", dir, err)
+ }
+ })
+ if util.IsSensitivePath(dir) {
+ t.Fatalf("public data fixture is sensitive: %q", dir)
+ }
+ return dir
+ }
+ t.Fatalf("cannot create a non-sensitive public data fixture under any of %q", parents)
+ return ""
+}
diff --git a/kernel/internal/testutil/path_test.go b/kernel/internal/testutil/path_test.go
new file mode 100644
index 0000000000..a5f7dbe224
--- /dev/null
+++ b/kernel/internal/testutil/path_test.go
@@ -0,0 +1,40 @@
+// 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.
+
+package testutil
+
+import (
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestPublicDataDirIgnoresAmbientTemp(t *testing.T) {
+ ambient := t.TempDir()
+ for _, goTemp := range []string{"", ambient} {
+ t.Run("GOTMPDIR="+goTemp, func(t *testing.T) {
+ t.Setenv("TMPDIR", ambient)
+ t.Setenv("GOTMPDIR", goTemp)
+ var dir string
+ t.Run("fixture", func(t *testing.T) {
+ dir = PublicDataDir(t)
+ if filepath.Dir(dir) == ambient || util.IsSensitivePath(dir) {
+ t.Fatalf("fixture depends on ambient temporary directory: %q", dir)
+ }
+ if err := os.WriteFile(filepath.Join(dir, "note.md"), []byte("note"), 0600); err != nil {
+ t.Fatal(err)
+ }
+ })
+ if _, err := os.Stat(dir); !os.IsNotExist(err) {
+ t.Fatalf("fixture was not cleaned up: %q, %v", dir, err)
+ }
+ })
+ }
+}
diff --git a/kernel/model/import_obsidian_test.go b/kernel/model/import_obsidian_test.go
index 70cb6e1744..0430ad6d93 100644
--- a/kernel/model/import_obsidian_test.go
+++ b/kernel/model/import_obsidian_test.go
@@ -19,11 +19,22 @@ import (
"testing"
"github.com/88250/lute/ast"
+ "github.com/siyuan-note/siyuan/kernel/internal/testutil"
"github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
)
+// newObsidianTestDir 隔离工作空间,确保外部 Vault 夹具不依赖进程的当前目录。
+func newObsidianTestDir(t *testing.T) string {
+ t.Helper()
+ originalWorkspace := util.WorkspaceDir
+ util.WorkspaceDir = t.TempDir()
+ t.Cleanup(func() { util.WorkspaceDir = originalWorkspace })
+ return testutil.PublicDataDir(t)
+}
+
func TestAnalyzeObsidianVault(t *testing.T) {
- root := t.TempDir()
+ root := newObsidianTestDir(t)
if err := os.Mkdir(filepath.Join(root, ".obsidian"), 0755); err != nil {
t.Fatal(err)
}
@@ -53,7 +64,7 @@ func TestAnalyzeObsidianVault(t *testing.T) {
}
func TestRevalidateObsidianVaultDetectsAttachmentListChanges(t *testing.T) {
- root := t.TempDir()
+ root := newObsidianTestDir(t)
if err := os.Mkdir(filepath.Join(root, ".obsidian"), 0755); err != nil {
t.Fatal(err)
}
@@ -79,7 +90,7 @@ func TestRevalidateObsidianVaultDetectsAttachmentListChanges(t *testing.T) {
}
func TestObsidianVaultValidationErrors(t *testing.T) {
- notDirectory := filepath.Join(t.TempDir(), "vault.md")
+ notDirectory := filepath.Join(newObsidianTestDir(t), "vault.md")
if err := os.WriteFile(notDirectory, []byte("content"), 0644); err != nil {
t.Fatal(err)
}
@@ -87,12 +98,12 @@ func TestObsidianVaultValidationErrors(t *testing.T) {
t.Fatalf("unexpected non-directory error: %v", err)
}
- missingConfig := t.TempDir()
+ missingConfig := newObsidianTestDir(t)
if _, err := validateObsidianVaultRoot(missingConfig); !errors.Is(err, errObsidianVaultConfigMissing) || obsidianVaultErrorLanguage(err) != 339 {
t.Fatalf("unexpected missing config error: %v", err)
}
- missingMarkdown := t.TempDir()
+ missingMarkdown := newObsidianTestDir(t)
if err := os.Mkdir(filepath.Join(missingMarkdown, ".obsidian"), 0755); err != nil {
t.Fatal(err)
}
@@ -103,7 +114,7 @@ func TestObsidianVaultValidationErrors(t *testing.T) {
}
func TestAnalyzeObsidianVaultReportsMarkdownEncodingPath(t *testing.T) {
- root := t.TempDir()
+ root := newObsidianTestDir(t)
if err := os.Mkdir(filepath.Join(root, ".obsidian"), 0755); err != nil {
t.Fatal(err)
}
@@ -303,7 +314,7 @@ func TestResolveObsidianSubdirectoryPaths(t *testing.T) {
}
func TestImportObsidianRelativeSubdirectoryLinks(t *testing.T) {
- root := t.TempDir()
+ root := newObsidianTestDir(t)
source := "![[Note-assets/image.png]]\n\n[[Sub/Target]]\n\n![[Sub/Target]]\n\n![image](Note-assets/image.png)\n\n[Target](Sub/Target.md)\n"
for name, content := range map[string]string{
"Folder/Current.md": source,
@@ -587,7 +598,7 @@ func TestParseObsidianCalloutAndCustomTaskMarker(t *testing.T) {
}
func TestStartObsidianVaultAnalysisReplacesPreImportTask(t *testing.T) {
- root := t.TempDir()
+ root := newObsidianTestDir(t)
if err := os.Mkdir(filepath.Join(root, ".obsidian"), 0755); err != nil {
t.Fatal(err)
}
diff --git a/kernel/server/serve_static_test.go b/kernel/server/serve_static_test.go
index 6e7d8e4638..5dd62bec3e 100644
--- a/kernel/server/serve_static_test.go
+++ b/kernel/server/serve_static_test.go
@@ -30,6 +30,7 @@ import (
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/internal/testutil"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/util"
)
@@ -48,7 +49,7 @@ func TestCleanStaticRelativePath(t *testing.T) {
func TestRegisterStaticFileHandlers(t *testing.T) {
gin.SetMode(gin.TestMode)
- root := t.TempDir()
+ root := testutil.PublicDataDir(t)
if err := os.MkdirAll(filepath.Join(root, "package"), 0755); err != nil {
t.Fatal(err)
}
@@ -166,7 +167,7 @@ func TestGzipMiddlewareImages(t *testing.T) {
func TestStaticFileNestedSymlinkEscape(t *testing.T) {
gin.SetMode(gin.TestMode)
- root, outside := t.TempDir(), t.TempDir()
+ root, outside := testutil.PublicDataDir(t), testutil.PublicDataDir(t)
packagePath := filepath.Join(root, "package")
if err := os.MkdirAll(packagePath, 0755); err != nil {
t.Fatal(err)
@@ -263,7 +264,7 @@ func TestStaticFileSymlinkWorkspace(t *testing.T) {
func TestWidgetResponseCacheControl(t *testing.T) {
gin.SetMode(gin.TestMode)
originalDataDir, originalConf := util.DataDir, model.Conf
- util.DataDir = t.TempDir()
+ util.DataDir = testutil.PublicDataDir(t)
model.Conf = model.NewAppConf()
t.Cleanup(func() {
util.DataDir = originalDataDir
@@ -387,7 +388,7 @@ func TestThemeResponseDisablesCache(t *testing.T) {
func TestTemplatesAndExportRequireAdministrator(t *testing.T) {
gin.SetMode(gin.TestMode)
originalDataDir, originalTempDir := util.DataDir, util.TempDir
- util.DataDir, util.TempDir = t.TempDir(), t.TempDir()
+ util.DataDir, util.TempDir = testutil.PublicDataDir(t), testutil.PublicDataDir(t)
t.Cleanup(func() {
util.DataDir, util.TempDir = originalDataDir, originalTempDir
})
@@ -436,7 +437,7 @@ func TestTemplatesAndExportRequireAdministrator(t *testing.T) {
func TestSnippetPublishAccess(t *testing.T) {
gin.SetMode(gin.TestMode)
originalSnippetsPath := util.SnippetsPath
- util.SnippetsPath = t.TempDir()
+ util.SnippetsPath = testutil.PublicDataDir(t)
t.Cleanup(func() {
util.SnippetsPath = originalSnippetsPath
})
@@ -482,7 +483,7 @@ func TestPluginPublishAccess(t *testing.T) {
gin.SetMode(gin.TestMode)
originalDataDir := util.DataDir
originalConf := model.Conf
- util.DataDir = t.TempDir()
+ util.DataDir = testutil.PublicDataDir(t)
model.Conf = model.NewAppConf()
model.Conf.Bazaar = &conf.Bazaar{Trust: true}
t.Cleanup(func() {
diff --git a/kernel/util/path_test.go b/kernel/util/path_test.go
index eb0ce9947e..06ab9c6097 100644
--- a/kernel/util/path_test.go
+++ b/kernel/util/path_test.go
@@ -172,10 +172,6 @@ func TestIsSensitivePathWorkspaceFilesNotBlocked(t *testing.T) {
// TestIsSensitivePathSymlinkWorkspace 验证工作空间父目录为符号链接时的真实路径判定。
func TestIsSensitivePathSymlinkWorkspace(t *testing.T) {
- if filepath.Separator == '/' {
- // 该用例需要系统敏感目录作为父目录,确保工作空间前缀相同的相邻目录仍被拦截。
- t.Setenv("TMPDIR", "/var/tmp")
- }
realHome, err := filepath.EvalSymlinks(t.TempDir())
if err != nil {
t.Fatal(err)
@@ -220,10 +216,23 @@ func TestIsSensitivePathSymlinkWorkspace(t *testing.T) {
if p := filepath.Join(realHome, ".ssh", "id_rsa"); !IsSensitivePath(p) {
t.Errorf("external credential should be sensitive: %s", p)
}
- if filepath.Separator == '/' {
- // Linux 临时目录同样命中系统目录黑名单,可覆盖 /var/home 场景且不写入系统家目录。
- if !isSensitivePath(filepath.Join(realWorkspace+"-outside", "public.txt")) {
- t.Fatal("workspace prefix sibling should remain sensitive")
+}
+
+// TestIsSensitivePathWorkspacePrefixBoundary 显式覆盖敏感父目录下的工作空间路径边界。
+func TestIsSensitivePathWorkspacePrefixBoundary(t *testing.T) {
+ parents := []string{"/tmp", "/var/home"}
+ if filepath.Separator == '\\' {
+ parents = []string{`C:\Windows\System32`}
+ }
+ originalWorkspace := WorkspaceDir
+ t.Cleanup(func() { WorkspaceDir = originalWorkspace })
+ for _, parent := range parents {
+ WorkspaceDir = filepath.Join(parent, "siyuan-test-workspace")
+ if isSensitivePath(filepath.Join(WorkspaceDir, "data", "public.txt")) {
+ t.Fatalf("workspace data should be allowed: %s", WorkspaceDir)
+ }
+ if !isSensitivePath(filepath.Join(WorkspaceDir+"-outside", "public.txt")) {
+ t.Fatalf("workspace prefix sibling should remain sensitive: %s", WorkspaceDir)
}
}
}