{"record":{"id":"f01addbf2f18d3f6","repo":"siyuan-note/siyuan","slug":"invalid-trailing-encrypted-asset-data","errorCode":null,"errorMessage":"invalid trailing encrypted asset data","messagePattern":"invalid trailing encrypted asset data","errorType":"error_code","errorClass":null,"httpStatus":null,"severity":"error","filePath":"kernel/model/crypto.go","lineNumber":2497,"sourceCode":"\t\twritten += int64(n)\n\t\tzeroAndClear(plainChunk)\n\t\tif writeErr != nil {\n\t\t\treturn \"\", writeErr\n\t\t}\n\t\tif n != len(plainChunk) {\n\t\t\treturn \"\", io.ErrShortWrite\n\t\t}\n\t}\n\tvar terminator uint32\n\tif err = binary.Read(reader, binary.BigEndian, &terminator); err != nil {\n\t\treturn \"\", err\n\t}\n\tif terminator != 0 || written != metadata.Size {\n\t\treturn \"\", errors.New(\"invalid encrypted asset content length\")\n\t}\n\tvar trailing [1]byte\n\tif _, trailingErr := io.ReadFull(reader, trailing[:]); trailingErr != io.EOF {\n\t\treturn \"\", errors.New(\"invalid trailing encrypted asset data\")\n\t}\n\treturn metadata.OriginalName, nil\n}\n\n// DecryptAsset 对应解密。\nfunc DecryptAsset(boxID, diskName string, dek, ciphertext []byte) ([]byte, error) {\n\tplaintext, _, err := DecryptAssetWithName(boxID, diskName, dek, ciphertext)\n\treturn plaintext, err\n}\n\n// notebookCryptoBackupPath 返回加密笔记本的独立 BoxCrypt 备份路径。\n// 该文件在主 conf.json 丢失时用作\"此笔记本是加密笔记本\"的标识和降级恢复源。\n// 与全局 NotebookCrypto 备份（<DataDir>/.siyuan/data-crypto-backup.json）配合使用，\n// 全局备份存 MasterSalt/KEKVerifier，per-notebook 备份存 WrappedDEK/WrapNonce。\nconst notebookCryptoBackupFilename = \"notebook-crypto-backup.json\"\n\nfunc notebookCryptoBackupPath(boxID string) string {\n\treturn filepath.Join(util.DataDir, boxID, \".siyuan\", notebookCryptoBackupFilename)","sourceCodeStart":2479,"sourceCodeEnd":2515,"githubUrl":"https://github.com/siyuan-note/siyuan/blob/9f775e8a12daef8255556097396f9b2739078892/kernel/model/crypto.go#L2479-L2515","documentation":"After the terminator check, DecryptAssetToWriter attempts to read one more byte and requires exactly io.EOF. Any extra trailing byte means the file contains data beyond the declared envelope — likely appended content, a different format, or corruption — so decryption fails to prevent silently processing unverified data.","triggerScenarios":"Reading an encrypted asset file that has bytes appended after the terminating uint32 — e.g. someone appended data, a sync tool concatenated two copies, or the wrong file (a different container) was passed in.","commonSituations":"rsync/backup tools appending instead of replacing on resume; log or error text appended to the asset; copy operations targeting an existing file without truncation (O_APPEND).","solutions":["Re-copy the asset from a known-good source ensuring truncation on write (O_TRUNC)","Trim the file to the exact envelope length only after verifying integrity elsewhere — prefer re-download/re-sync instead","Check the copying tool for append-on-resume behavior and redo the transfer","Restore from history/snapshot where the byte length matches the metadata"],"exampleFix":"// before\ndata, _ := os.ReadFile(src)\nos.WriteFile(dst, data, 0644) // appends if dst exists via some helpers\n// after\ndata, _ := os.ReadFile(src)\nos.WriteFile(dst, data, 0644) // ensure O_TRUNC\n// or: os.Remove(dst) before copying on resume-capable transports","handlingStrategy":"validation","validationCode":"func envelopeLengthExact(data []byte) (bool, int64) {\n    if len(data) < 12 { return false, 0 }\n    off := 8 + int(binary.BigEndian.Uint32(data[4:8]))\n    for {\n        if off+4 > len(data) { return false, 0 }\n        l := binary.BigEndian.Uint32(data[off : off+4])\n        off += 4 + int(l)\n        if off+4 > len(data) { return false, 0 }\n        if binary.BigEndian.Uint32(data[off-4:off]) == 0 && l < uint32(1<<20)-16 { break }\n    }\n    return off+4 == len(data), int64(off + 4)\n}","typeGuard":null,"tryCatchPattern":"_, err := model.DecryptAsset(boxID, diskName, dek, data)\nif err != nil && strings.Contains(err.Error(), \"trailing\") {\n    // recopy with truncation from the authoritative source\n    return recopyWithTrunc(srcURL, diskName)\n}","preventionTips":["Always open destination files with O_TRUNC when copying assets","Disable append/resume semantics for ciphertext transfers, or verify lengths after resume","Compare file size to the computed envelope size before decrypting","Never let other tools (logs, editors) write into the assets directory"],"tags":["crypto","format","corruption"],"backgroundTag":"unexpected-response-shape","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"}