Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Control channel: connections must authenticate within 10 s, however active (#4965) (#5229)

Michael Higgins64520f645e07
diff --git a/apps/photocraft/src/control_server.rs b/apps/photocraft/src/control_server.rs
index 258d89e1e..30ae610b7 100644
--- a/apps/photocraft/src/control_server.rs
+++ b/apps/photocraft/src/control_server.rs
@@ -5,11 +5,12 @@ use std::io::{BufReader, Write};
use std::net::{TcpListener, TcpStream};
use std::sync::Arc;
use std::sync::mpsc::{Receiver, Sender, channel};
-use std::time::Instant;
+use std::time::{Duration, Instant};
use photocraft_automation::budgets::write_reply;
use photocraft_automation::security::{
- ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, authentication_reply, configure_stream, read_bounded_line, repeat_auth_reply,
+ AUTH_DEADLINE, AuthDeadlineStream, ConnectionLimiter, LineRead, MAX_CONNECTIONS, MAX_REQUEST_BYTES, authentication_reply, configure_stream,
+ read_bounded_line, repeat_auth_reply,
};
use photocraft_ui_egui::ControlRequest;
use photocraft_ui_egui::control::REPLY_DEADLINE;
@@ -47,11 +48,17 @@ pub fn start(port: u16, token: String, ctx: egui::Context) -> Receiver<ControlRe
}
fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::Context) {
+ serve_with_auth_deadline(stream, token, tx, ctx, AUTH_DEADLINE);
+}
+
+/// [`serve`] for a connection that must complete `auth` within `auth_deadline` of connecting,
+/// however much it sends meanwhile (#4965); after that only the idle timeout applies.
+fn serve_with_auth_deadline(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::Context, auth_deadline: Duration) {
if configure_stream(&stream).is_err() {
return;
}
let Ok(read) = stream.try_clone() else { return };
- let mut reader = BufReader::new(read);
+ let mut reader = BufReader::new(AuthDeadlineStream::new(read, auth_deadline));
let mut out = stream;
let mut line = String::new();
let mut authenticated = false;
@@ -74,6 +81,9 @@ fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::
if !authenticated {
let (reply, ok) = authentication_reply(&line, token);
authenticated = ok;
+ if ok && reader.get_mut().authenticated().is_err() {
+ break;
+ }
if write_reply(&mut out, &reply).is_err() || out.flush().is_err() || !authenticated {
break;
}
@@ -120,7 +130,34 @@ fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::
mod tests {
use super::*;
use std::io::BufRead;
- use std::time::Duration;
+
+ /// #4965: a connection that keeps sending without authenticating is closed at the deadline
+ /// (releasing its connection permit), and nothing it sent is dispatched.
+ #[test]
+ fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() {
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = listener.local_addr().unwrap();
+ let (tx, rx) = channel::<ControlRequest>();
+ let server = std::thread::spawn(move || {
+ let (stream, _) = listener.accept().unwrap();
+ let started = Instant::now();
+ serve_with_auth_deadline(stream, "unused", tx, egui::Context::default(), Duration::from_millis(300));
+ started.elapsed()
+ });
+ // Blank lines and partial frames, one byte every 20 ms: each read succeeds long before
+ // the idle timeout.
+ let mut stream = TcpStream::connect(addr).unwrap();
+ for i in 0..150 {
+ let byte: &[u8] = if i % 5 == 0 { b"\n" } else { b" " };
+ if stream.write_all(byte).is_err() {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ let served = server.join().unwrap();
+ assert!(served < Duration::from_secs(3), "the trickle did not extend the deadline: {served:?}");
+ assert!(rx.try_recv().is_err(), "nothing was dispatched");
+ }
#[test]
fn oversized_reply_preserves_framing_id_and_the_next_control_request() {
diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs
index dc01f0f2b..15a0e24e3 100644
--- a/crates/automation/src/rpc.rs
+++ b/crates/automation/src/rpc.rs
@@ -29,8 +29,8 @@ use serde_json::{Value, json};
use crate::budgets::{BatchReplyBudget, write_reply};
use crate::security::{
- ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, authentication_reply, configure_stream, discard_rest_of_line,
- read_bounded_line, repeat_auth_reply,
+ AUTH_DEADLINE, AuthDeadlineStream, ConnectionLimiter, LineRead, MAX_BATCH_STEPS, MAX_CONNECTIONS, MAX_REQUEST_BYTES, authentication_reply,
+ configure_stream, discard_rest_of_line, read_bounded_line, repeat_auth_reply,
};
use crate::{AutomationError, Headless};
@@ -262,10 +262,12 @@ pub fn serve_lines(h: &Mutex<Headless>, mut r: impl BufRead, mut w: impl Write)
}
}
-fn serve_tcp_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token: &str) -> std::io::Result<()> {
+/// Serve one connection. It must complete `auth` within `auth_deadline` of connecting, however
+/// much it sends meanwhile (#4965); after that only the idle timeout applies.
+fn serve_tcp_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token: &str, auth_deadline: std::time::Duration) -> std::io::Result<()> {
configure_stream(&stream)?;
let read = stream.try_clone()?;
- let mut reader = std::io::BufReader::new(read);
+ let mut reader = std::io::BufReader::new(AuthDeadlineStream::new(read, auth_deadline));
let mut out = stream;
let mut line = String::new();
let mut authenticated = false;
@@ -290,6 +292,9 @@ fn serve_tcp_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token:
} else {
let (reply, ok) = authentication_reply(&line, token);
authenticated = ok;
+ if ok {
+ reader.get_mut().authenticated()?;
+ }
reply
};
write_reply(&mut out, &reply)?;
@@ -322,7 +327,7 @@ pub fn serve_tcp(addr: &str, h: Arc<Mutex<Headless>>, token: String, ready: impl
let token = Arc::clone(&token);
std::thread::spawn(move || {
let _permit = permit;
- let _ = serve_tcp_connection(&h, stream, &token);
+ let _ = serve_tcp_connection(&h, stream, &token, AUTH_DEADLINE);
});
}
Ok(())
@@ -814,6 +819,60 @@ mod tests {
assert!(v["result"].as_array().unwrap().iter().any(|m| m == "batch"));
}
+ /// #4965: a connection that keeps sending without authenticating is closed at the deadline,
+ /// and one that authenticated in time keeps being served after it.
+ #[test]
+ fn tcp_connections_must_authenticate_before_the_deadline_whatever_they_send() {
+ use std::io::{BufReader, Write as _};
+ use std::time::{Duration, Instant};
+ const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
+ let listener = TcpListener::bind("127.0.0.1:0").unwrap();
+ let addr = listener.local_addr().unwrap();
+ let server = std::thread::spawn(move || {
+ let h = Mutex::new(Headless::new());
+ let mut results = Vec::new();
+ for _ in 0..2 {
+ let (stream, _) = listener.accept().unwrap();
+ let started = Instant::now();
+ let r = serve_tcp_connection(&h, stream, TOKEN, Duration::from_millis(300));
+ results.push((r.map_err(|e| e.kind()), started.elapsed()));
+ }
+ results
+ });
+
+ // Never a newline, a byte every 20 ms: each read succeeds long before the idle timeout.
+ let mut slow = std::net::TcpStream::connect(addr).unwrap();
+ for _ in 0..150 {
+ if slow.write_all(b" ").is_err() {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ drop(slow);
+
+ // Authenticates at once, then asks again 300 ms after the deadline.
+ let mut s = std::net::TcpStream::connect(addr).unwrap();
+ s.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
+ writeln!(s, r#"{{"id":"auth","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap();
+ let mut reader = BufReader::new(s.try_clone().unwrap());
+ let mut line = String::new();
+ reader.read_line(&mut line).unwrap();
+ assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["result"]["authenticated"], true);
+ std::thread::sleep(Duration::from_millis(600));
+ writeln!(s, r#"{{"id":"a","method":"methods"}}"#).unwrap();
+ line.clear();
+ reader.read_line(&mut line).unwrap();
+ assert_eq!(serde_json::from_str::<Value>(&line).unwrap()["id"], "a");
+ drop(reader);
+ drop(s);
+
+ let results = server.join().unwrap();
+ let (slow_result, slow_time) = &results[0];
+ assert!(matches!(slow_result, Err(std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock)), "{slow_result:?}");
+ assert!(*slow_time < Duration::from_secs(3), "the trickle did not extend the deadline: {slow_time:?}");
+ assert_eq!(results[1].0, Ok(()), "the authenticated connection ended with its client");
+ }
+
#[test]
fn tcp_repeat_auth_reports_already_authenticated_and_keeps_serving() {
use std::io::{BufReader, Write as _};
diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs
index 4659a3ff1..7928420b1 100644
--- a/crates/automation/src/security.rs
+++ b/crates/automation/src/security.rs
@@ -1,11 +1,11 @@
//! Shared security primitives for the loopback JSON control transports.
use std::fs::OpenOptions;
-use std::io::{BufRead, Write};
+use std::io::{BufRead, Read, Write};
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
-use std::time::Duration;
+use std::time::{Duration, Instant};
use serde_json::{Value, json};
@@ -21,6 +21,10 @@ pub const MAX_CONNECTIONS: usize = 16;
pub const MAX_BATCH_STEPS: usize = 256;
/// Idle/read and write timeout for loopback TCP connections.
pub const IO_TIMEOUT: Duration = Duration::from_secs(30);
+/// How long a new TCP connection has to authenticate, however active it is. [`IO_TIMEOUT`] starts
+/// again with every read, so a client that kept sending without ever completing `auth` held one
+/// of the [`MAX_CONNECTIONS`] permits for as long as it liked (#4965).
+pub const AUTH_DEADLINE: Duration = Duration::from_secs(10);
const TOKEN_BYTES: usize = 32;
const TOKEN_HEX_LEN: usize = TOKEN_BYTES * 2;
@@ -242,6 +246,44 @@ pub fn configure_stream(stream: &std::net::TcpStream) -> std::io::Result<()> {
stream.set_write_timeout(Some(IO_TIMEOUT))
}
+/// The read half of a control connection. Until [`Self::authenticated`] is called, reads fail
+/// with `TimedOut` once the authentication deadline has passed, whatever arrived in the meantime;
+/// the caller then drops the connection and its [`ConnectionPermit`].
+pub struct AuthDeadlineStream {
+ stream: std::net::TcpStream,
+ /// `None` once authenticated.
+ deadline: Option<Instant>,
+}
+
+impl AuthDeadlineStream {
+ /// `stream` must authenticate within `limit` from now (normally [`AUTH_DEADLINE`]).
+ pub fn new(stream: std::net::TcpStream, limit: Duration) -> Self {
+ // A limit too large to represent expires at once rather than never.
+ let now = Instant::now();
+ Self { stream, deadline: Some(now.checked_add(limit).unwrap_or(now)) }
+ }
+
+ /// The connection authenticated: only the idle timeout applies from here on.
+ pub fn authenticated(&mut self) -> std::io::Result<()> {
+ self.deadline = None;
+ self.stream.set_read_timeout(Some(IO_TIMEOUT))
+ }
+}
+
+impl Read for AuthDeadlineStream {
+ fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
+ if let Some(deadline) = self.deadline {
+ let left = deadline.saturating_duration_since(Instant::now());
+ if left.is_zero() {
+ return Err(std::io::Error::new(std::io::ErrorKind::TimedOut, "not authenticated in time"));
+ }
+ // Wait no longer than what is left, so a silent client is dropped at the deadline too.
+ self.stream.set_read_timeout(Some(left.min(IO_TIMEOUT)))?;
+ }
+ self.stream.read(buf)
+ }
+}
+
/// Environment-aware token inputs shared by the desktop app and CLI.
pub fn token_inputs(supplied: Option<String>, token_file: Option<PathBuf>) -> (Option<String>, Option<PathBuf>) {
let supplied = supplied.or_else(|| std::env::var("PHOTOCRAFT_CONTROL_TOKEN").ok());
@@ -327,6 +369,70 @@ mod tests {
std::fs::remove_file(path).unwrap();
}
+ /// A connected loopback pair: the accepted (server) end and the client end.
+ fn tcp_pair() -> (std::net::TcpStream, std::net::TcpStream) {
+ let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
+ let client = std::net::TcpStream::connect(listener.local_addr().unwrap()).unwrap();
+ let (server, _) = listener.accept().unwrap();
+ configure_stream(&server).unwrap();
+ (server, client)
+ }
+
+ /// #4965: activity must not extend the time a connection may stay unauthenticated.
+ #[test]
+ fn an_active_connection_is_dropped_at_the_authentication_deadline() {
+ let (server, mut client) = tcp_pair();
+ // A byte every 20 ms and never a newline: each read succeeds long before the idle timeout.
+ let trickle = std::thread::spawn(move || {
+ for _ in 0..150 {
+ if client.write_all(b"x").is_err() {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(20));
+ }
+ });
+ let mut reader = std::io::BufReader::new(AuthDeadlineStream::new(server, Duration::from_millis(300)));
+ let mut line = String::new();
+ let started = Instant::now();
+ let err = read_bounded_line(&mut reader, &mut line).unwrap_err();
+ assert!(matches!(err.kind(), std::io::ErrorKind::TimedOut | std::io::ErrorKind::WouldBlock), "{err}");
+ assert!(started.elapsed() >= Duration::from_millis(250), "not before the deadline: {:?}", started.elapsed());
+ assert!(started.elapsed() < Duration::from_secs(3), "the trickle did not extend it: {:?}", started.elapsed());
+ // It stays expired.
+ assert!(read_bounded_line(&mut reader, &mut line).is_err());
+ drop(reader);
+ trickle.join().unwrap();
+ }
+
+ #[test]
+ fn a_silent_connection_is_dropped_at_the_authentication_deadline() {
+ let (server, _client) = tcp_pair();
+ let mut reader = std::io::BufReader::new(AuthDeadlineStream::new(server, Duration::from_millis(200)));
+ let mut line = String::new();
+ let started = Instant::now();
+ assert!(read_bounded_line(&mut reader, &mut line).is_err());
+ assert!(started.elapsed() < Duration::from_secs(3), "{:?}", started.elapsed());
+ }
+
+ #[test]
+ fn an_authenticated_connection_outlives_the_authentication_deadline() {
+ let (server, mut client) = tcp_pair();
+ let sender = std::thread::spawn(move || {
+ client.write_all(b"one\n").unwrap();
+ std::thread::sleep(Duration::from_millis(500));
+ client.write_all(b"two\n").unwrap();
+ });
+ let mut reader = std::io::BufReader::new(AuthDeadlineStream::new(server, Duration::from_millis(200)));
+ let mut line = String::new();
+ assert_eq!(read_bounded_line(&mut reader, &mut line).unwrap(), LineRead::Line);
+ assert_eq!(line, "one\n");
+ reader.get_mut().authenticated().unwrap();
+ // Sent 300 ms after the deadline: only the idle timeout applies now.
+ assert_eq!(read_bounded_line(&mut reader, &mut line).unwrap(), LineRead::Line);
+ assert_eq!(line, "two\n");
+ sender.join().unwrap();
+ }
+
#[test]
fn connection_limiter_releases_capacity() {
let limiter = ConnectionLimiter::new(1);