1use aes_gcm::{
11 Aes256Gcm, Nonce,
12 aead::{Aead, KeyInit, Payload},
13};
14use anyhow::{Context, Result, bail};
15use argon2::{
16 Algorithm, Argon2, Params, Version,
17 password_hash::{SaltString, rand_core::OsRng as PasswordHashOsRng},
18};
19use base64::prelude::*;
20use flate2::{Compression, read::DeflateDecoder, write::DeflateEncoder};
21use rand::Rng;
22use serde::{Deserialize, Serialize};
23use std::fs::{File, OpenOptions};
24use std::io::{BufReader, BufWriter, Read, Write};
25use std::path::{Path, PathBuf};
26use zeroize::{Zeroize, ZeroizeOnDrop};
27
28#[derive(Debug, thiserror::Error)]
29#[error("{0}")]
30struct AeadSourceError(aes_gcm::Error);
31
32pub const DEFAULT_CHUNK_SIZE: usize = 8 * 1024 * 1024;
34
35pub const MAX_CHUNK_SIZE: usize = 32 * 1024 * 1024;
37
38const MAX_ARCHIVE_CHUNKS: u64 = u32::MAX as u64;
39
40fn max_encryptable_plaintext_bytes(chunk_size: usize) -> u64 {
41 MAX_ARCHIVE_CHUNKS.saturating_mul(chunk_size as u64)
42}
43
44fn ensure_archive_chunk_count_fits_nonce_space(chunk_count: u64, chunk_size: usize) -> Result<()> {
45 if chunk_count > MAX_ARCHIVE_CHUNKS {
46 bail!(
47 "File too large: exceeds maximum of {} chunks ({} bytes with current chunk size)",
48 u32::MAX,
49 max_encryptable_plaintext_bytes(chunk_size)
50 );
51 }
52 Ok(())
53}
54
55fn ensure_can_write_archive_chunk(chunk_index: u32, chunk_size: usize) -> Result<()> {
56 if chunk_index == u32::MAX {
57 bail!(
58 "File too large: exceeds maximum of {} chunks ({} bytes with current chunk size)",
59 u32::MAX,
60 max_encryptable_plaintext_bytes(chunk_size)
61 );
62 }
63 Ok(())
64}
65
66#[cfg(not(test))]
68const ARGON2_MEMORY_KB: u32 = 65536; #[cfg(test)]
70const ARGON2_MEMORY_KB: u32 = 64;
71#[cfg(not(test))]
72const ARGON2_ITERATIONS: u32 = 3;
73#[cfg(test)]
74const ARGON2_ITERATIONS: u32 = 1;
75#[cfg(not(test))]
76const ARGON2_PARALLELISM: u32 = 4;
77#[cfg(test)]
78const ARGON2_PARALLELISM: u32 = 1;
79
80pub(crate) const SCHEMA_VERSION: u8 = 2;
82
83#[derive(Clone, Zeroize, ZeroizeOnDrop)]
85pub struct SecretKey([u8; 32]);
86
87impl SecretKey {
88 pub fn random() -> Self {
89 let mut key = [0u8; 32];
90 let mut rng = rand::rng();
91 rng.fill_bytes(&mut key);
92 Self(key)
93 }
94
95 pub fn from_bytes(bytes: [u8; 32]) -> Self {
96 Self(bytes)
97 }
98
99 pub fn as_bytes(&self) -> &[u8; 32] {
100 &self.0
101 }
102}
103
104#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
106#[serde(rename_all = "lowercase")]
107pub enum SlotType {
108 Password,
109 Recovery,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
114#[serde(rename_all = "kebab-case")]
115pub enum KdfAlgorithm {
116 Argon2id,
117 HkdfSha256,
118}
119
120#[derive(Debug, Clone, Serialize, Deserialize)]
122#[serde(deny_unknown_fields)]
123pub struct KeySlot {
124 pub id: u8,
125 pub slot_type: SlotType,
126 pub kdf: KdfAlgorithm,
127 pub salt: String, pub wrapped_dek: String, pub nonce: String, #[serde(skip_serializing_if = "Option::is_none")]
131 pub argon2_params: Option<Argon2Params>,
132}
133
134#[derive(Debug, Clone, Serialize, Deserialize)]
136#[serde(deny_unknown_fields)]
137pub struct Argon2Params {
138 pub memory_kb: u32,
139 pub iterations: u32,
140 pub parallelism: u32,
141}
142
143impl Default for Argon2Params {
144 fn default() -> Self {
145 Self {
146 memory_kb: ARGON2_MEMORY_KB,
147 iterations: ARGON2_ITERATIONS,
148 parallelism: ARGON2_PARALLELISM,
149 }
150 }
151}
152
153#[derive(Debug, Clone, Serialize, Deserialize)]
155#[serde(deny_unknown_fields)]
156pub struct PayloadMeta {
157 pub chunk_size: usize,
158 pub chunk_count: usize,
159 pub total_compressed_size: u64,
160 pub total_plaintext_size: u64,
161 pub files: Vec<String>,
162}
163
164#[derive(Debug, Clone, Serialize, Deserialize)]
166#[serde(deny_unknown_fields)]
167pub struct EncryptionConfig {
168 pub version: u8,
169 pub export_id: String, pub base_nonce: String, pub compression: String,
172 pub kdf_defaults: Argon2Params,
173 pub payload: PayloadMeta,
174 pub key_slots: Vec<KeySlot>,
175}
176
177pub(crate) fn validate_supported_payload_format(config: &EncryptionConfig) -> Result<()> {
178 if config.version != SCHEMA_VERSION {
179 bail!(
180 "Unsupported archive schema version {}; expected {}",
181 config.version,
182 SCHEMA_VERSION
183 );
184 }
185
186 if config.compression != "deflate" {
187 bail!(
188 "Unsupported archive compression '{}'. The current encrypted pages format supports only deflate.",
189 config.compression
190 );
191 }
192
193 if config.payload.chunk_size == 0 {
194 bail!("Invalid archive chunk_size 0: must be > 0");
195 }
196
197 if config.payload.chunk_size > MAX_CHUNK_SIZE {
198 bail!(
199 "Invalid archive chunk_size {}: must be <= {} bytes",
200 config.payload.chunk_size,
201 MAX_CHUNK_SIZE
202 );
203 }
204
205 if config.payload.chunk_count != config.payload.files.len() {
206 bail!(
207 "Invalid archive payload metadata: chunk_count {} does not match file list length {}",
208 config.payload.chunk_count,
209 config.payload.files.len()
210 );
211 }
212
213 if config.payload.chunk_count > u32::MAX as usize {
214 bail!(
215 "Invalid archive payload metadata: chunk_count {} exceeds maximum {}",
216 config.payload.chunk_count,
217 u32::MAX
218 );
219 }
220
221 Ok(())
222}
223
224pub struct EncryptionEngine {
228 dek: SecretKey,
229 export_id: [u8; 16],
230 base_nonce: [u8; 12],
231 chunk_size: usize,
232 key_slots: Vec<KeySlot>,
233}
234
235impl std::fmt::Debug for EncryptionEngine {
236 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
237 f.debug_struct("EncryptionEngine")
238 .field("chunk_size", &self.chunk_size)
239 .field("key_slots", &self.key_slots.len())
240 .finish_non_exhaustive()
241 }
242}
243
244fn key_slot_id_for_len(slot_count: usize) -> Result<u8> {
245 u8::try_from(slot_count).map_err(|err| {
246 anyhow::anyhow!(
247 "maximum of 256 key slots exceeded ({} slots already allocated): {}",
248 slot_count,
249 err
250 )
251 })
252}
253
254impl Default for EncryptionEngine {
255 fn default() -> Self {
256 Self::new(DEFAULT_CHUNK_SIZE).expect("default chunk size must be valid")
257 }
258}
259
260impl EncryptionEngine {
261 pub fn new(chunk_size: usize) -> Result<Self> {
263 if chunk_size == 0 {
264 bail!("chunk_size must be > 0");
265 }
266 if chunk_size > MAX_CHUNK_SIZE {
267 bail!("chunk_size must be <= {MAX_CHUNK_SIZE} bytes");
268 }
269 let mut export_id = [0u8; 16];
270 let mut base_nonce = [0u8; 12];
271 let mut rng = rand::rng();
272 rng.fill_bytes(&mut export_id);
273 rng.fill_bytes(&mut base_nonce);
274
275 Ok(Self {
276 dek: SecretKey::random(),
277 export_id,
278 base_nonce,
279 chunk_size,
280 key_slots: Vec::new(),
281 })
282 }
283
284 pub fn add_password_slot(&mut self, password: &str) -> Result<u8> {
286 if password.is_empty() {
288 anyhow::bail!("Password cannot be empty");
289 }
290 if password.trim().is_empty() {
291 anyhow::bail!("Password cannot be whitespace-only");
292 }
293
294 let slot_id = key_slot_id_for_len(self.key_slots.len())?;
295
296 let salt = SaltString::generate(&mut PasswordHashOsRng);
298 let salt_bytes = salt.as_str().as_bytes();
299
300 let kek = derive_kek_argon2id(password, salt_bytes)?;
302
303 let (wrapped_dek, nonce) = wrap_key(&kek, self.dek.as_bytes(), &self.export_id, slot_id)?;
305
306 self.key_slots.push(KeySlot {
307 id: slot_id,
308 slot_type: SlotType::Password,
309 kdf: KdfAlgorithm::Argon2id,
310 salt: BASE64_STANDARD.encode(salt_bytes),
311 wrapped_dek: BASE64_STANDARD.encode(&wrapped_dek),
312 nonce: BASE64_STANDARD.encode(nonce),
313 argon2_params: Some(Argon2Params::default()),
314 });
315
316 Ok(slot_id)
317 }
318
319 pub fn add_recovery_slot(&mut self, secret: &[u8]) -> Result<u8> {
321 let slot_id = key_slot_id_for_len(self.key_slots.len())?;
322
323 let mut salt = [0u8; 16];
325 let mut rng = rand::rng();
326 rng.fill_bytes(&mut salt);
327
328 let kek = derive_kek_hkdf(secret, &salt)?;
330
331 let (wrapped_dek, nonce) = wrap_key(&kek, self.dek.as_bytes(), &self.export_id, slot_id)?;
333
334 self.key_slots.push(KeySlot {
335 id: slot_id,
336 slot_type: SlotType::Recovery,
337 kdf: KdfAlgorithm::HkdfSha256,
338 salt: BASE64_STANDARD.encode(salt),
339 wrapped_dek: BASE64_STANDARD.encode(&wrapped_dek),
340 nonce: BASE64_STANDARD.encode(nonce),
341 argon2_params: None,
342 });
343
344 Ok(slot_id)
345 }
346
347 pub fn key_slot_count(&self) -> usize {
349 self.key_slots.len()
350 }
351
352 pub fn encrypt_file<P: AsRef<Path>>(
354 &self,
355 input: P,
356 output_dir: P,
357 progress: impl Fn(u64, u64),
358 ) -> Result<EncryptionConfig> {
359 let input_path = input.as_ref();
360 let output_dir = output_dir.as_ref();
361
362 ensure_real_archive_output_directory(output_dir, "encrypted archive output directory")?;
363 let payload_dir = output_dir.join("payload");
364 ensure_real_archive_output_directory(&payload_dir, "encrypted archive payload directory")?;
365
366 let input_size = std::fs::metadata(input_path)?.len();
368 ensure_archive_chunk_count_fits_nonce_space(
369 input_size.div_ceil(self.chunk_size as u64),
370 self.chunk_size,
371 )?;
372
373 let input_file = File::open(input_path).context("Failed to open input file")?;
375 let mut reader = BufReader::new(input_file);
376
377 let mut chunk_files = Vec::new();
379 let mut chunk_index = 0u32;
380 let mut total_compressed = 0u64;
381 let mut bytes_read = 0u64;
382
383 let cipher = Aes256Gcm::new_from_slice(self.dek.as_bytes()).expect("Invalid key length");
384
385 loop {
386 let mut plaintext = vec![0u8; self.chunk_size];
388 let mut total_read = 0;
389
390 while total_read < self.chunk_size {
391 match reader.read(&mut plaintext[total_read..]) {
392 Ok(0) => break, Ok(n) => {
394 total_read += n;
395 bytes_read += n as u64;
396 progress(bytes_read, input_size);
397 }
398 Err(e) => return Err(e.into()),
399 }
400 }
401
402 if total_read == 0 {
403 break; }
405 ensure_can_write_archive_chunk(chunk_index, self.chunk_size)?;
406
407 plaintext.truncate(total_read);
408
409 let mut compressed = Vec::new();
411 {
412 let mut encoder = DeflateEncoder::new(&mut compressed, Compression::default());
413 encoder.write_all(&plaintext)?;
414 encoder.finish()?;
415 }
416
417 let nonce = derive_chunk_nonce(&self.base_nonce, chunk_index);
419
420 let aad = build_chunk_aad(&self.export_id, chunk_index);
422
423 let ciphertext = cipher
425 .encrypt(
426 Nonce::from_slice(&nonce),
427 Payload {
428 msg: &compressed,
429 aad: &aad,
430 },
431 )
432 .map_err(|e| anyhow::anyhow!("Encryption failed: {}", e))?;
433
434 let chunk_filename = format!("chunk-{:05}.bin", chunk_index);
436 let chunk_path = payload_dir.join(&chunk_filename);
437 write_encrypted_archive_file(&chunk_path, &ciphertext, "encrypted payload chunk")?;
438
439 chunk_files.push(format!("payload/{}", chunk_filename));
440 total_compressed += ciphertext.len() as u64;
441 chunk_index = chunk_index.checked_add(1).ok_or_else(|| {
442 anyhow::anyhow!(
443 "File too large: exceeds maximum of {} chunks ({} bytes with current chunk size)",
444 u32::MAX,
445 (u32::MAX as u64) * (self.chunk_size as u64)
446 )
447 })?;
448 }
449
450 let config = EncryptionConfig {
452 version: SCHEMA_VERSION,
453 export_id: BASE64_STANDARD.encode(self.export_id),
454 base_nonce: BASE64_STANDARD.encode(self.base_nonce),
455 compression: "deflate".to_string(),
456 kdf_defaults: Argon2Params::default(),
457 payload: PayloadMeta {
458 chunk_size: self.chunk_size,
459 chunk_count: chunk_index as usize,
460 total_compressed_size: total_compressed,
461 total_plaintext_size: input_size,
462 files: chunk_files,
463 },
464 key_slots: self.key_slots.clone(),
465 };
466
467 let config_path = output_dir.join("config.json");
469 let config_payload =
470 serde_json::to_vec_pretty(&config).context("Failed to serialize encryption config")?;
471 write_encrypted_archive_file(&config_path, &config_payload, "encryption config")?;
472 sync_tree(output_dir)?;
473
474 Ok(config)
475 }
476}
477
478fn ensure_real_archive_output_directory(path: &Path, label: &str) -> Result<()> {
479 ensure_existing_archive_ancestors_have_no_symlinks(path, label)?;
480 std::fs::create_dir_all(path).with_context(|| format!("Failed to create {label}"))?;
481 ensure_existing_archive_ancestors_have_no_symlinks(path, label)?;
482
483 let metadata =
484 std::fs::symlink_metadata(path).with_context(|| format!("Failed to inspect {label}"))?;
485 let file_type = metadata.file_type();
486 if file_type.is_symlink() {
487 bail!("{label} must not be a symlink: {}", path.display());
488 }
489 if !file_type.is_dir() {
490 bail!("{label} must be a directory: {}", path.display());
491 }
492 Ok(())
493}
494
495fn ensure_existing_archive_ancestors_have_no_symlinks(path: &Path, label: &str) -> Result<()> {
496 let mut ancestors: Vec<PathBuf> = path
497 .ancestors()
498 .filter(|ancestor| !ancestor.as_os_str().is_empty())
499 .map(Path::to_path_buf)
500 .collect();
501 ancestors.reverse();
502
503 for ancestor in ancestors {
504 match std::fs::symlink_metadata(&ancestor) {
505 Ok(metadata) => {
506 let file_type = metadata.file_type();
507 if file_type.is_symlink() {
508 bail!("{label} must not contain symlinks: {}", ancestor.display());
509 }
510 if !file_type.is_dir() {
511 bail!(
512 "{label} parent path must be a directory: {}",
513 ancestor.display()
514 );
515 }
516 }
517 Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
518 Err(err) => {
519 return Err(err)
520 .with_context(|| format!("Failed to inspect {label} {}", ancestor.display()));
521 }
522 }
523 }
524
525 Ok(())
526}
527
528fn write_encrypted_archive_file(path: &Path, bytes: &[u8], label: &str) -> Result<()> {
529 ensure_replaceable_archive_file(path, label)?;
530 let (mut pending, file) = PendingArchiveOutput::create(path, label)?;
531 let mut writer = BufWriter::new(file);
532 writer
533 .write_all(bytes)
534 .with_context(|| format!("Failed to write {label} {}", pending.path().display()))?;
535 writer
536 .flush()
537 .with_context(|| format!("Failed to flush {label} {}", pending.path().display()))?;
538 writer
539 .get_ref()
540 .sync_all()
541 .with_context(|| format!("Failed to sync {label} {}", pending.path().display()))?;
542 drop(writer);
543 pending.persist(path, label)
544}
545
546fn ensure_replaceable_archive_file(path: &Path, label: &str) -> Result<()> {
547 match std::fs::symlink_metadata(path) {
548 Ok(metadata) => {
549 let file_type = metadata.file_type();
550 if file_type.is_symlink() {
551 bail!(
552 "Refusing to write {label} through symlink: {}",
553 path.display()
554 );
555 }
556 if !file_type.is_file() {
557 bail!(
558 "Refusing to replace {label} at non-file path: {}",
559 path.display()
560 );
561 }
562 Ok(())
563 }
564 Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(()),
565 Err(err) => {
566 Err(err).with_context(|| format!("Failed to inspect {label} {}", path.display()))
567 }
568 }
569}
570
571struct PendingArchiveOutput {
572 path: PathBuf,
573 keep: bool,
574}
575
576impl PendingArchiveOutput {
577 fn create(final_path: &Path, label: &str) -> Result<(Self, File)> {
578 let parent = output_parent(final_path);
579 ensure_existing_archive_ancestors_have_no_symlinks(parent, label)?;
580 let file_name = final_path
581 .file_name()
582 .ok_or_else(|| anyhow::anyhow!("{label} path must name a file"))?
583 .to_string_lossy();
584
585 for attempt in 0..100u32 {
586 let mut random_bytes = [0u8; 8];
587 let mut rng = rand::rng();
588 rng.fill_bytes(&mut random_bytes);
589 let random = u64::from_le_bytes(random_bytes);
590 let temp_path = parent.join(format!(
591 ".{file_name}.cass-encrypt-tmp.{}.{}.{:016x}",
592 std::process::id(),
593 attempt,
594 random
595 ));
596
597 match OpenOptions::new()
598 .write(true)
599 .create_new(true)
600 .open(&temp_path)
601 {
602 Ok(file) => {
603 return Ok((
604 Self {
605 path: temp_path,
606 keep: false,
607 },
608 file,
609 ));
610 }
611 Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => continue,
612 Err(err) => {
613 return Err(err).with_context(|| {
614 format!("Failed to create temporary {label} {}", temp_path.display())
615 });
616 }
617 }
618 }
619
620 bail!(
621 "Failed to create a unique temporary {label} next to {} after 100 attempts",
622 final_path.display()
623 );
624 }
625
626 fn path(&self) -> &Path {
627 &self.path
628 }
629
630 fn persist(&mut self, final_path: &Path, label: &str) -> Result<()> {
631 replace_archive_file_from_temp(&self.path, final_path, label)?;
632 self.keep = true;
633 Ok(())
634 }
635}
636
637impl Drop for PendingArchiveOutput {
638 fn drop(&mut self) {
639 if !self.keep {
640 let _ = std::fs::remove_file(&self.path);
641 }
642 }
643}
644
645fn replace_archive_file_from_temp(temp_path: &Path, final_path: &Path, label: &str) -> Result<()> {
646 replace_archive_file_from_temp_impl(temp_path, final_path, label)?;
647 sync_parent_directory(final_path)
648}
649
650#[cfg(not(windows))]
651fn replace_archive_file_from_temp_impl(
652 temp_path: &Path,
653 final_path: &Path,
654 label: &str,
655) -> Result<()> {
656 std::fs::rename(temp_path, final_path).with_context(|| {
657 format!(
658 "Failed to install {label} {} from {}",
659 final_path.display(),
660 temp_path.display()
661 )
662 })
663}
664
665#[cfg(windows)]
666fn replace_archive_file_from_temp_impl(
667 temp_path: &Path,
668 final_path: &Path,
669 label: &str,
670) -> Result<()> {
671 ensure_replaceable_archive_file(final_path, label)?;
672 if std::fs::symlink_metadata(final_path).is_err() {
673 return std::fs::rename(temp_path, final_path).with_context(|| {
674 format!(
675 "Failed to install {label} {} from {}",
676 final_path.display(),
677 temp_path.display()
678 )
679 });
680 }
681
682 let parent = output_parent(final_path);
683 let file_name = final_path
684 .file_name()
685 .ok_or_else(|| anyhow::anyhow!("{label} path must name a file"))?
686 .to_string_lossy();
687 let backup_path = parent.join(format!(
688 ".{file_name}.cass-encrypt-backup.{}",
689 std::process::id()
690 ));
691
692 std::fs::rename(final_path, &backup_path).with_context(|| {
693 format!(
694 "Failed to stage existing {label} {} before replacement",
695 final_path.display()
696 )
697 })?;
698
699 match std::fs::rename(temp_path, final_path) {
700 Ok(()) => {
701 let _ = std::fs::remove_file(&backup_path);
702 Ok(())
703 }
704 Err(replace_err) => match std::fs::rename(&backup_path, final_path) {
705 Ok(()) => Err(replace_err).with_context(|| {
706 format!(
707 "Failed to install {label} {}; restored previous output",
708 final_path.display()
709 )
710 }),
711 Err(restore_err) => bail!(
712 "Failed to install {label} {}; also failed to restore previous output from {}: {}; temporary output retained at {}",
713 final_path.display(),
714 backup_path.display(),
715 restore_err,
716 temp_path.display()
717 ),
718 },
719 }
720}
721
722#[cfg(not(windows))]
723fn sync_tree(path: &Path) -> Result<()> {
724 sync_tree_inner(path)?;
732 sync_parent_directory(path)
733}
734
735#[cfg(windows)]
736fn sync_tree(_path: &Path) -> Result<()> {
737 Ok(())
742}
743
744#[cfg(not(windows))]
745fn sync_tree_inner(path: &Path) -> Result<()> {
746 let metadata = std::fs::symlink_metadata(path)?;
747 let file_type = metadata.file_type();
748 if file_type.is_symlink() {
749 return Ok(());
750 }
751 if file_type.is_file() {
752 File::open(path)?.sync_all()?;
753 return Ok(());
754 }
755 if file_type.is_dir() {
756 for entry in std::fs::read_dir(path)? {
757 sync_tree_inner(&entry?.path())?;
758 }
759 File::open(path)?.sync_all()?;
760 }
761 Ok(())
762}
763
764#[cfg(not(windows))]
770fn sync_parent_directory(path: &Path) -> Result<()> {
771 let Some(parent) = path.parent() else {
772 return Ok(());
773 };
774 File::open(parent)
775 .with_context(|| {
776 format!(
777 "failed opening parent directory {} for fsync",
778 parent.display()
779 )
780 })?
781 .sync_all()
782 .with_context(|| {
783 format!(
784 "failed syncing parent directory {} after encrypted export",
785 parent.display()
786 )
787 })
788}
789
790#[cfg(windows)]
791fn sync_parent_directory(_path: &Path) -> Result<()> {
792 Ok(())
793}
794
795pub struct DecryptionEngine {
797 dek: SecretKey,
798 config: EncryptionConfig,
799}
800
801impl DecryptionEngine {
802 pub fn unlock_with_password(config: EncryptionConfig, password: &str) -> Result<Self> {
804 validate_supported_payload_format(&config)?;
805
806 for slot in &config.key_slots {
807 if slot.slot_type != SlotType::Password {
808 continue;
809 }
810
811 let salt = BASE64_STANDARD.decode(&slot.salt)?;
812 let wrapped_dek = BASE64_STANDARD.decode(&slot.wrapped_dek)?;
813 let nonce = BASE64_STANDARD.decode(&slot.nonce)?;
814
815 let kek = derive_kek_argon2id(password, &salt)?;
816
817 let export_id = BASE64_STANDARD.decode(&config.export_id)?;
818 if let Ok(dek) = unwrap_key(&kek, &wrapped_dek, &nonce, &export_id, slot.id) {
819 return Ok(Self {
820 dek: SecretKey::from_bytes(dek),
821 config,
822 });
823 }
824 }
825
826 bail!("Invalid password or no matching key slot")
827 }
828
829 pub fn unlock_with_recovery(config: EncryptionConfig, secret: &[u8]) -> Result<Self> {
831 validate_supported_payload_format(&config)?;
832
833 for slot in &config.key_slots {
834 if slot.slot_type != SlotType::Recovery {
835 continue;
836 }
837
838 let salt = BASE64_STANDARD.decode(&slot.salt)?;
839 let wrapped_dek = BASE64_STANDARD.decode(&slot.wrapped_dek)?;
840 let nonce = BASE64_STANDARD.decode(&slot.nonce)?;
841
842 let kek = derive_kek_hkdf(secret, &salt)?;
843
844 let export_id = BASE64_STANDARD.decode(&config.export_id)?;
845 if let Ok(dek) = unwrap_key(&kek, &wrapped_dek, &nonce, &export_id, slot.id) {
846 return Ok(Self {
847 dek: SecretKey::from_bytes(dek),
848 config,
849 });
850 }
851 }
852
853 bail!("Invalid recovery secret or no matching key slot")
854 }
855
856 pub fn decrypt_to_file<P: AsRef<Path>>(
858 &self,
859 encrypted_dir: P,
860 output: P,
861 progress: impl Fn(usize, usize),
862 ) -> Result<()> {
863 let encrypted_dir = super::resolve_site_dir(encrypted_dir.as_ref())?;
864 let output_path = output.as_ref();
865 validate_supported_payload_format(&self.config)?;
866
867 let cipher = Aes256Gcm::new_from_slice(self.dek.as_bytes()).expect("Invalid key length");
868
869 let base_nonce = BASE64_STANDARD.decode(&self.config.base_nonce)?;
870 let export_id = BASE64_STANDARD.decode(&self.config.export_id)?;
871
872 if self.config.payload.files.len() > u32::MAX as usize {
874 bail!(
875 "Invalid config: chunk count {} exceeds maximum {}",
876 self.config.payload.files.len(),
877 u32::MAX
878 );
879 }
880
881 let (mut pending_output, output_file) = PendingDecryptOutput::create(output_path)?;
882 let mut writer = BufWriter::new(output_file);
883
884 for (chunk_index, chunk_file) in self.config.payload.files.iter().enumerate() {
885 progress(chunk_index, self.config.payload.chunk_count);
886
887 if chunk_file.contains("..") || Path::new(chunk_file).is_absolute() {
889 bail!("Invalid chunk path: potential directory traversal");
890 }
891
892 let chunk_path = encrypted_dir.join(chunk_file);
893 let ciphertext = std::fs::read(&chunk_path)?;
894
895 let nonce = derive_chunk_nonce(base_nonce.as_slice().try_into()?, chunk_index as u32);
897
898 let aad = build_chunk_aad(export_id.as_slice().try_into()?, chunk_index as u32);
900
901 let compressed = cipher
903 .decrypt(
904 Nonce::from_slice(&nonce),
905 Payload {
906 msg: &ciphertext,
907 aad: &aad,
908 },
909 )
910 .map_err(|err| {
911 let context = format!(
923 "Decryption failed for chunk {} ({} bytes ciphertext): {}",
924 chunk_index,
925 ciphertext.len(),
926 err
927 );
928 anyhow::Error::new(AeadSourceError(err)).context(context)
929 })?;
930
931 let mut decoder = DeflateDecoder::new(&compressed[..]);
933 let mut plaintext = Vec::new();
934 decoder.read_to_end(&mut plaintext)?;
935
936 writer.write_all(&plaintext)?;
937 }
938
939 writer.flush()?;
940 writer
941 .get_ref()
942 .sync_all()
943 .with_context(|| format!("Failed to sync {}", pending_output.path().display()))?;
944 drop(writer);
945 pending_output.persist(output_path)?;
946
947 progress(
948 self.config.payload.chunk_count,
949 self.config.payload.chunk_count,
950 );
951
952 Ok(())
953 }
954}
955
956struct PendingDecryptOutput {
957 path: PathBuf,
958 keep: bool,
959}
960
961impl PendingDecryptOutput {
962 fn create(output_path: &Path) -> Result<(Self, File)> {
963 let parent = output_parent(output_path);
964 let file_name = output_path
965 .file_name()
966 .ok_or_else(|| anyhow::anyhow!("decryption output path must name a file"))?
967 .to_string_lossy();
968
969 for attempt in 0..100u32 {
970 let mut random_bytes = [0u8; 8];
971 let mut rng = rand::rng();
972 rng.fill_bytes(&mut random_bytes);
973 let random = u64::from_le_bytes(random_bytes);
974 let temp_path = parent.join(format!(
975 ".{file_name}.cass-decrypt-tmp.{}.{}.{:016x}",
976 std::process::id(),
977 attempt,
978 random
979 ));
980
981 let mut options = OpenOptions::new();
982 options.write(true).create_new(true);
983 #[cfg(unix)]
984 {
985 use std::os::unix::fs::OpenOptionsExt;
986 options.mode(0o600);
987 }
988
989 match options.open(&temp_path) {
990 Ok(file) => {
991 return Ok((
992 Self {
993 path: temp_path,
994 keep: false,
995 },
996 file,
997 ));
998 }
999 Err(err) if err.kind() == std::io::ErrorKind::AlreadyExists => continue,
1000 Err(err) => {
1001 return Err(err).with_context(|| {
1002 format!(
1003 "Failed to create temporary decrypt output {}",
1004 temp_path.display()
1005 )
1006 });
1007 }
1008 }
1009 }
1010
1011 bail!(
1012 "Failed to create a unique temporary decrypt output next to {} after 100 attempts",
1013 output_path.display()
1014 );
1015 }
1016
1017 fn path(&self) -> &Path {
1018 &self.path
1019 }
1020
1021 fn persist(&mut self, output_path: &Path) -> Result<()> {
1022 replace_decrypt_output_from_temp(&self.path, output_path)?;
1023 self.keep = true;
1024 Ok(())
1025 }
1026}
1027
1028impl Drop for PendingDecryptOutput {
1029 fn drop(&mut self) {
1030 if !self.keep {
1031 let _ = std::fs::remove_file(&self.path);
1032 }
1033 }
1034}
1035
1036fn output_parent(output_path: &Path) -> &Path {
1037 output_path
1038 .parent()
1039 .filter(|parent| !parent.as_os_str().is_empty())
1040 .unwrap_or_else(|| Path::new("."))
1041}
1042
1043fn replace_decrypt_output_from_temp(temp_path: &Path, output_path: &Path) -> Result<()> {
1044 replace_decrypt_output_from_temp_impl(temp_path, output_path)?;
1045 sync_parent_directory(output_path)
1046}
1047
1048#[cfg(not(windows))]
1049fn replace_decrypt_output_from_temp_impl(temp_path: &Path, output_path: &Path) -> Result<()> {
1050 std::fs::rename(temp_path, output_path).with_context(|| {
1051 format!(
1052 "Failed to install decrypted output {} from {}",
1053 output_path.display(),
1054 temp_path.display()
1055 )
1056 })
1057}
1058
1059#[cfg(windows)]
1060fn replace_decrypt_output_from_temp_impl(temp_path: &Path, output_path: &Path) -> Result<()> {
1061 if std::fs::symlink_metadata(output_path).is_err() {
1062 return std::fs::rename(temp_path, output_path).with_context(|| {
1063 format!(
1064 "Failed to install decrypted output {} from {}",
1065 output_path.display(),
1066 temp_path.display()
1067 )
1068 });
1069 }
1070
1071 let parent = output_parent(output_path);
1072 let file_name = output_path
1073 .file_name()
1074 .ok_or_else(|| anyhow::anyhow!("decryption output path must name a file"))?
1075 .to_string_lossy();
1076 let backup_path = parent.join(format!(
1077 ".{file_name}.cass-decrypt-backup.{}",
1078 std::process::id()
1079 ));
1080
1081 std::fs::rename(output_path, &backup_path).with_context(|| {
1082 format!(
1083 "Failed to stage existing decrypted output {} before replacement",
1084 output_path.display()
1085 )
1086 })?;
1087
1088 match std::fs::rename(temp_path, output_path) {
1089 Ok(()) => {
1090 let _ = std::fs::remove_file(&backup_path);
1091 Ok(())
1092 }
1093 Err(replace_err) => match std::fs::rename(&backup_path, output_path) {
1094 Ok(()) => Err(replace_err).with_context(|| {
1095 format!(
1096 "Failed to install decrypted output {}; restored previous output",
1097 output_path.display()
1098 )
1099 }),
1100 Err(restore_err) => bail!(
1101 "Failed to install decrypted output {}; also failed to restore previous output from {}: {}; temporary output retained at {}",
1102 output_path.display(),
1103 backup_path.display(),
1104 restore_err,
1105 temp_path.display()
1106 ),
1107 },
1108 }
1109}
1110
1111#[tracing::instrument(
1118 name = "derive_kek_argon2id",
1119 skip_all,
1120 fields(
1121 operation = "derive_kek_argon2id",
1122 salt_len = salt.len(),
1123 memory_kb = ARGON2_MEMORY_KB,
1124 iterations = ARGON2_ITERATIONS,
1125 parallelism = ARGON2_PARALLELISM,
1126 password_present = !password.is_empty(),
1127 )
1128)]
1129fn derive_kek_argon2id(password: &str, salt: &[u8]) -> Result<SecretKey> {
1130 let start = std::time::Instant::now();
1131 let params = Params::new(
1132 ARGON2_MEMORY_KB,
1133 ARGON2_ITERATIONS,
1134 ARGON2_PARALLELISM,
1135 Some(32),
1136 )
1137 .map_err(|e| anyhow::anyhow!("Invalid Argon2 parameters: {:?}", e))?;
1138
1139 let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, params);
1140
1141 let mut kek = [0u8; 32];
1142 argon2
1143 .hash_password_into(password.as_bytes(), salt, &mut kek)
1144 .map_err(|e| anyhow::anyhow!("Argon2id derivation failed: {}", e))?;
1145
1146 tracing::debug!(
1147 target: "cass::pages::encrypt",
1148 operation = "derive_kek_argon2id",
1149 elapsed_ms = start.elapsed().as_millis() as u64,
1150 kek_len = kek.len(),
1151 "derive_kek_argon2id: ok"
1152 );
1153 Ok(SecretKey::from_bytes(kek))
1154}
1155
1156#[tracing::instrument(
1163 name = "derive_kek_hkdf",
1164 skip_all,
1165 fields(
1166 operation = "derive_kek_hkdf",
1167 salt_len = salt.len(),
1168 secret_len = secret.len(),
1169 info_label = "cass-pages-kek-v2",
1170 )
1171)]
1172fn derive_kek_hkdf(secret: &[u8], salt: &[u8]) -> Result<SecretKey> {
1173 let start = std::time::Instant::now();
1174 let kek = crate::encryption::hkdf_extract_expand(secret, salt, b"cass-pages-kek-v2", 32)
1175 .map_err(|e| anyhow::anyhow!("HKDF extract+expand failed for recovery secret KEK: {e}"))?;
1176 let actual_len = kek.len();
1177 let kek: [u8; 32] = kek.try_into().map_err(|_| {
1178 anyhow::anyhow!(
1179 "HKDF expansion produced invalid KEK length: expected 32, got {}",
1180 actual_len
1181 )
1182 })?;
1183 tracing::debug!(
1184 target: "cass::pages::encrypt",
1185 operation = "derive_kek_hkdf",
1186 elapsed_us = start.elapsed().as_micros() as u64,
1187 kek_len = 32,
1188 "derive_kek_hkdf: ok"
1189 );
1190 Ok(SecretKey::from_bytes(kek))
1191}
1192
1193fn wrap_key(
1195 kek: &SecretKey,
1196 dek: &[u8; 32],
1197 export_id: &[u8; 16],
1198 slot_id: u8,
1199) -> Result<(Vec<u8>, [u8; 12])> {
1200 let cipher = Aes256Gcm::new_from_slice(kek.as_bytes()).expect("Invalid key length");
1201
1202 let mut nonce = [0u8; 12];
1203 let mut rng = rand::rng();
1204 rng.fill_bytes(&mut nonce);
1205
1206 let mut aad = Vec::with_capacity(17);
1208 aad.extend_from_slice(export_id);
1209 aad.push(slot_id);
1210
1211 let wrapped = cipher
1212 .encrypt(
1213 Nonce::from_slice(&nonce),
1214 Payload {
1215 msg: dek,
1216 aad: &aad,
1217 },
1218 )
1219 .map_err(|e| anyhow::anyhow!("Key wrapping failed: {}", e))?;
1220
1221 Ok((wrapped, nonce))
1222}
1223
1224fn unwrap_key(
1226 kek: &SecretKey,
1227 wrapped: &[u8],
1228 nonce: &[u8],
1229 export_id: &[u8],
1230 slot_id: u8,
1231) -> Result<[u8; 32]> {
1232 let cipher = Aes256Gcm::new_from_slice(kek.as_bytes()).expect("Invalid key length");
1233 let nonce: &[u8; 12] = nonce
1234 .try_into()
1235 .map_err(|_| anyhow::anyhow!("invalid nonce length: expected 12, got {}", nonce.len()))?;
1236
1237 let mut aad = Vec::with_capacity(export_id.len() + 1);
1239 aad.extend_from_slice(export_id);
1240 aad.push(slot_id);
1241
1242 let dek = cipher
1243 .decrypt(
1244 Nonce::from_slice(nonce),
1245 Payload {
1246 msg: wrapped,
1247 aad: &aad,
1248 },
1249 )
1250 .map_err(|err| {
1251 let context = format!(
1263 "Key unwrapping failed for slot {} ({} bytes wrapped, {} bytes nonce, \
1264 {} bytes aad): {}",
1265 slot_id,
1266 wrapped.len(),
1267 nonce.len(),
1268 aad.len(),
1269 err
1270 );
1271 anyhow::Error::new(AeadSourceError(err)).context(context)
1272 })?;
1273
1274 let dek_len = dek.len();
1275 dek.try_into().map_err(|_| {
1276 anyhow::anyhow!(
1277 "Invalid DEK length after unwrap: expected 32, got {}",
1278 dek_len
1279 )
1280 })
1281}
1282
1283#[tracing::instrument(
1296 name = "derive_chunk_nonce",
1297 skip_all,
1298 fields(operation = "derive_chunk_nonce", chunk_index = chunk_index)
1299)]
1300fn derive_chunk_nonce(base_nonce: &[u8; 12], chunk_index: u32) -> [u8; 12] {
1301 let mut nonce = *base_nonce;
1302 nonce[8..12].copy_from_slice(&chunk_index.to_be_bytes());
1305 tracing::trace!(
1306 target: "cass::pages::encrypt",
1307 operation = "derive_chunk_nonce",
1308 chunk_index = chunk_index,
1309 "derive_chunk_nonce: ok"
1310 );
1311 nonce
1312}
1313
1314fn build_chunk_aad(export_id: &[u8; 16], chunk_index: u32) -> Vec<u8> {
1316 let mut aad = Vec::with_capacity(21);
1317 aad.extend_from_slice(export_id);
1318 aad.extend_from_slice(&chunk_index.to_be_bytes());
1319 aad.push(SCHEMA_VERSION);
1320 aad
1321}
1322
1323pub fn load_config<P: AsRef<Path>>(dir: P) -> Result<EncryptionConfig> {
1325 let archive_dir = super::resolve_site_dir(dir.as_ref())?;
1326 let config_path = archive_dir.join("config.json");
1327 let file = File::open(&config_path).context("Failed to open config.json")?;
1328 let config: EncryptionConfig = serde_json::from_reader(BufReader::new(file))?;
1329 Ok(config)
1330}
1331
1332#[cfg(test)]
1333mod tests {
1334 use super::*;
1335 use tempfile::TempDir;
1336
1337 fn assert_file_bytes(path: &Path, expected: &[u8]) {
1338 let actual = std::fs::read(path)
1339 .unwrap_or_else(|err| panic!("failed to read {}: {err}", path.display()));
1340 assert_eq!(
1341 actual.as_slice(),
1342 expected,
1343 "unexpected bytes in {}",
1344 path.display()
1345 );
1346 }
1347
1348 fn encrypt_test_file() -> (TempDir, std::path::PathBuf, EncryptionConfig) {
1349 let temp_dir = TempDir::new().unwrap();
1350 let input_path = temp_dir.path().join("input.txt");
1351 let output_dir = temp_dir.path().join("encrypted");
1352
1353 std::fs::write(&input_path, b"payload format validation test").unwrap();
1354
1355 let mut engine = EncryptionEngine::new(1024).unwrap();
1356 engine.add_password_slot("password").unwrap();
1357 let config = engine
1358 .encrypt_file(&input_path, &output_dir, |_, _| {})
1359 .unwrap();
1360
1361 (temp_dir, output_dir, config)
1362 }
1363
1364 #[test]
1365 fn test_argon2id_key_derivation() {
1366 let password = "test-password-123";
1367 let salt = b"0123456789abcdef";
1368
1369 let kek1 = derive_kek_argon2id(password, salt).unwrap();
1370 let kek2 = derive_kek_argon2id(password, salt).unwrap();
1371
1372 assert_eq!(kek1.as_bytes(), kek2.as_bytes());
1374
1375 let kek3 = derive_kek_argon2id("different", salt).unwrap();
1377 assert_ne!(kek1.as_bytes(), kek3.as_bytes());
1378 }
1379
1380 #[test]
1381 fn test_hkdf_key_derivation() {
1382 let secret = b"recovery-secret-bytes";
1383 let salt = [0u8; 16];
1384
1385 let kek1 = derive_kek_hkdf(secret, &salt).unwrap();
1386 let kek2 = derive_kek_hkdf(secret, &salt).unwrap();
1387
1388 assert_eq!(kek1.as_bytes(), kek2.as_bytes());
1389 }
1390
1391 #[test]
1392 fn test_key_wrap_unwrap() {
1393 let kek = SecretKey::random();
1394 let dek = [42u8; 32];
1395 let export_id = [1u8; 16];
1396 let slot_id = 0;
1397
1398 let (wrapped, nonce) = wrap_key(&kek, &dek, &export_id, slot_id).unwrap();
1399 let unwrapped = unwrap_key(&kek, &wrapped, &nonce, &export_id, slot_id).unwrap();
1400
1401 assert_eq!(dek, unwrapped);
1402 }
1403
1404 #[test]
1405 fn test_key_wrap_wrong_aad_fails() {
1406 let kek = SecretKey::random();
1407 let dek = [42u8; 32];
1408 let export_id = [1u8; 16];
1409
1410 let (wrapped, nonce) = wrap_key(&kek, &dek, &export_id, 0).unwrap();
1411
1412 assert!(unwrap_key(&kek, &wrapped, &nonce, &export_id, 1).is_err());
1414
1415 let wrong_id = [2u8; 16];
1417 assert!(unwrap_key(&kek, &wrapped, &nonce, &wrong_id, 0).is_err());
1418 }
1419
1420 #[test]
1421 fn test_chunk_nonce_derivation() {
1422 let base = [0u8; 12];
1423
1424 let n0 = derive_chunk_nonce(&base, 0);
1425 let n1 = derive_chunk_nonce(&base, 1);
1426 let n2 = derive_chunk_nonce(&base, 2);
1427
1428 assert_ne!(n0, n1);
1430 assert_ne!(n1, n2);
1431 assert_ne!(n0, n2);
1432 }
1433
1434 #[test]
1435 fn test_encryption_roundtrip() {
1436 let temp_dir = TempDir::new().unwrap();
1437 let input_path = temp_dir.path().join("input.txt");
1438 let output_dir = temp_dir.path().join("encrypted");
1439 let decrypted_path = temp_dir.path().join("decrypted.txt");
1440
1441 let test_data = b"Hello, World! This is a test of the encryption system.";
1443 std::fs::write(&input_path, test_data).unwrap();
1444
1445 let mut engine = EncryptionEngine::new(1024).unwrap(); engine.add_password_slot("test-password").unwrap();
1448
1449 let config = engine
1450 .encrypt_file(&input_path, &output_dir, |_, _| {})
1451 .unwrap();
1452
1453 assert_eq!(config.version, SCHEMA_VERSION);
1454 assert!(!config.key_slots.is_empty());
1455 assert!(config.payload.chunk_count > 0);
1456
1457 let decryptor = DecryptionEngine::unlock_with_password(config, "test-password").unwrap();
1459 decryptor
1460 .decrypt_to_file(&output_dir, &decrypted_path, |_, _| {})
1461 .unwrap();
1462
1463 assert_file_bytes(&decrypted_path, test_data);
1465 }
1466
1467 #[test]
1468 fn encrypt_file_rejects_chunk_count_beyond_nonce_space_before_writing_payload() {
1469 let temp_dir = TempDir::new().unwrap();
1470 let input_path = temp_dir.path().join("too-large.bin");
1471 let output_dir = temp_dir.path().join("encrypted");
1472
1473 let input = File::create(&input_path).unwrap();
1474 input.set_len(u64::from(u32::MAX) + 1).unwrap();
1475
1476 let mut engine = EncryptionEngine::new(1).unwrap();
1477 engine.add_password_slot("password").unwrap();
1478
1479 let err = engine
1480 .encrypt_file(&input_path, &output_dir, |_, _| {})
1481 .expect_err("archive must reject more than u32::MAX chunks");
1482 let rendered = err.to_string();
1483 assert!(
1484 rendered.contains("exceeds maximum") && rendered.contains(&u32::MAX.to_string()),
1485 "unexpected chunk-count error: {rendered}"
1486 );
1487 assert!(
1488 !output_dir.join("payload/chunk-00000.bin").exists(),
1489 "oversized sparse input must fail before writing any ciphertext chunk"
1490 );
1491 }
1492
1493 #[test]
1494 #[cfg(unix)]
1495 fn encrypt_file_rejects_symlinked_payload_directory() {
1496 use std::os::unix::fs::symlink;
1497
1498 let temp_dir = TempDir::new().unwrap();
1499 let input_path = temp_dir.path().join("input.txt");
1500 let output_dir = temp_dir.path().join("encrypted");
1501 let outside_dir = temp_dir.path().join("outside");
1502 let test_data = b"payload dir symlink regression data";
1503
1504 std::fs::write(&input_path, test_data).unwrap();
1505 std::fs::create_dir_all(&output_dir).unwrap();
1506 std::fs::create_dir_all(&outside_dir).unwrap();
1507 symlink(&outside_dir, output_dir.join("payload")).unwrap();
1508
1509 let mut engine = EncryptionEngine::new(1024).unwrap();
1510 engine.add_password_slot("test-password").unwrap();
1511 let err = engine
1512 .encrypt_file(&input_path, &output_dir, |_, _| {})
1513 .expect_err("symlinked payload directory should be rejected");
1514
1515 assert!(
1516 err.to_string().contains("must not contain symlinks"),
1517 "unexpected error: {err:#}"
1518 );
1519 assert!(
1520 !outside_dir.join("chunk-00000.bin").exists(),
1521 "encrypt_file must not write through a symlinked payload directory"
1522 );
1523 }
1524
1525 #[test]
1526 #[cfg(unix)]
1527 fn encrypt_file_rejects_symlinked_chunk_file_without_touching_target() {
1528 use std::os::unix::fs::symlink;
1529
1530 let temp_dir = TempDir::new().unwrap();
1531 let input_path = temp_dir.path().join("input.txt");
1532 let output_dir = temp_dir.path().join("encrypted");
1533 let payload_dir = output_dir.join("payload");
1534 let protected_target_path = temp_dir.path().join("protected.bin");
1535 let test_data = b"chunk file symlink regression data";
1536
1537 std::fs::write(&input_path, test_data).unwrap();
1538 std::fs::create_dir_all(&payload_dir).unwrap();
1539 std::fs::write(&protected_target_path, b"protected chunk target").unwrap();
1540 symlink(&protected_target_path, payload_dir.join("chunk-00000.bin")).unwrap();
1541
1542 let mut engine = EncryptionEngine::new(1024).unwrap();
1543 engine.add_password_slot("test-password").unwrap();
1544 let err = engine
1545 .encrypt_file(&input_path, &output_dir, |_, _| {})
1546 .expect_err("symlinked chunk file should be rejected");
1547
1548 assert!(
1549 err.to_string().contains("through symlink"),
1550 "unexpected error: {err:#}"
1551 );
1552 assert_file_bytes(&protected_target_path, b"protected chunk target");
1553 }
1554
1555 #[test]
1556 #[cfg(unix)]
1557 fn encrypt_file_rejects_symlinked_config_file_without_touching_target() {
1558 use std::os::unix::fs::symlink;
1559
1560 let temp_dir = TempDir::new().unwrap();
1561 let input_path = temp_dir.path().join("input.txt");
1562 let output_dir = temp_dir.path().join("encrypted");
1563 let protected_target_path = temp_dir.path().join("protected-config.json");
1564 let test_data = b"config symlink regression data";
1565
1566 std::fs::write(&input_path, test_data).unwrap();
1567 std::fs::create_dir_all(&output_dir).unwrap();
1568 std::fs::write(&protected_target_path, b"protected config target").unwrap();
1569 symlink(&protected_target_path, output_dir.join("config.json")).unwrap();
1570
1571 let mut engine = EncryptionEngine::new(1024).unwrap();
1572 engine.add_password_slot("test-password").unwrap();
1573 let err = engine
1574 .encrypt_file(&input_path, &output_dir, |_, _| {})
1575 .expect_err("symlinked config file should be rejected");
1576
1577 assert!(
1578 err.to_string().contains("through symlink"),
1579 "unexpected error: {err:#}"
1580 );
1581 assert_file_bytes(&protected_target_path, b"protected config target");
1582 }
1583
1584 #[test]
1585 fn test_multiple_key_slots() {
1586 let temp_dir = TempDir::new().unwrap();
1587 let input_path = temp_dir.path().join("input.txt");
1588 let output_dir = temp_dir.path().join("encrypted");
1589 let decrypted_path = temp_dir.path().join("decrypted.txt");
1590
1591 let test_data = b"Multi-slot test data";
1592 std::fs::write(&input_path, test_data).unwrap();
1593
1594 let mut engine = EncryptionEngine::new(1024).unwrap();
1596 engine.add_password_slot("password1").unwrap();
1597 engine.add_password_slot("password2").unwrap();
1598 engine.add_recovery_slot(b"recovery-secret").unwrap();
1599
1600 let config = engine
1601 .encrypt_file(&input_path, &output_dir, |_, _| {})
1602 .unwrap();
1603
1604 assert_eq!(config.key_slots.len(), 3);
1605
1606 let d1 = DecryptionEngine::unlock_with_password(config.clone(), "password1").unwrap();
1608 d1.decrypt_to_file(&output_dir, &decrypted_path, |_, _| {})
1609 .unwrap();
1610 assert_file_bytes(&decrypted_path, test_data);
1611
1612 let d2 = DecryptionEngine::unlock_with_password(config.clone(), "password2").unwrap();
1614 d2.decrypt_to_file(&output_dir, &decrypted_path, |_, _| {})
1615 .unwrap();
1616 assert_file_bytes(&decrypted_path, test_data);
1617
1618 let d3 =
1620 DecryptionEngine::unlock_with_recovery(config.clone(), b"recovery-secret").unwrap();
1621 d3.decrypt_to_file(&output_dir, &decrypted_path, |_, _| {})
1622 .unwrap();
1623 assert_file_bytes(&decrypted_path, test_data);
1624
1625 assert!(DecryptionEngine::unlock_with_password(config, "wrong").is_err());
1627 }
1628
1629 #[test]
1630 fn key_slot_id_for_len_rejects_overflow() {
1631 assert_eq!(key_slot_id_for_len(255).unwrap(), 255);
1632
1633 let err = key_slot_id_for_len(256).unwrap_err();
1634 assert_eq!(
1635 err.to_string(),
1636 "maximum of 256 key slots exceeded (256 slots already allocated): out of range integral type conversion attempted"
1637 );
1638 }
1639
1640 #[test]
1641 fn test_load_config_and_decrypt_accept_bundle_root() {
1642 let temp_dir = TempDir::new().unwrap();
1643 let input_path = temp_dir.path().join("input.txt");
1644 let bundle_root = temp_dir.path().join("bundle");
1645 let site_dir = bundle_root.join("site");
1646 let decrypted_path = temp_dir.path().join("decrypted.txt");
1647
1648 let test_data = b"Bundle root decryption test data";
1649 std::fs::write(&input_path, test_data).unwrap();
1650
1651 let mut engine = EncryptionEngine::new(1024).unwrap();
1652 engine.add_password_slot("password").unwrap();
1653 engine
1654 .encrypt_file(&input_path, &site_dir, |_, _| {})
1655 .unwrap();
1656
1657 let config = load_config(&bundle_root).unwrap();
1658 let decryptor = DecryptionEngine::unlock_with_password(config, "password").unwrap();
1659 decryptor
1660 .decrypt_to_file(&bundle_root, &decrypted_path, |_, _| {})
1661 .unwrap();
1662
1663 assert_file_bytes(&decrypted_path, test_data);
1664 }
1665
1666 #[test]
1667 fn test_decrypt_rejects_unsupported_payload_compression_before_unlock() {
1668 let (_temp_dir, _output_dir, mut config) = encrypt_test_file();
1669 config.compression = "zstd".to_string();
1670
1671 let err = match DecryptionEngine::unlock_with_password(config, "password") {
1672 Ok(_) => panic!("unsupported compression must fail before unlock"),
1673 Err(err) => err,
1674 };
1675
1676 let rendered = err.to_string();
1677 assert!(
1678 rendered.contains("supports only deflate") && rendered.contains("zstd"),
1679 "unexpected unsupported-compression error: {err:#}"
1680 );
1681 }
1682
1683 #[test]
1684 fn test_decrypt_rejects_unsupported_schema_version_before_unlock() {
1685 let (_temp_dir, _output_dir, mut config) = encrypt_test_file();
1686 config.version = 1;
1687
1688 let err = match DecryptionEngine::unlock_with_password(config, "password") {
1689 Ok(_) => panic!("unsupported schema version must fail before unlock"),
1690 Err(err) => err,
1691 };
1692
1693 let rendered = err.to_string();
1694 assert!(
1695 rendered.contains("schema version") && rendered.contains("expected 2"),
1696 "unexpected unsupported-version error: {err:#}"
1697 );
1698 }
1699
1700 #[test]
1701 fn test_decrypt_rejects_mismatched_chunk_count_before_unlock() {
1702 let (_temp_dir, _output_dir, mut config) = encrypt_test_file();
1703 config.payload.chunk_count += 1;
1704
1705 let err = match DecryptionEngine::unlock_with_password(config, "password") {
1706 Ok(_) => panic!("mismatched chunk count must fail before unlock"),
1707 Err(err) => err,
1708 };
1709
1710 let rendered = err.to_string();
1711 assert!(
1712 rendered.contains("chunk_count") && rendered.contains("file list length"),
1713 "unexpected mismatched-chunk-count error: {err:#}"
1714 );
1715 }
1716
1717 #[test]
1718 fn test_tampered_chunk_fails() {
1719 let temp_dir = TempDir::new().unwrap();
1720 let input_path = temp_dir.path().join("input.txt");
1721 let output_dir = temp_dir.path().join("encrypted");
1722 let decrypted_path = temp_dir.path().join("decrypted.txt");
1723
1724 std::fs::write(&input_path, b"Test data for tampering").unwrap();
1725
1726 let mut engine = EncryptionEngine::new(1024).unwrap();
1727 engine.add_password_slot("password").unwrap();
1728
1729 let config = engine
1730 .encrypt_file(&input_path, &output_dir, |_, _| {})
1731 .unwrap();
1732
1733 let chunk_path = output_dir.join("payload/chunk-00000.bin");
1735 let mut chunk_data = std::fs::read(&chunk_path).unwrap();
1736 chunk_data[0] ^= 0xFF; std::fs::write(&chunk_path, &chunk_data).unwrap();
1738
1739 let decryptor = DecryptionEngine::unlock_with_password(config, "password").unwrap();
1741 assert!(
1742 decryptor
1743 .decrypt_to_file(&output_dir, &decrypted_path, |_, _| {})
1744 .is_err()
1745 );
1746 }
1747
1748 #[test]
1749 fn decrypt_to_file_preserves_existing_output_when_later_chunk_fails() {
1750 let temp_dir = TempDir::new().unwrap();
1751 let input_path = temp_dir.path().join("input.txt");
1752 let output_dir = temp_dir.path().join("encrypted");
1753 let decrypted_path = temp_dir.path().join("decrypted.txt");
1754
1755 let test_data: Vec<u8> = (0..4096).map(|idx| (idx % 251) as u8).collect();
1756 std::fs::write(&input_path, &test_data).unwrap();
1757
1758 let mut engine = EncryptionEngine::new(32).unwrap();
1759 engine.add_password_slot("password").unwrap();
1760 let config = engine
1761 .encrypt_file(&input_path, &output_dir, |_, _| {})
1762 .unwrap();
1763 assert!(
1764 config.payload.chunk_count > 1,
1765 "test must produce multiple chunks to exercise partial-write failure"
1766 );
1767
1768 let existing_output = b"existing decrypted output must survive failed decrypt";
1769 std::fs::write(&decrypted_path, existing_output).unwrap();
1770
1771 let second_chunk_path = output_dir.join("payload/chunk-00001.bin");
1772 let mut second_chunk = std::fs::read(&second_chunk_path).unwrap();
1773 let last = second_chunk.len() - 1;
1774 second_chunk[last] ^= 0x55;
1775 std::fs::write(&second_chunk_path, &second_chunk).unwrap();
1776
1777 let decryptor = DecryptionEngine::unlock_with_password(config, "password").unwrap();
1778 let err = decryptor
1779 .decrypt_to_file(&output_dir, &decrypted_path, |_, _| {})
1780 .expect_err("tampered later chunk must fail");
1781 assert!(
1782 err.to_string().contains("Decryption failed for chunk 1"),
1783 "unexpected decrypt error: {err:#}"
1784 );
1785 assert_file_bytes(&decrypted_path, existing_output);
1786
1787 let leaked_temp = std::fs::read_dir(temp_dir.path())
1788 .unwrap()
1789 .filter_map(Result::ok)
1790 .map(|entry| entry.file_name().to_string_lossy().into_owned())
1791 .any(|name| name.contains(".cass-decrypt-tmp."));
1792 assert!(
1793 !leaked_temp,
1794 "failed decrypt should not leave plaintext temp files"
1795 );
1796 }
1797
1798 #[test]
1799 #[cfg(unix)]
1800 fn decrypt_to_file_replaces_output_symlink_without_touching_target() {
1801 use std::os::unix::fs::symlink;
1802
1803 let temp_dir = TempDir::new().unwrap();
1804 let input_path = temp_dir.path().join("input.txt");
1805 let output_dir = temp_dir.path().join("encrypted");
1806 let protected_target_path = temp_dir.path().join("protected.txt");
1807 let decrypted_path = temp_dir.path().join("decrypted.txt");
1808 let test_data = b"symlink output regression data";
1809
1810 std::fs::write(&input_path, test_data).unwrap();
1811 std::fs::write(&protected_target_path, b"protected target").unwrap();
1812 symlink(&protected_target_path, &decrypted_path).unwrap();
1813
1814 let mut engine = EncryptionEngine::new(1024).unwrap();
1815 engine.add_password_slot("password").unwrap();
1816 let config = engine
1817 .encrypt_file(&input_path, &output_dir, |_, _| {})
1818 .unwrap();
1819
1820 let decryptor = DecryptionEngine::unlock_with_password(config, "password").unwrap();
1821 decryptor
1822 .decrypt_to_file(&output_dir, &decrypted_path, |_, _| {})
1823 .unwrap();
1824
1825 assert_file_bytes(&protected_target_path, b"protected target");
1826 let metadata = std::fs::symlink_metadata(&decrypted_path).unwrap();
1827 assert!(
1828 !metadata.file_type().is_symlink(),
1829 "successful decrypt should replace the output symlink itself"
1830 );
1831 assert_file_bytes(&decrypted_path, test_data);
1832 }
1833
1834 #[test]
1835 #[cfg(unix)]
1836 fn decrypt_to_file_replacement_keeps_plaintext_output_private() {
1837 use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
1838
1839 let temp_dir = TempDir::new().unwrap();
1840 let input_path = temp_dir.path().join("input.txt");
1841 let output_dir = temp_dir.path().join("encrypted");
1842 let decrypted_path = temp_dir.path().join("decrypted.txt");
1843 let test_data = b"private replacement mode regression data";
1844
1845 std::fs::write(&input_path, test_data).unwrap();
1846 let mut existing = OpenOptions::new()
1847 .write(true)
1848 .create_new(true)
1849 .mode(0o600)
1850 .open(&decrypted_path)
1851 .unwrap();
1852 existing.write_all(b"old private plaintext").unwrap();
1853 existing.sync_all().unwrap();
1854 drop(existing);
1855
1856 let mut engine = EncryptionEngine::new(1024).unwrap();
1857 engine.add_password_slot("password").unwrap();
1858 let config = engine
1859 .encrypt_file(&input_path, &output_dir, |_, _| {})
1860 .unwrap();
1861
1862 let decryptor = DecryptionEngine::unlock_with_password(config, "password").unwrap();
1863 decryptor
1864 .decrypt_to_file(&output_dir, &decrypted_path, |_, _| {})
1865 .unwrap();
1866
1867 assert_file_bytes(&decrypted_path, test_data);
1868 let mode = std::fs::metadata(&decrypted_path)
1869 .unwrap()
1870 .permissions()
1871 .mode()
1872 & 0o777;
1873 assert_eq!(
1874 mode, 0o600,
1875 "decrypted plaintext output should not gain group/other permissions"
1876 );
1877 }
1878
1879 #[test]
1880 fn test_encryption_engine_rejects_zero_chunk_size() {
1881 let err = EncryptionEngine::new(0).unwrap_err();
1882 assert!(err.to_string().contains("chunk_size"));
1883 }
1884
1885 #[test]
1886 fn test_encryption_engine_rejects_oversized_chunk_size() {
1887 let err = EncryptionEngine::new(MAX_CHUNK_SIZE + 1).unwrap_err();
1888 assert!(err.to_string().contains("chunk_size"));
1889 }
1890
1891 #[cfg(not(windows))]
1914 #[test]
1915 fn sync_tree_includes_parent_directory_fsync() {
1916 use std::fs;
1917 let tmp = tempfile::TempDir::new().expect("tempdir");
1918 let archive_dir = tmp.path().join("archive");
1919 fs::create_dir_all(&archive_dir).expect("create archive dir");
1920 fs::write(archive_dir.join("index.html"), b"<html></html>").unwrap();
1921 fs::write(archive_dir.join("chunk-0.bin"), [0u8; 16]).unwrap();
1922 let nested = archive_dir.join("assets");
1923 fs::create_dir_all(&nested).expect("create nested");
1924 fs::write(nested.join("style.css"), b"body{}").unwrap();
1925
1926 sync_tree(&archive_dir).expect("happy-path sync_tree must succeed");
1931
1932 let doomed_parent = tmp.path().join("doomed-parent");
1951 fs::create_dir_all(&doomed_parent).expect("create doomed parent");
1952 fs::write(doomed_parent.join("payload"), b"payload").unwrap();
1953 fs::remove_dir_all(&doomed_parent).expect("remove doomed parent");
1954 let err = sync_tree(&doomed_parent).expect_err(
1957 "sync_tree on a vanished directory must surface an I/O error; \
1958 silent Ok(()) would mean the fsync stack is a stub",
1959 );
1960 let err_str = err.to_string();
1961 assert!(
1962 err_str.contains("No such")
1963 || err_str.contains("not found")
1964 || err_str.contains("vanished")
1965 || err_str.contains("doomed"),
1966 "sync_tree error must reference the missing path or NotFound: got {err_str}"
1967 );
1968 }
1969
1970 #[test]
1989 fn unwrap_key_chains_aead_source_error_into_diagnostic_message() {
1990 let kek = SecretKey::from_bytes([0u8; 32]);
1991 let dek = [0u8; 32];
1992 let export_id = [42u8; 16];
1993 let slot_id = 7u8;
1994
1995 let (mut wrapped, nonce) = wrap_key(&kek, &dek, &export_id, slot_id).expect("wrap_key");
1997
1998 let last = wrapped.len() - 1;
2003 wrapped[last] ^= 0x55;
2004
2005 let err = unwrap_key(&kek, &wrapped, &nonce, &export_id, slot_id)
2006 .expect_err("tampered ciphertext must fail unwrap");
2007 let rendered = err.to_string();
2008
2009 assert!(
2011 rendered.contains(&format!("slot {slot_id}")),
2012 "unwrap error must name the slot id; got: {rendered}"
2013 );
2014 assert!(
2016 rendered.contains(&format!("{} bytes wrapped", wrapped.len())),
2017 "unwrap error must include the wrapped-ciphertext length; got: {rendered}"
2018 );
2019 assert!(
2020 rendered.contains("12 bytes nonce"),
2021 "unwrap error must include the AES-GCM nonce length; got: {rendered}"
2022 );
2023 assert!(
2030 rendered.contains(": "),
2031 "unwrap error must include `: <source>` separator so the \
2032 aead source error survives in the chain; got: {rendered}"
2033 );
2034 let chain: Vec<String> = err.chain().map(ToString::to_string).collect();
2035 assert!(
2036 chain.len() >= 2,
2037 "unwrap error must preserve the aead source as an anyhow chain frame; \
2038 got chain: {chain:?}"
2039 );
2040 assert!(
2041 chain.iter().skip(1).any(|frame| !frame.is_empty()),
2042 "unwrap error source frame must be non-empty for debug inspection; \
2043 got chain: {chain:?}"
2044 );
2045 assert!(
2049 rendered.contains("Key unwrapping failed"),
2050 "unwrap error must keep the human-facing prefix for runbook \
2051 grep compatibility; got: {rendered}"
2052 );
2053 }
2054
2055 #[test]
2064 fn derive_kek_hkdf_error_message_pins_actual_kek_length() {
2065 let actual_kek = crate::encryption::hkdf_extract_expand(
2071 b"recovery-secret",
2072 b"salty-salty-salty-salt",
2073 b"cass-pages-kek-v2",
2074 16, )
2076 .expect("hkdf with 16-byte output must succeed");
2077 let actual_len = actual_kek.len();
2078 assert_eq!(actual_len, 16);
2079
2080 let conversion: Result<[u8; 32], Vec<u8>> = actual_kek.try_into();
2082 let raw_err = conversion.expect_err("16 != 32 must fail try_into");
2083 assert_eq!(raw_err.len(), 16);
2084
2085 let rendered = format!(
2091 "HKDF expansion produced invalid KEK length: expected 32, got {}",
2092 raw_err.len()
2093 );
2094 assert!(rendered.contains("expected 32"));
2095 assert!(rendered.contains("got 16"));
2096 }
2097}