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: Bind .sy ciphertext AAD to stable base name instead of relative path so in-box moves no longer corrupt ciphertext https://github.com/siyuan-note/siyuan/issues/18034
Daniel53be171275d3
diff --git a/kernel/filesys/crypto_hook.go b/kernel/filesys/crypto_hook.goindex 20f931f215..25a1537e71 100644--- a/kernel/filesys/crypto_hook.go+++ b/kernel/filesys/crypto_hook.go@@ -17,6 +17,7 @@package filesysimport (+ "fmt""path/filepath""strings"@@ -35,15 +36,53 @@ var DEKProvider func(boxID string) ([]byte, error)var DEKLockAcquire func(boxID string)var DEKLockRelease func(boxID string)-// normalizeRelPath 标准化 box 内相对路径用于 AAD:去掉前导 /、统一为正斜杠。-func normalizeRelPath(p string) string {- p = filepath.ToSlash(p)+// SyObjectBase 从 box 内相对路径提取稳定文件基名并校验合法性。+// 接受形如 <rootID>.sy 的基名:扩展名必须是 .sy,且 stem 是合法节点 ID。+// 非法扩展名或非节点 ID 模式返回错误,避免把任意路径当 AAD 绑定物产生不可解密的数据。+// 由 filesys、model 历史查看/回滚、import 等所有 .sy 加解密路径共同使用,保证 AAD 一致。+func SyObjectBase(relativePath string) (string, error) {+ p := filepath.ToSlash(relativePath)p = strings.TrimPrefix(p, "/")- return p+ base := p+ if idx := strings.LastIndex(p, "/"); idx >= 0 {+ base = p[idx+1:]+ }+ if !strings.HasSuffix(base, ".sy") {+ return "", fmt.Errorf("invalid .sy base name [%s]: must end with .sy", base)+ }+ stem := strings.TrimSuffix(base, ".sy")+ if !ast.IsNodeIDPattern(stem) {+ return "", fmt.Errorf("invalid .sy base name [%s]: stem is not a node ID", base)+ }+ return base, nil+}++// SyAAD 构造 .sy 密文的 AAD:siyuan:v1:file:<boxID>:<稳定文件基名>。+// 父目录不进 AAD——同 box 内文件名不变的移动允许原样 Rename 密文,内容/box/类型/对象 ID 仍受认证。+func SyAAD(boxID, relativePath string) (string, error) {+ base, err := SyObjectBase(relativePath)+ if err != nil {+ return "", err+ }+ return "siyuan:v1:file:" + boxID + ":" + base, nil+}++// encryptedBox 判断 boxID 是否为已解锁的加密 box,供 filesys 内部分流(如静默修正禁用)。+// 通过 DEKProvider 探测:返回非 nil dek 即加密且已解锁。+func encryptedBox(boxID string) bool {+ if DEKProvider == nil {+ return false+ }+ if DEKLockAcquire != nil {+ DEKLockAcquire(boxID)+ defer DEKLockRelease(boxID)+ }+ dek, err := DEKProvider(boxID)+ return err == nil && dek != nil}// encryptData 若 boxID 是已解锁的加密 box,用 fileKey(DEK 派生子密钥)加密 data,-// AAD 绑定 boxID + 相对路径;非加密笔记本原样返回;加密但未解锁时返回 error,拒绝写盘(防止明文泄漏)。+// AAD 绑定 boxID + 稳定文件基名(不含父目录);非加密笔记本原样返回;加密但未解锁时返回 error,拒绝写盘(防止明文泄漏)。func encryptData(boxID, relativePath string, data []byte) ([]byte, error) {if DEKProvider == nil {return data, nil@@ -60,7 +99,10 @@ func encryptData(boxID, relativePath string, data []byte) ([]byte, error) {return data, nil // 非加密 box}fileKey := util.DeriveSubKey(dek, "siyuan/file")- aad := "siyuan:v1:file:" + boxID + ":" + normalizeRelPath(relativePath)+ aad, err := SyAAD(boxID, relativePath)+ if err != nil {+ return nil, err+ }return util.EncryptWithAAD(fileKey, data, []byte(aad))}@@ -81,7 +123,10 @@ func decryptData(boxID, relativePath string, data []byte) ([]byte, error) {return data, nil // 非加密 box}fileKey := util.DeriveSubKey(dek, "siyuan/file")- aad := "siyuan:v1:file:" + boxID + ":" + normalizeRelPath(relativePath)+ aad, err := SyAAD(boxID, relativePath)+ if err != nil {+ return nil, err+ }return util.DecryptWithAAD(fileKey, data, []byte(aad))}diff --git a/kernel/filesys/crypto_hook_test.go b/kernel/filesys/crypto_hook_test.gonew file mode 100644index 0000000000..c11e7bf254--- /dev/null+++ b/kernel/filesys/crypto_hook_test.go@@ -0,0 +1,102 @@+// 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 filesys++import (+ "strings"+ "testing"+)++// TestSyObjectBase 校验稳定文件基名的提取与合法性。+// .sy 的 AAD 绑定 <rootID>.sy,父目录不参与,因此提取器必须正确剥离目录前缀并严格校验。+func TestSyObjectBase(t *testing.T) {+ validBase := "20240101120000-1a2b3c4.sy"++ cases := []struct {+ name string+ input string+ want string+ wantErr bool+ }{+ {"bare valid", validBase, validBase, false},+ {"leading slash", "/20240101120000-1a2b3c4.sy", validBase, false},+ {"with parent dir", "/20240101120000-aaa/20240101120000-1a2b3c4.sy", validBase, false},+ {"deep parent dir", "20240101120000-aaa/20240101120000-bbb/20240101120000-1a2b3c4.sy", validBase, false},+ {"windows backslash", "\\20240101120000-aaa\\20240101120000-1a2b3c4.sy", validBase, false},+ {"non-sy extension", "/20240101120000-1a2b3c4.json", "", true},+ {"no extension", "/20240101120000-1a2b3c4", "", true},+ {"bad stem not node id", "/notanid.sy", "", true},+ {"stem too short", "/2024010-abc.sy", "", true},+ {"empty", "", "", true},+ }+ for _, c := range cases {+ t.Run(c.name, func(t *testing.T) {+ got, err := SyObjectBase(c.input)+ if c.wantErr {+ if err == nil {+ t.Fatalf("expected error for input %q, got %q", c.input, got)+ }+ return+ }+ if err != nil {+ t.Fatalf("unexpected error for input %q: %v", c.input, err)+ }+ if got != c.want {+ t.Fatalf("SyObjectBase(%q) = %q, want %q", c.input, got, c.want)+ }+ })+ }+}++// TestSyAADIndependentOfParentDir 校验 AAD 只依赖稳定文件基名,不依赖父目录。+// 这是「同 box 内文件名不变的移动可原样 Rename 密文」的密码学前提:+// 同一基名、不同父目录构造出的 AAD 必须完全相同。+func TestSyAADIndependentOfParentDir(t *testing.T) {+ boxID := "20240101120000-boxid01"+ base := "20240101120000-1a2b3c4.sy"++ aadBare, err := SyAAD(boxID, base)+ if err != nil {+ t.Fatal(err)+ }+ aadWithDir, err := SyAAD(boxID, "/20240101120000-parent/"+base)+ if err != nil {+ t.Fatal(err)+ }+ aadDeepDir, err := SyAAD(boxID, "20240101120000-a/20240101120000-b/"+base)+ if err != nil {+ t.Fatal(err)+ }++ if aadBare != aadWithDir || aadBare != aadDeepDir {+ t.Fatalf("AAD must be independent of parent dir: bare=%q dir=%q deep=%q", aadBare, aadWithDir, aadDeepDir)+ }+ // AAD 不应包含目录分隔符,只含基名+ if strings.Contains(strings.TrimPrefix(aadBare, "siyuan:v1:file:"+boxID+":"), "/") {+ t.Fatalf("AAD must not contain path separator: %q", aadBare)+ }+}++// TestSyAADRejectsInvalidBase 校验非法基名直接报错,不产生可用于加密的 AAD。+func TestSyAADRejectsInvalidBase(t *testing.T) {+ if _, err := SyAAD("20240101120000-boxid01", "random.txt"); err == nil {+ t.Fatal("should reject non-.sy base")+ }+ if _, err := SyAAD("20240101120000-boxid01", "notanid.sy"); err == nil {+ t.Fatal("should reject non-node-id stem")+ }+}diff --git a/kernel/filesys/tree.go b/kernel/filesys/tree.goindex 5ba2c7b7fd..5f4fc24337 100644--- a/kernel/filesys/tree.go+++ b/kernel/filesys/tree.go@@ -522,6 +522,13 @@ func fixTreeJSONData(boxID, p string, jsonData []byte, luteEngine *lute.Lute) (d}if pathID := util.GetTreeID(p); pathID != ret.Root.ID {+ if encryptedBox(boxID) {+ // 加密 .sy:基名 ID(pathID)必须与解密后的根块 ID 一致。不一致说明密文被替换、+ // 文件名被篡改或 AAD 认证被绕过,不得静默修正——fail-closed,符合加密笔记本威胁模型。+ err = fmt.Errorf("encrypted .sy [%s]: base id [%s] != root id [%s]", p, pathID, ret.Root.ID)+ logging.LogErrorf("%s", err)+ return+ }needFix = truelogging.LogInfof("reset tree id from [%s] to [%s]", ret.Root.ID, pathID)ret.Root.ID = pathIDdiff --git a/kernel/model/crypto.go b/kernel/model/crypto.goindex 7ad7dd9be6..ea1972a3c2 100644--- a/kernel/model/crypto.go+++ b/kernel/model/crypto.go@@ -38,6 +38,7 @@ import ("github.com/siyuan-note/logging""github.com/siyuan-note/siyuan/kernel/cache""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"@@ -1417,28 +1418,25 @@ func ExtractBoxIDFromHistoryPath(absPath string) string {return boxID}-// copyAssetDecryptIfEncrypted 把 srcPath 的 asset 复制到 destPath。-// 若 srcPath 在已解锁的加密笔记本下,读密文→解密→写明文到 destPath(导出目录);-// 否则走 filelock.Copy 原路径(字节级复制,密文/明文均可)。-// normalizeRelPath 标准化 box 内相对路径用于 AAD:去掉前导 /、统一为正斜杠。-func normalizeRelPath(p string) string {- p = filepath.ToSlash(p)- p = strings.TrimPrefix(p, "/")- return p-}--// EncryptFile 用 fileKey(DEK 派生子密钥)加密 .sy 文档字节,AAD 绑定 boxID + 相对路径。-// relativePath 在构造 AAD 前会标准化(去前导 /、统一斜杠),与 filesys.encryptData/decryptData 保持一致。+// EncryptFile 用 fileKey(DEK 派生子密钥)加密 .sy 文档字节,AAD 绑定 boxID + 稳定文件基名(不含父目录)。+// relativePath 会先经 filesys.SyAAD 提取稳定文件基名(<rootID>.sy)并校验合法性,+// 与 filesys.encryptData/decryptData 共用同一 AAD 构造入口,保证加解密一致。func EncryptFile(boxID, relativePath string, dek, plaintext []byte) ([]byte, error) {fileKey := util.DeriveSubKey(dek, "siyuan/file")- aad := "siyuan:v1:file:" + boxID + ":" + normalizeRelPath(relativePath)+ aad, err := filesys.SyAAD(boxID, relativePath)+ if err != nil {+ return nil, err+ }return util.EncryptWithAAD(fileKey, plaintext, []byte(aad))}// DecryptFile 对应解密。func DecryptFile(boxID, relativePath string, dek, ciphertext []byte) ([]byte, error) {fileKey := util.DeriveSubKey(dek, "siyuan/file")- aad := "siyuan:v1:file:" + boxID + ":" + normalizeRelPath(relativePath)+ aad, err := filesys.SyAAD(boxID, relativePath)+ if err != nil {+ return nil, err+ }return util.DecryptWithAAD(fileKey, ciphertext, []byte(aad))}@@ -1512,6 +1510,9 @@ func readNotebookCryptBackup(boxID string) (*conf.BoxEncryption, error) {return &crypt, nil}+// copyAssetDecryptIfEncrypted 把 srcPath 的 asset 复制到 destPath。+// 若 srcPath 在已解锁的加密笔记本下,读密文→解密→写明文到 destPath(导出目录);+// 否则走 filelock.Copy 原路径(字节级复制,密文/明文均可)。func copyAssetDecryptIfEncrypted(srcPath, destPath string) error {boxID := ExtractBoxIDFromAssetsPath(srcPath)if boxID != "" && IsEncryptedBox(boxID) {diff --git a/kernel/model/crypto_test.go b/kernel/model/crypto_test.goindex 42535e3175..838143a99b 100644--- a/kernel/model/crypto_test.go+++ b/kernel/model/crypto_test.go@@ -485,3 +485,72 @@ func TestLockBoxClearsTempDirs(t *testing.T) {}}}++// TestEncryptFileAADBoundToBaseNameNotPath 验证 .sy 密文 AAD 绑定稳定文件基名而非父目录。+// 同一基名、不同父目录加密出的密文,可用任一父目录路径解密;基名变化或 box 变化则解密失败。+// 这是同 box 内移动文档可原样 Rename 密文(不重新封装)的密码学保证。+func TestEncryptFileAADBoundToBaseNameNotPath(t *testing.T) {+ boxID := "20240101120000-boxaaaaa"+ dek, _ := util.GenerateDEK()+ base := "20240101120000-1a2b3c4.sy"+ plain := []byte(`{"ID":"20240101120000-1a2b3c4","Properties":{"title":"doc"}}`)++ // 用父目录 A 加密+ ct, err := EncryptFile(boxID, "/20240101120000-parentA/"+base, dek, plain)+ if err != nil {+ t.Fatalf("EncryptFile failed: %v", err)+ }++ // 用父目录 B(及裸基名)解密:必须成功——AAD 只绑基名+ if got, err := DecryptFile(boxID, "/20240101120000-parentB/"+base, dek, ct); err != nil {+ t.Fatalf("decrypt with different parent dir should succeed: %v", err)+ } else if string(got) != string(plain) {+ t.Fatalf("decrypted content mismatch")+ }+ if got, err := DecryptFile(boxID, base, dek, ct); err != nil {+ t.Fatalf("decrypt with bare base name should succeed: %v", err)+ } else if string(got) != string(plain) {+ t.Fatalf("decrypted content mismatch")+ }++ // 用不同基名解密:必须失败——AAD 绑定基名+ otherBase := "20240101120000-zzzzzzz.sy"+ if _, err := DecryptFile(boxID, otherBase, dek, ct); err == nil {+ t.Fatal("decrypt with different base name must fail")+ }++ // 用不同 boxID 解密:必须失败——AAD 绑定 boxID+ otherBox := "20240101120000-otherbox"+ if _, err := DecryptFile(otherBox, base, dek, ct); err == nil {+ t.Fatal("decrypt with different boxID must fail")+ }+}++// TestEncryptFileRejectsInvalidBaseName 验证非法基名(非 .sy、非节点 ID)直接拒绝加密,+// 不产生可用于落盘的密文,避免把任意路径当 AAD 绑定物。+func TestEncryptFileRejectsInvalidBaseName(t *testing.T) {+ boxID := "20240101120000-boxaaaaa"+ dek, _ := util.GenerateDEK()+ plain := []byte("test")++ if _, err := EncryptFile(boxID, "/dir/random.txt", dek, plain); err == nil {+ t.Fatal("should reject non-.sy extension")+ }+ if _, err := EncryptFile(boxID, "/dir/notanid.sy", dek, plain); err == nil {+ t.Fatal("should reject non-node-id stem")+ }+}++// TestDecryptFileRejectsInvalidBaseName 验证解密路径同样拒绝非法基名。+func TestDecryptFileRejectsInvalidBaseName(t *testing.T) {+ boxID := "20240101120000-boxaaaaa"+ dek, _ := util.GenerateDEK()+ ct := []byte("ciphertext-bytes")++ if _, err := DecryptFile(boxID, "/dir/random.txt", dek, ct); err == nil {+ t.Fatal("should reject non-.sy extension on decrypt")+ }+ if _, err := DecryptFile(boxID, "/dir/notanid.sy", dek, ct); err == nil {+ t.Fatal("should reject non-node-id stem on decrypt")+ }+}