Skip to content

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

:bug: Keep password migration snapshots and uploads coherent https://github.com/siyuan-note/siyuan/issues/20971

Danielf4b4c3443f27
diff --git a/docs/ENCRYPTED-NOTEBOOK.md b/docs/ENCRYPTED-NOTEBOOK.md
index a1be2ae007..8ecc47bdf8 100644
--- a/docs/ENCRYPTED-NOTEBOOK.md
+++ b/docs/ENCRYPTED-NOTEBOOK.md
@@ -598,6 +598,8 @@ The SQLCipher main database, WAL, SHM, rollback journal, temporary files, and ba
On a password change, live notebooks' WrappedDEKs are rewrapped under the new KEK. Previous KEKs and the outgoing KEK are deduplicated, individually authenticated and encrypted under the new KEK with the versioned AAD `siyuan:history-kek:v1`, and stored in `HistoryKEKs`. The global backup digest and HMAC protect this field, and the password-change migration manifest retains it for recovery. Removing the last notebook involved in migration must not discard historical keys before the backup transition completes. Recovery and unlock try the current KEK, then historical KEKs unwrapped from authenticated configuration; plaintext KEKs are cleared after use and not cached. Historical ciphertext directories need no rewriting. The current backup and password can recover envelopes retained through earlier password changes, including directories later restored from another device or an offline snapshot.
+The complete password change is serialized with synchronization and repository snapshot readers. An outstanding migration blocks manual snapshot creation and upload-capable synchronization. Download-only recovery retains its existing local safety checkpoint, excludes the local migration manifest from its comparison index, and cannot replace or delete that manifest. Downloaded notebooks receive the retained envelopes before the user authenticates the new password to finish the global backup transition. These guards preserve existing ciphertext and recovery formats.
+
Backup persistence follows the project's existing file-write semantics. The global `data-crypto-backup.json` is written to a random temporary file in the same directory and then atomically replaced; each notebook's `notebook-crypto-backup.json` uses the ordinary file-lock-protected configuration write. Neither path makes an additional power-loss durability guarantee through file or directory `fsync`. Startup validates the structure and digest that can be checked without a key; recovery validates the HMAC and key-envelope compatibility after the master password is entered. Corruption or mismatch is safely rejected instead of generating replacement key material.
An HMAC proves only that a party without the KEK did not alter the backup; it does not prove that the backup is the latest version. The current scope introduces no trusted external monotonic counter, so an authenticated historical backup or ciphertext may pass validation. `BackupID` and `CreatedAt` are information for diagnostics and manual comparison, not rollback anchors. Sync, history, and recovery flows must not describe successful authentication as proof of freshness or source trust. Strong rollback prevention requires independent trusted state and is outside this design's scope.
diff --git a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
index 39a4b73022..30a74538d2 100644
--- a/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
+++ b/docs/ENCRYPTED-NOTEBOOK.zh-CN.md
@@ -598,6 +598,8 @@ SQLCipher 的主数据库、WAL、SHM、回滚日志、临时文件和备份副
改密时,现存笔记本的 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` 只是供诊断和人工比较的信息,不是防回滚锚点。同步、历史或恢复流程不得把“认证成功”表述为“最新”或“来源可信”;真正防回滚需要独立可信状态,超出本设计范围。
diff --git a/kernel/model/crypto.go b/kernel/model/crypto.go
index d71fe0ab0e..28b5cef0c0 100644
--- a/kernel/model/crypto.go
+++ b/kernel/model/crypto.go
@@ -1749,6 +1749,10 @@ func ChangeMasterPassword(oldPassword, newPassword string) error {
if len(newPassword) == 0 {
return errors.New("new password must not be empty")
}
+ // Serialize the complete multi-file change with snapshot readers and all sync modes.
+ // Acquire these locks before notebookCryptoMu, as sync refresh also uses that mutex.
+ release := lockAssetSourceChange()
+ defer release()
notebookCryptoMu.Lock()
defer notebookCryptoMu.Unlock()
diff --git a/kernel/model/document_addressing.go b/kernel/model/document_addressing.go
index 696d2d99e2..1fb8d471d8 100644
--- a/kernel/model/document_addressing.go
+++ b/kernel/model/document_addressing.go
@@ -26,6 +26,9 @@ func checkDocumentAddressingConf(boxID string, data []byte) error {
// documentAddressingPreflight 在整批写入和删除前检查快照的规范路径及源规格。
func documentAddressingPreflight(repo *dejavu.Repo) func(*dejavu.CheckoutPlan) error {
return func(plan *dejavu.CheckoutPlan) error {
+ if err := checkPasswordMigrationCheckout(plan); err != nil {
+ return err
+ }
upserts := make([]string, 0, len(plan.Upserts))
removes := make([]string, 0, len(plan.Removes))
paths := map[string]string{}
diff --git a/kernel/model/repository.go b/kernel/model/repository.go
index 9e343586e2..73dcc0240b 100644
--- a/kernel/model/repository.go
+++ b/kernel/model/repository.go
@@ -1934,6 +1934,9 @@ func CreateRepoSnapshotWithFullCheck(memo string, fullCheck bool) (id string, cr
assetDownloadSourceMu.RLock()
defer assetDownloadSourceMu.RUnlock()
+ if err = checkRepositoryPasswordMigration(); err != nil {
+ return
+ }
repo, err := newRepositoryWithAssetSourceLocked()
if err != nil {
return
@@ -2088,12 +2091,16 @@ func syncRepoDownload() (err error) {
}
logging.LogInfof("downloading data repo [device=%s, kernel=%s, provider=%d, mode=%s/%t]", Conf.System.Load().ID, KernelID, Conf.Sync.Load().Provider, "d", true)
+ passwordRecovery, err := preparePasswordRecoveryDownload(repo)
+ if err != nil {
+ return err
+ }
checkoutTask := startSyncCheckout(repo)
defer checkoutTask.finish(repo, &err)
defer finishAssetDownloadRecovery(repo, &err)
start := time.Now()
indexStart := time.Now()
- _, _, err = indexRepoBeforeCloudSync(repo)
+ _, _, err = indexRepoBeforeCloudSync0(repo)
indexElapsed := time.Since(indexStart)
if err != nil {
planSyncAfter(fixSyncInterval)
@@ -2135,6 +2142,13 @@ func syncRepoDownload() (err error) {
calcPetalDiff(beforeSyncPetals, mergeResult)
postProcessStart := time.Now()
err = processAssetSyncMergeResult(repo, false, true, mergeResult, trafficStat, "d", elapsed)
+ if passwordRecovery {
+ // Reapply the retained envelopes to notebooks brought back by download.
+ // Final backup authentication still requires the user's new password.
+ notebookCryptoMu.Lock()
+ recoverMasterPasswordMigration()
+ notebookCryptoMu.Unlock()
+ }
logging.LogInfof("download data repo phases [index=%.2fs, cloud=%.2fs, post-process=%.2fs, total=%.2fs]",
indexElapsed.Seconds(), cloudElapsed.Seconds(), time.Since(postProcessStart).Seconds(), time.Since(start).Seconds())
return
@@ -3068,6 +3082,14 @@ func needFullReindex(upsertTrees int) bool {
var promotedPurgeDataRepo bool
func indexRepoBeforeCloudSync(repo *dejavu.Repo) (beforeIndex, afterIndex *entity.Index, err error) {
+ if err = checkRepositoryPasswordMigration(); err != nil {
+ return
+ }
+ return indexRepoBeforeCloudSync0(repo)
+}
+
+// Download-only recovery keeps the existing local safety index, without publishing it.
+func indexRepoBeforeCloudSync0(repo *dejavu.Repo) (beforeIndex, afterIndex *entity.Index, err error) {
start := time.Now()
beforeIndex, _ = repo.Latest()
diff --git a/kernel/model/repository_crypto.go b/kernel/model/repository_crypto.go
new file mode 100644
index 0000000000..c5659ad072
--- /dev/null
+++ b/kernel/model/repository_crypto.go
@@ -0,0 +1,56 @@
+package model
+
+import (
+ "errors"
+ "os"
+ "strings"
+
+ "github.com/siyuan-note/dejavu"
+)
+
+// Incomplete password changes retain recovery material locally. Do not publish
+// their intermediate key files as a completed manual snapshot or upload.
+func checkRepositoryPasswordMigration() error {
+ if _, err := os.Stat(masterPasswordMigrationPath()); os.IsNotExist(err) {
+ return nil
+ } else if err != nil {
+ return err
+ }
+ return errMasterPasswordMigrationPending
+}
+
+func preparePasswordRecoveryDownload(repo *dejavu.Repo) (bool, error) {
+ if err := checkRepositoryPasswordMigration(); err != nil && !errors.Is(err, errMasterPasswordMigrationPending) {
+ return false, err
+ }
+ migration, err := readMasterPasswordMigration()
+ if err != nil || migration == nil {
+ return false, err
+ }
+ // Keep the local manifest outside this download's comparison index so a
+ // complete remote snapshot without it cannot delete the recovery instructions.
+ // The existing local safety checkpoint before download remains available.
+ repo.IgnoreLines = append(append([]string(nil), repo.IgnoreLines...), "/.siyuan/master-password-migration.json")
+ return true, nil
+}
+
+func checkPasswordMigrationCheckout(plan *dejavu.CheckoutPlan) error {
+ err := checkRepositoryPasswordMigration()
+ if err == nil {
+ return nil
+ }
+ if !errors.Is(err, errMasterPasswordMigrationPending) {
+ return err
+ }
+ for _, file := range plan.Upserts {
+ if strings.EqualFold(file.Path, "/.siyuan/master-password-migration.json") {
+ return err
+ }
+ }
+ for _, file := range plan.Removes {
+ if strings.EqualFold(file.Path, "/.siyuan/master-password-migration.json") {
+ return err
+ }
+ }
+ return nil
+}
diff --git a/kernel/model/repository_crypto_fts5_test.go b/kernel/model/repository_crypto_fts5_test.go
new file mode 100644
index 0000000000..8af665df03
--- /dev/null
+++ b/kernel/model/repository_crypto_fts5_test.go
@@ -0,0 +1,127 @@
+//go:build fts5
+
+package model
+
+import (
+ "bytes"
+ "encoding/json"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "testing"
+
+ "github.com/siyuan-note/siyuan/kernel/conf"
+ "github.com/siyuan-note/siyuan/kernel/sql"
+ "github.com/siyuan-note/siyuan/kernel/util"
+)
+
+func TestPasswordMigrationDownloadRecoversMissingNotebook(t *testing.T) {
+ const childEnv = "SIYUAN_TEST_PASSWORD_DOWNLOAD_RECOVERY"
+ if os.Getenv(childEnv) == "" {
+ cmd := exec.Command(os.Args[0], "-test.run=^TestPasswordMigrationDownloadRecoversMissingNotebook$", "-test.timeout=30s")
+ cmd.Env = append(os.Environ(), childEnv+"=1")
+ if output, err := cmd.CombinedOutput(); err != nil {
+ t.Fatalf("%v\n%s", err, output)
+ }
+ return
+ }
+ _, repo, _ := prepareAssetDownloadRepoTest(t)
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ Conf.Editor.Store(conf.NewEditor())
+ Conf.Flashcard.Store(conf.NewFlashcard())
+ Conf.FileTree.Store(conf.NewFileTree())
+ util.QueueDir = filepath.Join(util.TempDir, "queue")
+ util.DBPath = filepath.Join(util.TempDir, "siyuan.db")
+ util.BlockTreeDBPath = filepath.Join(util.TempDir, "blocktree.db")
+ util.HistoryDBPath = filepath.Join(util.TempDir, "history.db")
+ util.AssetContentDBPath = filepath.Join(util.TempDir, "asset_content.db")
+ sql.InitDatabase(true)
+ sql.InitHistoryDatabase(true)
+ sql.InitAssetContentDatabase(true)
+ t.Cleanup(sql.CloseDatabase)
+ if err := ensureAllSyncAssets(); err != nil {
+ t.Fatal(err)
+ }
+ if err := EnableEncryptedNotebook("old-password"); err != nil {
+ t.Fatal(err)
+ }
+ oldKey, err := deriveKEK("old-password")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer zeroAndClear(oldKey)
+ const boxID = "20261027000000-recover"
+ original := notebookArchiveTestBox(t, boxID, oldKey)
+ oldVerifier := bytes.Clone(currentNotebookCrypto().KEKVerifier)
+ oldBackup, err := os.ReadFile(dataCryptoBackupPath())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err = CreateRepoSnapshotWithFullCheck("coherent old-password state", true); err != nil {
+ t.Fatal(err)
+ }
+ if _, err = repo.SyncUpload(nil); err != nil {
+ t.Fatal(err)
+ }
+ if err = ChangeMasterPassword("old-password", "new-password"); err != nil {
+ t.Fatal(err)
+ }
+ nc := currentNotebookCrypto()
+ crypt, err := GetBoxEncryption(boxID)
+ if err != nil {
+ t.Fatal(err)
+ }
+ params, _ := json.Marshal(nc.KDFParams)
+ manifest := &masterPasswordMigration{OldVerifier: oldVerifier, NewVerifier: nc.KEKVerifier,
+ NewVerifierNonce: nc.VerifierNonce, NewKDFParams: params, NewHistoryKEKs: nc.HistoryKEKs,
+ Boxes: []migrationBoxEntry{{BoxID: boxID, NewSpec: crypt.Spec, NewWrappedDEK: crypt.WrappedDEK,
+ NewWrapNonce: crypt.WrapNonce, Metadata: crypt.Metadata}}}
+ // Reproduce an interrupted change before the global recovery backup was replaced.
+ if err = writeMasterPasswordMigration(manifest); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(dataCryptoBackupPath(), oldBackup, 0600); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.Rename(filepath.Join(util.DataDir, boxID), filepath.Join(util.WorkspaceDir, "retained-notebook")); err != nil {
+ t.Fatal(err)
+ }
+ lockSync()
+ err = syncRepoDownload()
+ unlockSync()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if pending, _ := MasterPasswordMigrationStatus(); !pending {
+ t.Fatal("download discarded the recovery manifest before password authentication")
+ }
+ if data, readErr := os.ReadFile(filepath.Join(util.DataDir, boxID, boxID+".sy")); readErr != nil || !bytes.Equal(data, original) {
+ t.Fatalf("download did not recover the original ciphertext: %v", readErr)
+ }
+ key, err := deriveKEK("new-password")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer zeroAndClear(key)
+ dek, _, err := decryptBoxCrypt(boxID, key)
+ zeroAndClear(dek)
+ if err != nil {
+ t.Fatalf("new password could not recover downloaded notebook: %v", err)
+ }
+ if pending, _ := MasterPasswordMigrationStatus(); pending {
+ t.Fatal("authenticated recovery did not complete migration")
+ }
+ if _, _, err = CreateRepoSnapshotWithFullCheck("recovered", true); err != nil {
+ t.Fatal(err)
+ }
+ lockSync()
+ err = syncRepoUpload()
+ unlockSync()
+ if err != nil {
+ t.Fatalf("complete recovered state could not upload: %v", err)
+ }
+ backup, err := loadNotebookCryptoBackup()
+ if err != nil || !verifyKEKMAC(backup, key) {
+ t.Fatalf("recovery did not publish authenticated backup: %v", err)
+ }
+}
diff --git a/kernel/model/repository_crypto_test.go b/kernel/model/repository_crypto_test.go
new file mode 100644
index 0000000000..1ee915826c
--- /dev/null
+++ b/kernel/model/repository_crypto_test.go
@@ -0,0 +1,124 @@
+package model
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "os"
+ "path/filepath"
+ "testing"
+ "time"
+
+ "github.com/siyuan-note/dejavu"
+ "github.com/siyuan-note/dejavu/entity"
+ "github.com/siyuan-note/filelock"
+ "github.com/siyuan-note/siyuan/kernel/conf"
+)
+
+func TestPasswordChangeSerializesRepositoryAccess(t *testing.T) {
+ _, repo, _ := prepareAssetDownloadRepoTest(t)
+ Conf.NotebookCrypto = conf.NewNotebookCrypto()
+ if err := EnableEncryptedNotebook("old-password"); err != nil {
+ t.Fatal(err)
+ }
+ filelock.Lock(masterPasswordMigrationPath())
+ locked := true
+ defer func() {
+ if locked {
+ filelock.Unlock(masterPasswordMigrationPath())
+ }
+ }()
+ changed := make(chan error, 1)
+ go func() { changed <- ChangeMasterPassword("old-password", "new-password") }()
+ deadline := time.Now().Add(5 * time.Second)
+ for {
+ if !syncLock.TryLock() {
+ break
+ }
+ syncLock.Unlock()
+ if time.Now().After(deadline) {
+ t.Fatal("password change did not exclude synchronization")
+ }
+ time.Sleep(time.Millisecond)
+ }
+ snapshot := make(chan error, 1)
+ go func() { _, _, err := CreateRepoSnapshotWithFullCheck("after password change", true); snapshot <- err }()
+ select {
+ case err := <-snapshot:
+ t.Fatalf("snapshot sampled an active password change: %v", err)
+ case <-time.After(30 * time.Millisecond):
+ }
+ filelock.Unlock(masterPasswordMigrationPath())
+ locked = false
+ if err := <-changed; err != nil {
+ t.Fatal(err)
+ }
+ if err := <-snapshot; err != nil {
+ t.Fatal(err)
+ }
+ index, err := repo.Latest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ var backup conf.NotebookCrypto
+ if err = json.Unmarshal([]byte(repoSnapshotTestContent(t, repo, index.ID, "/.siyuan/data-crypto-backup.json")), &backup); err != nil {
+ t.Fatal(err)
+ }
+ key, err := deriveKEK("new-password")
+ if err != nil {
+ t.Fatal(err)
+ }
+ defer zeroAndClear(key)
+ if !verifyKEKMAC(&backup, key) {
+ t.Fatal("snapshot did not contain the completed authenticated key backup")
+ }
+}
+
+func TestPasswordMigrationBlocksRepositoryPublication(t *testing.T) {
+ _, repo, _ := prepareAssetDownloadRepoTest(t)
+ before, err := repo.Latest()
+ if err != nil {
+ t.Fatal(err)
+ }
+ remoteBefore, err := repo.GetCloudLatestFast(nil)
+ if err != nil {
+ t.Fatal(err)
+ }
+ for _, content := range []string{`{"boxes":[]}`, `{"boxes":`} {
+ if err = os.MkdirAll(filepath.Dir(masterPasswordMigrationPath()), 0755); err != nil {
+ t.Fatal(err)
+ }
+ if err = os.WriteFile(masterPasswordMigrationPath(), []byte(content), 0600); err != nil {
+ t.Fatal(err)
+ }
+ if _, _, err = CreateRepoSnapshot("must not publish"); !errors.Is(err, errMasterPasswordMigrationPending) {
+ t.Fatalf("manual snapshot accepted pending migration: %v", err)
+ }
+ lockSync()
+ uploadErr := syncRepoUpload()
+ _, fullErr := syncRepoWithContext(context.Background(), false, true)
+ unlockSync()
+ if !errors.Is(uploadErr, errMasterPasswordMigrationPending) || !errors.Is(fullErr, errMasterPasswordMigrationPending) {
+ t.Fatalf("pending migration was uploaded: upload=%v full=%v", uploadErr, fullErr)
+ }
+ after, readErr := repo.Latest()
+ if readErr != nil || after.ID != before.ID {
+ t.Fatalf("publication gate changed latest index: %v", readErr)
+ }
+ if data, readErr := os.ReadFile(masterPasswordMigrationPath()); readErr != nil || string(data) != content {
+ t.Fatalf("publication gate changed recovery material: %v", readErr)
+ }
+ for _, plan := range []*dejavu.CheckoutPlan{
+ {Upserts: []*entity.File{{Path: "/.siyuan/master-password-migration.json"}}},
+ {Removes: []*entity.File{{Path: "/.siyuan/master-password-migration.json"}}},
+ } {
+ if err = documentAddressingPreflight(repo)(plan); !errors.Is(err, errMasterPasswordMigrationPending) {
+ t.Fatalf("checkout accepted replacement of local recovery material: %v", err)
+ }
+ }
+ remoteAfter, readErr := repo.GetCloudLatestFast(nil)
+ if readErr != nil || remoteAfter.ID != remoteBefore.ID {
+ t.Fatalf("publication gate changed cloud latest: %v", readErr)
+ }
+ }
+}