{"record":{"id":"614d25ad1cd5c6d1","repo":"siyuan-note/siyuan","slug":"cannot-generate-notebook-crypto-backup-without-kek","errorCode":null,"errorMessage":"cannot generate notebook crypto backup without KEK","messagePattern":"cannot generate notebook crypto backup without KEK","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"kernel/model/crypto.go","lineNumber":382,"sourceCode":"\tif err := writeNotebookCryptoBackupData(nc, kek); err != nil {\n\t\treturn fmt.Errorf(\"failed to persist key backup: %w\", err)\n\t}\n\tConf.m.Lock()\n\t*Conf.NotebookCrypto = *nc\n\tConf.m.Unlock()\n\tConf.Save()\n\tIncSync()\n\treturn nil\n}\n\n// saveNotebookCryptoBackup 把当前 NotebookCrypto（含 MasterSalt/KEKVerifier/KDFParams）备份到 DataDir。\n// kek 必须非 nil：在 Checksum 定型后计算 KEKMAC 并落盘，保证恢复路径可通过 MAC 校验。\n// 无 KEK 生成的备份 KEKMAC 必为空，会被 deriveKEK/恢复路径拒绝，等于制造无法解锁的状态（详见设计 §19）。\nfunc saveNotebookCryptoBackup(kek []byte) error {\n\tif kek == nil {\n\t\t// 无 KEK 时不得生成当前格式备份：KEKMAC 缺失会被 deriveKEK/恢复路径拒绝，\n\t\t// 生成即等于制造无法解锁的状态。\n\t\treturn errors.New(\"cannot generate notebook crypto backup without KEK\")\n\t}\n\tConf.m.Lock()\n\tnc := *Conf.NotebookCrypto // 值拷贝\n\tprepareBackupForWrite(&nc)\n\tnc.KEKMAC = computeKEKMAC(&nc, kek)\n\tif !notebookCryptoConfigurationComplete(&nc) {\n\t\tConf.m.Unlock()\n\t\treturn errors.New(\"cannot save incomplete notebook crypto configuration\")\n\t}\n\tConf.NotebookCrypto.Spec = nc.Spec\n\tConf.NotebookCrypto.BackupID = nc.BackupID\n\tConf.NotebookCrypto.CreatedAt = nc.CreatedAt\n\tConf.NotebookCrypto.Checksum = nc.Checksum\n\tConf.NotebookCrypto.KEKMAC = nc.KEKMAC // 保持 Conf 与备份文件的 KEKMAC 一致\n\tConf.m.Unlock()\n\tbackupPath := dataCryptoBackupPath()\n\tif err := os.MkdirAll(filepath.Dir(backupPath), 0755); err != nil {\n\t\treturn fmt.Errorf(\"mkdir notebook crypto backup dir failed: %w\", err)","sourceCodeStart":364,"sourceCodeEnd":400,"githubUrl":"https://github.com/siyuan-note/siyuan/blob/9f775e8a12daef8255556097396f9b2739078892/kernel/model/crypto.go#L364-L400","documentation":"saveNotebookCryptoBackup refuses to write a key backup when the kek argument is nil. A backup without a KEK would have an empty KEKMAC, which deriveKEK and every recovery path reject — generating it would create a backup that can never unlock the workspace (a self-inflicted lockout, see design doc §19). This is an internal invariant guard, normally only reachable through programming errors or the dedicated test.","triggerScenarios":"Calling saveNotebookCryptoBackup(nil) directly, or an internal caller (EnableEncryptedNotebook / deriveKEK / ChangeMasterPassword code path) passing a nil KEK because the key-derivation step silently failed or was skipped.","commonSituations":"Custom/test code invoking the unexported helper with nil; a regression where deriveKEK returns nil on failure instead of erroring out first; refactoring that reordered KEK derivation after the backup call.","solutions":["Fix the caller to derive the KEK first and return its error instead of proceeding with nil","Add/keep an explicit check: if kek derivation fails, abort before calling saveNotebookCryptoBackup","In tests, only pass nil intentionally (TestSaveNotebookCryptoBackupRejectsNilKEK) to assert the guard","If this fires in production code paths, treat it as a bug — users should never reach it"],"exampleFix":"// before\nkek, err := deriveKEK(password)\n_ = err\nsaveNotebookCryptoBackup(kek) // panics into \"cannot generate notebook crypto backup without KEK\"\n// after\nkek, err := deriveKEK(password)\nif err != nil {\n    return err\n}\nreturn saveNotebookCryptoBackup(kek)","handlingStrategy":"type-guard","validationCode":"if kek == nil || len(kek) == 0 {\n    return errors.New(\"KEK derivation failed; refusing to write backup\")\n}","typeGuard":"func hasKEK(kek []byte) bool { return len(kek) > 0 }","tryCatchPattern":"if err := saveNotebookCryptoBackup(kek); err != nil {\n    if err.Error() == \"cannot generate notebook crypto backup without KEK\" {\n        // caller bug: fix the derivation path, never retry with the same nil KEK\n    }\n}","preventionTips":["Always check the error from KEK derivation before using the key","Never reorder derive-after-save in refactors; keep the invariant \"no backup without KEK\"","Keep the nil-KEK test (TestSaveNotebookCryptoBackupRejectsNilKEK) in CI","Treat any production occurrence of this error as a code bug to file immediately"],"tags":["encryption","internal-invariant","backup","nil-argument"],"backgroundTag":"internal-invariant-violation","analyzedSha":"9f775e8a12daef8255556097396f9b2739078892","analyzedAt":"2026-09-19T03:17:15.984Z","contentChangedAt":"2026-09-19T03:17:15.984Z","schemaVersion":2},"datasetVersion":"2026-09-23T08:17:48.524Z"}