{"record":{"id":"c7eed877501b0f11","repo":"siyuan-note/siyuan","slug":"cannot-write-incomplete-notebook-crypto-backup","errorCode":null,"errorMessage":"cannot write incomplete notebook crypto backup","messagePattern":"cannot write incomplete notebook crypto backup","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"kernel/model/crypto.go","lineNumber":421,"sourceCode":"\tif err != nil {\n\t\treturn fmt.Errorf(\"marshal notebook crypto backup failed: %w\", err)\n\t}\n\tif err := atomicWriteFile(backupPath, data); err != nil {\n\t\treturn fmt.Errorf(\"write notebook crypto backup failed: %w\", err)\n\t}\n\treturn nil\n}\n\n// writeNotebookCryptoBackupData 将指定的 NotebookCrypto 写入备份文件（不依赖 Conf.NotebookCrypto）。\n// kek 必须非 nil：在 Checksum 定型后计算 KEKMAC，保证落盘 MAC 与落盘内容一致。\nfunc writeNotebookCryptoBackupData(nc *conf.NotebookCrypto, kek []byte) error {\n\tif kek == nil {\n\t\treturn errors.New(\"cannot generate notebook crypto backup without KEK\")\n\t}\n\tprepareBackupForWrite(nc)\n\tnc.KEKMAC = computeKEKMAC(nc, kek)\n\tif !notebookCryptoConfigurationComplete(nc) {\n\t\treturn errors.New(\"cannot write incomplete notebook crypto backup\")\n\t}\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)\n\t}\n\tdata, err := json.Marshal(nc)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"marshal notebook crypto backup failed: %w\", err)\n\t}\n\tif err := atomicWriteFile(backupPath, data); err != nil {\n\t\treturn fmt.Errorf(\"write notebook crypto backup failed: %w\", err)\n\t}\n\treturn nil\n}\n\n// verifyKEKAgainstExistingBoxes 用 KEK 对所有现有加密笔记本的 WrappedDEK 做无副作用解密校验。\n// 优先尝试 conf 的 WrappedDEK，解密失败时 fallback 到 backup（与解锁路径一致）；\n// GetBoxEncryption 报错时 fail-closed（元数据损坏的加密笔记本不能静默跳过）。","sourceCodeStart":403,"sourceCodeEnd":439,"githubUrl":"https://github.com/siyuan-note/siyuan/blob/9f775e8a12daef8255556097396f9b2739078892/kernel/model/crypto.go#L403-L439","documentation":"After computing the KEKMAC, writeNotebookCryptoBackupData validates the NotebookCrypto struct with notebookCryptoConfigurationComplete. If required fields (spec, salts, wrapped DEKs, checksum, KEKMAC, etc.) are missing or inconsistent, it refuses to persist an incomplete backup, because a partial backup could never be authenticated back during restore and would endanger recoverability.","triggerScenarios":"Calling writeNotebookCryptoBackupData with a NotebookCrypto struct that fails notebookCryptoConfigurationComplete — e.g. missing MasterSalt, missing WrappedDEK, empty Checksum, unset Spec, or a KEKMAC that was never computed because kek was garbage. Raised from ImportNotebookCryptoBackup with a truncated/malformed import payload, or restore/repair paths that built a partial config.","commonSituations":"Importing a backup JSON that was hand-edited or truncated; master-password migration interrupted midway leaving fields empty; constructing a NotebookCrypto in tests or tooling without filling every mandatory field; a version change introduced a new required field the old config lacks.","solutions":["Validate the NotebookCrypto struct and fill all fields required by notebookCryptoConfigurationComplete before writing the backup","Re-run the full enable-encryption setup (salt generation, DEK wrap, checksum finalization) instead of writing a partially built config","When importing, verify the imported JSON is a complete, unmodified backup produced by a compatible version","Check for version skew: if a newer format added required fields, migrate the old config through the supported migration path rather than writing it directly"],"exampleFix":"// before\nnc := &conf.NotebookCrypto{Spec: conf.CurrentNotebookCryptoSpec}\nwriteNotebookCryptoBackupData(nc, kek) // fails: incomplete\n\n// after\nnc := newCompleteNotebookCrypto(password) // generates salt, wraps DEK, finalizes checksum\nnc.KEKMAC = computeKEKMAC(nc, kek)\nwriteNotebookCryptoBackupData(nc, kek)","handlingStrategy":"validation","validationCode":"if !notebookCryptoConfigurationComplete(nc) {\n    return errors.New(\"notebook crypto config incomplete; run full setup before backup\")\n}\n// proceed to writeNotebookCryptoBackupData(nc, kek)","typeGuard":"func backupWritable(nc *conf.NotebookCrypto) bool {\n    return nc != nil && nc.Spec == conf.CurrentNotebookCryptoStatus && notebookCryptoConfigurationComplete(nc)\n}","tryCatchPattern":"if err := writeNotebookCryptoBackupData(nc, kek); err != nil {\n    return fmt.Errorf(\"refusing to persist incomplete backup: %w\", err)\n}","preventionTips":["Build NotebookCrypto only through the official setup path that generates salt, wraps DEK, and finalizes the checksum","Never hand-edit backup JSON; import only backups produced by a compatible version","Check notebookCryptoConfigurationComplete in tests before exercising write paths"],"tags":["go","crypto","backup","validation","incomplete-data"],"backgroundTag":"schema-validation-failed","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"}