//! M10: fail-closed file transfer — frames, names, assemble, slash parse. use std::time::Instant; use onionwire::dispatch::{Kind, classify}; use onionwire::file::{self, MAX_BYTES}; use onionwire::ratelimit::TokenBucket; use onionwire::tui::{SlashCmd, parse_cmd}; #[test] fn encode_decode_roundtrip_one_chunk() { let body = b"hello file"; let chunks = file::chunks("note.txt", body).unwrap(); assert_eq!(chunks.len(), 1); let encoded = file::encode(&chunks[0]); let decoded = file::decode(&encoded).expect("decode"); assert_eq!(decoded.filename, "note.txt"); assert_eq!(decoded.idx, 0); assert_eq!(decoded.total, 1); assert_eq!(decoded.data, body); assert_eq!(decoded.sha256, chunks[0].sha256); assert_eq!(decoded.xfer_id, chunks[0].xfer_id); } #[test] fn chat_is_not_file() { assert_eq!(file::decode(b"hello wire"), None); } #[test] fn name_with_dotdot_or_slash_rejected() { assert!(file::chunks("../secret", b"x").is_err()); assert!(file::chunks("a/b", b"x").is_err()); assert!(file::safe_name("..").is_err()); assert!(file::safe_name("foo/bar").is_err()); assert!(file::safe_name("a\0b").is_err()); assert!(file::safe_name("ok.txt").is_ok()); } #[test] fn name_with_bidi_or_controls_rejected() { assert!(file::safe_name("ok.txt").is_ok()); assert!(file::safe_name("safe.txt\u{202e}gpj.exe").is_err()); assert!(file::safe_name("a\u{1b}b.txt").is_err()); assert!(file::safe_name("a\u{009b}b.txt").is_err()); assert!(file::safe_name("a\tb.txt").is_err()); } #[test] fn oversize_rejected_before_send() { let too_big = vec![0u8; MAX_BYTES + 1]; assert!(file::chunks("big.bin", &too_big).is_err()); assert!(file::chunks("ok.bin", &vec![0u8; MAX_BYTES]).is_ok()); } #[test] fn assemble_two_chunks_writes_file_and_matches_hash() { let dir = tempfile::tempdir().unwrap(); let body = vec![7u8; 80_000]; let chunks = file::chunks("pic.bin", &body).unwrap(); assert!(chunks.len() >= 2, "expected split, got {}", chunks.len()); let mut inbox = file::Inbox::new(dir.path()); let fp = "aabbccddeeff"; let mut done = None; for c in &chunks { done = inbox.ingest(fp, c).unwrap(); } let path = done.expect("assembled path"); assert_eq!(std::fs::read(&path).unwrap(), body); assert!(path.ends_with("pic.bin")); assert!(path.to_string_lossy().contains(fp)); } #[test] fn bad_hash_leaves_no_inbox_file() { let dir = tempfile::tempdir().unwrap(); let chunks = file::chunks("evil.bin", b"payload").unwrap(); let mut bad = chunks[0].clone(); bad.sha256 = [0u8; 32]; let mut inbox = file::Inbox::new(dir.path()); let fp = "deadbeef"; assert!(inbox.ingest(fp, &bad).is_err()); let dest = dir.path().join(fp).join("evil.bin"); assert!(!dest.exists(), "hash mismatch must not write inbox file"); let partials: Vec<_> = std::fs::read_dir(dir.path()) .unwrap() .filter_map(|e| e.ok()) .filter(|e| e.file_name().to_string_lossy().starts_with(".partial-")) .collect(); assert!( partials.is_empty(), "partial must be deleted on hash mismatch" ); } #[test] fn ingest_rejects_oversize_and_deletes_partial() { let dir = tempfile::tempdir().unwrap(); let mut inbox = file::Inbox::new(dir.path()); let mut chunk = file::chunks("fat.bin", b"x").unwrap().remove(0); chunk.total = 2; chunk.idx = 0; chunk.data = vec![1u8; MAX_BYTES + 1]; assert!(inbox.ingest("aa", &chunk).is_err()); assert!(!dir.path().join("aa").join("fat.bin").exists()); let leftover: Vec<_> = std::fs::read_dir(dir.path()) .unwrap() .filter_map(|e| e.ok()) .filter(|e| e.file_name().to_string_lossy().starts_with(".partial-")) .collect(); assert!(leftover.is_empty()); } #[test] fn ingest_rejects_cumulative_oversize() { let dir = tempfile::tempdir().unwrap(); let mut inbox = file::Inbox::new(dir.path()); let mut a = file::chunks("fat.bin", b"x").unwrap().remove(0); a.total = 2; a.idx = 0; a.data = vec![1u8; MAX_BYTES - 10]; assert_eq!(inbox.ingest("aa", &a).unwrap(), None); let mut b = a.clone(); b.idx = 1; b.data = vec![1u8; 11]; assert!(inbox.ingest("aa", &b).is_err()); assert!(!dir.path().join("aa").join("fat.bin").exists()); } #[test] fn slash_file_parses_path_and_empty_is_none() { assert_eq!( parse_cmd("/file /tmp/a"), Some(SlashCmd::File { path: "/tmp/a".into() }) ); assert_eq!(parse_cmd("/file"), None); } #[test] fn dispatch_fil_is_file_not_chat() { assert_eq!(classify(b"fil abc"), Kind::File); assert_eq!(classify(b"hello wire"), Kind::Chat); } #[test] fn one_mib_seventeen_chunks_fit_default_bucket_when_paced() { let body = vec![0u8; MAX_BYTES]; let chunks = file::chunks("file.bin", &body).unwrap(); assert_eq!( chunks.len(), 17, "1 MiB with an 8-char name must be 17 one-shot sessions" ); let t0 = Instant::now(); let mut unpaced = TokenBucket::default(); let dropped = (0..chunks.len()) .filter(|_| !unpaced.try_acquire_at(t0)) .count(); assert_eq!( dropped, 7, "the bug: 17 back-to-back accepts blow the burst of 10" ); let mut paced = TokenBucket::default(); for i in 0..chunks.len() { let t = t0 + file::CHUNK_PACE * i as u32; assert!( paced.try_acquire_at(t), "chunk {i} dropped under CHUNK_PACE={:?}", file::CHUNK_PACE ); } } #[tokio::test] async fn transient_chunk_failure_is_retried_and_transfer_completes() { let mut attempts = 0u32; file::send_chunks(1, |_| { attempts += 1; let fail = attempts == 1; async move { if fail { Err("rate-limit drop") } else { Ok(()) } } }) .await .expect("one transient failure must not kill the transfer"); assert_eq!(attempts, 2, "second attempt must succeed"); } #[tokio::test] async fn exhausted_chunk_retries_return_err_and_skip_later_chunks() { let mut attempts = 0u32; let mut recorded = false; let err = file::send_chunks(2, |i| { attempts += 1; async move { Err(format!("fail chunk {i}")) } }) .await .expect_err("permanent failure must not look like success"); assert!(err.contains("fail chunk 0"), "{err}"); assert_eq!( attempts, file::CHUNK_ATTEMPTS, "must stop after the first chunk exhausts retries" ); if err.is_empty() { recorded = true; } assert!(!recorded, "caller must not record a success report"); }