Skip to content

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

:bug: Harden encrypted notebook access and recovery https://github.com/siyuan-note/siyuan/issues/18034

Daniela1e49bae7788
diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
index 8c56b3baf7..e01654bf3b 100644
--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
@@ -94,7 +94,7 @@
MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2id 派生 KEK,KEK 再解开各笔记本的 WrappedDEK。**MasterSalt 丢失等于数据永久锁死**:即使输入相同主密码,因 salt 变化派生出的 KEK 不同,旧 WrappedDEK 无法解开。为此引入备份与恢复机制。
-**备份**:`<DataDir>/.siyuan/data-crypto-backup.json`,保存整套 NotebookCrypto(MasterSalt/KEKVerifier/KDFParams)。位于 DataDir 内,**进入 dejavu 同步范围**。启用加密笔记本、修改主密码时刷新;只有禁用前确认不存在现存加密笔记本,也不存在依赖该备份的内核可枚举历史或恢复快照,或用户明确选择永久清除这些恢复数据后,才能删除。备份文件按明文 JSON 存储(salt 不保密、verifier 是密文,与 `conf/conf.json` 的存储方式一致)。
+**备份**:`<DataDir>/.siyuan/data-crypto-backup.json`,保存整套 NotebookCrypto(MasterSalt/KEKVerifier/KDFParams/HistoryKEKs)。位于 DataDir 内,**进入 dejavu 同步范围**。启用加密笔记本、修改主密码时刷新;只有禁用前确认不存在现存加密笔记本,也不存在依赖该备份的内核可枚举历史或恢复快照,或用户明确选择永久清除这些恢复数据后,才能删除。备份文件按明文 JSON 存储,其中 verifier 和历史 KEK 均为密文,与 `conf/conf.json` 的存储方式一致。
每个加密笔记本另行保存 `<DataDir>/<boxID>/.siyuan/notebook-crypto-backup.json`,其中包含该笔记本的 BoxEncryption 密钥包络(WrappedDEK/WrapNonce 和认证元数据)。全局 `data-crypto-backup.json` 提供 KEK 派生身份,单笔记本 `notebook-crypto-backup.json` 提供已封装 DEK,两者不能相互替代。
@@ -182,7 +182,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
**assets 加密**:
- 上传时全量读入内存 + 加密 + 写盘(无法流式加密)
- 文件名脱敏:加密笔记本的 asset 文件名为 `<uuid>-<blockID>.<ext>`,原始名、明文大小和分块数量作为认证加密元数据存入同一个资源容器
-- 容器固定以 `SYAE` 标识开头,名称元数据和内容分块分别使用绑定 boxID、磁盘文件名及分块序号的 AAD 认证
+- 容器固定以 `SYAE` 标识开头,认证加密元数据包含 `spec=2`、每次写入由操作系统 CSPRNG 生成的 32 字节 `containerID`、原始名称、明文大小及分块数量;内容分块的 AAD 为 `siyuan:asset:<boxID>:assets/<diskName>:content:v2:<containerID 的小写十六进制>:<从零开始的分块序号>`,名称元数据使用同一前缀加 `:metadata` 认证。不同写入版本的分块或元数据不能互换,整份旧容器回滚仍不在防护范围内
- 读取时先认证并解密名称元数据,再逐块认证解密内容;下载时使用容器中的原始名
- 加密笔记本禁用全局 assets 回退,强制笔记本级
- 资源文件重命名禁止(脱敏磁盘文件名参与 AAD,改名需要重新封装整个资源)
@@ -371,7 +371,7 @@ MasterSalt 是 KEK 派生的全局根基——主密码 + MasterSalt 经 Argon2i
2. **全局密钥与包络元数据**:`NotebookCrypto` 保存 KDF 算法、参数、MasterSalt、verifier 格式、KEK 包络版本和备份 HMAC 版本;`BoxConf.WrappedDEK` 保存每个笔记本的 DEK 包络。它们不随每个数据对象重复保存。
3. **用途隔离**:每个笔记本的 DEK 通过固定域分隔符派生文件内容、资源、数据库定义、content SQLCipher 和 blocktree SQLCipher 子密钥。资源名称元数据与内容分块共用资源子密钥,并通过不同的 AAD 后缀隔离;不要求为每一种对象再派生独立子密钥。KEK 可以直接用于 verifier、DEK 包络和备份 HMAC,这些用途由不同算法、版本化 AAD 或被认证的数据格式隔离;不得把 WrappedDEK 认证错误地归入 DEK 域。
4. **数据库兼容信息**:SQLCipher 版本、cipher 参数和 schema 版本保存在数据库头部可验证位置或对应的加密配置边界,不写入每个数据对象。content 与 blocktree 索引可重建;源密文认证通过后,版本不兼容的索引应关闭并重建,而不是降低 cipher 参数或回退到明文 SQLite。
-5. **改名与格式稳定性**:首个发布格式直接以稳定对象 ID 构造 AAD,不兼容开发阶段按完整逻辑相对路径生成的试验密文,也不提供双格式读取或迁移;开发数据在格式切换后删除并重建。只改变父目录不重新封装内容,稳定文件基名变化时才使用旧基名认证解密并按新基名生成新封装。首个发布版本冻结后,未来再修改信封或 AAD 语义必须提升格式版本并另行设计迁移。
+5. **改名与格式稳定性**:首个发布格式直接以稳定对象 ID 构造 AAD,不兼容开发阶段按完整逻辑相对路径生成的试验密文,以及缺少 `spec=2` 或 `containerID` 的试验资源容器,也不提供双格式读取或迁移;开发数据在格式切换后删除并重建。只改变父目录不重新封装内容,稳定文件基名变化时才使用旧基名认证解密并按新基名生成新封装。首个发布版本冻结后,未来再修改信封或 AAD 语义必须提升格式版本并另行设计迁移。
SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副本都是受保护对象,必须放在受控目录并使用对应的用途密钥。锁定、崩溃恢复和历史快照必须枚举这些伴随文件;未加密 SQLite 页面、查询结果或诊断转储不得写入全局临时目录。
@@ -379,6 +379,8 @@ SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副
`data-crypto-backup.json` 是恢复材料而非秘密。文件带格式版本、备份 ID、创建时间、内容摘要和基于 KEK 的 HMAC;主密码派生 KEK 后,HMAC 缺失或不匹配必须拒绝恢复,不得作为兼容路径放行。恢复不得静默覆盖已启用配置。格式无效或与已有加密笔记本不匹配的备份进入错误状态,而不是生成新的 MasterSalt。
+改密时,现存笔记本的 WrappedDEK 重新包络到新 KEK,同时把历次 KEK 和本次旧 KEK 去重后,以新 KEK 和版本化 AAD `siyuan:history-kek:v1` 分别认证加密,写入 `HistoryKEKs`。该字段受全局备份的摘要和 HMAC 共同保护,并随改密迁移清单恢复;删除最后一个迁移中的笔记本也不得丢弃尚未完成备份切换的历史密钥。恢复和解锁先尝试当前 KEK,再尝试从认证配置解封的历史 KEK,使用结束后清零,不缓存明文 KEK。历史密文目录无需改写,当前备份与当前密码可恢复此前历次改密遗留的包络,包括随后从其他设备或离线快照恢复的目录。
+
备份持久化遵循项目现有文件写入语义:全局 `data-crypto-backup.json` 通过同目录随机临时文件写入后原子替换,每个笔记本的 `notebook-crypto-backup.json` 使用文件锁保护的常规配置写入。两者都不额外承诺断电场景下的文件或目录 `fsync` 持久性;启动时校验无需密钥即可验证的结构和摘要,输入主密码后的恢复再校验 HMAC 以及密钥包络匹配关系。损坏或不匹配时安全拒绝,而不是生成替代密钥材料。
HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明它是最新版本。当前范围不引入可信外部单调计数器,因此一个认证有效的历史备份或历史密文可能通过校验;`BackupID` 和 `CreatedAt` 只是供诊断和人工比较的信息,不是防回滚锚点。同步、历史或恢复流程不得把“认证成功”表述为“最新”或“来源可信”;真正防回滚需要独立可信状态,超出本设计范围。
@@ -417,6 +419,9 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明
| 同一加密笔记本内移动文档,随后清空缓存并重启 | 文件基名不变时密文保持不变并可按稳定对象 ID 认证解密;新父目录按普通笔记本语义生效,旧目录位置不存在,失败处理与普通笔记本一致 |
| 加密笔记本与普通笔记本、两个加密笔记本之间的引用、移动、镜像、资源和数据库操作 | 必须保持孤岛边界;拒绝时不得产生半完成文件、全局索引或关联数据 |
| 资源加密容器写入失败 | 调用方收到错误,不产生独立名称映射或明文临时文件;未完成的目标文件不能作为有效资源读取 |
+| 将同名资源的不同写入版本互换分块或名称元数据 | 内容认证失败;未知版本或缺少容器标识时,名称读取和内容读取均拒绝处理 |
+| 通用归档入口的父目录、压缩包内部路径及符号链接指向加密笔记本 | 打包前检查全部源条目,解压前检查全部目标条目;非法归档不得先写入其他条目,正常归档仍可使用 |
+| 块读取省略 notebook 参数,或批量请求跨多个加密笔记本 | 根据块的实际归属取得所有相关笔记本的响应租约,锁定等到响应写入完成;无法确定归属时拒绝读取,不在后续解锁后无租约返回内容 |
| 删除加密笔记本后保留历史,再尝试禁用或恢复 | 存在密钥依赖时拒绝删除全局配置和备份;使用匹配备份与主密码可恢复,只有明确永久清除恢复数据后才允许解除依赖 |
| 文档生成历史后移动父目录或改变文件基名,再查看或回滚旧历史 | 使用历史条目记录的快照 boxID、对象类型和稳定文件基名认证解密;仅在目标基名变化时重新封装,缺失快照上下文时拒绝操作 |
| 文件、资源、数据库、WAL/SHM、历史、快照和日志的磁盘检查 | 加密笔记本持久化范围内不存在可读正文、资源内容、原始资源名称或 SQLite 明文页;`temp/` 可能在导出期间或清理失败后包含明文 |
@@ -425,7 +430,7 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明
| 加密笔记本的 `conf.json` 与笔记本密钥备份同时缺失,或同步删除当前已打开的加密笔记本 | 密文或运行时身份使前者进入 `Error` 且不生成普通配置;后者先排空在途租约,再清除 DEK、挂载、专属数据库、缓存和索引,不受删除后 `Conf.GetBox` 为空影响 |
| nonce 随机源失败、达到用途密钥调用限制或事后发现 nonce 重用 | 随机源失败或达到限制时在加密前拒绝写入;AES-GCM 认证本身不能发现已发生的 nonce 重用,发现后必须按密钥泄露事件处理并轮换 DEK 后重新加密 |
| 回放认证有效的历史密文或密钥备份 | 可能被识别为有效旧版本,但不得被宣称为最新或来源可信;数据回退风险明确,当前设计不声称提供回滚防护 |
-| 改主密码和 KEK 重新包络 | WrappedDEK 与备份原子更新;更新中断后旧配置仍可恢复使用;旧密码暴露风险提示正确;迁移前后数据与历史均可验证读取 |
+| 改主密码和 KEK 重新包络 | WrappedDEK、历史 KEK 和备份通过可恢复事务更新;连续改密、删除笔记本、备份导入与迁移中断后仍可用当前密码恢复旧包络;旧密码暴露风险提示正确 |
| 多个笔记本并发操作与自动锁定 | 锁顺序无死锁;认证用户界面活动或显式保活统一刷新所有当前已解锁笔记本,后台任务不自动刷新;锁定中的笔记本不再接受新租约 |
## 22. 使用指南
@@ -445,7 +450,7 @@ HMAC 只能证明备份内容未被不知道 KEK 的一方篡改,不能证明
> 重要:加密笔记本在锁定状态下提供最强的应用级保护,但锁定只会尽力清理应用可控的内存和临时数据,不承诺抹除操作系统或底层介质中的所有瞬时副本。解锁期间,获得主应用授权的调用方(API、插件、AI/LLM 含 MCP)能像读普通笔记本一样读到明文;发布服务的读者与匿名访问者以及内核 CLI 始终被拒绝(详见 §12 安全前提)。
### 修改主密码
-进入 **设置 - 鉴权 - 加密笔记本 - 修改主密码**。改密只需重新包络各笔记本的 WrappedDEK,**不重新加密文档数据**,因此即时完成。改密后密钥备份会自动刷新并同步。
+进入 **设置 - 鉴权 - 加密笔记本 - 修改主密码**。改密会重新包络各笔记本的 WrappedDEK,并用新密码保护历史恢复密钥,**不重新加密文档数据**。改密后密钥备份会自动刷新并同步;使用当前备份和当前密码仍可恢复改密前的已删除笔记本历史。
> 重要语义:改密采用 KEK 包络模式——DEK 本身不变,只是用新主密码派生的新 KEK 重新包络 WrappedDEK。这意味着**改密不能吊销旧主密码的解密能力**:如果旧主密码和旧 WrappedDEK(如同步端、备份、历史快照中保留的)同时泄露,仍能解出同一个 DEK,进而解当前数据。如果怀疑旧主密码已泄露,应迁移内容到新建的加密笔记本(新 DEK)而非仅改密。
diff --git a/kernel/api/archive.go b/kernel/api/archive.go
index cdd61baa15..a577c7d14e 100644
--- a/kernel/api/archive.go
+++ b/kernel/api/archive.go
@@ -17,32 +17,72 @@
package api
import (
+ archivezip "archive/zip"
"fmt"
+ "io"
+ "io/fs"
"net/http"
+ "os"
"path/filepath"
+ "strings"
+ "unicode/utf8"
"github.com/88250/gulu"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/logging"
"github.com/siyuan-note/siyuan/kernel/model"
"github.com/siyuan-note/siyuan/kernel/util"
+ "golang.org/x/text/encoding/simplifiedchinese"
)
// rejectEncryptedArchivePath 检查路径是否落入加密笔记本目录(含 symlink 绕过),是则返回错误。
func rejectEncryptedArchivePath(absPath string) error {
- boxID := model.ExtractBoxIDFromAssetsPath(absPath)
- if boxID != "" && model.IsEncryptedBox(boxID) {
+ if boxID := model.EncryptedRawPathBoxID(absPath); boxID != "" {
return fmt.Errorf("path belongs to encrypted notebook [%s]", boxID)
}
- if resolved := util.ResolveLongestExistingParent(absPath); resolved != absPath {
- boxID = model.ExtractBoxIDFromAssetsPath(resolved)
- if boxID != "" && model.IsEncryptedBox(boxID) {
- return fmt.Errorf("symlink resolves into encrypted notebook [%s]", boxID)
+ resolved, err := resolveArchivePath(absPath)
+ if err != nil {
+ return err
+ }
+ dataDir, err := resolveArchivePath(util.DataDir)
+ if err != nil {
+ return err
+ }
+ if rel, relErr := filepath.Rel(dataDir, resolved); relErr == nil && filepath.IsLocal(rel) {
+ if boxID := model.EncryptedRawPathBoxID(filepath.Join(util.DataDir, rel)); boxID != "" {
+ return fmt.Errorf("path belongs to encrypted notebook [%s]", boxID)
}
}
return nil
}
+// resolveArchivePath 解析最长已存在父路径的最终位置,包含 Windows 目录联接;解析失败时拒绝访问。
+func resolveArchivePath(path string) (string, error) {
+ cleaned, err := filepath.Abs(path)
+ if err != nil {
+ return "", err
+ }
+ parent := cleaned
+ for {
+ if _, err = os.Lstat(parent); err == nil {
+ break
+ }
+ if !os.IsNotExist(err) || filepath.Dir(parent) == parent {
+ return "", err
+ }
+ parent = filepath.Dir(parent)
+ }
+ resolved, err := model.ResolveRealPath(parent)
+ if err != nil {
+ return "", err
+ }
+ rel, err := filepath.Rel(parent, cleaned)
+ if err != nil {
+ return "", err
+ }
+ return filepath.Join(resolved, rel), nil
+}
+
func zip(c *gin.Context) {
ret := gulu.Ret.NewResult()
defer c.JSON(http.StatusOK, ret)
@@ -81,6 +121,23 @@ func zip(c *gin.Context) {
ret.Msg = err.Error()
return
}
+ // 在创建归档前检查全部源条目,避免通过父目录打包加密笔记本。
+ resolvedEntryPath, err := resolveArchivePath(entryAbsPath)
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+ if err = filepath.WalkDir(resolvedEntryPath, func(path string, _ fs.DirEntry, walkErr error) error {
+ if walkErr != nil {
+ return walkErr
+ }
+ return rejectEncryptedArchivePath(path)
+ }); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
zipFile, err := gulu.Zip.Create(zipAbsFilePath)
if err != nil {
@@ -156,10 +213,94 @@ func unzip(c *gin.Context) {
return
}
- if err := gulu.Zip.Unzip(zipAbsFilePath, entryAbsPath); err != nil {
+ if err := unzipWorkspaceArchive(zipAbsFilePath, entryAbsPath); err != nil {
logging.LogErrorf("unzip [%s] -> [%s] failed: %s", zipAbsFilePath, entryAbsPath, err)
ret.Code = -1
ret.Msg = "unzip failed" + errMsgSeeKernelLog
return
}
}
+
+// unzipWorkspaceArchive 先校验全部条目,阻止已知非法路径导致部分写入,再从同一个归档句柄解压。
+func unzipWorkspaceArchive(zipPath, destination string) error {
+ reader, err := archivezip.OpenReader(zipPath)
+ if err != nil {
+ return err
+ }
+ defer reader.Close()
+
+ paths := make([]string, len(reader.File))
+ for i, entry := range reader.File {
+ name := entry.Name
+ if !utf8.ValidString(name) {
+ if name, err = simplifiedchinese.GB18030.NewDecoder().String(name); err != nil {
+ return err
+ }
+ }
+ name = strings.ReplaceAll(name, "\\", "/")
+ if !filepath.IsLocal(filepath.FromSlash(name)) || entry.Mode()&os.ModeSymlink != 0 {
+ return fmt.Errorf("invalid archive entry [%s]", name)
+ }
+ paths[i] = filepath.Join(destination, filepath.FromSlash(name))
+ if err = validateArchiveEntryPath(destination, paths[i]); err != nil {
+ return err
+ }
+ }
+ for i, entry := range reader.File {
+ // 解压前再次检查已有符号链接和加密身份,不复用预检阶段的路径判定结果。
+ if err = validateArchiveEntryPath(destination, paths[i]); err != nil {
+ return err
+ }
+ if err = extractWorkspaceArchiveEntry(entry, paths[i]); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+func validateArchiveEntryPath(destination, entryPath string) error {
+ rel, err := filepath.Rel(destination, entryPath)
+ if err != nil || !filepath.IsLocal(rel) {
+ return fmt.Errorf("invalid archive entry path [%s]", entryPath)
+ }
+ resolved, err := resolveArchivePath(entryPath)
+ if err != nil {
+ return err
+ }
+ resolvedDestination, err := resolveArchivePath(destination)
+ if err != nil {
+ return err
+ }
+ rel, err = filepath.Rel(resolvedDestination, resolved)
+ if err != nil || !filepath.IsLocal(rel) {
+ return fmt.Errorf("archive entry resolves outside destination [%s]", entryPath)
+ }
+ return rejectEncryptedArchivePath(entryPath)
+}
+
+func extractWorkspaceArchiveEntry(entry *archivezip.File, destination string) error {
+ if entry.FileInfo().IsDir() {
+ return os.MkdirAll(destination, 0755)
+ }
+ if err := os.MkdirAll(filepath.Dir(destination), 0755); err != nil {
+ return err
+ }
+ source, err := entry.Open()
+ if err != nil {
+ return err
+ }
+ defer source.Close()
+ target, err := os.Create(destination)
+ if err != nil {
+ return err
+ }
+ _, copyErr := io.Copy(target, source)
+ closeErr := target.Close()
+ if copyErr != nil {
+ return copyErr
+ }
+ if closeErr != nil {
+ return closeErr
+ }
+ return os.Chtimes(destination, entry.Modified, entry.Modified)
+}
diff --git a/kernel/api/archive_test.go b/kernel/api/archive_test.go
new file mode 100644
index 0000000000..96ae6573a2
--- /dev/null
+++ b/kernel/api/archive_test.go
@@ -0,0 +1,199 @@
+// SiYuan - From thought to insight, with agents
+// Copyright (c) 2020-present, b3log.org
+// SPDX-License-Identifier: AGPL-3.0-or-later
+
+package api
+
+import (
+ archivezip "archive/zip"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strings"
+ "testing"
+
+ "github.com/88250/gulu"
+ "github.com/88250/lute/ast"
+ "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 setupArchiveWorkspace(t *testing.T) (root, boxID string) {
+ t.Helper()
+ root, boxID = t.TempDir(), ast.NewNodeID()
+ oldWorkspace, oldData, oldHistory := util.WorkspaceDir, util.DataDir, util.HistoryDir
+ util.WorkspaceDir, util.DataDir, util.HistoryDir = root, filepath.Join(root, "data"), filepath.Join(root, "history")
+ t.Cleanup(func() { util.WorkspaceDir, util.DataDir, util.HistoryDir = oldWorkspace, oldData, oldHistory })
+ boxConf := conf.NewBoxConf()
+ boxConf.Encrypted = true
+ confPath := filepath.Join(util.DataDir, boxID, ".siyuan", "conf.json")
+ if err := os.MkdirAll(filepath.Dir(confPath), 0755); err != nil {
+ t.Fatal(err)
+ }
+ data, err := json.Marshal(boxConf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(confPath, data, 0644); err != nil {
+ t.Fatal(err)
+ }
+ if !model.IsEncryptedBox(boxID) || model.IsBoxUnlocked(boxID) {
+ t.Fatal("fixture is not a locked encrypted notebook")
+ }
+ return
+}
+
+func writeArchiveFixture(t *testing.T, path string, names ...string) {
+ t.Helper()
+ file, err := os.Create(path)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer file.Close()
+ writer := archivezip.NewWriter(file)
+ for _, name := range names {
+ entry, createErr := writer.Create(name)
+ if createErr != nil {
+ t.Fatal(createErr)
+ }
+ if strings.HasSuffix(name, "/") {
+ continue
+ }
+ if _, err = entry.Write([]byte("archive contents")); err != nil {
+ t.Fatal(err)
+ }
+ }
+ if err = writer.Close(); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func callArchiveAPI(t *testing.T, handler gin.HandlerFunc, body string) *gulu.Result {
+ t.Helper()
+ gin.SetMode(gin.TestMode)
+ engine := gin.New()
+ engine.POST("/archive", handler)
+ recorder := httptest.NewRecorder()
+ request := httptest.NewRequest(http.MethodPost, "/archive", strings.NewReader(body))
+ request.Header.Set("Content-Type", "application/json")
+ engine.ServeHTTP(recorder, request)
+ var result gulu.Result
+ if err := json.Unmarshal(recorder.Body.Bytes(), &result); err != nil {
+ t.Fatalf("invalid response %s: %v", recorder.Body.String(), err)
+ }
+ return &result
+}
+
+func TestUnzipRejectsEncryptedDescendantBeforeAnyWrite(t *testing.T) {
+ root, boxID := setupArchiveWorkspace(t)
+ writeArchiveFixture(t, filepath.Join(root, "payload.zip"), "allowed.txt", boxID+"/assets/payload.txt")
+ result := callArchiveAPI(t, unzip, `{"zipPath":"payload.zip","path":"data"}`)
+ if result.Code == 0 {
+ t.Fatal("archive API accepted encrypted descendant")
+ }
+ for _, path := range []string{filepath.Join(util.DataDir, "allowed.txt"), filepath.Join(util.DataDir, boxID, "assets", "payload.txt")} {
+ if _, err := os.Stat(path); !os.IsNotExist(err) {
+ t.Fatalf("rejected archive modified %s: %v", path, err)
+ }
+ }
+}
+
+func TestZipRejectsEncryptedDescendant(t *testing.T) {
+ root, _ := setupArchiveWorkspace(t)
+ result := callArchiveAPI(t, zip, `{"zipPath":"result.zip","path":"data"}`)
+ if result.Code == 0 {
+ t.Fatal("archive API packaged ancestor of encrypted notebook")
+ }
+ if _, err := os.Stat(filepath.Join(root, "result.zip")); !os.IsNotExist(err) {
+ t.Fatalf("rejected zip created output: %v", err)
+ }
+}
+
+func TestZipRejectsEncryptedDescendantThroughRootSymlink(t *testing.T) {
+ root, _ := setupArchiveWorkspace(t)
+ createArchiveDirectoryLink(t, filepath.Join(root, "alias"), util.DataDir)
+ result := callArchiveAPI(t, zip, `{"zipPath":"result.zip","path":"alias"}`)
+ if result.Code == 0 {
+ t.Fatal("archive API packaged encrypted descendant through root symlink")
+ }
+ if _, err := os.Stat(filepath.Join(root, "result.zip")); !os.IsNotExist(err) {
+ t.Fatalf("rejected zip created output: %v", err)
+ }
+}
+
+func TestUnzipWorkspaceArchiveValidatesAllEntryPaths(t *testing.T) {
+ root, _ := setupArchiveWorkspace(t)
+ for _, name := range []string{"../outside.txt", `..\outside.txt`, "/absolute.txt", "C:/absolute.txt"} {
+ t.Run(name, func(t *testing.T) {
+ if strings.HasPrefix(name, "C:") && filepath.VolumeName(name) == "" {
+ t.Skip("drive paths are local filenames on this platform")
+ }
+ zipPath := filepath.Join(root, "payload.zip")
+ writeArchiveFixture(t, zipPath, "allowed.txt", name)
+ destination := filepath.Join(root, "extract")
+ if err := unzipWorkspaceArchive(zipPath, destination); err == nil {
+ t.Fatal("archive accepted escaping path")
+ }
+ if _, err := os.Stat(filepath.Join(destination, "allowed.txt")); !os.IsNotExist(err) {
+ t.Fatalf("archive wrote entry before path validation: %v", err)
+ }
+ })
+ }
+}
+
+func TestUnzipRejectsSymlinkDestination(t *testing.T) {
+ root, boxID := setupArchiveWorkspace(t)
+ destination := filepath.Join(root, "extract")
+ if err := os.MkdirAll(destination, 0755); err != nil {
+ t.Fatal(err)
+ }
+ createArchiveDirectoryLink(t, filepath.Join(destination, "alias"), filepath.Join(util.DataDir, boxID))
+ zipPath := filepath.Join(root, "payload.zip")
+ writeArchiveFixture(t, zipPath, "allowed.txt", "alias/assets/payload.txt")
+ if err := unzipWorkspaceArchive(zipPath, destination); err == nil {
+ t.Fatal("archive accepted encrypted symlink destination")
+ }
+ if _, err := os.Stat(filepath.Join(destination, "allowed.txt")); !os.IsNotExist(err) {
+ t.Fatalf("archive wrote entry before symlink validation: %v", err)
+ }
+}
+
+func createArchiveDirectoryLink(t *testing.T, link, target string) {
+ t.Helper()
+ if err := os.Symlink(target, link); err != nil {
+ if runtime.GOOS != "windows" {
+ t.Skipf("symlinks unavailable: %v", err)
+ }
+ if output, junctionErr := exec.Command("cmd", "/d", "/c", "mklink", "/J", link, target).CombinedOutput(); junctionErr != nil {
+ t.Skipf("directory links unavailable: %v %s", junctionErr, output)
+ }
+ }
+ t.Cleanup(func() {
+ if err := os.Remove(link); err != nil {
+ t.Errorf("remove directory link: %v", err)
+ }
+ })
+}
+
+func TestUnzipWorkspaceArchiveNormalFiles(t *testing.T) {
+ root, _ := setupArchiveWorkspace(t)
+ zipPath := filepath.Join(root, "payload.zip")
+ writeArchiveFixture(t, zipPath, "nested/file.txt", "empty/")
+ destination := filepath.Join(root, "extract")
+ if err := unzipWorkspaceArchive(zipPath, destination); err != nil {
+ t.Fatal(err)
+ }
+ data, err := os.ReadFile(filepath.Join(destination, "nested", "file.txt"))
+ if err != nil || string(data) != "archive contents" {
+ t.Fatalf("normal extraction failed: %q %v", data, err)
+ }
+ if info, err := os.Stat(filepath.Join(destination, "empty")); err != nil || !info.IsDir() {
+ t.Fatalf("directory entry was not extracted: %v", err)
+ }
+}
diff --git a/kernel/api/block.go b/kernel/api/block.go
index 17b47e9570..08d7eb5326 100644
--- a/kernel/api/block.go
+++ b/kernel/api/block.go
@@ -112,7 +112,7 @@ func checkBlockRef(c *gin.Context) {
if "" != notebook && util.InvalidIDPattern(notebook, ret) {
return
}
- if "" != notebook && !holdBlockRequest(c, ret, notebook) {
+ if !holdBlockRequest(c, ret, notebook, arg, true) {
return
}
ids = filterBlockIDsByPublishAccess(c, ids, notebook)
@@ -157,7 +157,7 @@ func checkBlockRef(c *gin.Context) {
if util.InvalidIDPattern(notebook, ret) {
return
}
- if !holdBlockRequest(c, ret, notebook) {
+ if !holdBlockRequest(c, ret, notebook, arg) {
return
}
if model.IsReadOnlyRoleContext(c) {
@@ -220,7 +220,7 @@ func getBlockTreeInfos(c *gin.Context) {
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
ids = filterBlockIDsByPublishAccess(c, ids, boxID)
@@ -238,7 +238,7 @@ func getBlockSiblingID(c *gin.Context) {
id := arg["id"].(string)
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
if !isBlockPublishAccessible(c, id, boxID) {
@@ -269,7 +269,7 @@ func getBlockRelevantIDs(c *gin.Context) {
id := arg["id"].(string)
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
if !isBlockPublishAccessible(c, id, boxID) {
@@ -589,7 +589,7 @@ func getUnfoldedParentID(c *gin.Context) {
id := arg["id"].(string)
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
if !isBlockPublishAccessible(c, id, boxID) {
@@ -615,7 +615,7 @@ func checkBlockFold(c *gin.Context) {
id := arg["id"].(string)
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg, true) {
return
}
if !isBlockPublishAccessible(c, id, boxID) {
@@ -643,7 +643,7 @@ func checkBlockExist(c *gin.Context) {
id := arg["id"].(string)
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg, true) {
return
}
if !isBlockPublishAccessible(c, id, boxID) {
@@ -670,7 +670,7 @@ func checkBlocksExist(c *gin.Context) {
}
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg, true) {
return
}
ids = filterBlockIDsByPublishAccess(c, ids, boxID)
@@ -688,7 +688,7 @@ func getDocInfo(c *gin.Context) {
id := arg["id"].(string)
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
if !checkBlockPublishAccessInBox(c, id, boxID, ret) {
@@ -805,7 +805,7 @@ func getBlocksWordCount(c *gin.Context) {
ids = append(ids, id.(string))
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
ids = filterBlockIDsByPublishAccess(c, ids, boxID)
@@ -833,7 +833,7 @@ func getTreeStat(c *gin.Context) {
return
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
if !isBlockPublishAccessible(c, id, boxID) {
@@ -896,7 +896,7 @@ func getRefText(c *gin.Context) {
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
if !isBlockPublishAccessible(c, id, boxID) {
@@ -951,7 +951,7 @@ func getRefIDs(c *gin.Context) {
return
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
refDefs, originalRefBlockIDs := model.GetBlockRefsInBox(id, boxID)
@@ -1038,7 +1038,7 @@ func getBlockBreadcrumb(c *gin.Context) {
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
if !isBlockPublishAccessible(c, id, boxID) {
@@ -1092,7 +1092,7 @@ func getBlockBreadcrumbChildren(c *gin.Context) {
limit = int(limitArg.(float64))
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
if !isBlockPublishAccessible(c, id, boxID) {
@@ -1120,7 +1120,7 @@ func getBlockIndex(c *gin.Context) {
id := arg["id"].(string)
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
if !isBlockPublishAccessible(c, id, boxID) {
@@ -1146,7 +1146,7 @@ func getBlocksIndexes(c *gin.Context) {
ids = append(ids, id.(string))
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
ids = filterBlockIDsByPublishAccess(c, ids, boxID)
@@ -1197,7 +1197,7 @@ func getBlockInfo(c *gin.Context) {
return
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
blockTree, publishAccessRequired, publishMetadataVisible, publishAccessible := getBlockInfoPublishAccess(c, id, boxID)
@@ -1375,7 +1375,7 @@ func getBlockDOM(c *gin.Context) {
return
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
dom := model.GetBlockDOMInBox(id, boxID)
@@ -1417,7 +1417,7 @@ func getOrderedListContinueStart(c *gin.Context) {
return
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
start, found := model.GetOrderedListContinueStartInBox(id, boxID)
@@ -1448,7 +1448,7 @@ func getBlockDOMs(c *gin.Context) {
return
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
doms := model.GetBlockDOMsInBox(ids, boxID)
@@ -1478,7 +1478,7 @@ func getBlockDOMWithEmbed(c *gin.Context) {
return
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
isReadOnlyRole := model.IsReadOnlyRoleContext(c)
@@ -1532,7 +1532,7 @@ func getBlockDOMsWithEmbed(c *gin.Context) {
return
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
isReadOnlyRole := model.IsReadOnlyRoleContext(c)
@@ -1562,8 +1562,21 @@ func encryptedNotebookFromArg(arg map[string]any) string {
return ""
}
-func holdBlockRequest(c *gin.Context, ret *gulu.Result, boxID string) bool {
- if err := holdEncryptedBoxRequest(c, boxID); err != nil {
+func holdBlockRequest(c *gin.Context, ret *gulu.Result, boxID string, arg map[string]any, allowMissingIDs ...bool) bool {
+ var ids []string
+ if id, ok := arg["id"].(string); ok {
+ ids = append(ids, id)
+ }
+ if values, ok := arg["ids"].([]any); ok {
+ for _, value := range values {
+ if id, ok := value.(string); ok {
+ ids = append(ids, id)
+ }
+ }
+ }
+ // 存在性与状态检查需要接受已删除的块 ID;输出块内容的接口必须在准入时确定全部归属。
+ allowMissing := len(allowMissingIDs) > 0 && allowMissingIDs[0]
+ if err := holdEncryptedBlockRequests(c, boxID, ids, allowMissing); err != nil {
ret.Code = -1
ret.Msg = err.Error()
return false
@@ -1625,7 +1638,7 @@ func getBlockKramdown(c *gin.Context) {
return
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
var kramdown string
@@ -1693,7 +1706,7 @@ func getBlockKramdowns(c *gin.Context) {
return
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
var kramdowns map[string]string
@@ -1744,7 +1757,7 @@ func getChildBlocks(c *gin.Context) {
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
ret.Data = model.GetChildBlocksInBox(id, boxID)
@@ -1774,7 +1787,7 @@ func getTailChildBlocks(c *gin.Context) {
}
boxID := encryptedNotebookFromArg(arg)
- if !holdBlockRequest(c, ret, boxID) {
+ if !holdBlockRequest(c, ret, boxID, arg) {
return
}
ret.Data = model.GetTailChildBlocksInBox(id, n, boxID)
diff --git a/kernel/api/block_test.go b/kernel/api/block_test.go
index 26061a57d3..b15da8d7e9 100644
--- a/kernel/api/block_test.go
+++ b/kernel/api/block_test.go
@@ -352,6 +352,15 @@ func TestBlockPublishAccessGuards(t *testing.T) {
if response := blockGuardRequest(model.RoleAdministrator, `{"id":"`+disabledID+`"}`, checkBlockExist); !response["data"].(bool) {
t.Fatalf("disabled block should be visible to the administrator, got %v", response["data"])
}
+ missingID := "20260905120000-missing"
+ response := blockGuardRequest(model.RoleAdministrator, `{"id":"`+missingID+`"}`, checkBlockExist)
+ if response["code"].(float64) != 0 || response["data"] != false {
+ t.Fatalf("missing block should report false without an API error: %v", response)
+ }
+ response = blockGuardRequest(model.RoleAdministrator, `{"ids":["`+missingID+`"]}`, checkBlocksExist)
+ if response["code"].(float64) != 0 || response["data"].(map[string]any)[missingID] != false {
+ t.Fatalf("missing blocks should report false without an API error: %v", response)
+ }
})
}
diff --git a/kernel/api/box_lease.go b/kernel/api/box_lease.go
index 160ec53558..d797e4a8ab 100644
--- a/kernel/api/box_lease.go
+++ b/kernel/api/box_lease.go
@@ -18,9 +18,12 @@ package api
import (
"errors"
+ "sort"
+ "github.com/88250/lute/ast"
"github.com/gin-gonic/gin"
"github.com/siyuan-note/siyuan/kernel/model"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
)
const requestBoxLeasesKey = "siyuan-request-box-leases"
@@ -49,6 +52,41 @@ func holdEncryptedBoxRequest(c *gin.Context, boxID string) error {
return nil
}
+// holdEncryptedBlockRequests 按块的实际归属取得响应租约,覆盖省略笔记本参数的通用和批量读取。
+func holdEncryptedBlockRequests(c *gin.Context, boxID string, ids []string, allowMissing bool) error {
+ if boxID != "" {
+ return holdEncryptedBoxRequest(c, boxID)
+ }
+ boxIDSet := map[string]struct{}{}
+ for _, id := range ids {
+ if !ast.IsNodeIDPattern(id) {
+ continue
+ }
+ block := treenode.GetBlockTree(id)
+ if block == nil {
+ if allowMissing {
+ continue
+ }
+ // 查不到的块直接拒绝,防止随后解锁的笔记本在第二次查找时被无租约访问。
+ return errors.New("block not found or its encrypted notebook is locked")
+ }
+ if model.IsEncryptedBox(block.BoxID) {
+ boxIDSet[block.BoxID] = struct{}{}
+ }
+ }
+ boxIDs := make([]string, 0, len(boxIDSet))
+ for id := range boxIDSet {
+ boxIDs = append(boxIDs, id)
+ }
+ sort.Strings(boxIDs)
+ for _, id := range boxIDs {
+ if err := holdEncryptedBoxRequest(c, id); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
func requestBoxLeases(c *gin.Context) []string {
value, ok := c.Get(requestBoxLeasesKey)
if !ok {
diff --git a/kernel/api/box_lease_test.go b/kernel/api/box_lease_test.go
new file mode 100644
index 0000000000..daad4bef09
--- /dev/null
+++ b/kernel/api/box_lease_test.go
@@ -0,0 +1,200 @@
+//go:build (sqlcipher || libsqlcipher) && cgo
+
+// 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 (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "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/sql"
+ "github.com/siyuan-note/siyuan/kernel/treenode"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+type blockedBlockResponseWriter struct {
+ *httptest.ResponseRecorder
+ ready chan []byte
+ proceed chan struct{}
+}
+
+func (w *blockedBlockResponseWriter) Write(data []byte) (int, error) {
+ w.ready <- append([]byte(nil), data...)
+ <-w.proceed
+ return w.ResponseRecorder.Write(data)
+}
+
+func TestImplicitNotebookResponseLease(t *testing.T) {
+ runNotebookResponseLease(t, false, false)
+}
+
+func TestExplicitNotebookResponseLease(t *testing.T) {
+ runNotebookResponseLease(t, true, false)
+}
+
+func TestBatchNotebookResponseLease(t *testing.T) {
+ runNotebookResponseLease(t, false, true)
+}
+
+func runNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {
+ t.Helper()
+ if os.Getenv("SIYUAN_TEST_NOTEBOOK_RESPONSE_LEASE") == t.Name() {
+ testNotebookResponseLease(t, explicitNotebook, batch)
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
+ defer cancel()
+ command := exec.CommandContext(ctx, os.Args[0], "-test.run=^"+t.Name()+"$", "-test.v")
+ command.Env = append(os.Environ(), "SIYUAN_TEST_NOTEBOOK_RESPONSE_LEASE="+t.Name())
+ if output, err := command.CombinedOutput(); err != nil {
+ t.Fatalf("response lease subprocess failed: %v\n%s", err, output)
+ }
+}
+
+func testNotebookResponseLease(t *testing.T, explicitNotebook, batch bool) {
+ root := t.TempDir()
+ oldConf := model.Conf
+ oldData, oldTemp, oldConfDir, oldHistory := util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir
+ oldQueue, oldDB, oldHistoryDB, oldAssetDB, oldBTDB := util.QueueDir, util.DBPath, util.HistoryDBPath, util.AssetContentDBPath, util.BlockTreeDBPath
+ defer func() {
+ model.Conf = oldConf
+ util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir = oldData, oldTemp, oldConfDir, oldHistory
+ util.QueueDir, util.DBPath, util.HistoryDBPath, util.AssetContentDBPath, util.BlockTreeDBPath = oldQueue, oldDB, oldHistoryDB, oldAssetDB, oldBTDB
+ }()
+ util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir = filepath.Join(root, "data"), filepath.Join(root, "temp"), filepath.Join(root, "conf"), filepath.Join(root, "history")
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.DBPath, util.HistoryDBPath, util.AssetContentDBPath, util.BlockTreeDBPath = filepath.Join(util.TempDir, util.DBName), filepath.Join(util.TempDir, "history.db"), filepath.Join(util.TempDir, "asset_content.db"), filepath.Join(util.TempDir, "blocktree.db")
+ for _, dir := range []string{util.DataDir, util.TempDir, util.ConfDir, util.HistoryDir} {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ model.Conf = model.NewAppConf()
+ model.Conf.NotebookCrypto, model.Conf.Sync, model.Conf.FileTree = conf.NewNotebookCrypto(), conf.NewSync(), conf.NewFileTree()
+ model.Conf.Editor, model.Conf.Export, model.Conf.Search = conf.NewEditor(), conf.NewExport(), conf.NewSearch()
+ *model.Conf.FileTree.BoxDocEnabled = true
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ defer sql.CloseDatabase()
+ if err := model.EnableEncryptedNotebook("review-password"); err != nil {
+ t.Fatal(err)
+ }
+ count := 1
+ if batch {
+ count = 2
+ }
+ var boxIDs []string
+ for range count {
+ boxID, err := model.CreateEncryptedBox("Response lease", "review-password")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer model.LockBox(boxID)
+ boxIDs = append(boxIDs, boxID)
+ tree, err := filesys.LoadTree(boxID, "/"+boxID+".sy", util.NewLute())
+ if err != nil {
+ t.Fatal(err)
+ }
+ paragraph := &ast.Node{Type: ast.NodeParagraph, ID: ast.NewNodeID()}
+ paragraph.AppendChild(&ast.Node{Type: ast.NodeText, Tokens: []byte("REVIEW-SECRET-CONTENT")})
+ tree.Root.AppendChild(paragraph)
+ if _, err = filesys.WriteTree(tree); err != nil {
+ t.Fatal(err)
+ }
+ treenode.UpsertBlockTree(tree)
+ }
+ gin.SetMode(gin.TestMode)
+ engine := gin.New()
+ engine.Use(boxLeaseMiddleware)
+ engine.Use(func(c *gin.Context) { c.Set(model.RoleContextKey, model.RoleAdministrator); c.Next() })
+ engine.POST("/api/block/getBlockKramdown", getBlockKramdown)
+ engine.POST("/api/block/getBlockKramdowns", getBlockKramdowns)
+ writer := &blockedBlockResponseWriter{ResponseRecorder: httptest.NewRecorder(), ready: make(chan []byte, 1), proceed: make(chan struct{})}
+ var releaseWriter sync.Once
+ defer releaseWriter.Do(func() { close(writer.proceed) })
+ args := map[string]any{"id": boxIDs[0]}
+ if explicitNotebook {
+ args["notebook"] = boxIDs[0]
+ }
+ endpoint := "/api/block/getBlockKramdown"
+ if batch {
+ delete(args, "id")
+ args["ids"] = boxIDs
+ endpoint += "s"
+ }
+ requestBody, err := json.Marshal(args)
+ if err != nil {
+ t.Fatal(err)
+ }
+ request := httptest.NewRequest(http.MethodPost, endpoint, strings.NewReader(string(requestBody)))
+ request.Header.Set("Content-Type", "application/json")
+ responseDone := make(chan struct{})
+ go func() { engine.ServeHTTP(writer, request); close(responseDone) }()
+ var body []byte
+ select {
+ case body = <-writer.ready:
+ case <-time.After(5 * time.Second):
+ t.Fatal("response never reached writer")
+ }
+ if strings.Count(string(body), "REVIEW-SECRET-CONTENT") != count {
+ releaseWriter.Do(func() { close(writer.proceed) })
+ <-responseDone
+ t.Fatalf("fixture did not produce plaintext: %s", body)
+ }
+ lockDone := make(chan string, len(boxIDs))
+ for _, boxID := range boxIDs {
+ go func() { model.LockBox(boxID); lockDone <- boxID }()
+ }
+ lockedBeforeResponse := false
+ select {
+ case <-lockDone:
+ lockedBeforeResponse = true
+ case <-time.After(300 * time.Millisecond):
+ }
+ releaseWriter.Do(func() { close(writer.proceed) })
+ <-responseDone
+ remaining := len(boxIDs)
+ if lockedBeforeResponse {
+ remaining--
+ }
+ for range remaining {
+ select {
+ case <-lockDone:
+ case <-time.After(5 * time.Second):
+ t.Fatal("lock did not complete after response lease release")
+ }
+ }
+ if lockedBeforeResponse {
+ t.Fatalf("lock completed before plaintext response was sent: %s", writer.Body.String())
+ }
+}
diff --git a/kernel/conf/notebook_crypto.go b/kernel/conf/notebook_crypto.go
index 257b16286a..6387c42dfa 100644
--- a/kernel/conf/notebook_crypto.go
+++ b/kernel/conf/notebook_crypto.go
@@ -34,6 +34,9 @@ type NotebookCrypto struct {
CreatedAt int64 `json:"createdAt,omitempty"` // 备份创建/更新时间(unix 秒)
Checksum string `json:"checksum,omitempty"` // SHA-256 校验和
KEKMAC []byte `json:"kekMAC,omitempty"` // KEK HMAC-SHA256(需主密码验证)
+
+ // 历次 KEK 由当前 KEK 认证加密,用于恢复本机、其他设备或离线快照中尚未重新包络的笔记本。
+ HistoryKEKs [][]byte `json:"historyKEKs,omitempty"`
}
// NewNotebookCrypto 创建带默认 Argon2id 参数的 NotebookCrypto。
diff --git a/kernel/model/conf_secret_test.go b/kernel/model/conf_secret_test.go
index fa3b0cf58c..725266d263 100644
--- a/kernel/model/conf_secret_test.go
+++ b/kernel/model/conf_secret_test.go
@@ -73,6 +73,7 @@ func TestHideConfSecretPreservesNotebookCryptoSettings(t *testing.T) {
appConf.NotebookCrypto.KEKVerifier = verifier
appConf.NotebookCrypto.VerifierNonce = nonce
appConf.NotebookCrypto.AutoLockMinutes = 17
+ appConf.NotebookCrypto.HistoryKEKs = [][]byte{bytes.Repeat([]byte{3}, 64)}
prepareBackupForWrite(appConf.NotebookCrypto)
appConf.NotebookCrypto.KEKMAC = computeKEKMAC(appConf.NotebookCrypto, kek)
@@ -96,7 +97,8 @@ func TestHideConfSecretPreservesNotebookCryptoSettings(t *testing.T) {
"" != notebookCrypto.BackupID ||
0 != notebookCrypto.CreatedAt ||
"" != notebookCrypto.Checksum ||
- 0 < len(notebookCrypto.KEKMAC) {
+ 0 < len(notebookCrypto.KEKMAC) ||
+ 0 < len(notebookCrypto.HistoryKEKs) {
t.Fatalf("notebook crypto key material was not hidden: %#v", notebookCrypto)
}
}
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index 956b5dd8b1..a8494deec5 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -19,6 +19,7 @@ package model
import (
"bytes"
"crypto/hmac"
+ "crypto/rand"
"crypto/sha256"
"encoding/binary"
"encoding/hex"
@@ -153,10 +154,14 @@ func hasEncryptedNotebookPayloadAtPath(boxDir string) (bool, error) {
}
const encryptedAssetMetadataMaxSize = 1024 * 1024
+const encryptedAssetSpec = 2
+const encryptedAssetContainerIDSize = 32
const encryptedAssetChunkSize = 1024 * 1024
const encryptedAssetChunkMaxCiphertextSize = encryptedAssetChunkSize + 1024
type encryptedAssetMetadata struct {
+ Spec int `json:"spec"`
+ ContainerID []byte `json:"containerID"`
OriginalName string `json:"originalName"`
Size int64 `json:"size"`
Chunks uint64 `json:"chunks"`
@@ -347,7 +352,7 @@ func ImportNotebookCryptoBackup(data []byte, password string) error {
}
// 校验 KEK 能解密现存笔记本和已删除笔记本历史中的 WrappedDEK,避免导入不匹配的备份。
- if !verifyKEKAgainstExistingBoxes(kek) || !verifyKEKAgainstEncryptedHistory(kek) {
+ if !verifyKEKAgainstExistingBoxes(kek, nc) || !verifyKEKAgainstEncryptedHistory(kek, nc) {
return errors.New(Conf.Language(316)) // 密钥不匹配
}
@@ -432,7 +437,14 @@ func writeNotebookCryptoBackupData(nc *conf.NotebookCrypto, kek []byte) error {
// 优先尝试 conf 的 WrappedDEK,解密失败时 fallback 到 backup(与解锁路径一致);
// GetBoxEncryption 报错时 fail-closed(元数据损坏的加密笔记本不能静默跳过)。
// 全部通过或不存在加密笔记本时返回 true。
-func verifyKEKAgainstExistingBoxes(kek []byte) bool {
+func verifyKEKAgainstExistingBoxes(kek []byte, nc *conf.NotebookCrypto) bool {
+ if nc != nil {
+ keys, err := decryptHistoryKEKs(kek, nc.HistoryKEKs)
+ clearHistoryKEKs(keys)
+ if err != nil {
+ return false
+ }
+ }
boxIDs, err := listAllEncryptedBoxIDs()
if err != nil {
logging.LogErrorf("list encrypted notebooks failed: %s", err)
@@ -446,14 +458,16 @@ func verifyKEKAgainstExistingBoxes(kek []byte) bool {
if boxCrypt == nil || len(boxCrypt.WrappedDEK) == 0 {
return false // ListAllEncryptedBoxIDs 认定为加密但无可用 key material → fail-closed
}
- if _, dErr := decryptWrappedDEK(id, boxCrypt, kek); dErr == nil {
+ if dek, dErr := decryptWrappedDEKWithHistory(id, boxCrypt, kek, nc); dErr == nil {
+ zeroAndClear(dek)
continue // 解密成功
}
// conf 的 WrappedDEK 无法解密:尝试 backup(与解锁路径 fallback 一致)
backup, bErr := readNotebookCryptBackup(id)
if bErr == nil && backup != nil && len(backup.WrappedDEK) > 0 &&
!bytes.Equal(backup.WrappedDEK, boxCrypt.WrappedDEK) {
- if _, err2 := decryptWrappedDEK(id, backup, kek); err2 == nil {
+ if dek, err2 := decryptWrappedDEKWithHistory(id, backup, kek, nc); err2 == nil {
+ zeroAndClear(dek)
continue // backup 解密成功
}
}
@@ -497,6 +511,7 @@ type masterPasswordMigration struct {
NewVerifier []byte `json:"newVerifier"`
NewVerifierNonce []byte `json:"newVerifierNonce"`
NewKDFParams json.RawMessage `json:"newKDFParams"`
+ NewHistoryKEKs [][]byte `json:"newHistoryKEKs,omitempty"`
Boxes []migrationBoxEntry `json:"boxes"`
}
@@ -588,7 +603,7 @@ func removeMasterPasswordMigrationBox(boxID string) {
if !found {
return
}
- if len(remaining) == 0 {
+ if len(remaining) == 0 && len(mig.NewHistoryKEKs) == 0 {
removeMasterPasswordMigrationUnlocked()
return
}
@@ -658,7 +673,7 @@ func recoverMasterPasswordMigration() {
}
if len(remaining) != len(mig.Boxes) {
mig.Boxes = remaining
- if len(mig.Boxes) == 0 {
+ if len(mig.Boxes) == 0 && len(mig.NewHistoryKEKs) == 0 {
removeMasterPasswordMigration()
return
}
@@ -673,6 +688,11 @@ func recoverMasterPasswordMigration() {
Conf.m.RUnlock()
if bytes.Equal(currentVerifier, mig.NewVerifier) {
+ if mig.NewHistoryKEKs != nil {
+ Conf.m.Lock()
+ Conf.NotebookCrypto.HistoryKEKs = mig.NewHistoryKEKs
+ Conf.m.Unlock()
+ }
// Phase 2 已完成(verifier 已切换),补写未完成的 box
for _, entry := range mig.Boxes {
box := &Box{ID: entry.BoxID}
@@ -829,7 +849,7 @@ func hasEncryptedNotebookDeleteHistory(boxID string) (bool, error) {
return false, nil
}
-func verifyKEKAgainstEncryptedHistory(kek []byte) bool {
+func verifyKEKAgainstEncryptedHistory(kek []byte, nc *conf.NotebookCrypto) bool {
boxDirs, err := encryptedNotebookHistoryBoxDirs()
if err != nil {
logging.LogErrorf("list encrypted notebook history failed: %s", err)
@@ -844,7 +864,7 @@ func verifyKEKAgainstEncryptedHistory(kek []byte) bool {
}
matched := false
for _, candidate := range candidates {
- dek, decryptErr := decryptWrappedDEK(boxID, candidate, kek)
+ dek, decryptErr := decryptWrappedDEKWithHistory(boxID, candidate, kek, nc)
if decryptErr == nil {
zeroAndClear(dek)
matched = true
@@ -1187,7 +1207,7 @@ func deriveNotebookCryptoBackupCandidate(password string) (backup *conf.Notebook
zeroAndClear(kek)
return nil, nil, errors.New(Conf.Language(316))
}
- if !verifyKEKAgainstExistingBoxes(kek) || !verifyKEKAgainstEncryptedHistory(kek) {
+ if !verifyKEKAgainstExistingBoxes(kek, backup) || !verifyKEKAgainstEncryptedHistory(kek, backup) {
zeroAndClear(kek)
return nil, nil, errors.New(Conf.Language(316))
}
@@ -1253,7 +1273,11 @@ func deriveKEK(password string) ([]byte, error) {
zeroAndClear(kek)
return nil, errors.New(Conf.Language(315))
}
- if !verifyKEKAgainstExistingBoxes(kek) {
+ trusted := &nc
+ if !localAuthenticated {
+ trusted = backup
+ }
+ if !verifyKEKAgainstExistingBoxes(kek, trusted) {
zeroAndClear(kek)
return nil, errors.New(Conf.Language(315))
}
@@ -1274,7 +1298,9 @@ func deriveKEK(password string) ([]byte, error) {
if migrationPending {
// 崩溃恢复后的首次新密码验证:确认所有笔记本都已切换到新 KEK,再生成带认证的全局备份并结束迁移。
- if !verifyKEKAgainstExistingBoxes(kek) {
+ keys, keyErr := decryptHistoryKEKs(kek, nc.HistoryKEKs)
+ clearHistoryKEKs(keys)
+ if keyErr != nil || !verifyKEKAgainstExistingBoxes(kek, nil) || !verifyKEKAgainstEncryptedHistory(kek, &nc) {
zeroAndClear(kek)
return nil, errMasterPasswordMigrationPending
}
@@ -1297,7 +1323,8 @@ func decryptBoxCrypt(boxID string, kek []byte) (dek []byte, boxCrypt *conf.BoxEn
return nil, nil, fmt.Errorf("no encrypted key material for box [%s]", boxID)
}
- dek, err = decryptWrappedDEK(boxID, boxCrypt, kek)
+ nc := currentNotebookCrypto()
+ dek, err = decryptWrappedDEKWithHistory(boxID, boxCrypt, kek, nc)
if err == nil {
return dek, boxCrypt, nil
}
@@ -1306,7 +1333,7 @@ func decryptBoxCrypt(boxID string, kek []byte) (dek []byte, boxCrypt *conf.BoxEn
backup, bErr := readNotebookCryptBackup(boxID)
if bErr == nil && backup != nil && len(backup.WrappedDEK) > 0 &&
!bytes.Equal(backup.WrappedDEK, boxCrypt.WrappedDEK) {
- dek, err = decryptWrappedDEK(boxID, backup, kek)
+ dek, err = decryptWrappedDEKWithHistory(boxID, backup, kek, nc)
if err == nil {
// backup 解密成功:修复 conf + 刷新 backup
box := &Box{ID: boxID}
@@ -1705,9 +1732,7 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
}
defer zeroAndClear(oldKEK)
- Conf.m.Lock()
- nc := Conf.NotebookCrypto
- Conf.m.Unlock()
+ nc := currentNotebookCrypto()
params, validErr := util.ValidateArgon2Params(nc.KDFParams)
if validErr != nil {
@@ -1715,6 +1740,10 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
}
newKEK := util.DeriveKey(newPassword, nc.MasterSalt, params)
defer zeroAndClear(newKEK)
+ newHistoryKEKs, err := rewrapHistoryKEKs(oldKEK, newKEK, nc.HistoryKEKs)
+ if err != nil {
+ return err
+ }
newVerifier, err := util.EncryptWithAAD(newKEK, kekVerifierMagic, []byte("siyuan:kek-verifier"))
if err != nil {
return err
@@ -1733,6 +1762,7 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
return errors.New(Conf.Language(316) + " [box=" + id + "]")
}
newWrapped, nErr := util.EncryptWithAAD(newKEK, dek, wrappedDEKAAD(id))
+ zeroAndClear(dek)
if nErr != nil {
return nErr
}
@@ -1752,6 +1782,7 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
NewVerifier: newVerifier,
NewVerifierNonce: mustEncryptionNonce(newVerifier),
NewKDFParams: newParamsJSON,
+ NewHistoryKEKs: newHistoryKEKs,
Boxes: entries,
}
if err = writeMasterPasswordMigration(mig); err != nil {
@@ -1763,6 +1794,7 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
Conf.NotebookCrypto.KEKVerifier = newVerifier
Conf.NotebookCrypto.VerifierNonce = mustEncryptionNonce(newVerifier)
Conf.NotebookCrypto.KDFParams = params
+ Conf.NotebookCrypto.HistoryKEKs = newHistoryKEKs
Conf.m.Unlock()
// Conf.Save 内部会加 Conf.m,不能在持锁状态下调用(RWMutex 不可重入)
@@ -2214,7 +2246,13 @@ func EncryptAsset(boxID, diskName, originalName string, dek, plaintext []byte) (
if chunkCount == 0 {
chunkCount = 1
}
+ containerID := make([]byte, encryptedAssetContainerIDSize)
+ if _, err := rand.Read(containerID); err != nil {
+ return nil, err
+ }
metadata, err := json.Marshal(&encryptedAssetMetadata{
+ Spec: encryptedAssetSpec,
+ ContainerID: containerID,
OriginalName: originalName,
Size: int64(len(plaintext)),
Chunks: chunkCount,
@@ -2247,7 +2285,7 @@ func EncryptAsset(boxID, diskName, originalName string, dek, plaintext []byte) (
encryptedChunk, encryptErr := util.EncryptWithAAD(
assetKey,
plaintext[start:end],
- []byte(fmt.Sprintf("%s:content:%d", aadPrefix, chunkIndex)),
+ encryptedAssetChunkAAD(aadPrefix, containerID, chunkIndex),
)
if encryptErr != nil {
return nil, encryptErr
@@ -2278,18 +2316,41 @@ func decryptAssetMetadata(boxID, diskName string, dek, ciphertext []byte) (metad
if decryptErr != nil {
return nil, 0, decryptErr
}
- metadata = &encryptedAssetMetadata{}
- if err = json.Unmarshal(plainMetadata, metadata); err != nil {
+ defer zeroAndClear(plainMetadata)
+ if metadata, err = parseEncryptedAssetMetadata(plainMetadata); err != nil {
return nil, 0, err
}
+ return metadata, 8 + metadataSize, nil
+}
+
+// encryptedAssetChunkAAD 将分块绑定到本次写入的容器,阻止同名资源的不同版本互换分块。
+func encryptedAssetChunkAAD(prefix string, containerID []byte, index uint64) []byte {
+ return []byte(fmt.Sprintf("%s:content:v%d:%x:%d", prefix, encryptedAssetSpec, containerID, index))
+}
+
+func parseEncryptedAssetMetadata(data []byte) (*encryptedAssetMetadata, error) {
+ metadata := &encryptedAssetMetadata{}
+ if err := json.Unmarshal(data, metadata); err != nil {
+ return nil, err
+ }
+ if metadata.Spec != encryptedAssetSpec || len(metadata.ContainerID) != encryptedAssetContainerIDSize {
+ return nil, errors.New("unsupported encrypted asset container version")
+ }
if metadata.OriginalName == "" || metadata.OriginalName == "." ||
filepath.Base(metadata.OriginalName) != metadata.OriginalName || strings.ContainsAny(metadata.OriginalName, `/\`) {
- return nil, 0, errors.New("invalid encrypted asset original name")
+ return nil, errors.New("invalid encrypted asset original name")
}
- if metadata.Size < 0 || metadata.Chunks == 0 {
- return nil, 0, errors.New("invalid encrypted asset content metadata")
+ if metadata.Size < 0 {
+ return nil, errors.New("invalid encrypted asset content metadata")
}
- return metadata, 8 + metadataSize, nil
+ chunks := uint64(metadata.Size) / encryptedAssetChunkSize
+ if metadata.Size%encryptedAssetChunkSize != 0 || metadata.Size == 0 {
+ chunks++
+ }
+ if metadata.Chunks != chunks {
+ return nil, errors.New("invalid encrypted asset chunk count")
+ }
+ return metadata, nil
}
// DecryptAssetWithName 解密资源内容并返回原始名称。
@@ -2335,17 +2396,11 @@ func DecryptAssetNameFromReader(boxID, diskName string, dek []byte, reader io.Re
if decryptErr != nil {
return "", decryptErr
}
- metadata := &encryptedAssetMetadata{}
- if err = json.Unmarshal(plainMetadata, metadata); err != nil {
+ defer zeroAndClear(plainMetadata)
+ metadata, err := parseEncryptedAssetMetadata(plainMetadata)
+ if err != nil {
return "", err
}
- if metadata.OriginalName == "" || metadata.OriginalName == "." ||
- filepath.Base(metadata.OriginalName) != metadata.OriginalName || strings.ContainsAny(metadata.OriginalName, `/\`) {
- return "", errors.New("invalid encrypted asset original name")
- }
- if metadata.Size < 0 || metadata.Chunks == 0 {
- return "", errors.New("invalid encrypted asset content metadata")
- }
return metadata.OriginalName, nil
}
@@ -2374,17 +2429,11 @@ func DecryptAssetToWriter(boxID, diskName string, dek []byte, reader io.Reader,
if decryptErr != nil {
return "", decryptErr
}
- metadata := &encryptedAssetMetadata{}
- if err = json.Unmarshal(plainMetadata, metadata); err != nil {
+ defer zeroAndClear(plainMetadata)
+ metadata, err := parseEncryptedAssetMetadata(plainMetadata)
+ if err != nil {
return "", err
}
- if metadata.OriginalName == "" || metadata.OriginalName == "." ||
- filepath.Base(metadata.OriginalName) != metadata.OriginalName || strings.ContainsAny(metadata.OriginalName, `/\`) {
- return "", errors.New("invalid encrypted asset original name")
- }
- if metadata.Size < 0 || metadata.Chunks == 0 {
- return "", errors.New("invalid encrypted asset content metadata")
- }
var written int64
for chunkIndex := uint64(0); chunkIndex < metadata.Chunks; chunkIndex++ {
@@ -2402,11 +2451,19 @@ func DecryptAssetToWriter(boxID, diskName string, dek []byte, reader io.Reader,
plainChunk, chunkErr := util.DecryptWithAAD(
assetKey,
encryptedChunk,
- []byte(fmt.Sprintf("%s:content:%d", aadPrefix, chunkIndex)),
+ encryptedAssetChunkAAD(aadPrefix, metadata.ContainerID, chunkIndex),
)
if chunkErr != nil {
return "", chunkErr
}
+ expectedSize := int64(encryptedAssetChunkSize)
+ if remaining := metadata.Size - written; remaining < expectedSize {
+ expectedSize = remaining
+ }
+ if int64(len(plainChunk)) != expectedSize {
+ zeroAndClear(plainChunk)
+ return "", errors.New("invalid encrypted asset plaintext chunk size")
+ }
n, writeErr := writer.Write(plainChunk)
written += int64(n)
zeroAndClear(plainChunk)
diff --git a/kernel/model/crypto_history_keys.go b/kernel/model/crypto_history_keys.go
new file mode 100644
index 0000000000..a148326857
--- /dev/null
+++ b/kernel/model/crypto_history_keys.go
@@ -0,0 +1,112 @@
+// 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 model
+
+import (
+ "bytes"
+ "errors"
+
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+const historyKEKAAD = "siyuan:history-kek:v1"
+
+// decryptHistoryKEKs 只在当前配置已经完成主密码认证后使用,返回值由调用方在使用结束时清零。
+func decryptHistoryKEKs(kek []byte, wrappedKeys [][]byte) (keys [][]byte, err error) {
+ defer func() {
+ if err != nil {
+ clearHistoryKEKs(keys)
+ keys = nil
+ }
+ }()
+ for _, wrapped := range wrappedKeys {
+ key, decryptErr := util.DecryptWithAAD(kek, wrapped, []byte(historyKEKAAD))
+ if decryptErr != nil {
+ return keys, decryptErr
+ }
+ if len(key) != 32 {
+ zeroAndClear(key)
+ return keys, errors.New("invalid historical notebook encryption key")
+ }
+ keys = append(keys, key)
+ }
+ return keys, nil
+}
+
+func clearHistoryKEKs(keys [][]byte) {
+ for _, key := range keys {
+ zeroAndClear(key)
+ }
+}
+
+// rewrapHistoryKEKs 将历次 KEK 和本次旧 KEK 一起封装到新 KEK 下,恢复不依赖历史所在设备。
+func rewrapHistoryKEKs(oldKEK, newKEK []byte, wrappedKeys [][]byte) (ret [][]byte, err error) {
+ keys, err := decryptHistoryKEKs(oldKEK, wrappedKeys)
+ if err != nil {
+ return nil, err
+ }
+ keys = append(keys, append([]byte(nil), oldKEK...))
+ defer clearHistoryKEKs(keys)
+ for i, key := range keys {
+ if bytes.Equal(key, newKEK) {
+ continue
+ }
+ duplicate := false
+ for _, previous := range keys[:i] {
+ if bytes.Equal(key, previous) {
+ duplicate = true
+ break
+ }
+ }
+ if duplicate {
+ continue
+ }
+ wrapped, wrapErr := util.EncryptWithAAD(newKEK, key, []byte(historyKEKAAD))
+ if wrapErr != nil {
+ return nil, wrapErr
+ }
+ ret = append(ret, wrapped)
+ }
+ return ret, nil
+}
+
+// decryptWrappedDEKWithHistory 同时支持当前包络和历史包络,不缓存派生或解封出的 KEK。
+func decryptWrappedDEKWithHistory(boxID string, enc *conf.BoxEncryption, kek []byte, nc *conf.NotebookCrypto) ([]byte, error) {
+ dek, err := decryptWrappedDEK(boxID, enc, kek)
+ if err == nil || nc == nil || len(nc.HistoryKEKs) == 0 {
+ return dek, err
+ }
+ keys, keyErr := decryptHistoryKEKs(kek, nc.HistoryKEKs)
+ if keyErr != nil {
+ return nil, keyErr
+ }
+ defer clearHistoryKEKs(keys)
+ for _, key := range keys {
+ if dek, err = decryptWrappedDEK(boxID, enc, key); err == nil {
+ return dek, nil
+ }
+ }
+ return nil, err
+}
+
+func currentNotebookCrypto() *conf.NotebookCrypto {
+ Conf.m.RLock()
+ defer Conf.m.RUnlock()
+ ret := *Conf.NotebookCrypto
+ return &ret
+}
diff --git a/kernel/model/crypto_regression_test.go b/kernel/model/crypto_regression_test.go
new file mode 100644
index 0000000000..6a1ae6ae27
--- /dev/null
+++ b/kernel/model/crypto_regression_test.go
@@ -0,0 +1,325 @@
+// 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 model
+
+import (
+ "bytes"
+ "encoding/binary"
+ "encoding/json"
+ "os"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestEncryptedAssetRejectsSplicedVersions(t *testing.T) {
+ boxID := "20260905120000-review1"
+ diskName := "asset-20260905120000-review1.bin"
+ dek := bytes.Repeat([]byte{42}, 32)
+ firstPlain := bytes.Repeat([]byte("A"), encryptedAssetChunkSize*2)
+ secondPlain := bytes.Repeat([]byte("B"), encryptedAssetChunkSize*2)
+ first, err := EncryptAsset(boxID, diskName, "first.bin", dek, firstPlain)
+ if err != nil {
+ t.Fatal(err)
+ }
+ second, err := EncryptAsset(boxID, diskName, "second.bin", dek, secondPlain)
+ if err != nil {
+ t.Fatal(err)
+ }
+ firstOffset := 8 + int(binary.BigEndian.Uint32(first[4:8]))
+ secondOffset := 8 + int(binary.BigEndian.Uint32(second[4:8]))
+ firstSize := 4 + int(binary.BigEndian.Uint32(first[firstOffset:firstOffset+4]))
+ secondSize := 4 + int(binary.BigEndian.Uint32(second[secondOffset:secondOffset+4]))
+ if firstSize != secondSize {
+ t.Fatal("fixture chunk lengths differ")
+ }
+ for _, part := range []string{"first chunk", "last chunk", "all chunks", "metadata"} {
+ t.Run(part, func(t *testing.T) {
+ mixed := append([]byte(nil), second...)
+ switch part {
+ case "first chunk":
+ copy(mixed[secondOffset:secondOffset+secondSize], first[firstOffset:firstOffset+firstSize])
+ case "last chunk":
+ copy(mixed[secondOffset+secondSize:], first[firstOffset+firstSize:])
+ case "all chunks":
+ copy(mixed[secondOffset:], first[firstOffset:])
+ case "metadata":
+ mixed = append(append([]byte(nil), first[:firstOffset]...), second[secondOffset:]...)
+ }
+ if _, _, err := DecryptAssetWithName(boxID, diskName, dek, mixed); err == nil {
+ t.Fatal("accepted a never-encrypted mixed version")
+ }
+ })
+ }
+}
+
+func TestEncryptedAssetRejectsUnboundContainerMetadata(t *testing.T) {
+ boxID, diskName := "20260905120000-review1", "asset.bin"
+ dek := bytes.Repeat([]byte{42}, 32)
+ for _, spec := range []int{0, 1, encryptedAssetSpec + 1, encryptedAssetSpec} {
+ metadata, err := json.Marshal(&encryptedAssetMetadata{Spec: spec, OriginalName: "asset.bin", Size: 0, Chunks: 1})
+ if err != nil {
+ t.Fatal(err)
+ }
+ key := util.DeriveSubKey(dek, "siyuan/asset")
+ encryptedMetadata, err := util.EncryptWithAAD(key, metadata, []byte("siyuan:asset:"+boxID+":assets/"+diskName+":metadata"))
+ zeroAndClear(key)
+ if err != nil {
+ t.Fatal(err)
+ }
+ container := append([]byte(nil), encryptedAssetMagic...)
+ container = binary.BigEndian.AppendUint32(container, uint32(len(encryptedMetadata)))
+ container = append(container, encryptedMetadata...)
+ container = binary.BigEndian.AppendUint32(container, 0)
+ if _, err = DecryptAssetName(boxID, diskName, dek, container); err == nil {
+ t.Fatalf("metadata reader accepted unbound container spec %d", spec)
+ }
+ if _, err = DecryptAssetNameFromReader(boxID, diskName, dek, bytes.NewReader(container)); err == nil {
+ t.Fatalf("streaming metadata reader accepted unbound container spec %d", spec)
+ }
+ var output bytes.Buffer
+ if _, err = DecryptAssetToWriter(boxID, diskName, dek, bytes.NewReader(container), &output); err == nil || output.Len() != 0 {
+ t.Fatalf("content reader accepted unbound container spec %d", spec)
+ }
+ }
+}
+
+func TestEncryptedAssetEmptyAndChunkBoundaries(t *testing.T) {
+ boxID, diskName := "20260905120000-review1", "asset.bin"
+ dek := bytes.Repeat([]byte{42}, 32)
+ for _, size := range []int{0, encryptedAssetChunkSize - 1, encryptedAssetChunkSize, encryptedAssetChunkSize + 1} {
+ plain := bytes.Repeat([]byte{23}, size)
+ ciphertext, err := EncryptAsset(boxID, diskName, "asset.bin", dek, plain)
+ if err != nil {
+ t.Fatal(err)
+ }
+ decrypted, _, err := DecryptAssetWithName(boxID, diskName, dek, ciphertext)
+ if err != nil || !bytes.Equal(plain, decrypted) {
+ t.Fatalf("asset size %d failed round trip: %v", size, err)
+ }
+ if name, err := DecryptAssetNameFromReader(boxID, diskName, dek, bytes.NewReader(ciphertext)); err != nil || name != "asset.bin" {
+ t.Fatalf("streaming name read failed: %v", err)
+ }
+ }
+}
+
+func TestPasswordChangePreservesDeletedHistoryRecovery(t *testing.T) {
+ oldConf, oldDataDir, oldHistoryDir, oldConfDir := Conf, util.DataDir, util.HistoryDir, util.ConfDir
+ root := t.TempDir()
+ util.DataDir, util.HistoryDir, util.ConfDir = filepath.Join(root, "data"), filepath.Join(root, "history"), filepath.Join(root, "conf")
+ defer func() {
+ Conf, util.DataDir, util.HistoryDir, util.ConfDir = oldConf, oldDataDir, oldHistoryDir, oldConfDir
+ }()
+ for _, dir := range []string{util.DataDir, util.HistoryDir, util.ConfDir} {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ Conf = NewAppConf()
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ Conf.Sync = conf.NewSync()
+ if err := EnableEncryptedNotebook("old-review-password"); err != nil {
+ t.Fatal(err)
+ }
+ oldKEK, err := deriveKEK("old-review-password")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer zeroAndClear(oldKEK)
+ boxID := "20260905120100-review2"
+ crypt, dek, err := WrapNewDEK(boxID, oldKEK)
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer zeroAndClear(dek)
+ boxConf := conf.NewBoxConf()
+ boxConf.Encrypted, boxConf.BoxCrypt = true, crypt
+ if err = encryptBoxMetadata(boxID, boxConf, dek); err != nil {
+ t.Fatal(err)
+ }
+ historyDir := filepath.Join(util.HistoryDir, "2026-09-05-120100-delete", boxID, ".siyuan")
+ if err = os.MkdirAll(historyDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ data, err := json.Marshal(boxConf)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filepath.Join(historyDir, "conf.json"), data, 0644); err != nil {
+ t.Fatal(err)
+ }
+ data, err = json.Marshal(crypt)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(filepath.Join(historyDir, notebookCryptoBackupFilename), data, 0644); err != nil {
+ t.Fatal(err)
+ }
+ if !verifyKEKAgainstEncryptedHistory(oldKEK, nil) {
+ t.Fatal("fixture history cannot be decrypted")
+ }
+ if err = ChangeMasterPassword("old-review-password", "new-review-password"); err != nil {
+ t.Fatal(err)
+ }
+ if err = ChangeMasterPassword("new-review-password", "latest-password"); err != nil {
+ t.Fatal(err)
+ }
+ newKEK, err := deriveKEK("latest-password")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer zeroAndClear(newKEK)
+ if !verifyKEKAgainstEncryptedHistory(newKEK, currentNotebookCrypto()) {
+ t.Fatal("current password cannot decrypt historical envelopes")
+ }
+ backupData, err := os.ReadFile(dataCryptoBackupPath())
+ if err != nil {
+ t.Fatal(err)
+ }
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ _, recoveredKEK, err := deriveNotebookCryptoBackupCandidate("latest-password")
+ if recoveredKEK != nil {
+ zeroAndClear(recoveredKEK)
+ }
+ if err != nil {
+ t.Fatalf("current valid backup cannot restore deleted history after successful password change: %v", err)
+ }
+ if err = ImportNotebookCryptoBackup(backupData, "latest-password"); err != nil {
+ t.Fatalf("importing current backup cannot restore history: %v", err)
+ }
+ // 模拟从其他设备恢复改密前的目录,确认解锁路径也接受由当前备份保护的历史包络。
+ boxDir := filepath.Join(util.DataDir, boxID, ".siyuan")
+ if err = os.MkdirAll(boxDir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ for _, name := range []string{"conf.json", notebookCryptoBackupFilename} {
+ fileData, readErr := os.ReadFile(filepath.Join(historyDir, name))
+ if readErr != nil {
+ t.Fatal(readErr)
+ }
+ if err = os.WriteFile(filepath.Join(boxDir, name), fileData, 0644); err != nil {
+ t.Fatal(err)
+ }
+ }
+ restoredDEK, _, err := decryptBoxCrypt(boxID, newKEK)
+ defer zeroAndClear(restoredDEK)
+ if err != nil || !bytes.Equal(restoredDEK, dek) {
+ t.Fatalf("restored notebook cannot use current password: %v", err)
+ }
+}
+
+func TestHistoryKEKsAuthenticateAndDeduplicate(t *testing.T) {
+ first, second, third := bytes.Repeat([]byte{1}, 32), bytes.Repeat([]byte{2}, 32), bytes.Repeat([]byte{3}, 32)
+ wrapped, err := rewrapHistoryKEKs(first, second, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wrapped, err = rewrapHistoryKEKs(second, third, wrapped)
+ if err != nil {
+ t.Fatal(err)
+ }
+ wrapped, err = rewrapHistoryKEKs(third, first, wrapped)
+ if err != nil {
+ t.Fatal(err)
+ }
+ keys, err := decryptHistoryKEKs(first, wrapped)
+ defer clearHistoryKEKs(keys)
+ if err != nil || len(keys) != 2 || !bytes.Equal(keys[0], second) || !bytes.Equal(keys[1], third) {
+ t.Fatalf("password reuse lost or duplicated history keys: count=%d err=%v", len(keys), err)
+ }
+ nc := conf.NewNotebookCrypto()
+ nc.HistoryKEKs = wrapped
+ prepareBackupForWrite(nc)
+ nc.KEKMAC = computeKEKMAC(nc, first)
+ if !verifyKEKMAC(nc, first) {
+ t.Fatal("history key backup failed authentication")
+ }
+ nc.HistoryKEKs = nc.HistoryKEKs[:1]
+ if verifyKEKMAC(nc, first) {
+ t.Fatal("backup MAC accepted removed history key")
+ }
+ wrapped[1][len(wrapped[1])-1] ^= 1
+ if keys, err = decryptHistoryKEKs(first, wrapped); err == nil || len(keys) != 0 {
+ clearHistoryKEKs(keys)
+ t.Fatal("tampered keyring was accepted or returned partial plaintext keys")
+ }
+}
+
+func TestMasterPasswordMigrationRetainsHistoryKeysAfterBoxRemoval(t *testing.T) {
+ oldDataDir, oldConfDir, oldHistoryDir, oldConf := util.DataDir, util.ConfDir, util.HistoryDir, Conf
+ root := t.TempDir()
+ util.DataDir, util.ConfDir, util.HistoryDir = filepath.Join(root, "data"), filepath.Join(root, "conf"), filepath.Join(root, "history")
+ defer func() {
+ util.DataDir, util.ConfDir, util.HistoryDir, Conf = oldDataDir, oldConfDir, oldHistoryDir, oldConf
+ }()
+ for _, dir := range []string{util.DataDir, util.ConfDir, util.HistoryDir} {
+ if err := os.MkdirAll(dir, 0755); err != nil {
+ t.Fatal(err)
+ }
+ }
+ Conf = NewAppConf()
+ Conf.NotebookCrypto, Conf.Sync = conf.NewNotebookCrypto(), conf.NewSync()
+ if err := EnableEncryptedNotebook("migration-old"); err != nil {
+ t.Fatal(err)
+ }
+ oldKEK, err := deriveKEK("migration-old")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer zeroAndClear(oldKEK)
+ newKEK := util.DeriveKey("migration-new", Conf.NotebookCrypto.MasterSalt, Conf.NotebookCrypto.KDFParams)
+ defer zeroAndClear(newKEK)
+ wrapped, err := rewrapHistoryKEKs(oldKEK, newKEK, nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ verifier, err := util.EncryptWithAAD(newKEK, kekVerifierMagic, []byte("siyuan:kek-verifier"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ boxID := "20260905124500-migrate"
+ manifest := &masterPasswordMigration{OldVerifier: Conf.NotebookCrypto.KEKVerifier, NewVerifier: verifier, NewHistoryKEKs: wrapped, Boxes: []migrationBoxEntry{{BoxID: boxID}}}
+ if err = writeMasterPasswordMigration(manifest); err != nil {
+ t.Fatal(err)
+ }
+ Conf.NotebookCrypto.KEKVerifier = verifier
+ Conf.NotebookCrypto.VerifierNonce = mustEncryptionNonce(verifier)
+ removeMasterPasswordMigrationBox(boxID)
+ if pending, _ := MasterPasswordMigrationStatus(); !pending {
+ t.Fatal("removing last notebook discarded pending recovery keys")
+ }
+ recoverMasterPasswordMigration()
+ derived, err := deriveKEK("migration-new")
+ defer zeroAndClear(derived)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if pending, _ := MasterPasswordMigrationStatus(); pending {
+ t.Fatal("authenticated recovery did not finish migration")
+ }
+ backup, err := loadNotebookCryptoBackup()
+ if err != nil || backup == nil || !verifyKEKMAC(backup, newKEK) {
+ t.Fatalf("recovery did not publish authenticated backup: %v", err)
+ }
+ keys, err := decryptHistoryKEKs(newKEK, backup.HistoryKEKs)
+ defer clearHistoryKEKs(keys)
+ if err != nil || len(keys) != 1 || !bytes.Equal(keys[0], oldKEK) {
+ t.Fatalf("recovery lost historical key: %v", err)
+ }
+}