Merge pull request 'fil: pad chunk bodies to a length ladder, document the residual' (#196) from onionwire/t_7a5e3d1d-pad-fil-chunks-to-length-buckets-and-doc into onionwire/t_438331aa-close-the-legacy-signature-surface-and-d
Reviewed-on: #196
This commit is contained in:
commit
37545410f9
6 changed files with 383 additions and 54 deletions
|
|
@ -96,17 +96,19 @@ uint8 body[length]
|
|||
- Other `version` values are a hard fail (close the stream).
|
||||
- Length that does not match the bytes on the wire is a hard fail.
|
||||
|
||||
`length` still reveals the exact ciphertext size. Chat hides it by padding the
|
||||
plaintext to a bucket before encryption (see [Length buckets](#length-buckets)).
|
||||
Other frame types are not padded.
|
||||
`length` still reveals the exact ciphertext size. Chat and `fil ` chunk bodies
|
||||
hide it by padding the plaintext to a bucket before encryption (see
|
||||
[Length buckets](#length-buckets)). Other frame types are not padded.
|
||||
|
||||
## Length buckets
|
||||
|
||||
Normative for chat. A chat line is padded to one fixed ladder **before** the
|
||||
ratchet encrypts it, so the padding is inside ChaCha20-Poly1305, inside the
|
||||
Noise session, and authenticated by both. An observer sees a ciphertext whose
|
||||
length is one of the ladder values (plus constant overhead), never the body
|
||||
length.
|
||||
Normative for chat lines and `fil ` chunk bodies. A chat line is padded to one
|
||||
fixed ladder **before** the ratchet encrypts it, so the padding is inside
|
||||
ChaCha20-Poly1305, inside the Noise session, and authenticated by both. A `fil `
|
||||
chunk body is padded with the same encoding on a longer ladder before its
|
||||
one-shot Noise session encrypts it, so its padding is authenticated by that
|
||||
session's tag. An observer sees a ciphertext whose length is one of the ladder
|
||||
values (plus constant overhead), never the body length.
|
||||
|
||||
Ladder — padded-plaintext sizes in bytes:
|
||||
|
||||
|
|
@ -179,10 +181,36 @@ first hybrid ratchet step (`kem_pub[1184] || kem_ct[1088]`). Epoch 0 of a chat
|
|||
is always classical, so the first `rat ` frame of a friend relationship uses
|
||||
the 40-byte header.
|
||||
|
||||
`fil ` chunks are deliberately **not** padded. They are raw file bytes paced
|
||||
through the accept token bucket, and padding them would either cut the usable
|
||||
chunk size or spend the 65535 frame cap on fill; the chunk size stays as
|
||||
specified under `fil ` — file chunk.
|
||||
### `fil ` chunk bodies
|
||||
|
||||
A `fil ` chunk body — everything after the last newline of the frame, see
|
||||
`fil ` — file chunk below — is padded with the chat encoding above and a longer
|
||||
ladder:
|
||||
|
||||
```
|
||||
512, 1024, 2048, 4096, 8192, 16384, 32768, 49152
|
||||
```
|
||||
|
||||
- The rungs up to 32768 are the chat ladder's. The chat floor of 256 is not
|
||||
used: every `fil ` frame already carries ~115 bytes of ASCII header, so a
|
||||
256-byte rung would round almost every chunk up for no gain.
|
||||
- 49152 (48 KiB) is the top rung. The doubled 65536 cannot fit one Noise body
|
||||
(a plaintext is at most 65519 bytes, tag included), and 48 KiB leaves the
|
||||
worst-case `fil ` header — 128-byte name, 5-digit `idx` and `total`, 243
|
||||
bytes — more than 16 KiB of slack.
|
||||
- The raw chunk cap is the top rung's body, 49150 bytes. A chunk therefore
|
||||
never needs more than one rung and `pad_len` always fits a `uint16`. A chunk
|
||||
body larger than 49150 bytes is a protocol error and MUST fail closed.
|
||||
- The receiver rules above are unchanged: `pad_len` is the only authority for
|
||||
the chunk body's length, an overrun is a hard failure and the chunk is
|
||||
dropped whole, and the total padded length is not required to be a ladder
|
||||
value.
|
||||
|
||||
This hides the chunk body length only. The *number* of `fil ` chunks still
|
||||
reveals the file's size in buckets (a 1 MiB file is 22 chunks), and transfer is
|
||||
still one Noise session per chunk, so timing, circuit patterns and retry
|
||||
cadence remain visible exactly as they are for chat. Padding adds no persistent
|
||||
session, no channel binding and no ratchet between chunks.
|
||||
|
||||
This hides length, not timing: one Noise session per message, retry cadence and
|
||||
circuit timing are unchanged and remain accepted costs (see
|
||||
|
|
@ -495,15 +523,27 @@ fails the transfer. No outbox, no resume, no continuation under a new
|
|||
`xfer_id`.
|
||||
|
||||
```
|
||||
fil <xfer_id_hex>\n<filename>\n<sha256_hex>\n<idx>/<total>\n<raw bytes>
|
||||
fil <xfer_id_hex>\n<filename>\n<sha256_hex>\n<idx>/<total>\n<padded chunk body>
|
||||
```
|
||||
|
||||
- `xfer_id` — 16 random bytes (32 hex)
|
||||
- `filename` — 1–128 bytes, no `/`, NUL, newline, `.`, or `..`; no C0/C1 controls or bidi/format marks (U+202A–U+202E, U+2066–U+2069, U+200E, U+200F, U+200B, U+200C)
|
||||
- `sha256` — SHA-256 of the **entire** file (64 hex), repeated on every chunk
|
||||
- `idx` is 0-based; `total` ≥ 1; `idx < total`
|
||||
- last line is raw chunk bytes (not hex), length chosen so the framed Noise
|
||||
ciphertext stays ≤ 65535 (account for a 16-byte Poly1305 tag plus ASCII header)
|
||||
- last line is the chunk body padded to a `fil ` length bucket (see
|
||||
[Length buckets](#length-buckets)): `uint16 pad_len` big-endian, the raw
|
||||
chunk bytes, then `pad_len` random fill bytes. The padded body MUST be
|
||||
exactly the smallest `fil ` ladder value that is at least `2 + data_len`,
|
||||
and `pad_len = bucket - 2 - data_len`.
|
||||
- The raw chunk is at most **49150** bytes (the top rung's body). The ASCII
|
||||
header, the padded body and the 16-byte Poly1305 tag together stay under the
|
||||
65535 frame cap.
|
||||
- The padding is inside the one-shot Noise session, so `pad_len` is
|
||||
authenticated by that session's ChaCha20-Poly1305 tag — a tampered length
|
||||
fails the session rather than a checksum and the chunk is never written.
|
||||
`pad_len` is the only authority for the boundary: a receiver MUST NOT trim
|
||||
trailing fill, and MUST reject a `pad_len` that overruns the body as a
|
||||
protocol error, dropping the whole chunk instead of writing a truncated one.
|
||||
|
||||
Chunks MUST arrive in order for a given `xfer_id`. A bad chunk or hash
|
||||
mismatch deletes the partial. Empty files are one chunk. Successful receive
|
||||
|
|
|
|||
100
src/file.rs
100
src/file.rs
|
|
@ -12,6 +12,7 @@ use rand::RngCore;
|
|||
use sha2::{Digest, Sha256};
|
||||
|
||||
use crate::frame;
|
||||
use crate::padding;
|
||||
use crate::sanitize;
|
||||
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
|
@ -141,8 +142,32 @@ pub fn chunks(filename: &str, bytes: &[u8]) -> Result<Vec<Chunk>> {
|
|||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn encode(chunk: &Chunk) -> Vec<u8> {
|
||||
let mut out = Vec::from(PREFIX);
|
||||
/// Bytes of a `fil ` plaintext before the padded chunk body: prefix, the four
|
||||
/// newline-terminated metadata fields and the final newline. The body that
|
||||
/// follows is `uint16 pad_len || data || random fill`, sized to one
|
||||
/// [`padding::FIL_BUCKETS`] rung, so
|
||||
/// `encode(chunk).len() == overhead(chunk) + fil_bucket_for(data.len())`.
|
||||
pub fn overhead(chunk: &Chunk) -> usize {
|
||||
PREFIX.len()
|
||||
+ XFER_LEN * 2
|
||||
+ 1
|
||||
+ chunk.filename.len()
|
||||
+ 1
|
||||
+ 64
|
||||
+ 1
|
||||
+ chunk.idx.to_string().len()
|
||||
+ 1
|
||||
+ chunk.total.to_string().len()
|
||||
+ 1
|
||||
}
|
||||
|
||||
/// `fil ` plaintext with the chunk body padded to a length bucket. The padding
|
||||
/// sits after the last newline, inside the Noise session, so its `pad_len` is
|
||||
/// authenticated by the same ChaCha20-Poly1305 tag as the chunk itself.
|
||||
pub fn encode(chunk: &Chunk) -> Result<Vec<u8>> {
|
||||
let body = padding::encode_fil(&chunk.data).map_err(Error)?;
|
||||
let mut out = Vec::with_capacity(overhead(chunk) + body.len());
|
||||
out.extend_from_slice(PREFIX);
|
||||
out.extend_from_slice(to_hex(&chunk.xfer_id).as_bytes());
|
||||
out.push(b'\n');
|
||||
out.extend_from_slice(chunk.filename.as_bytes());
|
||||
|
|
@ -153,35 +178,63 @@ pub fn encode(chunk: &Chunk) -> Vec<u8> {
|
|||
out.push(b'/');
|
||||
out.extend_from_slice(chunk.total.to_string().as_bytes());
|
||||
out.push(b'\n');
|
||||
out.extend_from_slice(&chunk.data);
|
||||
out
|
||||
out.extend_from_slice(&body);
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
pub fn decode(pt: &[u8]) -> Option<Chunk> {
|
||||
let rest = pt.strip_prefix(PREFIX)?;
|
||||
/// Decode one `fil ` plaintext. `Ok(None)` means the bytes are not a `fil `
|
||||
/// frame at all; `Err` means a `fil ` frame that is malformed or whose
|
||||
/// `pad_len` does not describe a body, which the caller must drop rather than
|
||||
/// truncate. `pad_len` is the only authority for the body boundary.
|
||||
pub fn decode_checked(pt: &[u8]) -> Result<Option<Chunk>> {
|
||||
let Some(rest) = pt.strip_prefix(PREFIX) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut parts = rest.splitn(5, |&b| b == b'\n');
|
||||
let xfer_hex = std::str::from_utf8(parts.next()?).ok()?;
|
||||
let filename = std::str::from_utf8(parts.next()?).ok()?;
|
||||
let sha_hex = std::str::from_utf8(parts.next()?).ok()?;
|
||||
let idx_total = std::str::from_utf8(parts.next()?).ok()?;
|
||||
let data = parts.next()?.to_vec();
|
||||
safe_name(filename).ok()?;
|
||||
let xfer_id: [u8; XFER_LEN] = from_hex(xfer_hex)?.try_into().ok()?;
|
||||
let sha256: [u8; 32] = from_hex(sha_hex)?.try_into().ok()?;
|
||||
let (idx_s, total_s) = idx_total.split_once('/')?;
|
||||
let idx: u32 = idx_s.parse().ok()?;
|
||||
let total: u32 = total_s.parse().ok()?;
|
||||
let (Some(xfer_hex), Some(filename), Some(sha_hex), Some(idx_total), Some(body)) = (
|
||||
parts.next(),
|
||||
parts.next(),
|
||||
parts.next(),
|
||||
parts.next(),
|
||||
parts.next(),
|
||||
) else {
|
||||
return Err(Error("short fil frame".into()));
|
||||
};
|
||||
let bad = || Error("bad fil frame".into());
|
||||
let xfer_hex = std::str::from_utf8(xfer_hex).map_err(|_| bad())?;
|
||||
let filename = std::str::from_utf8(filename).map_err(|_| bad())?;
|
||||
let sha_hex = std::str::from_utf8(sha_hex).map_err(|_| bad())?;
|
||||
let idx_total = std::str::from_utf8(idx_total).map_err(|_| bad())?;
|
||||
safe_name(filename)?;
|
||||
let xfer_id: [u8; XFER_LEN] = from_hex(xfer_hex)
|
||||
.ok_or_else(bad)?
|
||||
.try_into()
|
||||
.map_err(|_| bad())?;
|
||||
let sha256: [u8; 32] = from_hex(sha_hex)
|
||||
.ok_or_else(bad)?
|
||||
.try_into()
|
||||
.map_err(|_| bad())?;
|
||||
let (idx_s, total_s) = idx_total.split_once('/').ok_or_else(bad)?;
|
||||
let idx: u32 = idx_s.parse().map_err(|_| bad())?;
|
||||
let total: u32 = total_s.parse().map_err(|_| bad())?;
|
||||
if total == 0 || idx >= total {
|
||||
return None;
|
||||
return Err(Error("bad chunk index".into()));
|
||||
}
|
||||
Some(Chunk {
|
||||
let data = padding::decode(body).map_err(Error)?;
|
||||
Ok(Some(Chunk {
|
||||
xfer_id,
|
||||
filename: filename.to_string(),
|
||||
sha256,
|
||||
idx,
|
||||
total,
|
||||
data,
|
||||
})
|
||||
data: data.to_vec(),
|
||||
}))
|
||||
}
|
||||
|
||||
/// `Option` shape for callers that only care whether a chunk parsed. Use
|
||||
/// [`decode_checked`] when the failure reason matters.
|
||||
pub fn decode(pt: &[u8]) -> Option<Chunk> {
|
||||
decode_checked(pt).ok().flatten()
|
||||
}
|
||||
|
||||
pub fn chat_line(name: &str, nbytes: usize) -> String {
|
||||
|
|
@ -347,6 +400,9 @@ fn total_chunks(filename: &str, len: usize) -> Result<u32> {
|
|||
}
|
||||
}
|
||||
|
||||
/// Raw chunk bytes that fit one frame once the body is padded: the frame budget
|
||||
/// (`MAX_FRAME` minus the Noise tag, the ASCII header and the 2-byte `pad_len`)
|
||||
/// and never more than the largest `fil ` bucket body.
|
||||
fn data_cap(filename: &str, total: u32) -> usize {
|
||||
let digits = total.to_string().len().max(1);
|
||||
let header =
|
||||
|
|
@ -354,6 +410,8 @@ fn data_cap(filename: &str, total: u32) -> usize {
|
|||
frame::MAX_FRAME
|
||||
.saturating_sub(NOISE_TAG)
|
||||
.saturating_sub(header)
|
||||
.saturating_sub(padding::PAD_HEADER_LEN)
|
||||
.min(padding::FIL_MAX_BODY)
|
||||
}
|
||||
|
||||
fn write_partial(path: &Path, data: &[u8], append: bool) -> Result<()> {
|
||||
|
|
|
|||
21
src/node.rs
21
src/node.rs
|
|
@ -1875,7 +1875,15 @@ impl Node {
|
|||
pub async fn send_file(&self, friend_pk: &[u8], path: &Path) -> Result<String, String> {
|
||||
let (name, bytes) = file::read_limited(path).map_err(|e| e.to_string())?;
|
||||
let chunks = file::chunks(&name, &bytes).map_err(|e| e.to_string())?;
|
||||
let frames: Vec<Vec<u8>> = chunks.iter().map(file::encode).collect();
|
||||
// Each chunk body is padded to the `fil ` length ladder before the
|
||||
// one-shot Noise session encrypts it, so the frame length reveals only
|
||||
// a bucket. A chunk is capped at the largest bucket body, so `encode`
|
||||
// cannot fail here.
|
||||
let frames: Vec<Vec<u8>> = chunks
|
||||
.iter()
|
||||
.map(file::encode)
|
||||
.collect::<std::result::Result<_, _>>()
|
||||
.map_err(|e| e.to_string())?;
|
||||
file::send_chunks(frames.len(), |i| self.send_once(friend_pk, &frames[i])).await?;
|
||||
self.store
|
||||
.lock()
|
||||
|
|
@ -2058,8 +2066,17 @@ impl Node {
|
|||
}
|
||||
|
||||
fn ingest_file(&self, peer: &[u8], pt: &[u8]) -> Result<(), String> {
|
||||
let Some(chunk) = file::decode(pt) else {
|
||||
// A `fil ` plaintext carries its chunk body padded to a length bucket;
|
||||
// `decode_checked` strips the fill and treats an overrunning `pad_len`
|
||||
// as a protocol error rather than writing a truncated chunk. Bytes that
|
||||
// are not a `fil ` frame are simply not ours.
|
||||
let chunk = match file::decode_checked(pt) {
|
||||
Ok(Some(chunk)) => chunk,
|
||||
Ok(None) => return Ok(()),
|
||||
Err(e) => {
|
||||
eprintln!("fil dropped ({e})");
|
||||
return Ok(());
|
||||
}
|
||||
};
|
||||
let fp: String = peer.iter().map(|b| format!("{b:02x}")).collect();
|
||||
let done = {
|
||||
|
|
|
|||
|
|
@ -1,10 +1,13 @@
|
|||
//! Length buckets for chat plaintext. Normative spec: `docs/PROTOCOL.md`,
|
||||
//! “Length buckets”.
|
||||
//! Length buckets for chat and file-chunk plaintext. Normative spec:
|
||||
//! `docs/PROTOCOL.md`, “Length buckets”.
|
||||
//!
|
||||
//! Chat bodies are padded to one of eight sizes *before* the ratchet encrypts
|
||||
//! them, so the padding is authenticated by ChaCha20-Poly1305 and by the Noise
|
||||
//! session around it. An observer sees only the bucket. The encoding is
|
||||
//! explicit and never trimmed:
|
||||
//! session around it. `fil ` chunk bodies use the same encoding and a longer
|
||||
//! ladder ([`FIL_BUCKETS`]): a chunk is capped by the frame budget rather than
|
||||
//! by a line of human text, so chat's 32 KiB ceiling would double the number of
|
||||
//! one-shot sessions a file costs. An observer sees only the bucket. The
|
||||
//! encoding is explicit and never trimmed:
|
||||
//!
|
||||
//! ```text
|
||||
//! uint16 pad_len = big-endian length of the random fill that follows
|
||||
|
|
@ -29,19 +32,50 @@ pub const BUCKETS: [usize; 8] = [256, 512, 1024, 2048, 4096, 8192, 16384, 32768]
|
|||
/// The largest body that fits the largest bucket (`32768 - 2`).
|
||||
pub const MAX_BODY: usize = BUCKETS[BUCKETS.len() - 1] - PAD_HEADER_LEN;
|
||||
|
||||
/// The `fil ` chunk ladder. Same encoding and the same 2-byte header as chat;
|
||||
/// the rungs continue past chat's 32 KiB ceiling because a chunk body is
|
||||
/// bounded by the frame budget (one Noise plaintext is at most 65519 bytes),
|
||||
/// not by a line of human text. The top rung is a half-step: the next doubling
|
||||
/// (65536) cannot fit one Noise body, and 49152 leaves the worst-case `fil `
|
||||
/// header (128-byte name, 5-digit counters, ~243 bytes) 16 KiB of slack.
|
||||
pub const FIL_BUCKETS: [usize; 8] = [512, 1024, 2048, 4096, 8192, 16384, 32768, 49152];
|
||||
|
||||
/// The largest chunk body that fits the largest `fil ` bucket.
|
||||
pub const FIL_MAX_BODY: usize = FIL_BUCKETS[FIL_BUCKETS.len() - 1] - PAD_HEADER_LEN;
|
||||
|
||||
/// The ladder value a body of `body_len` bytes is padded to, or `None` when it
|
||||
/// does not fit the largest bucket.
|
||||
pub fn bucket_for(body_len: usize) -> Option<usize> {
|
||||
BUCKETS
|
||||
bucket_in(&BUCKETS, body_len)
|
||||
}
|
||||
|
||||
/// The `fil ` ladder value a chunk body of `body_len` bytes is padded to, or
|
||||
/// `None` when it does not fit [`FIL_MAX_BODY`].
|
||||
pub fn fil_bucket_for(body_len: usize) -> Option<usize> {
|
||||
bucket_in(&FIL_BUCKETS, body_len)
|
||||
}
|
||||
|
||||
fn bucket_in(ladder: &[usize], body_len: usize) -> Option<usize> {
|
||||
ladder
|
||||
.iter()
|
||||
.copied()
|
||||
.find(|bucket| bucket - PAD_HEADER_LEN >= body_len)
|
||||
}
|
||||
|
||||
/// `uint16 pad_len || body || random fill`, sized to one ladder value.
|
||||
/// `uint16 pad_len || body || random fill`, sized to one chat ladder value.
|
||||
pub fn encode(body: &[u8]) -> Result<Vec<u8>, String> {
|
||||
let bucket = bucket_for(body.len()).ok_or_else(|| {
|
||||
format!("chat message too large for the largest length bucket ({MAX_BODY} bytes)")
|
||||
encode_in(body, &BUCKETS, "chat message")
|
||||
}
|
||||
|
||||
/// `uint16 pad_len || body || random fill`, sized to one [`FIL_BUCKETS`] value.
|
||||
pub fn encode_fil(body: &[u8]) -> Result<Vec<u8>, String> {
|
||||
encode_in(body, &FIL_BUCKETS, "file chunk")
|
||||
}
|
||||
|
||||
fn encode_in(body: &[u8], ladder: &[usize], what: &str) -> Result<Vec<u8>, String> {
|
||||
let bucket = bucket_in(ladder, body.len()).ok_or_else(|| {
|
||||
let max = ladder[ladder.len() - 1] - PAD_HEADER_LEN;
|
||||
format!("{what} too large for the largest length bucket ({max} bytes)")
|
||||
})?;
|
||||
let pad_len = bucket - PAD_HEADER_LEN - body.len();
|
||||
let mut out = Vec::with_capacity(bucket);
|
||||
|
|
|
|||
112
tests/file.rs
112
tests/file.rs
|
|
@ -4,6 +4,7 @@ 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};
|
||||
|
||||
|
|
@ -12,7 +13,7 @@ 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 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);
|
||||
|
|
@ -22,6 +23,103 @@ fn encode_decode_roundtrip_one_chunk() {
|
|||
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);
|
||||
|
|
@ -145,13 +243,15 @@ fn dispatch_fil_is_file_not_chat() {
|
|||
}
|
||||
|
||||
#[test]
|
||||
fn one_mib_seventeen_chunks_fit_default_bucket_when_paced() {
|
||||
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(),
|
||||
17,
|
||||
"1 MiB with an 8-char name must be 17 one-shot sessions"
|
||||
22,
|
||||
"1 MiB with an 8-char name must be 22 one-shot sessions"
|
||||
);
|
||||
|
||||
let t0 = Instant::now();
|
||||
|
|
@ -160,8 +260,8 @@ fn one_mib_seventeen_chunks_fit_default_bucket_when_paced() {
|
|||
.filter(|_| !unpaced.try_acquire_at(t0))
|
||||
.count();
|
||||
assert_eq!(
|
||||
dropped, 7,
|
||||
"the bug: 17 back-to-back accepts blow the burst of 10"
|
||||
dropped, 12,
|
||||
"the bug: 22 back-to-back accepts blow the burst of 10"
|
||||
);
|
||||
|
||||
let mut paced = TokenBucket::default();
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@
|
|||
//! bucketed size, a tampered field failing closed) lives in `src/node.rs`'s
|
||||
//! unit tests, because `tests/*.rs` cannot build a `Node`.
|
||||
|
||||
use onionwire::padding::{self, BUCKETS, MAX_BODY, PAD_HEADER_LEN};
|
||||
use onionwire::padding::{self, BUCKETS, FIL_BUCKETS, FIL_MAX_BODY, MAX_BODY, PAD_HEADER_LEN};
|
||||
use onionwire::ratchet::{
|
||||
FRAME_VERSION, FRAME_VERSION_HYBRID, HEADER_LEN, HEADER_LEN_HYBRID, RatchetKeyPair,
|
||||
RatchetState,
|
||||
|
|
@ -221,6 +221,86 @@ fn a_classical_frame_keeps_the_329_byte_floor() {
|
|||
assert_eq!(frame.len() + 16 + 5, 350, "classical frame on the wire");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fil_ladder_continues_past_the_chat_ceiling_and_fits_one_noise_body() {
|
||||
// `fil ` chunk bodies are bounded by the frame budget (~64 KiB plaintext),
|
||||
// not by a line of human text, so the ladder cannot stop at chat's 32 KiB:
|
||||
// that would double the chunk count of a 1 MiB file and spend twice the
|
||||
// one-shot sessions. The top rung is a half-step because the next doubling
|
||||
// (65536) does not fit one Noise body.
|
||||
assert_eq!(
|
||||
FIL_BUCKETS,
|
||||
[512, 1024, 2048, 4096, 8192, 16384, 32768, 49152]
|
||||
);
|
||||
assert_eq!(FIL_MAX_BODY, 49150);
|
||||
assert_eq!(
|
||||
FIL_BUCKETS[FIL_BUCKETS.len() - 1] - PAD_HEADER_LEN,
|
||||
FIL_MAX_BODY
|
||||
);
|
||||
// Strictly increasing rungs, same 2-byte header as chat.
|
||||
for w in FIL_BUCKETS.windows(2) {
|
||||
assert!(w[1] > w[0], "ladder must increase: {w:?}");
|
||||
}
|
||||
// Worst-case `fil ` header (128-byte name, 5-digit idx/total) plus the top
|
||||
// rung plus the Noise tag must still fit one frame body.
|
||||
let worst_header = 4 + 32 + 1 + 128 + 1 + 64 + 1 + 5 + 1 + 5 + 1;
|
||||
assert!(
|
||||
worst_header + FIL_BUCKETS[FIL_BUCKETS.len() - 1] + 16 <= onionwire::frame::MAX_FRAME,
|
||||
"the top rung must fit one Noise body"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fil_buckets_follow_the_body_plus_the_two_byte_header() {
|
||||
let cases = [
|
||||
(0, Some(512)),
|
||||
(1, Some(512)),
|
||||
(510, Some(512)),
|
||||
(511, Some(1024)),
|
||||
(1022, Some(1024)),
|
||||
(1023, Some(2048)),
|
||||
(32766, Some(32768)),
|
||||
(32767, Some(49152)),
|
||||
(49150, Some(49152)),
|
||||
(49151, None),
|
||||
];
|
||||
for (body_len, want) in cases {
|
||||
assert_eq!(
|
||||
padding::fil_bucket_for(body_len),
|
||||
want,
|
||||
"fil bucket for a {body_len}-byte body"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fil_chunk_body_round_trips_and_an_oversized_one_fails_closed() {
|
||||
for body in [&b""[..], &b"x"[..], &[0u8; 510][..], &[7u8; 49150][..]] {
|
||||
let padded = padding::encode_fil(body).expect("encode");
|
||||
let bucket = padding::fil_bucket_for(body.len()).expect("bucket");
|
||||
assert_eq!(padded.len(), bucket);
|
||||
assert_eq!(padding::decode(&padded).expect("decode"), body);
|
||||
}
|
||||
let err = padding::encode_fil(&vec![0u8; FIL_MAX_BODY + 1]).expect_err("must not fit");
|
||||
assert!(err.contains("too large"), "{err}");
|
||||
}
|
||||
|
||||
/// `fil ` bodies reuse the chat encoding verbatim: the same `uint16 pad_len`,
|
||||
/// the same "overrun is a hard failure" rule. The ladders differ, the bytes do
|
||||
/// not.
|
||||
#[test]
|
||||
fn fil_and_chat_share_the_same_encoding() {
|
||||
let padded = padding::encode_fil(b"hello").expect("encode");
|
||||
assert_eq!(padded.len(), 512);
|
||||
assert_eq!(padded[..2], [0x01, 0xf9], "pad_len = 512 - 2 - 5 = 505");
|
||||
assert_eq!(padding::decode(&padded).expect("decode"), b"hello");
|
||||
|
||||
let mut bad = Vec::new();
|
||||
bad.extend_from_slice(&15u16.to_be_bytes());
|
||||
bad.extend_from_slice(&[0u8; 14]);
|
||||
assert!(padding::decode(&bad).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_receiver_accepts_a_padded_plaintext_of_any_total_length() {
|
||||
// Interop: another implementation's ladder is not ours, and the receiver
|
||||
|
|
|
|||
Loading…
Reference in a new issue