1
0
mirror of https://github.com/aziascreations/BakaShrot.git synced 2026-11-23 20:58:46 +01:00

Kept attachments whose read-back failed, Closed the Rust client's connection when out of step

- Replication: a peer's DataMismatch has the sender read its own copy
  back. Dropped as damaged only when read whole and not matching, or a
  part missing; a read-back that failed otherwise (a busy database, a
  connection not opened) dropped it too, the only copy if this server
  was its origin: now kept and warned about (push_to.rs, judge)
- bakashrot-client: an I/O error, a timeout, an answer that isn't the
  request's or doesn't decode, parts cut short or interrupted, a source
  failing mid-upload close the connection; requests after fail with
  NotConnected without reading, so a late answer is never taken for
  the next request's (a push could return the previous one's id).
  is_closed(), set_answer_timeout() / answer_timeout() (30 s by
  default), is_open() always blocking again
- The DLL forgets a client its connection closed that way, whatever the
  code, so connecting again works
- tests/failures.rs in bakashrot-client: a fake TLS server answering
  late, wrongly, cut short; end_to_end.rs for a revoked certificate and
  a failed upload; docs (client.md, server.md) and revamp.md (step 18)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-19 23:37:01 +01:00
parent 6fae7e61c9
commit 8ebac633d0
8 changed files with 681 additions and 50 deletions
+150 -40
View File
@@ -17,6 +17,13 @@
//! ALPN `bakashrot`, both ends' protocol versions, then the server's
//! `Welcome` (`docs/protocol.md`). Errors carry the protocol's codes
//! (`bakashrot_proto::ErrorCode`): a server's refusal keeps its own.
//!
//! **A failure that leaves the connection out of step closes it:** an
//! I/O error, an answer that didn't come in time ([`Client::answer_timeout`]),
//! one that isn't the request's, a part cut short. Every request after
//! fails with `NotConnected` at once, without reading: a late answer is
//! never taken for the next request's. Connect again. A refusal, or an
//! argument refused before sending, keeps it.
use aws_lc_rs::digest;
use bakashrot_pki::{Revocations, tls};
@@ -102,6 +109,11 @@ pub struct Client {
stream: StreamOwned<ClientConnection, TcpStream>,
server: String,
node: String,
/// How long an answer may take: [`ANSWER_TIMEOUT`] until changed.
answer_timeout: Duration,
/// Closed, after a failure that left it out of step: requests fail
/// with `NotConnected`.
closed: bool,
}
impl fmt::Debug for Client {
@@ -166,20 +178,43 @@ impl Client {
stream,
server: String::new(),
node: String::new(),
answer_timeout: CONNECT_TIMEOUT,
closed: false,
};
match client.answer()? {
Packet::Welcome(welcome) => {
client.server = welcome.server;
client.node = welcome.node;
}
other => return Err(unexpected(&other)),
other => return Err(client.unexpected(&other)),
}
let tcp = &client.stream.sock;
tcp.set_read_timeout(Some(ANSWER_TIMEOUT)).map_err(lost)?;
tcp.set_write_timeout(Some(ANSWER_TIMEOUT)).map_err(lost)?;
client.set_answer_timeout(ANSWER_TIMEOUT)?;
Ok(client)
}
/// How long an answer may take before its request fails
/// (`ConnectionLost`, the connection closed): [`ANSWER_TIMEOUT`] (30 s)
/// until changed.
pub fn answer_timeout(&self) -> Duration {
self.answer_timeout
}
/// Sets how long an answer may take, more than 0: longer for a slow
/// query, say. It's also how long sending a packet may take. Past it,
/// the request fails and the connection is closed (a late answer would
/// be taken for the next request's).
pub fn set_answer_timeout(&mut self, timeout: Duration) -> Result<()> {
require(!timeout.is_zero(), || "an answer timeout of 0".to_owned())?;
self.check_open()?;
let tcp = &self.stream.sock;
let set = tcp
.set_read_timeout(Some(timeout))
.and_then(|()| tcp.set_write_timeout(Some(timeout)));
set.map_err(|error| self.io_failed(error))?;
self.answer_timeout = timeout;
Ok(())
}
/// The server's name.
pub fn server(&self) -> &str {
&self.server
@@ -193,6 +228,9 @@ impl Client {
/// Whether the connection still looks open: the server hasn't closed
/// it (after its idle timeout, say). Only a request tells for sure.
pub fn is_open(&self) -> bool {
if self.closed {
return false;
}
let tcp = &self.stream.sock;
if tcp.set_nonblocking(true).is_err() {
return false;
@@ -201,7 +239,17 @@ impl Client {
Ok(read) => read > 0,
Err(error) => error.kind() == io::ErrorKind::WouldBlock,
};
open && tcp.set_nonblocking(false).is_ok()
// Blocking again whatever it found: the next request waits for
// its answer.
let blocking = tcp.set_nonblocking(false).is_ok();
open && blocking
}
/// Whether a failure closed the connection: every request fails with
/// `NotConnected` now, connect again. Unlike [`Client::is_open`], it
/// doesn't look at the socket.
pub fn is_closed(&self) -> bool {
self.closed
}
/// Keeps the connection open: the server closes one silent for
@@ -210,7 +258,7 @@ impl Client {
pub fn ping(&mut self) -> Result<()> {
match self.request(Ping {}.into())? {
Packet::Pong(_) => Ok(()),
other => Err(unexpected(&other)),
other => Err(self.unexpected(&other)),
}
}
@@ -225,7 +273,7 @@ impl Client {
};
match self.request(push.into())? {
Packet::MessagePushed(pushed) => Ok(pushed.message_id),
other => Err(unexpected(&other)),
other => Err(self.unexpected(&other)),
}
}
@@ -272,23 +320,22 @@ impl Client {
};
match self.request(push.into())? {
Packet::Continue(_) => {}
other => return Err(unexpected(&other)),
other => return Err(self.unexpected(&other)),
}
for part in 0..attachment.part_count() {
let part = &mut buffer[..attachment.part_len(part) as usize];
if let Err(error) = source.read_exact(part) {
self.close();
return Err(file_error(error));
// The server waits for parts that won't come.
return Err(self.out_of_step(file_error(error)));
}
let packet = Packet::from(AttachmentPart {
self.send(&Packet::from(AttachmentPart {
data: part.to_vec(),
});
frame::write(&mut self.stream, &packet.encode()).map_err(lost)?;
}))?;
}
self.stream.flush().map_err(lost)?;
self.flush()?;
match self.answer()? {
Packet::MessagePushed(pushed) => Ok(pushed.message_id),
other => Err(unexpected(&other)),
other => Err(self.unexpected(&other)),
}
}
@@ -315,27 +362,26 @@ impl Client {
};
let attachment = match self.request(get.into())? {
Packet::Attachment(attachment) => attachment,
other => return Err(unexpected(&other)),
other => return Err(self.unexpected(&other)),
};
let mut sha256 = digest::Context::new(&digest::SHA256);
// A failing `out`: the parts are still all read, the connection
// stays usable.
let mut failed = None;
for part in 0..attachment.part_count() {
let data = match self.answer()? {
Packet::AttachmentPart(part) => part.data,
other => {
self.close();
return Err(unexpected(&other));
}
// Parts come without a request each: anything else, a refusal
// too, leaves the rest of them unread.
let data = match self.answer() {
Ok(Packet::AttachmentPart(part)) => part.data,
Ok(other) => return Err(self.unexpected(&other)),
Err(error) => return Err(self.out_of_step(error)),
};
let expected = attachment.part_len(part);
if data.len() as u64 != expected {
self.close();
return Err(Error::new(
return Err(self.out_of_step(Error::new(
ErrorCode::ProtocolError,
format!("part {part}: {} bytes, {expected} expected", data.len()),
));
)));
}
sha256.update(&data);
if failed.is_none() {
@@ -407,7 +453,7 @@ impl Client {
};
match self.request(get.into())? {
Packet::Messages(messages) => Ok(messages),
other => Err(unexpected(&other)),
other => Err(self.unexpected(&other)),
}
}
@@ -437,7 +483,7 @@ impl Client {
};
match self.request(list.into())? {
Packet::NamesList(names) => Ok(names),
other => Err(unexpected(&other)),
other => Err(self.unexpected(&other)),
}
}
@@ -450,40 +496,104 @@ impl Client {
};
match self.request(query.into())? {
Packet::QueryResult(result) => Ok(result.json),
other => Err(unexpected(&other)),
other => Err(self.unexpected(&other)),
}
}
/// Closes the connection: it's out of step (a part not sent, or not
/// as expected). Every request fails then (`ConnectionLost`).
/// Closes the connection for good: every request fails then
/// (`NotConnected`).
fn close(&mut self) {
self.closed = true;
let _ = self.stream.sock.shutdown(Shutdown::Both);
}
/// `NotConnected` once closed.
fn check_open(&self) -> Result<()> {
match self.closed {
false => Ok(()),
true => Err(Error::new(
ErrorCode::NotConnected,
"the connection was closed after an earlier failure: connect again",
)),
}
}
/// `error`, which left the connection out of step: closed.
fn out_of_step(&mut self, error: Error) -> Error {
self.close();
error
}
/// An I/O error on the connection: closed. A timeout says so (its
/// answer may still come, after the next request).
fn io_failed(&mut self, error: io::Error) -> Error {
let timed_out = matches!(
error.kind(),
io::ErrorKind::WouldBlock | io::ErrorKind::TimedOut
);
let error = match timed_out {
true => Error::new(
ErrorCode::ConnectionLost,
format!(
"no answer within {:?}: the connection is closed",
self.answer_timeout
),
),
false => lost(error),
};
self.out_of_step(error)
}
/// An answer that isn't the request's: `ProtocolError`, closed.
fn unexpected(&mut self, packet: &Packet) -> Error {
self.out_of_step(unexpected(packet))
}
/// Writes a packet's frame (not flushed).
fn send(&mut self, packet: &Packet) -> Result<()> {
self.check_open()?;
// Refused before anything is written: the connection stays.
let frame = frame::encode(&packet.encode())
.map_err(|error| Error::new(ErrorCode::InvalidArgument, error.to_string()))?;
let written = self.stream.write_all(&frame);
written.map_err(|error| self.io_failed(error))
}
fn flush(&mut self) -> Result<()> {
let flushed = self.stream.flush();
flushed.map_err(|error| self.io_failed(error))
}
/// Sends a request, reads its answer.
fn request(&mut self, packet: Packet) -> Result<Packet> {
frame::write(&mut self.stream, &packet.encode()).map_err(lost)?;
self.stream.flush().map_err(lost)?;
self.send(&packet)?;
self.flush()?;
self.answer()
}
/// Reads the server's next packet: a refusal is an error.
/// Reads the server's next packet: a refusal is an error (the
/// connection kept), anything else wrong closes it.
fn answer(&mut self) -> Result<Packet> {
let bytes = frame::read(&mut self.stream, MAX_PACKET_SIZE)
.map_err(lost)?
.ok_or_else(|| {
Error::new(
self.check_open()?;
let bytes = match frame::read(&mut self.stream, MAX_PACKET_SIZE) {
Ok(Some(bytes)) => bytes,
Ok(None) => {
return Err(self.out_of_step(Error::new(
ErrorCode::ConnectionLost,
"the server closed the connection",
)
})?;
)));
}
Err(error) => return Err(self.io_failed(error)),
};
match Packet::decode(&bytes) {
Ok(Packet::RequestRefused(refused)) => Err(Error {
code: refused.code,
message: refused.reason,
}),
Ok(packet) => Ok(packet),
Err(error) => Err(Error::new(ErrorCode::ProtocolError, error.to_string())),
Err(error) => {
Err(self.out_of_step(Error::new(ErrorCode::ProtocolError, error.to_string())))
}
}
}
}
+408
View File
@@ -0,0 +1,408 @@
//! What a failure does to the connection, against a fake server that
//! answers late, wrongly or not at all: a refusal keeps it, anything that
//! leaves it out of step closes it, and nothing is read after (a late
//! answer is never taken for the next request's).
use bakashrot_client::{ANSWER_TIMEOUT, Client, Settings};
use bakashrot_pki::{Ca, Identity, Issued, Revocations, Usage, tls};
use bakashrot_proto::limits::{ATTACHMENT_PART_SIZE, MAX_PACKET_SIZE};
use bakashrot_proto::packets::{
Attachment, AttachmentPart, Continue, MessagePushed, Pong, RequestRefused, Welcome,
};
use bakashrot_proto::{ErrorCode, Packet, frame};
use rustls::{ServerConnection, StreamOwned};
use std::io::{self, Cursor, Read, Seek, SeekFrom, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::mpsc;
use std::thread::{self, JoinHandle};
use std::time::Duration;
/// The fake server's end of the connection.
type Stream = StreamOwned<ServerConnection, TcpStream>;
/// A fake server for one connection, running its script once the client
/// is welcomed, and the client's certificates.
struct Fake {
address: String,
ca: String,
client: Issued,
script: Option<JoinHandle<()>>,
}
impl Fake {
fn start(script: impl FnOnce(&mut Stream) + Send + 'static) -> Fake {
let ca = Ca::create("Fake CA", 1).unwrap();
let loaded = Ca::load(&ca.certificate, &ca.key).unwrap();
let issue = |name: &str, usage| {
loaded
.issue(&Identity::new(name, &["sensor"]).unwrap(), usage, 1)
.unwrap()
};
let server = issue("fake", Usage::Server);
let client = issue("kitchen", Usage::Client);
let config = tls::server_config(
&ca.certificate,
&server.certificate,
&server.key,
Revocations::none().shared(),
)
.unwrap();
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap().to_string();
let script = thread::spawn(move || {
let (tcp, _) = listener.accept().unwrap();
tcp.set_read_timeout(Some(Duration::from_secs(10))).unwrap();
let mut stream = StreamOwned::new(ServerConnection::new(config).unwrap(), tcp);
while stream.conn.is_handshaking() {
stream.conn.complete_io(&mut stream.sock).unwrap();
}
frame::write_version(&mut stream).unwrap();
frame::read_version(&mut stream).unwrap();
answer(
&mut stream,
Welcome {
server: "fake".into(),
node: "kitchen".into(),
},
);
script(&mut stream);
});
Fake {
address,
ca: ca.certificate,
client,
script: Some(script),
}
}
fn connect(&self) -> Client {
Client::connect(
&self.address,
&Settings {
ca: &self.ca,
certificate: &self.client.certificate,
key: &self.client.key,
crl: None,
},
)
.unwrap()
}
/// Waits for the script to end (its asserts included).
fn finish(mut self) {
self.script.take().unwrap().join().unwrap();
}
}
/// The client's next packet, none once it closed the connection.
fn request(stream: &mut Stream) -> Option<Packet> {
let bytes = frame::read(stream, MAX_PACKET_SIZE).ok()??;
Some(Packet::decode(&bytes).unwrap())
}
fn answer(stream: &mut Stream, packet: impl Into<Packet>) {
frame::write(stream, &packet.into().encode()).unwrap();
stream.flush().unwrap();
}
/// Whether the client closed the connection without sending anything
/// more: what the script reports after its answer.
fn nothing_more(stream: &mut Stream) -> bool {
request(stream).is_none()
}
#[track_caller]
fn fails(result: Result<impl std::fmt::Debug, bakashrot_client::Error>, code: ErrorCode) {
let error = result.unwrap_err();
assert_eq!(error.code(), code.code(), "{error}");
}
#[test]
fn a_late_answer_is_never_taken_for_the_next_request() {
let (report, reported) = mpsc::channel();
let fake = Fake::start(move |stream| {
assert!(matches!(request(stream), Some(Packet::PushMessage(_))));
thread::sleep(Duration::from_millis(600));
// Too late: the client gave up, and closed.
let _ = frame::write(
stream,
&Packet::from(MessagePushed { message_id: 1 }).encode(),
);
let _ = stream.flush();
report.send(nothing_more(stream)).unwrap();
});
let mut client = fake.connect();
client
.set_answer_timeout(Duration::from_millis(200))
.unwrap();
let error = client.push("logs", "{}").unwrap_err();
assert_eq!(error.code(), ErrorCode::ConnectionLost.code(), "{error}");
assert!(
error.message().contains("no answer within 200ms"),
"{error}"
);
assert!(!client.is_open() && client.is_closed());
// Once the late answer is there, the next push mustn't read it as its
// own (it got #1 before).
thread::sleep(Duration::from_millis(700));
fails(client.push("logs", "{}"), ErrorCode::NotConnected);
fails(client.ping(), ErrorCode::NotConnected);
assert!(reported.recv().unwrap(), "the client sent something more");
fake.finish();
}
#[test]
fn a_wrong_answer_closes() {
let (report, reported) = mpsc::channel();
let fake = Fake::start(move |stream| {
assert!(matches!(request(stream), Some(Packet::PushMessage(_))));
answer(stream, Pong {});
report.send(nothing_more(stream)).unwrap();
});
let mut client = fake.connect();
fails(client.push("logs", "{}"), ErrorCode::ProtocolError);
assert!(!client.is_open() && client.is_closed());
fails(client.ping(), ErrorCode::NotConnected);
assert!(reported.recv().unwrap());
fake.finish();
}
#[test]
fn a_malformed_answer_closes() {
let (report, reported) = mpsc::channel();
let fake = Fake::start(move |stream| {
assert!(matches!(request(stream), Some(Packet::Ping(_))));
// 0xc1 is never MessagePack.
frame::write(stream, &[0xc1]).unwrap();
stream.flush().unwrap();
report.send(nothing_more(stream)).unwrap();
});
let mut client = fake.connect();
fails(client.ping(), ErrorCode::ProtocolError);
fails(client.query("SELECT 1"), ErrorCode::NotConnected);
assert!(reported.recv().unwrap());
fake.finish();
}
#[test]
fn an_answer_cut_short_closes() {
let fake = Fake::start(|stream| {
assert!(matches!(request(stream), Some(Packet::GetMessages(_))));
// A frame of 100 bytes, 3 of them sent, then the connection gone.
stream.write_all(&[100, 0, 0, 0, 1, 2, 3]).unwrap();
stream.flush().unwrap();
stream.conn.send_close_notify();
let _ = stream.conn.complete_io(&mut stream.sock);
});
let mut client = fake.connect();
fails(
client.get_messages("logs", "kitchen", Some(0), 10),
ErrorCode::ConnectionLost,
);
fails(client.ping(), ErrorCode::NotConnected);
fake.finish();
}
#[test]
fn a_refusal_keeps_the_connection() {
let fake = Fake::start(|stream| {
assert!(matches!(request(stream), Some(Packet::PushMessage(_))));
answer(
stream,
RequestRefused::new(ErrorCode::NotAllowed, "not this topic"),
);
assert!(matches!(request(stream), Some(Packet::Ping(_))));
answer(stream, Pong {});
assert!(matches!(request(stream), Some(Packet::PushMessage(_))));
answer(stream, MessagePushed { message_id: 7 });
});
let mut client = fake.connect();
let error = client.push("logs", "{}").unwrap_err();
assert_eq!(error.code(), ErrorCode::NotAllowed.code());
assert_eq!(error.message(), "not this topic");
assert!(client.is_open() && !client.is_closed());
client.ping().unwrap();
assert_eq!(client.push("logs", "{}").unwrap(), 7);
fake.finish();
}
#[test]
fn an_argument_refused_before_sending_keeps_the_connection() {
let fake = Fake::start(|stream| {
assert!(matches!(request(stream), Some(Packet::Ping(_))));
answer(stream, Pong {});
});
let mut client = fake.connect();
fails(client.push("not a name", "{}"), ErrorCode::InvalidArgument);
fails(
client.get_messages("logs", "kitchen", Some(0), 0),
ErrorCode::InvalidArgument,
);
fails(
client.set_answer_timeout(Duration::ZERO),
ErrorCode::InvalidArgument,
);
assert_eq!(client.answer_timeout(), ANSWER_TIMEOUT);
client.ping().unwrap();
fake.finish();
}
#[test]
fn a_longer_timeout_waits_for_a_slow_answer() {
let fake = Fake::start(|stream| {
assert!(matches!(request(stream), Some(Packet::Ping(_))));
thread::sleep(Duration::from_millis(500));
answer(stream, Pong {});
});
let mut client = fake.connect();
client.set_answer_timeout(Duration::from_secs(5)).unwrap();
assert_eq!(client.answer_timeout(), Duration::from_secs(5));
client.ping().unwrap();
fake.finish();
}
/// `is_open()` looks without blocking, then blocks again: the next
/// request waits for its answer, slow as it is.
#[test]
fn is_open_leaves_the_connection_blocking() {
let fake = Fake::start(|stream| {
assert!(matches!(request(stream), Some(Packet::Ping(_))));
thread::sleep(Duration::from_millis(300));
answer(stream, Pong {});
});
let mut client = fake.connect();
assert!(client.is_open() && !client.is_closed());
client.ping().unwrap();
fake.finish();
}
/// The server gone (closed as it closes an idle one: the socket, no TLS
/// close_notify): `is_open()` says so, the next request fails as lost,
/// those after as not connected.
#[test]
fn a_connection_the_server_closed() {
let fake = Fake::start(|stream| {
let _ = stream.sock.shutdown(std::net::Shutdown::Both);
});
let mut client = fake.connect();
let address = fake.address.clone();
fake.finish();
let mut waited = 0;
while client.is_open() && waited < 50 {
thread::sleep(Duration::from_millis(20));
waited += 1;
}
assert!(!client.is_open(), "{address}: still open");
fails(client.ping(), ErrorCode::ConnectionLost);
fails(client.ping(), ErrorCode::NotConnected);
}
#[test]
fn a_part_of_the_wrong_size_closes() {
let (report, reported) = mpsc::channel();
let fake = Fake::start(move |stream| {
assert!(matches!(request(stream), Some(Packet::GetAttachment(_))));
answer(
stream,
Attachment {
size: 10,
sha256: [0; 32],
},
);
answer(stream, AttachmentPart { data: vec![1; 5] });
report.send(nothing_more(stream)).unwrap();
});
let mut client = fake.connect();
let mut out = Vec::new();
fails(
client.get_attachment("logs", "kitchen", 1, &mut out),
ErrorCode::ProtocolError,
);
fails(client.ping(), ErrorCode::NotConnected);
assert!(reported.recv().unwrap());
fake.finish();
}
/// A refusal where a part should be: the parts after it would be read as
/// the next request's answers.
#[test]
fn a_refusal_among_the_parts_closes() {
let (report, reported) = mpsc::channel();
let fake = Fake::start(move |stream| {
assert!(matches!(request(stream), Some(Packet::GetAttachment(_))));
answer(
stream,
Attachment {
size: ATTACHMENT_PART_SIZE + 1,
sha256: [0; 32],
},
);
answer(
stream,
AttachmentPart {
data: vec![1; ATTACHMENT_PART_SIZE as usize],
},
);
answer(
stream,
RequestRefused::new(ErrorCode::ServerError, "a disk"),
);
report.send(nothing_more(stream)).unwrap();
});
let mut client = fake.connect();
let mut out = Vec::new();
fails(
client.get_attachment("logs", "kitchen", 1, &mut out),
ErrorCode::ServerError,
);
fails(client.ping(), ErrorCode::NotConnected);
assert!(reported.recv().unwrap());
fake.finish();
}
/// Bytes that read the first time through, and fail the second.
struct FailingSecondTime {
data: Cursor<Vec<u8>>,
rewinds: usize,
}
impl Read for FailingSecondTime {
fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
if self.rewinds > 1 {
return Err(io::Error::other("the disk went away"));
}
self.data.read(buffer)
}
}
impl Seek for FailingSecondTime {
fn seek(&mut self, to: SeekFrom) -> io::Result<u64> {
self.rewinds += 1;
self.data.seek(to)
}
}
/// The source failing once the server said `Continue`: the server waits
/// for parts that won't come, the connection closes.
#[test]
fn a_source_failing_mid_upload_closes() {
let (report, reported) = mpsc::channel();
let fake = Fake::start(move |stream| {
assert!(matches!(request(stream), Some(Packet::PushMessage(_))));
answer(stream, Continue {});
report.send(nothing_more(stream)).unwrap();
});
let mut client = fake.connect();
let mut source = FailingSecondTime {
data: Cursor::new(vec![7; 100]),
rewinds: 0,
};
let error = client
.push_with_attachment("logs", "{}", &mut source)
.unwrap_err();
assert_eq!(error.code(), ErrorCode::FileError.code(), "{error}");
assert!(!client.is_open() && client.is_closed());
fails(client.ping(), ErrorCode::NotConnected);
assert!(reported.recv().unwrap());
fake.finish();
}