Skip to content

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

:sparkles: wire up encrypted-notebook enable flow + per-box unlock #18034

Daniel80c95904dcf8
diff --git a/kernel/api/notebook.go b/kernel/api/notebook.go
index a196c4f852..7624d6c7da 100644
--- a/kernel/api/notebook.go
+++ b/kernel/api/notebook.go
@@ -454,3 +454,162 @@ func lsNotebooks(c *gin.Context) {
"notebooks": notebooks,
}
}
+
+// enableEncryptedNotebooks 启用加密笔记本功能并设置主密码。
+// 重复启用返回错误,避免覆盖现有密钥参数。
+func enableEncryptedNotebooks(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var password string
+ if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("password", &password, true, true)) {
+ return
+ }
+
+ if err := model.EnableEncryptedNotebook(password); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+}
+
+// createEncryptedNotebook 创建一个新的加密笔记本。前置:加密功能已启用。
+// 创建时需提供主密码(用于派生 KEK 包络 DEK)。创建后笔记本处于锁定状态,
+// 调用方需再调 unlockBox + openNotebook 才能打开。
+func createEncryptedNotebook(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var name, password string
+ if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("name", &name, true, false),
+ util.BindJsonArg("password", &password, true, true),
+ ) {
+ return
+ }
+
+ id, err := model.CreateEncryptedBox(name, password)
+ if err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+
+ ret.Data = map[string]any{
+ "notebook": model.Conf.Box(id),
+ }
+}
+
+// unlockBox 用主密码派生 KEK 并解出指定加密笔记本的 DEK,缓存到内存。
+// 解锁后该笔记本即可被 Mount。每次调用跑一次 Argon2id(约 1 秒)。
+func unlockBox(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var notebook, password string
+ if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("notebook", &notebook, true, true),
+ util.BindJsonArg("password", &password, true, true),
+ ) {
+ return
+ }
+
+ if util.InvalidIDPattern(notebook, ret) {
+ return
+ }
+
+ box := &model.Box{ID: notebook}
+ boxConf := box.GetConf()
+ if boxConf == nil || !boxConf.Encrypted || boxConf.BoxCrypt == nil {
+ ret.Code = -1
+ ret.Msg = "notebook is not encrypted"
+ return
+ }
+
+ if err := model.UnlockBox(notebook, password, boxConf.BoxCrypt); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+}
+
+// lockBox 锁定指定加密笔记本:清除其 DEK 缓存并 Unmount。
+func lockBox(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var notebook string
+ if !util.ParseJsonArgs(arg, ret, util.BindJsonArg("notebook", &notebook, true, true)) {
+ return
+ }
+
+ if util.InvalidIDPattern(notebook, ret) {
+ return
+ }
+
+ if !model.IsEncryptedBox(notebook) {
+ ret.Code = -1
+ ret.Msg = "notebook is not encrypted"
+ return
+ }
+
+ model.LockBox(notebook)
+ model.Unmount(notebook)
+}
+
+// changeMasterPassword 修改加密笔记本的主密码。
+// 用旧密码校验后,用新密码派生新 KEK,重新加密 verifier 和所有加密笔记本的 WrappedDEK。
+// 必须在所有加密笔记本都已锁定(DEK 不在内存)的状态下调用。
+func changeMasterPassword(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ arg, ok := util.JsonArg(c, ret)
+ if !ok {
+ return
+ }
+
+ var oldPassword, newPassword string
+ if !util.ParseJsonArgs(arg, ret,
+ util.BindJsonArg("oldPassword", &oldPassword, true, true),
+ util.BindJsonArg("newPassword", &newPassword, true, true),
+ ) {
+ return
+ }
+
+ if err := model.ChangeMasterPassword(oldPassword, newPassword); err != nil {
+ ret.Code = -1
+ ret.Msg = err.Error()
+ return
+ }
+}
+
+// getEncryptedNotebookStatus 返回加密笔记本功能的启用状态。
+func getEncryptedNotebookStatus(c *gin.Context) {
+ ret := gulu.Ret.NewResult()
+ defer c.JSON(http.StatusOK, ret)
+
+ ret.Data = map[string]any{
+ "enabled": model.Conf.NotebookCrypto.Enabled,
+ }
+}
diff --git a/kernel/api/router.go b/kernel/api/router.go
index fc088de9ae..e99fa081fc 100644
--- a/kernel/api/router.go
+++ b/kernel/api/router.go
@@ -118,6 +118,12 @@ func ServeAPI(ginServer *gin.Engine) {
ginServer.Handle("POST", "/api/notebook/changeSortNotebook", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, changeSortNotebook)
ginServer.Handle("POST", "/api/notebook/setNotebookIcon", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, setNotebookIcon)
ginServer.Handle("POST", "/api/notebook/getNotebookInfo", model.CheckAuth, getNotebookInfo)
+ ginServer.Handle("POST", "/api/notebook/enableEncryptedNotebooks", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, enableEncryptedNotebooks)
+ ginServer.Handle("POST", "/api/notebook/createEncryptedNotebook", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, createEncryptedNotebook)
+ ginServer.Handle("POST", "/api/notebook/unlockBox", model.CheckAuth, model.CheckAdminRole, unlockBox)
+ ginServer.Handle("POST", "/api/notebook/lockBox", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, lockBox)
+ ginServer.Handle("POST", "/api/notebook/changeMasterPassword", model.CheckAuth, model.CheckAdminRole, model.CheckReadonly, changeMasterPassword)
+ ginServer.Handle("POST", "/api/notebook/getEncryptedNotebookStatus", model.CheckAuth, getEncryptedNotebookStatus)
ginServer.Handle("POST", "/api/filetree/searchDocs", model.CheckAuth, searchDocs)
ginServer.Handle("POST", "/api/filetree/listDocsByPath", model.CheckAuth, listDocsByPath)
diff --git a/kernel/model/box.go b/kernel/model/box.go
index c144e7f945..22ed8ce48a 100644
--- a/kernel/model/box.go
+++ b/kernel/model/box.go
@@ -59,6 +59,8 @@ type Box struct {
NewFlashcardCount int `json:"newFlashcardCount"`
DueFlashcardCount int `json:"dueFlashcardCount"`
FlashcardCount int `json:"flashcardCount"`
+
+ Encrypted bool `json:"encrypted"` // 是否为加密笔记本
}
func StatJob() {
@@ -138,12 +140,13 @@ func ListNotebooks() (ret []*Box, err error) {
}
box := &Box{
- ID: id,
- Name: boxConf.Name,
- Icon: icon,
- Sort: boxConf.Sort,
- SortMode: boxConf.SortMode,
- Closed: boxConf.Closed,
+ ID: id,
+ Name: boxConf.Name,
+ Icon: icon,
+ Sort: boxConf.Sort,
+ SortMode: boxConf.SortMode,
+ Closed: boxConf.Closed,
+ Encrypted: boxConf.Encrypted,
}
if !isExistConf {
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index acc7ac3bc2..5443476b3a 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -28,15 +28,17 @@ import (
// kekVerifierMagic 是写入 KEKVerifier 的固定魔数。启用时用 KEK 加密它,校验主密码时解密比对。
var kekVerifierMagic = []byte("siyuan-enc-v1")
+// cachedDEKs 缓存已解锁加密笔记本的 DEK,按 boxID 索引。
+// KEK 不全局缓存("严格每笔记本单独解锁"语义):UnlockBox 临时派生 KEK 解出 DEK 后即丢弃 KEK,
+// 仅保留 per-box DEK 供后续读写加解密。
var (
- cachedKEK []byte // 主密码派生的 KEK,启用且解锁后驻留内存
- cachedKEKLock sync.RWMutex
- cachedDEKs = map[string][]byte{} // boxID → DEK
+ cachedDEKs = map[string][]byte{}
cachedDEKsLock sync.RWMutex
)
// EnableEncryptedNotebook 启用加密笔记本功能:生成 MasterSalt、派生 KEK、写入校验值并持久化。
// 重复调用(已启用)返回错误,避免覆盖现有加密笔记本的密钥参数。
+// KEK 不缓存——启用后用户需对每个加密笔记本单独调 UnlockBox 解锁。
func EnableEncryptedNotebook(password string) error {
if len(password) == 0 {
return errors.New("password must not be empty")
@@ -58,7 +60,7 @@ func EnableEncryptedNotebook(password string) error {
}
kek := util.DeriveKey(password, salt, params)
- // 用 KEK 加密固定魔数作为校验值,落盘后供后续 UnlockKEK 离线校验
+ // 用 KEK 加密固定魔数作为校验值,落盘后供后续 UnlockBox 离线校验
verifierCT, err := util.Encrypt(kek, kekVerifierMagic)
if err != nil {
return err
@@ -67,27 +69,21 @@ func EnableEncryptedNotebook(password string) error {
Conf.NotebookCrypto.Enabled = true
Conf.NotebookCrypto.MasterSalt = salt
Conf.NotebookCrypto.KDFParams = params
- // Encrypt 返回 nonce||ciphertext,整段存为 KEKVerifier,nonce 从前 12 字节切出。
Conf.NotebookCrypto.KEKVerifier = verifierCT
Conf.NotebookCrypto.VerifierNonce = verifierCT[:12]
- cachedKEKLock.Lock()
- cachedKEK = kek
- cachedKEKLock.Unlock()
-
Conf.Save()
return nil
}
-// UnlockKEK 用主密码派生 KEK,校验通过后缓存到内存。
-// 校验方式:解 KEKVerifier,若能得到 kekVerifierMagic 则密码正确。
-func UnlockKEK(password string) error {
+// deriveKEK 从主密码派生 KEK 并校验。校验失败返回错误。KEK 仅在函数作用域内有效,调用方负责使用。
+func deriveKEK(password string) ([]byte, error) {
Conf.m.RLock()
nc := Conf.NotebookCrypto
Conf.m.RUnlock()
if !nc.Enabled {
- return errors.New("encrypted notebook not enabled")
+ return nil, errors.New("encrypted notebook not enabled")
}
params := nc.KDFParams
if params.KeyLength == 0 {
@@ -97,57 +93,65 @@ func UnlockKEK(password string) error {
decrypted, err := util.Decrypt(kek, nc.KEKVerifier)
if err != nil {
- return errors.New("incorrect password")
+ return nil, errors.New("incorrect password")
}
if string(decrypted) != string(kekVerifierMagic) {
- return errors.New("incorrect password")
+ return nil, errors.New("incorrect password")
}
+ return kek, nil
+}
- cachedKEKLock.Lock()
- cachedKEK = kek
- cachedKEKLock.Unlock()
+// UnlockBox 用主密码派生 KEK,解出该笔记本的 DEK 并缓存。KEK 用完即弃,不全局缓存。
+// 每次调用都跑一次 Argon2id(约 1 秒),严格满足"每笔记本单独解锁"语义。
+func UnlockBox(boxID string, password string, boxEnc *conf.BoxEncryption) error {
+ if boxEnc == nil || len(boxEnc.WrappedDEK) == 0 {
+ return errors.New("no encrypted key material for box")
+ }
+ kek, err := deriveKEK(password)
+ if err != nil {
+ return err
+ }
+ dek, err := util.Decrypt(kek, boxEnc.WrappedDEK)
+ if err != nil {
+ return err
+ }
+ cachedDEKsLock.Lock()
+ cachedDEKs[boxID] = dek
+ cachedDEKsLock.Unlock()
return nil
}
-// IsKEKUnlocked 返回 KEK 是否在内存(加密功能是否已解锁)。
-func IsKEKUnlocked() bool {
- cachedKEKLock.RLock()
- defer cachedKEKLock.RUnlock()
- return len(cachedKEK) > 0
+// IsBoxUnlocked 返回该笔记本的 DEK 是否在内存(是否已解锁)。
+func IsBoxUnlocked(boxID string) bool {
+ cachedDEKsLock.RLock()
+ defer cachedDEKsLock.RUnlock()
+ _, ok := cachedDEKs[boxID]
+ return ok
}
-// getKEK 取内存中的 KEK,未解锁时返回错误。
-func getKEK() ([]byte, error) {
- cachedKEKLock.RLock()
- defer cachedKEKLock.RUnlock()
- if len(cachedKEK) == 0 {
- return nil, errors.New("encrypted notebook locked, KEK unavailable")
+// LockBox 清除指定笔记本的 DEK。Unmount 单个加密笔记本或手动锁定时调用。
+func LockBox(boxID string) {
+ cachedDEKsLock.Lock()
+ defer cachedDEKsLock.Unlock()
+ if dek, ok := cachedDEKs[boxID]; ok {
+ zeroAndClear(dek)
+ delete(cachedDEKs, boxID)
}
- return cachedKEK, nil
}
-// LockKEK 清除内存中的 KEK 和所有已缓存的 DEK。Unmount 加密笔记本或全局锁定时调用。
-func LockKEK() {
- cachedKEKLock.Lock()
- zeroAndClear(cachedKEK)
- cachedKEK = nil
- cachedKEKLock.Unlock()
-
+// LockAllBoxes 清除所有已缓存的 DEK。退出登录或全局锁定时调用。
+func LockAllBoxes() {
cachedDEKsLock.Lock()
+ defer cachedDEKsLock.Unlock()
for id, dek := range cachedDEKs {
zeroAndClear(dek)
delete(cachedDEKs, id)
}
- cachedDEKsLock.Unlock()
}
-// WrapNewDEK 为新加密笔记本生成随机 DEK,用 KEK 包络后返回 BoxEncryption 元数据。
-// 调用方负责把返回值写入 BoxConf.BoxCrypt 并 SaveConf。
-func WrapNewDEK() (*conf.BoxEncryption, error) {
- kek, err := getKEK()
- if err != nil {
- return nil, err
- }
+// WrapNewDEK 用给定 KEK 生成随机 DEK 并包络,返回 BoxEncryption 元数据。
+// KEK 由调用方临时派生(不来自全局缓存),调用方负责使用后丢弃。
+func WrapNewDEK(kek []byte) (*conf.BoxEncryption, error) {
dek, err := util.GenerateDEK()
if err != nil {
return nil, err
@@ -164,14 +168,11 @@ func WrapNewDEK() (*conf.BoxEncryption, error) {
}
// UnwrapDEK 从 BoxEncryption 解出 DEK 并缓存到内存,供后续 GetDEK 使用。
-func UnwrapDEK(boxID string, enc *conf.BoxEncryption) error {
+// 仅在 KEK 已通过 UnlockBox 缓存 DEK 的场景之外使用(如改密流程内部)。
+func UnwrapDEK(boxID string, enc *conf.BoxEncryption, kek []byte) error {
if enc == nil || len(enc.WrappedDEK) == 0 {
return errors.New("no encrypted key material for box")
}
- kek, err := getKEK()
- if err != nil {
- return err
- }
dek, err := util.Decrypt(kek, enc.WrappedDEK)
if err != nil {
return err
@@ -195,20 +196,13 @@ func GetDEK(boxID string) ([]byte, error) {
// ClearDEK 清除指定笔记本的 DEK。Unmount 单个加密笔记本时调用。
func ClearDEK(boxID string) {
- cachedDEKsLock.Lock()
- defer cachedDEKsLock.Unlock()
- if dek, ok := cachedDEKs[boxID]; ok {
- zeroAndClear(dek)
- delete(cachedDEKs, boxID)
- }
+ LockBox(boxID)
}
// ChangeMasterPassword 改主密码:用旧密码校验后,用新密码派生新 KEK,
// 重新加密 verifier,并把所有加密笔记本的 WrappedDEK 用新 KEK 重新包络后写回各自的 BoxConf。
//
-// 注意:必须在所有加密笔记本都已 Unmount 的状态下调用(DEK 不在内存)。
-// 本函数会遍历磁盘上的加密笔记本,用旧 KEK 解开 WrappedDEK 再用新 KEK 重新 wrap,
-// 因此改密成本与加密笔记本数量、磁盘 IO 相关,但不涉及 .sy/assets 数据本身的重新加密。
+// 注意:必须在所有加密笔记本都已 Unmount 的状态下调用(DEK 不在内存),否则新旧 KEK 切换会让缓存与磁盘不一致。
func ChangeMasterPassword(oldPassword, newPassword string) error {
if len(newPassword) == 0 {
return errors.New("new password must not be empty")
@@ -219,14 +213,10 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
dekCount := len(cachedDEKs)
cachedDEKsLock.RUnlock()
if dekCount > 0 {
- return errors.New("cannot change master password while encrypted notebooks are mounted (DEKs in memory), unmount them first")
+ return errors.New("cannot change master password while encrypted notebooks are unlocked (DEKs in memory), lock them first")
}
- // 用旧密码校验并取出旧 KEK
- if err := UnlockKEK(oldPassword); err != nil {
- return err
- }
- oldKEK, err := getKEK()
+ oldKEK, err := deriveKEK(oldPassword)
if err != nil {
return err
}
@@ -241,8 +231,7 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
return err
}
- // 遍历所有笔记本,找到加密笔记本并用新 KEK 重新 wrap 其 WrappedDEK。
- // 当前设计只有一个加密笔记本(EncryptedBoxID),但用 Encrypted 标志遍历更稳健,也为未来多笔记本预留。
+ // 遍历所有笔记本,找到加密笔记本并用新 KEK 重新 wrap 其 WrappedDEK
boxes, err := ListNotebooks()
if err != nil {
return err
@@ -252,13 +241,10 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
if boxConf == nil || !boxConf.Encrypted || boxConf.BoxCrypt == nil {
continue
}
- // 用旧 KEK 解出 DEK 明文
dek, err := util.Decrypt(oldKEK, boxConf.BoxCrypt.WrappedDEK)
if err != nil {
- // 解不开说明 WrappedDEK 与旧 KEK 不匹配(配置损坏或 KEK 已被其他流程改过),中断改密避免数据不可用
return errors.New("failed to unwrap DEK for box " + b.ID + " during password change: " + err.Error())
}
- // 用新 KEK 重新 wrap
newWrapped, err := util.Encrypt(newKEK, dek)
if err != nil {
return err
@@ -271,20 +257,50 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
Conf.NotebookCrypto.KEKVerifier = newVerifier
Conf.NotebookCrypto.VerifierNonce = newVerifier[:12]
- cachedKEKLock.Lock()
- zeroAndClear(cachedKEK)
- cachedKEK = newKEK
- cachedKEKLock.Unlock()
-
Conf.Save()
return nil
}
// IsEncryptedBox 判断给定 boxID 是否为加密笔记本。
func IsEncryptedBox(boxID string) bool {
+ box := &Box{ID: boxID}
+ boxConf := box.GetConf()
+ return boxConf != nil && boxConf.Encrypted
+}
+
+// CreateEncryptedBox 创建一个新的加密笔记本。可多次调用创建多个。
+// 前置:加密功能已启用。创建时需要主密码(临时派生 KEK 用于 wrap DEK,用完即弃)。
+// 创建后笔记本处于"已锁定"状态(DEK 未缓存),需调用方再调 UnlockBox + Mount 才能打开。
+func CreateEncryptedBox(name, password string) (id string, err error) {
Conf.m.RLock()
- defer Conf.m.RUnlock()
- return Conf.NotebookCrypto.Enabled && Conf.NotebookCrypto.EncryptedBoxID == boxID
+ enabled := Conf.NotebookCrypto.Enabled
+ Conf.m.RUnlock()
+ if !enabled {
+ return "", errors.New("encrypted notebook feature not enabled")
+ }
+
+ kek, err := deriveKEK(password)
+ if err != nil {
+ return "", err
+ }
+
+ enc, err := WrapNewDEK(kek)
+ if err != nil {
+ return "", err
+ }
+
+ id, err = CreateBox(name)
+ if err != nil {
+ return "", err
+ }
+
+ box := &Box{ID: id}
+ boxConf := box.GetConf()
+ boxConf.Encrypted = true
+ boxConf.BoxCrypt = enc
+ box.SaveConf(boxConf)
+ IncSync()
+ return id, nil
}
// zeroAndClear 把密钥字节清零后再置空,尽量减少密钥在内存中的残留时间。
diff --git a/kernel/model/crypto_test.go b/kernel/model/crypto_test.go
index 97afbbdc62..50de266385 100644
--- a/kernel/model/crypto_test.go
+++ b/kernel/model/crypto_test.go
@@ -24,37 +24,72 @@ import (
"github.com/siyuan-note/siyuan/kernel/util"
)
-// setKEKForTest 把指定 KEK 注入内存缓存,跳过 EnableEncryptedNotebook 的落盘流程,便于纯内存测试。
-func setKEKForTest(kek []byte) {
- cachedKEKLock.Lock()
- defer cachedKEKLock.Unlock()
- cachedKEK = kek
+// setDEKForTest 把指定 DEK 直接注入 boxID 的缓存,绕过 UnlockBox 的 Argon2id 派生,便于纯内存测试。
+func setDEKForTest(boxID string, dek []byte) {
+ cachedDEKsLock.Lock()
+ defer cachedDEKsLock.Unlock()
+ cachedDEKs[boxID] = dek
}
-// TestIsKEKUnlockedLifecycle 验证 KEK 缓存的存在/缺失状态。
-func TestIsKEKUnlockedLifecycle(t *testing.T) {
- LockKEK() // 确保初始干净
- if IsKEKUnlocked() {
- t.Fatalf("KEK should not be available after LockKEK")
+// TestIsBoxUnlockedLifecycle 验证 DEK 缓存的存在/缺失状态。
+func TestIsBoxUnlockedLifecycle(t *testing.T) {
+ LockAllBoxes() // 确保初始干净
+ boxID := "lifecycle-test-box"
+ if IsBoxUnlocked(boxID) {
+ t.Fatalf("box should not be unlocked after LockAllBoxes")
}
- kek, _ := util.GenerateDEK()
- setKEKForTest(kek)
- if !IsKEKUnlocked() {
- t.Fatalf("KEK should be available after setKEKForTest")
+ dek, _ := util.GenerateDEK()
+ setDEKForTest(boxID, dek)
+ if !IsBoxUnlocked(boxID) {
+ t.Fatalf("box should be unlocked after setDEKForTest")
+ }
+ LockBox(boxID)
+ if IsBoxUnlocked(boxID) {
+ t.Fatalf("box should be locked after LockBox")
+ }
+}
+
+// TestLockAllBoxes 验证 LockAllBoxes 清空所有 DEK。
+func TestLockAllBoxes(t *testing.T) {
+ dek1, _ := util.GenerateDEK()
+ dek2, _ := util.GenerateDEK()
+ setDEKForTest("box-a", dek1)
+ setDEKForTest("box-b", dek2)
+
+ LockAllBoxes()
+ for _, id := range []string{"box-a", "box-b"} {
+ if IsBoxUnlocked(id) {
+ t.Fatalf("box %q should be locked after LockAllBoxes", id)
+ }
+ }
+}
+
+// TestGetDEKReturnsErrorAfterLock 验证 LockBox 后 GetDEK 报错。
+func TestGetDEKReturnsErrorAfterLock(t *testing.T) {
+ dek, _ := util.GenerateDEK()
+ boxID := "get-dek-test-box"
+ setDEKForTest(boxID, dek)
+
+ got, err := GetDEK(boxID)
+ if err != nil {
+ t.Fatalf("GetDEK before lock failed: %v", err)
+ }
+ if !bytes.Equal(dek, got) {
+ t.Fatalf("GetDEK returned wrong DEK")
}
- LockKEK()
- if IsKEKUnlocked() {
- t.Fatalf("KEK should be cleared after LockKEK")
+
+ LockBox(boxID)
+ if _, err := GetDEK(boxID); err == nil {
+ t.Fatalf("GetDEK should fail after LockBox")
}
}
-// TestWrapUnwrapDEKRoundTrip 验证生成 DEK → 包络 → 解包 → 还原。
-func TestWrapUnwrapDEKRoundTrip(t *testing.T) {
+// TestWrapNewDEKRoundTrip 验证用 KEK 生成 DEK → 包络 → 解包 → 还原。
+func TestWrapNewDEKRoundTrip(t *testing.T) {
kek, _ := util.GenerateDEK()
- setKEKForTest(kek)
- defer LockKEK()
+ defer LockAllBoxes()
- boxEnc, err := WrapNewDEK()
+ boxEnc, err := WrapNewDEK(kek)
if err != nil {
t.Fatalf("WrapNewDEK failed: %v", err)
}
@@ -62,8 +97,8 @@ func TestWrapUnwrapDEKRoundTrip(t *testing.T) {
t.Fatalf("BoxEncryption fields malformed: wrappedDEK=%d wrapNonce=%d", len(boxEnc.WrappedDEK), len(boxEnc.WrapNonce))
}
- boxID := "test-box-123"
- if err := UnwrapDEK(boxID, boxEnc); err != nil {
+ boxID := "wrap-roundtrip-box"
+ if err := UnwrapDEK(boxID, boxEnc, kek); err != nil {
t.Fatalf("UnwrapDEK failed: %v", err)
}
dek, err := GetDEK(boxID)
@@ -78,58 +113,30 @@ func TestWrapUnwrapDEKRoundTrip(t *testing.T) {
// TestUnwrapDEKWithWrongKEK 验证用错误的 KEK 解包失败(GCM MAC 校验)。
func TestUnwrapDEKWithWrongKEK(t *testing.T) {
kek1, _ := util.GenerateDEK()
- setKEKForTest(kek1)
- boxEnc, _ := WrapNewDEK()
+ boxEnc, _ := WrapNewDEK(kek1)
- // 换一个错误的 KEK
kek2, _ := util.GenerateDEK()
- setKEKForTest(kek2)
- defer LockKEK()
+ defer LockAllBoxes()
- if err := UnwrapDEK("wrong-kek-box", boxEnc); err == nil {
+ if err := UnwrapDEK("wrong-kek-box", boxEnc, kek2); err == nil {
t.Fatalf("UnwrapDEK with wrong KEK should fail")
}
}
-// TestClearDEK 验证 ClearDEK 后 DEK 不可再取。
-func TestClearDEK(t *testing.T) {
- kek, _ := util.GenerateDEK()
- setKEKForTest(kek)
- defer LockKEK()
-
- boxEnc, _ := WrapNewDEK()
- boxID := "clear-test-box"
- UnwrapDEK(boxID, boxEnc)
-
- ClearDEK(boxID)
- if _, err := GetDEK(boxID); err == nil {
- t.Fatalf("GetDEK should fail after ClearDEK")
- }
-}
-
-// TestLockKEKClearsAllDEKs 验证 LockKEK 同时清空所有 DEK。
-func TestLockKEKClearsAllDEKs(t *testing.T) {
+// TestWrapNewDEKProducesUniqueDEKs 验证两次调用 WrapNewDEK 生成不同的 DEK(随机性)。
+func TestWrapNewDEKProducesUniqueDEKs(t *testing.T) {
kek, _ := util.GenerateDEK()
- setKEKForTest(kek)
+ defer LockAllBoxes()
- boxEnc1, _ := WrapNewDEK()
- boxEnc2, _ := WrapNewDEK()
- UnwrapDEK("box-a", boxEnc1)
- UnwrapDEK("box-b", boxEnc2)
-
- LockKEK()
- for _, id := range []string{"box-a", "box-b"} {
- if _, err := GetDEK(id); err == nil {
- t.Fatalf("GetDEK(%q) should fail after LockKEK", id)
- }
- }
-}
+ enc1, _ := WrapNewDEK(kek)
+ enc2, _ := WrapNewDEK(kek)
-// TestWrapNewDEKRequiresKEK 验证 KEK 未缓存时 WrapNewDEK 报错。
-func TestWrapNewDEKRequiresKEK(t *testing.T) {
- LockKEK()
- if _, err := WrapNewDEK(); err == nil {
- t.Fatalf("WrapNewDEK should fail when KEK not cached")
+ UnwrapDEK("uniq-box-1", enc1, kek)
+ UnwrapDEK("uniq-box-2", enc2, kek)
+ dek1, _ := GetDEK("uniq-box-1")
+ dek2, _ := GetDEK("uniq-box-2")
+ if bytes.Equal(dek1, dek2) {
+ t.Fatalf("two WrapNewDEK calls produced identical DEKs (not random?)")
}
}
@@ -144,7 +151,6 @@ func TestBoxEncryptionRoundTripViaUtil(t *testing.T) {
WrapNonce: wrapped[:12],
}
- // 模拟 UnwrapDEK 的核心:用 KEK 解开
recoveredDEK, err := util.Decrypt(kek, boxEnc.WrappedDEK)
if err != nil {
t.Fatalf("Decrypt wrapped DEK failed: %v", err)
diff --git a/kernel/model/mount.go b/kernel/model/mount.go
index b34f88cf23..c594f874cc 100644
--- a/kernel/model/mount.go
+++ b/kernel/model/mount.go
@@ -208,6 +208,10 @@ func unmount0(boxID string) {
boxConf.Closed = true
box.SaveConf(boxConf)
box.Unindex()
+ if boxConf.Encrypted {
+ // 加密笔记本关闭时清除其 DEK 缓存,恢复"已锁定"状态
+ ClearDEK(boxID)
+ }
}
func Mount(boxID string) (alreadyMount bool, err error) {
@@ -291,6 +295,12 @@ func Mount(boxID string) (alreadyMount bool, err error) {
}
}
+ // 加密笔记本必须先通过 UnlockBox 解出 DEK,否则拒绝挂载。Mount 本身不接收密码,
+ // 前端流程为:先调 /api/notebook/unlockBox 解锁,再调 openNotebook 挂载。
+ if preConf := (&Box{ID: boxID}).GetConf(); preConf.Encrypted && !IsBoxUnlocked(boxID) {
+ return false, errors.New("encrypted notebook locked, please unlock it first")
+ }
+
box := &Box{ID: boxID}
boxConf := box.GetConf()
boxConf.Closed = false