[verified] fix(file): pace chunks to fit rendezvous rate limit
All checks were successful
ci / test (pull_request) Successful in 2m42s
All checks were successful
ci / test (pull_request) Successful in 2m42s
Sender-side only. First chunk attempt is immediate; later attempts (retries and later chunks) wait 3s. Three attempts per chunk, then fail closed. Token bucket 30/60s burst 10 is unchanged. A 1 MiB file is 17 one-shot sessions; pacing floor is 16*3s = 48s plus handshake time. Latency trade, not a security fix.
This commit is contained in:
parent
cb91ba2b78
commit
4bbc2de9ab
5 changed files with 122 additions and 4 deletions
|
|
@ -208,6 +208,14 @@ HTTP Digest; it is not this protocol.
|
|||
|
||||
Cap: 1 MiB reconstructed file. No resume. One Noise session per chunk.
|
||||
|
||||
The sender is responsible for fitting the receiver's documented rendezvous
|
||||
budget (30 accepts / 60s, burst 10). Chunks MUST be paced so the average
|
||||
interval between send attempts stays at least 3s — a margin under the 0.5/s
|
||||
refill; pacing at exactly 2s sits on the refill boundary and drains under
|
||||
jitter. A sender MAY retry an individual chunk a bounded number of times.
|
||||
Exhausting retries 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>
|
||||
```
|
||||
|
|
|
|||
|
|
@ -40,7 +40,7 @@ OnionWire never holds spend keys. Optional `ONIONWIRE_WALLET_RPC` talks HTTP Dig
|
|||
|
||||
## Rate limit is availability, not anonymity
|
||||
|
||||
Incoming rendezvous accepts are token-bucket limited (30/60s, burst 10). Excess is dropped without handshake. That is a DoS/availability control. It does not hide that you run an onion, and it is not a traffic-analysis defense.
|
||||
Incoming rendezvous accepts are token-bucket limited (30/60s, burst 10). Excess is dropped without handshake. That is a DoS/availability control. It does not hide that you run an onion, and it is not a traffic-analysis defense. The constants are unchanged. Clients absorb the cost: file senders pace and retry chunks to fit this budget. The accept loop does not distinguish a friend from a flood.
|
||||
|
||||
## Network (UDP / clearnet)
|
||||
|
||||
|
|
|
|||
40
src/file.rs
40
src/file.rs
|
|
@ -2,9 +2,11 @@
|
|||
|
||||
use std::collections::HashMap;
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::future::Future;
|
||||
use std::io::{Read, Write};
|
||||
use std::os::unix::fs::{OpenOptionsExt, PermissionsExt};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use rand::RngCore;
|
||||
use sha2::{Digest, Sha256};
|
||||
|
|
@ -31,6 +33,13 @@ impl From<std::io::Error> for Error {
|
|||
}
|
||||
|
||||
pub const MAX_BYTES: usize = 1024 * 1024;
|
||||
/// Minimum interval between chunk send *attempts*. First attempt of the first
|
||||
/// chunk fires immediately; every later attempt (retries and later chunks)
|
||||
/// waits this long. 3s is a margin under the receiver's 0.5/s rendezvous
|
||||
/// refill (30/60s, burst 10).
|
||||
pub const CHUNK_PACE: Duration = Duration::from_secs(3);
|
||||
/// Bounded attempts per chunk, counting the first try.
|
||||
pub const CHUNK_ATTEMPTS: u32 = 3;
|
||||
const PREFIX: &[u8] = b"fil ";
|
||||
const NOISE_TAG: usize = 16;
|
||||
const NAME_MAX: usize = 128;
|
||||
|
|
@ -177,6 +186,37 @@ pub fn chat_line(name: &str, nbytes: usize) -> String {
|
|||
format!("[file] {name} ({nbytes} bytes)")
|
||||
}
|
||||
|
||||
/// Pace and retry `n` one-shot chunk sends. `send(i)` is one attempt at chunk
|
||||
/// `i`. Fail closed: exhausting attempts on a chunk aborts the rest. No
|
||||
/// outbox, no resume.
|
||||
pub async fn send_chunks<E, F, Fut>(n: usize, mut send: F) -> std::result::Result<(), E>
|
||||
where
|
||||
F: FnMut(usize) -> Fut,
|
||||
Fut: Future<Output = std::result::Result<(), E>>,
|
||||
{
|
||||
let mut first = true;
|
||||
for i in 0..n {
|
||||
let mut last = None;
|
||||
for _ in 0..CHUNK_ATTEMPTS {
|
||||
if !first {
|
||||
tokio::time::sleep(CHUNK_PACE).await;
|
||||
}
|
||||
first = false;
|
||||
match send(i).await {
|
||||
Ok(()) => {
|
||||
last = None;
|
||||
break;
|
||||
}
|
||||
Err(e) => last = Some(e),
|
||||
}
|
||||
}
|
||||
if let Some(e) = last {
|
||||
return Err(e);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Inbox {
|
||||
pub fn new(root: impl Into<PathBuf>) -> Self {
|
||||
Self {
|
||||
|
|
|
|||
|
|
@ -486,12 +486,13 @@ impl Node {
|
|||
}
|
||||
|
||||
/// One-shot file to a friend. Fail closed; no outbox, no resume.
|
||||
/// Chunks are paced (`file::CHUNK_PACE`) with bounded per-chunk retry so
|
||||
/// a 1 MiB transfer fits the receiver's rendezvous token bucket.
|
||||
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())?;
|
||||
for chunk in &chunks {
|
||||
self.send_once(friend_pk, &file::encode(chunk)).await?;
|
||||
}
|
||||
let frames: Vec<Vec<u8>> = chunks.iter().map(file::encode).collect();
|
||||
file::send_chunks(frames.len(), |i| self.send_once(friend_pk, &frames[i])).await?;
|
||||
self.store
|
||||
.lock()
|
||||
.map_err(|e| e.to_string())?
|
||||
|
|
|
|||
|
|
@ -1,7 +1,10 @@
|
|||
//! 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]
|
||||
|
|
@ -131,3 +134,69 @@ 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");
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue