onionwire/tests/file.rs
agent 30f438c394
All checks were successful
ci / test (pull_request) Successful in 21m34s
ci / sdk (pull_request) Successful in 2m17s
fil: pad chunk bodies to a length ladder, document the residual
Each `fil ` chunk carried its raw bytes in a one-shot Noise session, so the
frame length was the exact chunk size: the tail chunk of every file told an
observer the file's size, and the chunk count told them the rest.

Pad the chunk body with the chat encoding (uint16 pad_len || data || random
fill) on a `fil ` ladder that continues past chat's 32 KiB ceiling —
512..49152 — because a chunk is bounded by the frame budget (~64 KiB of
plaintext), not by a line of human text. The top rung is a half-step: 65536
cannot fit one Noise body, and 48 KiB leaves the worst-case header (128-byte
name, 5-digit counters) more than 16 KiB of slack.

The raw chunk cap becomes the top rung's body (49150 bytes), so a 1 MiB file
is 22 one-shot sessions instead of 17. `pad_len` is authenticated by the
session's ChaCha20-Poly1305 tag; `decode_checked` treats an overrunning
`pad_len` as a protocol error and drops the chunk whole rather than writing a
truncated one. `total_chunks`/`data_cap` stay the reassembly authority and the
hash check is untouched.

PROTOCOL.md gains the ladder in “Length buckets” and the padded `fil ` frame
layout, and states the honest residual: padding hides per-chunk size only —
the chunk count still reveals total size in buckets, and timing, circuit
patterns and retry cadence remain visible. No persistent session, no channel
binding, no ratcheting of chunks.
2026-10-22 22:46:28 -04:00

311 lines
10 KiB
Rust

//! 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::padding;
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]).expect("encode");
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 every_fil_frame_lands_on_the_fil_ladder() {
for size in [0usize, 1, 510, 511, 49_150, 49_151, 80_000, MAX_BYTES] {
let body = vec![0x5au8; size];
let chunks = file::chunks("bucket.bin", &body).unwrap();
assert!(!chunks.is_empty(), "a {size}-byte file must have chunks");
for c in &chunks {
let encoded = file::encode(c).expect("encode");
let bucket = padding::fil_bucket_for(c.data.len()).expect("must fit the ladder");
assert_eq!(
encoded.len(),
file::overhead(c) + bucket,
"chunk {} of a {size}-byte file is not a ladder value",
c.idx
);
assert!(
padding::FIL_BUCKETS.contains(&(encoded.len() - file::overhead(c))),
"chunk {} of a {size}-byte file is not on the ladder",
c.idx
);
let decoded = file::decode_checked(&encoded)
.expect("decode")
.expect("still a fil frame");
assert_eq!(decoded.data, c.data);
}
}
}
#[test]
fn a_one_byte_file_and_a_bucket_sized_file_send_identical_frame_lengths() {
// Both fit the smallest fil bucket, so the tail chunk no longer reveals
// whether the file was 1 byte or 510.
let tiny = file::chunks("same.bin", b"x").unwrap();
let fullest = file::chunks("same.bin", &vec![0u8; 510]).unwrap();
assert_eq!(tiny.len(), 1);
assert_eq!(fullest.len(), 1);
let a = file::encode(&tiny[0]).expect("encode");
let b = file::encode(&fullest[0]).expect("encode");
assert_eq!(a.len(), file::overhead(&tiny[0]) + 512);
assert_eq!(
a.len(),
b.len(),
"frame length must not reveal the file size"
);
}
#[test]
fn an_oversized_pad_len_is_a_clean_protocol_error_not_a_truncation() {
let chunks = file::chunks("pad.bin", b"hello").unwrap();
let mut pt = file::encode(&chunks[0]).expect("encode");
let at = file::overhead(&chunks[0]);
pt[at..at + 2].copy_from_slice(&u16::MAX.to_be_bytes());
let err = file::decode_checked(&pt).expect_err("must fail closed");
assert!(err.to_string().contains("overrun"), "{err}");
assert_eq!(file::decode(&pt), None, "no partial chunk may surface");
}
#[test]
fn a_malformed_fil_frame_is_an_error_while_chat_is_not_a_fil_frame() {
assert_eq!(
file::decode_checked(b"hello wire").expect("not a fil frame"),
None
);
assert!(file::decode_checked(b"fil ").is_err(), "short headers fail");
let chunks = file::chunks("x.bin", b"x").unwrap();
let mut bare = file::encode(&chunks[0]).expect("encode");
bare.truncate(file::overhead(&chunks[0]) + 1);
assert!(
file::decode_checked(&bare).is_err(),
"a missing pad_len header is not an empty body"
);
}
#[test]
fn a_padded_multi_chunk_transfer_round_trips_with_an_equal_hash() {
let dir = tempfile::tempdir().unwrap();
let body: Vec<u8> = (0..120_000u32).map(|i| (i % 251) as u8).collect();
let chunks = file::chunks("payload.bin", &body).unwrap();
assert_eq!(chunks.len(), 3, "120000 bytes over 49150-byte chunks");
let mut inbox = file::Inbox::new(dir.path());
let mut done = None;
let mut reassembled = Vec::new();
for c in &chunks {
let wire = file::encode(c).expect("encode");
let got = file::decode_checked(&wire)
.expect("decode")
.expect("fil frame");
assert_eq!(got.data, c.data, "padding must not leak into the data");
assert_eq!(got.data.len(), c.data.len(), "no trailing fill");
reassembled.extend_from_slice(&got.data);
done = inbox.ingest("aabbccdd", &got).unwrap();
}
assert_eq!(reassembled, body);
let path = done.expect("assembled path");
assert_eq!(std::fs::read(&path).unwrap(), body);
}
#[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_twenty_two_chunks_fit_default_bucket_when_paced() {
let body = vec![0u8; MAX_BYTES];
let chunks = file::chunks("file.bin", &body).unwrap();
// The chunk cap is the top `fil ` bucket body (49150), so padding costs
// five more one-shot sessions than the old raw 64 KiB cap (17).
assert_eq!(
chunks.len(),
22,
"1 MiB with an 8-char name must be 22 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, 12,
"the bug: 22 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");
}