From dbeaccedf9a1be4d6f0ebfb4229eb810c48a6b07 Mon Sep 17 00:00:00 2001 From: qima Date: Mon, 9 Oct 2023 17:43:14 +0800 Subject: [PATCH] fix: ensure decrypter targeting file shall not be pre-existing --- src/lib.rs | 7 ++++++- src/tests.rs | 9 +++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/src/lib.rs b/src/lib.rs index bdcf2b2b8..d70176c50 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -112,7 +112,7 @@ use encrypt::encrypt_chunk; use itertools::Itertools; use std::{ collections::BTreeMap, - fs::{File, OpenOptions}, + fs::{self, File, OpenOptions}, io::{Read, Seek, SeekFrom, Write}, ops::Range, path::{Path, PathBuf}, @@ -277,6 +277,11 @@ impl StreamSelfDecryptor { pub fn decrypt_to_file(file_path: Box, data_map: &DataMap) -> Result { let temp_dir = tempdir()?; let src_hashes = extract_hashes(data_map); + + // The targeted file shall not be pre-exist. + // Hence we carry out a forced removal before carry out any further action. + let _ = fs::remove_file(&*file_path); + Ok(StreamSelfDecryptor { file_path, chunk_index: 0, diff --git a/src/tests.rs b/src/tests.rs index d8a0844fb..92a2b1408 100644 --- a/src/tests.rs +++ b/src/tests.rs @@ -58,6 +58,15 @@ fn test_stream_self_encryptor() -> Result<(), Error> { // Decrypt the shuffled chunks using StreamSelfDecryptor let decrypted_file_path = dir.path().join("decrypted"); + + // Write something to the decrypted file first to simulate it's corrupted. + { + let mut file = File::create(&decrypted_file_path)?; + let file_size = 1024; // 1KB + let data = random_bytes(file_size); + file.write_all(&data)?; + } + let mut decryptor = StreamSelfDecryptor::decrypt_to_file(Box::new(decrypted_file_path.clone()), &data_map)?; for chunk in encrypted_chunks {