Skip to content

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

:bug: Avoid encrypted notebook creation deadlock https://github.com/siyuan-note/siyuan/issues/18674

Danielba6c15395d69
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index a233d6c6df..fc38ab6e2f 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -2533,6 +2533,10 @@ func copyAssetDecryptIfEncrypted(srcPath, destPath string) error {
// 前置:加密功能已启用。创建时需要主密码(临时派生 KEK 用于 wrap DEK,用完即弃)。
// 创建后直接用生成的 DEK 打开加密 db 并缓存(已解锁状态),调用方随后调 openNotebook 即可挂载。
func CreateEncryptedBox(name, password string) (id string, err error) {
+ return createEncryptedBox(name, password, EnsureBoxDoc)
+}
+
+func createEncryptedBox(name, password string, initializeBoxDoc func(string) (string, error)) (id string, err error) {
notebookCryptoMu.Lock()
defer notebookCryptoMu.Unlock()
@@ -2553,12 +2557,15 @@ func CreateEncryptedBox(name, password string) (id string, err error) {
if err != nil {
return "", err
}
+ releaseTransition := holdEncryptedBoxTransition(id)
+ defer releaseTransition()
setEncryptedBoxState(id, EncryptedBoxStateUnlocking)
// 若后续步骤失败,清理已创建的 box 目录和加密 db 文件,避免半创建状态
createdBoxID := id
defer func() {
if err != nil {
+ setEncryptedBoxState(createdBoxID, EncryptedBoxStateError)
cleanupFailedEncryptedBox(createdBoxID)
id = ""
}
@@ -2605,14 +2612,15 @@ func CreateEncryptedBox(name, password string) (id string, err error) {
cachedDEKs[id] = dek
cachedDEKsLock.Unlock()
- if _, err = EnsureBoxDoc(id); err != nil {
- return "", fmt.Errorf("initialize encrypted notebook document failed: %w", err)
- }
-
- // 初始化自动锁定访问时间戳,与 UnlockBox 对称
+ // DEK 和加密数据库就绪后允许内部初始化读取密钥,但在笔记本文档创建完成前不接纳外部请求。
newVal := &atomic.Int64{}
newVal.Store(time.Now().UnixNano())
boxLastAccess.Store(id, newVal)
+ setEncryptedBoxStateWithAdmission(id, EncryptedBoxStateUnlocked, false)
+
+ if _, err = initializeBoxDoc(id); err != nil {
+ return "", fmt.Errorf("initialize encrypted notebook document failed: %w", err)
+ }
setEncryptedBoxState(id, EncryptedBoxStateUnlocked)
IncSync()
@@ -2640,6 +2648,7 @@ func cleanupFailedEncryptedBox(boxID string) {
}
cachedDEKsLock.Unlock()
mountedEncryptedBoxes.Delete(boxID)
+ boxLastAccess.Delete(boxID)
sql.RemoveEncryptedDBFile(boxID)
treenode.RemoveEncryptedBlockTreeDBFile(boxID)
removeEncryptedBoxLifecycle(boxID)
diff --git a/kernel/model/crypto_create_sqlcipher_test.go b/kernel/model/crypto_create_sqlcipher_test.go
new file mode 100644
index 0000000000..f942a9f36a
--- /dev/null
+++ b/kernel/model/crypto_create_sqlcipher_test.go
@@ -0,0 +1,157 @@
+// 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/>.
+
+//go:build sqlcipher || libsqlcipher
+
+package model
+
+import (
+ "context"
+ "errors"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "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"
+)
+
+const createEncryptedBoxTestHelperEnv = "SIYUAN_TEST_CREATE_ENCRYPTED_BOX"
+
+func TestCreateEncryptedBoxInitializesBoxDocument(t *testing.T) {
+ if os.Getenv(createEncryptedBoxTestHelperEnv) == "1" {
+ testCreateEncryptedBoxInitializesBoxDocument(t)
+ return
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestCreateEncryptedBoxInitializesBoxDocument$")
+ cmd.Env = append(os.Environ(), createEncryptedBoxTestHelperEnv+"=1")
+ output, err := cmd.CombinedOutput()
+ if errors.Is(ctx.Err(), context.DeadlineExceeded) {
+ t.Fatalf("creating an encrypted notebook timed out:\n%s", output)
+ }
+ if err != nil {
+ t.Fatalf("encrypted notebook creation helper failed: %v\n%s", err, output)
+ }
+}
+
+func testCreateEncryptedBoxInitializesBoxDocument(t *testing.T) {
+ root := t.TempDir()
+ util.DataDir = filepath.Join(root, "data")
+ util.TempDir = filepath.Join(root, "temp")
+ util.ConfDir = filepath.Join(root, "conf")
+ util.HistoryDir = filepath.Join(root, "history")
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.DBPath = filepath.Join(util.TempDir, util.DBName)
+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
+ util.BlockTreeDBPath = 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)
+ }
+ }
+
+ Conf = NewAppConf()
+ Conf.FileTree = conf.NewFileTree()
+ *Conf.FileTree.BoxDocEnabled = true
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ Conf.Sync = conf.NewSync()
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ t.Cleanup(sql.CloseDatabase)
+ password := "create-encrypted-notebook-test"
+ if err := EnableEncryptedNotebook(password); err != nil {
+ t.Fatalf("enable encrypted notebooks failed: %v", err)
+ }
+
+ boxID, err := CreateEncryptedBox("Encrypted", password)
+ if err != nil {
+ t.Fatalf("create encrypted notebook failed: %v", err)
+ }
+ if state := GetEncryptedBoxState(boxID); state != EncryptedBoxStateUnlocked {
+ t.Fatalf("expected Unlocked state after creation, got %s", state)
+ }
+ boxDocData, err := os.ReadFile(filepath.Join(util.DataDir, boxID, boxDocPath(boxID)))
+ if err != nil {
+ t.Fatalf("read encrypted notebook document failed: %v", err)
+ }
+ if !util.IsCiphertext(boxDocData) {
+ t.Fatal("encrypted notebook document was stored as plaintext")
+ }
+ tree, err := filesys.LoadTree(boxID, boxDocPath(boxID), util.NewLute())
+ if err != nil {
+ t.Fatalf("load encrypted notebook document failed: %v", err)
+ }
+ if tree.ID != boxID {
+ t.Fatalf("unexpected encrypted notebook document ID: %s", tree.ID)
+ }
+
+ if _, err = CreateBox("Normal"); err != nil {
+ t.Fatalf("create normal notebook after encrypted notebook failed: %v", err)
+ }
+
+ expectedInitializationError := errors.New("injected notebook document initialization failure")
+ failedBoxID := ""
+ _, err = createEncryptedBox("Failure", password, func(boxID string) (string, error) {
+ failedBoxID = boxID
+ if state := GetEncryptedBoxState(boxID); state != EncryptedBoxStateUnlocked {
+ return "", errors.New("encrypted notebook key was not ready for internal initialization")
+ }
+ if acquireErr := AcquireEncryptedBoxOperation(boxID); acquireErr == nil {
+ ReleaseEncryptedBoxOperation(boxID)
+ return "", errors.New("encrypted notebook admitted an external operation during initialization")
+ }
+ return "", expectedInitializationError
+ })
+ if !errors.Is(err, expectedInitializationError) {
+ t.Fatalf("unexpected encrypted notebook initialization error: %v", err)
+ }
+ if failedBoxID == "" {
+ t.Fatal("failed encrypted notebook ID was not captured")
+ }
+ if _, statErr := os.Stat(filepath.Join(util.DataDir, failedBoxID)); !os.IsNotExist(statErr) {
+ t.Fatalf("failed encrypted notebook directory was not removed: %v", statErr)
+ }
+ if IsBoxUnlocked(failedBoxID) {
+ t.Fatal("failed encrypted notebook retained its DEK")
+ }
+ if sql.GetEncryptedDB(failedBoxID) != nil {
+ t.Fatal("failed encrypted notebook retained its content database")
+ }
+ for _, openedBoxID := range treenode.GetOpenedEncryptedBoxIDs() {
+ if openedBoxID == failedBoxID {
+ t.Fatal("failed encrypted notebook retained its block tree database")
+ }
+ }
+ if _, ok := encryptedBoxLifecycles.Load(failedBoxID); ok {
+ t.Fatal("failed encrypted notebook retained its lifecycle")
+ }
+ if _, ok := boxLastAccess.Load(failedBoxID); ok {
+ t.Fatal("failed encrypted notebook retained its access timestamp")
+ }
+ if isRuntimeEncryptedBox(failedBoxID) {
+ t.Fatal("failed encrypted notebook retained its runtime identity")
+ }
+}
diff --git a/kernel/model/crypto_lifecycle.go b/kernel/model/crypto_lifecycle.go
index a6a1798c82..21da66ea20 100644
--- a/kernel/model/crypto_lifecycle.go
+++ b/kernel/model/crypto_lifecycle.go
@@ -51,6 +51,7 @@ type encryptedBoxLifecycle struct {
lock sync.Mutex
condition *sync.Cond
state EncryptedBoxState
+ acceptOperations bool
activeOperations int
}
@@ -70,9 +71,15 @@ func getEncryptedBoxLifecycle(boxID string) *encryptedBoxLifecycle {
}
func setEncryptedBoxState(boxID string, state EncryptedBoxState) {
+ setEncryptedBoxStateWithAdmission(boxID, state, state == EncryptedBoxStateUnlocked)
+}
+
+// setEncryptedBoxStateWithAdmission 更新生命周期状态,并控制是否接纳新的外部请求。
+func setEncryptedBoxStateWithAdmission(boxID string, state EncryptedBoxState, acceptOperations bool) {
lifecycle := getEncryptedBoxLifecycle(boxID)
lifecycle.lock.Lock()
lifecycle.state = state
+ lifecycle.acceptOperations = acceptOperations && state == EncryptedBoxStateUnlocked
lifecycle.condition.Broadcast()
lifecycle.lock.Unlock()
}
@@ -95,6 +102,7 @@ func repairEncryptedBoxStateFromDEK(boxID string) {
defer lifecycle.lock.Unlock()
if lifecycle.state == EncryptedBoxStateLocked && IsBoxUnlocked(boxID) {
lifecycle.state = EncryptedBoxStateUnlocked
+ lifecycle.acceptOperations = true
lifecycle.condition.Broadcast()
}
}
@@ -146,9 +154,10 @@ func AcquireEncryptedBoxOperation(boxID string) error {
defer lifecycle.lock.Unlock()
if lifecycle.state == EncryptedBoxStateLocked && IsBoxUnlocked(boxID) {
lifecycle.state = EncryptedBoxStateUnlocked
+ lifecycle.acceptOperations = true
lifecycle.condition.Broadcast()
}
- if lifecycle.state != EncryptedBoxStateUnlocked {
+ if lifecycle.state != EncryptedBoxStateUnlocked || !lifecycle.acceptOperations {
return ErrEncryptedBoxNotUnlocked
}
lifecycle.activeOperations++
@@ -173,6 +182,7 @@ func beginEncryptedBoxLock(boxID string) {
lifecycle := getEncryptedBoxLifecycle(boxID)
lifecycle.lock.Lock()
lifecycle.state = EncryptedBoxStateLocking
+ lifecycle.acceptOperations = false
for lifecycle.activeOperations > 0 {
lifecycle.condition.Wait()
}
diff --git a/kernel/model/crypto_lifecycle_test.go b/kernel/model/crypto_lifecycle_test.go
index c4508f98ac..c010496937 100644
--- a/kernel/model/crypto_lifecycle_test.go
+++ b/kernel/model/crypto_lifecycle_test.go
@@ -40,6 +40,23 @@ func TestAcquireEncryptedBoxOperationsAllowsEmptyClosedScope(t *testing.T) {
release()
}
+func TestEncryptedBoxOperationAdmissionCanWaitForInitialization(t *testing.T) {
+ boxID := "20260812223000-abcdefg"
+ cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)
+ defer cleanup()
+
+ setEncryptedBoxStateWithAdmission(boxID, EncryptedBoxStateUnlocked, false)
+ if err := AcquireEncryptedBoxOperation(boxID); err == nil {
+ ReleaseEncryptedBoxOperation(boxID)
+ t.Fatal("encrypted notebook admitted an operation before initialization completed")
+ }
+ setEncryptedBoxState(boxID, EncryptedBoxStateUnlocked)
+ if err := AcquireEncryptedBoxOperation(boxID); err != nil {
+ t.Fatalf("initialized encrypted notebook rejected an operation: %v", err)
+ }
+ ReleaseEncryptedBoxOperation(boxID)
+}
+
func TestAcquireEncryptedBoxOperationsReportsClosedScope(t *testing.T) {
boxID := "20260803190000-abcdefg"
cleanup := prepareEncryptedBoxLifecycleTest(t, boxID)