blob: f1e7529ee6f582bf46d9992f559fda2a00096a0c [file] [log] [blame]
Victor Hsiehac4f3f42021-02-26 12:35:58 -08001/*
2 * Copyright (C) 2021 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17//! A module for writing to a file from a trusted world to an untrusted storage.
18//!
19//! Architectural Model:
20//! * Trusted world: the writer, a signing secret, has some memory, but NO persistent storage.
21//! * Untrusted world: persistent storage, assuming untrusted.
22//! * IPC mechanism between trusted and untrusted world
23//!
24//! Use cases:
25//! * In the trusted world, we want to generate a large file, sign it, and share the signature for
26//! a third party to verify the file.
27//! * In the trusted world, we want to read a previously signed file back with signature check
28//! without having to touch the whole file.
29//!
30//! Requirements:
31//! * Communication between trusted and untrusted world is not cheap, and files can be large.
32//! * A file write pattern may not be sequential, neither does read.
33//!
34//! Considering the above, a technique similar to fs-verity is used. fs-verity uses an alternative
35//! hash function, a Merkle tree, to calculate the hash of file content. A file update at any
36//! location will propagate the hash update from the leaf to the root node. Unlike fs-verity, which
37//! assumes static files, to support write operation, we need to allow the file (thus tree) to
38//! update.
39//!
40//! For the trusted world to generate a large file with random write and hash it, the writer needs
41//! to hold some private information and update the Merkle tree during a file write (or even when
42//! the Merkle tree needs to be stashed to the untrusted storage).
43//!
44//! A write to a file must update the root hash. In order for the root hash to update, a tree
45//! walk to update from the write location to the root node is necessary. Importantly, in case when
46//! (part of) the Merkle tree needs to be read from the untrusted storage (e.g. not yet verified in
47//! cache), the original path must be verified by the trusted signature before the update to happen.
48//!
49//! Denial-of-service is a known weakness if the untrusted storage decides to simply remove the
50//! file. But there is nothing we can do in this architecture.
51//!
52//! Rollback attack is another possible attack, but can be addressed with a rollback counter when
53//! possible.
54
55use std::io;
56use std::sync::{Arc, RwLock};
57
Victor Hsieh09e26262021-03-03 16:00:55 -080058use super::builder::MerkleLeaves;
Victor Hsiehac4f3f42021-02-26 12:35:58 -080059use crate::common::{ChunkedSizeIter, CHUNK_SIZE};
60use crate::crypto::{CryptoError, Sha256Hash, Sha256Hasher};
Victor Hsiehd0bb5d32021-03-19 12:48:03 -070061use crate::file::{ChunkBuffer, RandomWrite, ReadByChunk};
Victor Hsiehac4f3f42021-02-26 12:35:58 -080062
63// Implement the conversion from `CryptoError` to `io::Error` just to avoid manual error type
64// mapping below.
65impl From<CryptoError> for io::Error {
66 fn from(error: CryptoError) -> Self {
67 io::Error::new(io::ErrorKind::Other, error)
68 }
69}
70
Victor Hsieh9d0ab622021-04-26 17:07:02 -070071fn debug_assert_usize_is_u64() {
72 // Since we don't need to support 32-bit CPU, make an assert to make conversion between
73 // u64 and usize easy below. Otherwise, we need to check `divide_roundup(offset + buf.len()
74 // <= usize::MAX` or handle `TryInto` errors.
75 debug_assert!(usize::MAX as u64 == u64::MAX, "Only 64-bit arch is supported");
76}
77
Victor Hsiehac4f3f42021-02-26 12:35:58 -080078/// VerifiedFileEditor provides an integrity layer to an underlying read-writable file, which may
79/// not be stored in a trusted environment. Only new, empty files are currently supported.
Victor Hsiehd0bb5d32021-03-19 12:48:03 -070080pub struct VerifiedFileEditor<F: ReadByChunk + RandomWrite> {
Victor Hsiehac4f3f42021-02-26 12:35:58 -080081 file: F,
82 merkle_tree: Arc<RwLock<MerkleLeaves>>,
83}
84
Victor Hsiehd0bb5d32021-03-19 12:48:03 -070085impl<F: ReadByChunk + RandomWrite> VerifiedFileEditor<F> {
Victor Hsiehac4f3f42021-02-26 12:35:58 -080086 /// Wraps a supposedly new file for integrity protection.
87 pub fn new(file: F) -> Self {
88 Self { file, merkle_tree: Arc::new(RwLock::new(MerkleLeaves::new())) }
89 }
90
Victor Hsieh71f10032021-08-13 11:24:02 -070091 /// Returns the fs-verity digest size in bytes.
92 pub fn get_fsverity_digest_size(&self) -> usize {
93 Sha256Hasher::HASH_SIZE
94 }
95
Victor Hsiehac4f3f42021-02-26 12:35:58 -080096 /// Calculates the fs-verity digest of the current file.
97 pub fn calculate_fsverity_digest(&self) -> io::Result<Sha256Hash> {
98 let merkle_tree = self.merkle_tree.read().unwrap();
99 merkle_tree.calculate_fsverity_digest().map_err(|e| io::Error::new(io::ErrorKind::Other, e))
100 }
101
102 fn new_hash_for_incomplete_write(
103 &self,
104 source: &[u8],
105 offset_from_alignment: usize,
106 output_chunk_index: usize,
107 merkle_tree: &mut MerkleLeaves,
108 ) -> io::Result<Sha256Hash> {
109 // The buffer is initialized to 0 purposely. To calculate the block hash, the data is
110 // 0-padded to the block size. When a chunk read is less than a chunk, the initial value
111 // conveniently serves the padding purpose.
112 let mut orig_data = [0u8; CHUNK_SIZE as usize];
113
114 // If previous data exists, read back and verify against the known hash (since the
115 // storage / remote server is not trusted).
116 if merkle_tree.is_index_valid(output_chunk_index) {
117 self.read_chunk(output_chunk_index as u64, &mut orig_data)?;
118
119 // Verify original content
120 let hash = Sha256Hasher::new()?.update(&orig_data)?.finalize()?;
121 if !merkle_tree.is_consistent(output_chunk_index, &hash) {
122 return Err(io::Error::new(io::ErrorKind::InvalidData, "Inconsistent hash"));
123 }
124 }
125
126 Ok(Sha256Hasher::new()?
127 .update(&orig_data[..offset_from_alignment])?
128 .update(source)?
129 .update(&orig_data[offset_from_alignment + source.len()..])?
130 .finalize()?)
131 }
132
133 fn new_chunk_hash(
134 &self,
135 source: &[u8],
136 offset_from_alignment: usize,
137 current_size: usize,
138 output_chunk_index: usize,
139 merkle_tree: &mut MerkleLeaves,
140 ) -> io::Result<Sha256Hash> {
141 if current_size as u64 == CHUNK_SIZE {
142 // Case 1: If the chunk is a complete one, just calculate the hash, regardless of
143 // write location.
144 Ok(Sha256Hasher::new()?.update(source)?.finalize()?)
145 } else {
146 // Case 2: For an incomplete write, calculate the hash based on previous data (if
147 // any).
148 self.new_hash_for_incomplete_write(
149 source,
150 offset_from_alignment,
151 output_chunk_index,
152 merkle_tree,
153 )
154 }
155 }
Victor Hsieh6a47e7f2021-03-03 15:53:49 -0800156
157 pub fn size(&self) -> u64 {
158 self.merkle_tree.read().unwrap().file_size()
159 }
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800160}
161
Victor Hsiehd0bb5d32021-03-19 12:48:03 -0700162impl<F: ReadByChunk + RandomWrite> RandomWrite for VerifiedFileEditor<F> {
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800163 fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700164 debug_assert_usize_is_u64();
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800165
166 // The write range may not be well-aligned with the chunk boundary. There are various cases
167 // to deal with:
168 // 1. A write of a full 4K chunk.
169 // 2. A write of an incomplete chunk, possibly beyond the original EOF.
170 //
171 // Note that a write beyond EOF can create a hole. But we don't need to handle it here
172 // because holes are zeros, and leaves in MerkleLeaves are hashes of 4096-zeros by
173 // default.
174
175 // Now iterate on the input data, considering the alignment at the destination.
176 for (output_offset, current_size) in
177 ChunkedSizeIter::new(buf.len(), offset, CHUNK_SIZE as usize)
178 {
179 // Lock the tree for the whole write for now. There may be room to improve to increase
180 // throughput.
181 let mut merkle_tree = self.merkle_tree.write().unwrap();
182
183 let offset_in_buf = (output_offset - offset) as usize;
184 let source = &buf[offset_in_buf as usize..offset_in_buf as usize + current_size];
185 let output_chunk_index = (output_offset / CHUNK_SIZE) as usize;
186 let offset_from_alignment = (output_offset % CHUNK_SIZE) as usize;
187
188 let new_hash = match self.new_chunk_hash(
189 source,
190 offset_from_alignment,
191 current_size,
192 output_chunk_index,
193 &mut merkle_tree,
194 ) {
195 Ok(hash) => hash,
196 Err(e) => {
197 // Return early when any error happens before the right. Even if the hash is not
198 // consistent for the current chunk, we can still consider the earlier writes
199 // successful. Note that nothing persistent has been done in this iteration.
200 let written = output_offset - offset;
201 if written > 0 {
202 return Ok(written as usize);
203 }
204 return Err(e);
205 }
206 };
207
208 // A failed, partial write here will make the backing file inconsistent to the (old)
209 // hash. Nothing can be done within this writer, but at least it still maintains the
210 // (original) integrity for the file. To matches what write(2) describes for an error
211 // case (though it's about direct I/O), "Partial data may be written ... should be
212 // considered inconsistent", an error below is propagated.
Chris Wailes68c39f82021-07-27 16:03:44 -0700213 self.file.write_all_at(source, output_offset)?;
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800214
215 // Update the hash only after the write succeeds. Note that this only attempts to keep
216 // the tree consistent to what has been written regardless the actual state beyond the
217 // writer.
218 let size_at_least = offset.saturating_add(buf.len() as u64);
219 merkle_tree.update_hash(output_chunk_index, &new_hash, size_at_least);
220 }
221 Ok(buf.len())
222 }
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700223
224 fn resize(&self, size: u64) -> io::Result<()> {
225 debug_assert_usize_is_u64();
226
227 let mut merkle_tree = self.merkle_tree.write().unwrap();
228 // In case when we are truncating the file, we may need to recalculate the hash of the (new)
229 // last chunk. Since the content is provided by the untrusted backend, we need to read the
230 // data back first, verify it, then override the truncated portion with 0-padding for
231 // hashing. As an optimization, we only need to read the data back if the new size isn't a
232 // multiple of CHUNK_SIZE (since the hash is already correct).
233 //
234 // The same thing does not need to happen when the size is growing. Since the new extended
235 // data is always 0, we can just resize the `MerkleLeaves`, where a new hash is always
236 // calculated from 4096 zeros.
237 if size < merkle_tree.file_size() && size % CHUNK_SIZE > 0 {
238 let new_tail_size = (size % CHUNK_SIZE) as usize;
239 let chunk_index = size / CHUNK_SIZE;
240 if new_tail_size > 0 {
241 let mut buf: ChunkBuffer = [0; CHUNK_SIZE as usize];
242 let s = self.read_chunk(chunk_index, &mut buf)?;
243 debug_assert!(new_tail_size <= s);
244
245 let zeros = vec![0; CHUNK_SIZE as usize - new_tail_size];
246 let new_hash = Sha256Hasher::new()?
247 .update(&buf[..new_tail_size])?
248 .update(&zeros)?
249 .finalize()?;
250 merkle_tree.update_hash(chunk_index as usize, &new_hash, size);
251 }
252 }
253
254 self.file.resize(size)?;
255 merkle_tree.resize(size as usize);
256
257 Ok(())
258 }
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800259}
260
Victor Hsiehd0bb5d32021-03-19 12:48:03 -0700261impl<F: ReadByChunk + RandomWrite> ReadByChunk for VerifiedFileEditor<F> {
262 fn read_chunk(&self, chunk_index: u64, buf: &mut ChunkBuffer) -> io::Result<usize> {
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800263 self.file.read_chunk(chunk_index, buf)
264 }
265}
266
267#[cfg(test)]
268mod tests {
269 // Test data below can be generated by:
270 // $ perl -e 'print "\x{00}" x 6000' > foo
271 // $ perl -e 'print "\x{01}" x 5000' >> foo
272 // $ fsverity digest foo
273 use super::*;
274 use anyhow::Result;
275 use std::cell::RefCell;
276 use std::convert::TryInto;
277
Victor Hsieh09e26262021-03-03 16:00:55 -0800278 struct InMemoryEditor {
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800279 data: RefCell<Vec<u8>>,
280 fail_read: bool,
281 }
282
Victor Hsieh09e26262021-03-03 16:00:55 -0800283 impl InMemoryEditor {
284 pub fn new() -> InMemoryEditor {
285 InMemoryEditor { data: RefCell::new(Vec::new()), fail_read: false }
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800286 }
287 }
288
Victor Hsieh09e26262021-03-03 16:00:55 -0800289 impl RandomWrite for InMemoryEditor {
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800290 fn write_at(&self, buf: &[u8], offset: u64) -> io::Result<usize> {
291 let begin: usize =
292 offset.try_into().map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
293 let end = begin + buf.len();
294 if end > self.data.borrow().len() {
295 self.data.borrow_mut().resize(end, 0);
296 }
Chris Wailes68c39f82021-07-27 16:03:44 -0700297 self.data.borrow_mut().as_mut_slice()[begin..end].copy_from_slice(buf);
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800298 Ok(buf.len())
299 }
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700300
301 fn resize(&self, size: u64) -> io::Result<()> {
302 let size: usize =
303 size.try_into().map_err(|e| io::Error::new(io::ErrorKind::Other, e))?;
304 self.data.borrow_mut().resize(size, 0);
305 Ok(())
306 }
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800307 }
308
Victor Hsiehd0bb5d32021-03-19 12:48:03 -0700309 impl ReadByChunk for InMemoryEditor {
310 fn read_chunk(&self, chunk_index: u64, buf: &mut ChunkBuffer) -> io::Result<usize> {
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800311 if self.fail_read {
312 return Err(io::Error::new(io::ErrorKind::Other, "test!"));
313 }
314
315 let borrowed = self.data.borrow();
316 let chunk = &borrowed
317 .chunks(CHUNK_SIZE as usize)
318 .nth(chunk_index as usize)
319 .ok_or_else(|| {
320 io::Error::new(
321 io::ErrorKind::InvalidInput,
322 format!("read_chunk out of bound: index {}", chunk_index),
323 )
324 })?;
Chris Wailes68c39f82021-07-27 16:03:44 -0700325 buf[..chunk.len()].copy_from_slice(chunk);
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800326 Ok(chunk.len())
327 }
328 }
329
330 #[test]
331 fn test_writer() -> Result<()> {
Victor Hsieh09e26262021-03-03 16:00:55 -0800332 let writer = InMemoryEditor::new();
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800333 let buf = [1; 4096];
334 assert_eq!(writer.data.borrow().len(), 0);
335
336 assert_eq!(writer.write_at(&buf, 16384)?, 4096);
337 assert_eq!(writer.data.borrow()[16384..16384 + 4096], buf);
338
339 assert_eq!(writer.write_at(&buf, 2048)?, 4096);
340 assert_eq!(writer.data.borrow()[2048..2048 + 4096], buf);
341
342 assert_eq!(writer.data.borrow().len(), 16384 + 4096);
343 Ok(())
344 }
345
346 #[test]
347 fn test_verified_writer_no_write() -> Result<()> {
348 // Verify fs-verity hash without any write.
Victor Hsieh09e26262021-03-03 16:00:55 -0800349 let file = VerifiedFileEditor::new(InMemoryEditor::new());
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800350 assert_eq!(
351 file.calculate_fsverity_digest()?,
352 to_u8_vec("3d248ca542a24fc62d1c43b916eae5016878e2533c88238480b26128a1f1af95")
353 .as_slice()
354 );
355 Ok(())
356 }
357
358 #[test]
359 fn test_verified_writer_from_zero() -> Result<()> {
360 // Verify a write of a full chunk.
Victor Hsieh09e26262021-03-03 16:00:55 -0800361 let file = VerifiedFileEditor::new(InMemoryEditor::new());
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800362 assert_eq!(file.write_at(&[1; 4096], 0)?, 4096);
363 assert_eq!(
364 file.calculate_fsverity_digest()?,
365 to_u8_vec("cd0875ca59c7d37e962c5e8f5acd3770750ac80225e2df652ce5672fd34500af")
366 .as_slice()
367 );
368
369 // Verify a write of across multiple chunks.
Victor Hsieh09e26262021-03-03 16:00:55 -0800370 let file = VerifiedFileEditor::new(InMemoryEditor::new());
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800371 assert_eq!(file.write_at(&[1; 4097], 0)?, 4097);
372 assert_eq!(
373 file.calculate_fsverity_digest()?,
374 to_u8_vec("2901b849fda2d91e3929524561c4a47e77bb64734319759507b2029f18b9cc52")
375 .as_slice()
376 );
377
378 // Verify another write of across multiple chunks.
Victor Hsieh09e26262021-03-03 16:00:55 -0800379 let file = VerifiedFileEditor::new(InMemoryEditor::new());
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800380 assert_eq!(file.write_at(&[1; 10000], 0)?, 10000);
381 assert_eq!(
382 file.calculate_fsverity_digest()?,
383 to_u8_vec("7545409b556071554d18973a29b96409588c7cda4edd00d5586b27a11e1a523b")
384 .as_slice()
385 );
386 Ok(())
387 }
388
389 #[test]
390 fn test_verified_writer_unaligned() -> Result<()> {
391 // Verify small, unaligned write beyond EOF.
Victor Hsieh09e26262021-03-03 16:00:55 -0800392 let file = VerifiedFileEditor::new(InMemoryEditor::new());
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800393 assert_eq!(file.write_at(&[1; 5], 3)?, 5);
394 assert_eq!(
395 file.calculate_fsverity_digest()?,
396 to_u8_vec("a23fc5130d3d7b3323fc4b4a5e79d5d3e9ddf3a3f5872639e867713512c6702f")
397 .as_slice()
398 );
399
400 // Verify bigger, unaligned write beyond EOF.
Victor Hsieh09e26262021-03-03 16:00:55 -0800401 let file = VerifiedFileEditor::new(InMemoryEditor::new());
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800402 assert_eq!(file.write_at(&[1; 6000], 4000)?, 6000);
403 assert_eq!(
404 file.calculate_fsverity_digest()?,
405 to_u8_vec("d16d4c1c186d757e646f76208b21254f50d7f07ea07b1505ff48b2a6f603f989")
406 .as_slice()
407 );
408 Ok(())
409 }
410
411 #[test]
412 fn test_verified_writer_with_hole() -> Result<()> {
413 // Verify an aligned write beyond EOF with holes.
Victor Hsieh09e26262021-03-03 16:00:55 -0800414 let file = VerifiedFileEditor::new(InMemoryEditor::new());
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800415 assert_eq!(file.write_at(&[1; 4096], 4096)?, 4096);
416 assert_eq!(
417 file.calculate_fsverity_digest()?,
418 to_u8_vec("4df2aefd8c2a9101d1d8770dca3ede418232eabce766bb8e020395eae2e97103")
419 .as_slice()
420 );
421
422 // Verify an unaligned write beyond EOF with holes.
Victor Hsieh09e26262021-03-03 16:00:55 -0800423 let file = VerifiedFileEditor::new(InMemoryEditor::new());
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800424 assert_eq!(file.write_at(&[1; 5000], 6000)?, 5000);
425 assert_eq!(
426 file.calculate_fsverity_digest()?,
427 to_u8_vec("47d5da26f6934484e260630a69eb2eebb21b48f69bc8fbf8486d1694b7dba94f")
428 .as_slice()
429 );
430
431 // Just another example with a small write.
Victor Hsieh09e26262021-03-03 16:00:55 -0800432 let file = VerifiedFileEditor::new(InMemoryEditor::new());
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800433 assert_eq!(file.write_at(&[1; 5], 16381)?, 5);
434 assert_eq!(
435 file.calculate_fsverity_digest()?,
436 to_u8_vec("8bd118821fb4aff26bb4b51d485cc481a093c68131b7f4f112e9546198449752")
437 .as_slice()
438 );
439 Ok(())
440 }
441
442 #[test]
443 fn test_verified_writer_various_writes() -> Result<()> {
Victor Hsieh09e26262021-03-03 16:00:55 -0800444 let file = VerifiedFileEditor::new(InMemoryEditor::new());
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800445 assert_eq!(file.write_at(&[1; 2048], 0)?, 2048);
446 assert_eq!(file.write_at(&[1; 2048], 4096 + 2048)?, 2048);
447 assert_eq!(
448 file.calculate_fsverity_digest()?,
449 to_u8_vec("4c433d8640c888b629dc673d318cbb8d93b1eebcc784d9353e07f09f0dcfe707")
450 .as_slice()
451 );
452 assert_eq!(file.write_at(&[1; 2048], 2048)?, 2048);
453 assert_eq!(file.write_at(&[1; 2048], 4096)?, 2048);
454 assert_eq!(
455 file.calculate_fsverity_digest()?,
456 to_u8_vec("2a476d58eb80394052a3a783111e1458ac3ecf68a7878183fed86ca0ff47ec0d")
457 .as_slice()
458 );
459 assert_eq!(file.write_at(&[0; 2048], 2048)?, 2048);
460 assert_eq!(file.write_at(&[0; 2048], 4096)?, 2048);
461 assert_eq!(
462 file.calculate_fsverity_digest()?,
463 to_u8_vec("4c433d8640c888b629dc673d318cbb8d93b1eebcc784d9353e07f09f0dcfe707")
464 .as_slice()
465 );
466 assert_eq!(file.write_at(&[1; 4096], 2048)?, 4096);
467 assert_eq!(
468 file.calculate_fsverity_digest()?,
469 to_u8_vec("2a476d58eb80394052a3a783111e1458ac3ecf68a7878183fed86ca0ff47ec0d")
470 .as_slice()
471 );
472 assert_eq!(file.write_at(&[1; 2048], 8192)?, 2048);
473 assert_eq!(file.write_at(&[1; 2048], 8192 + 2048)?, 2048);
474 assert_eq!(
475 file.calculate_fsverity_digest()?,
476 to_u8_vec("23cbac08371e6ee838ebcc7ae6512b939d2226e802337be7b383c3e046047d24")
477 .as_slice()
478 );
479 Ok(())
480 }
481
482 #[test]
483 fn test_verified_writer_inconsistent_read() -> Result<()> {
Victor Hsieh09e26262021-03-03 16:00:55 -0800484 let file = VerifiedFileEditor::new(InMemoryEditor::new());
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800485 assert_eq!(file.write_at(&[1; 8192], 0)?, 8192);
486
487 // Replace the expected hash of the first/0-th chunk. An incomplete write will fail when it
488 // detects the inconsistent read.
489 {
490 let mut merkle_tree = file.merkle_tree.write().unwrap();
491 let overriding_hash = [42; Sha256Hasher::HASH_SIZE];
492 merkle_tree.update_hash(0, &overriding_hash, 8192);
493 }
494 assert!(file.write_at(&[1; 1], 2048).is_err());
495
496 // A write of full chunk can still succeed. Also fixed the inconsistency.
497 assert_eq!(file.write_at(&[1; 4096], 4096)?, 4096);
498
499 // Replace the expected hash of the second/1-th chunk. A write range from previous chunk can
500 // still succeed, but returns early due to an inconsistent read but still successfully. A
501 // resumed write will fail since no bytes can be written due to the same inconsistency.
502 {
503 let mut merkle_tree = file.merkle_tree.write().unwrap();
504 let overriding_hash = [42; Sha256Hasher::HASH_SIZE];
505 merkle_tree.update_hash(1, &overriding_hash, 8192);
506 }
507 assert_eq!(file.write_at(&[10; 8000], 0)?, 4096);
508 assert!(file.write_at(&[10; 8000 - 4096], 4096).is_err());
509 Ok(())
510 }
511
512 #[test]
513 fn test_verified_writer_failed_read_back() -> Result<()> {
Victor Hsieh09e26262021-03-03 16:00:55 -0800514 let mut writer = InMemoryEditor::new();
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800515 writer.fail_read = true;
516 let file = VerifiedFileEditor::new(writer);
517 assert_eq!(file.write_at(&[1; 8192], 0)?, 8192);
518
519 // When a read back is needed, a read failure will fail to write.
520 assert!(file.write_at(&[1; 1], 2048).is_err());
521 Ok(())
522 }
523
Victor Hsieh9d0ab622021-04-26 17:07:02 -0700524 #[test]
525 fn test_resize_to_same_size() -> Result<()> {
526 let file = VerifiedFileEditor::new(InMemoryEditor::new());
527 assert_eq!(file.write_at(&[1; 2048], 0)?, 2048);
528
529 assert!(file.resize(2048).is_ok());
530 assert_eq!(file.size(), 2048);
531
532 assert_eq!(
533 file.calculate_fsverity_digest()?,
534 to_u8_vec("fef1b4f19bb7a2cd944d7cdee44d1accb12726389ca5b0f61ac0f548ae40876f")
535 .as_slice()
536 );
537 Ok(())
538 }
539
540 #[test]
541 fn test_resize_to_grow() -> Result<()> {
542 let file = VerifiedFileEditor::new(InMemoryEditor::new());
543 assert_eq!(file.write_at(&[1; 2048], 0)?, 2048);
544
545 // Resize should grow with 0s.
546 assert!(file.resize(4096).is_ok());
547 assert_eq!(file.size(), 4096);
548
549 assert_eq!(
550 file.calculate_fsverity_digest()?,
551 to_u8_vec("9e0e2745c21e4e74065240936d2047340d96a466680c3c9d177b82433e7a0bb1")
552 .as_slice()
553 );
554 Ok(())
555 }
556
557 #[test]
558 fn test_resize_to_shrink() -> Result<()> {
559 let file = VerifiedFileEditor::new(InMemoryEditor::new());
560 assert_eq!(file.write_at(&[1; 4096], 0)?, 4096);
561
562 // Truncate.
563 file.resize(2048)?;
564 assert_eq!(file.size(), 2048);
565
566 assert_eq!(
567 file.calculate_fsverity_digest()?,
568 to_u8_vec("fef1b4f19bb7a2cd944d7cdee44d1accb12726389ca5b0f61ac0f548ae40876f")
569 .as_slice()
570 );
571 Ok(())
572 }
573
574 #[test]
575 fn test_resize_to_shrink_with_read_failure() -> Result<()> {
576 let mut writer = InMemoryEditor::new();
577 writer.fail_read = true;
578 let file = VerifiedFileEditor::new(writer);
579 assert_eq!(file.write_at(&[1; 4096], 0)?, 4096);
580
581 // A truncate needs a read back. If the read fail, the resize should fail.
582 assert!(file.resize(2048).is_err());
583 Ok(())
584 }
585
586 #[test]
587 fn test_resize_to_shirink_to_chunk_boundary() -> Result<()> {
588 let mut writer = InMemoryEditor::new();
589 writer.fail_read = true;
590 let file = VerifiedFileEditor::new(writer);
591 assert_eq!(file.write_at(&[1; 8192], 0)?, 8192);
592
593 // Truncate to a chunk boundary. A read error doesn't matter since we won't need to
594 // recalcuate the leaf hash.
595 file.resize(4096)?;
596 assert_eq!(file.size(), 4096);
597
598 assert_eq!(
599 file.calculate_fsverity_digest()?,
600 to_u8_vec("cd0875ca59c7d37e962c5e8f5acd3770750ac80225e2df652ce5672fd34500af")
601 .as_slice()
602 );
603 Ok(())
604 }
605
Victor Hsiehac4f3f42021-02-26 12:35:58 -0800606 fn to_u8_vec(hex_str: &str) -> Vec<u8> {
607 assert!(hex_str.len() % 2 == 0);
608 (0..hex_str.len())
609 .step_by(2)
610 .map(|i| u8::from_str_radix(&hex_str[i..i + 2], 16).unwrap())
611 .collect()
612 }
613}