Skip to content

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

Answer a repeat auth with "already authenticated" (#3723)

Fabio Lussi89312de597db
diff --git a/apps/photocraft/src/control_server.rs b/apps/photocraft/src/control_server.rs
index 932e31ee6..b1282419d 100644
--- a/apps/photocraft/src/control_server.rs
+++ b/apps/photocraft/src/control_server.rs
@@ -9,7 +9,7 @@ use std::time::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,
+ 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, timeout_error};
@@ -79,6 +79,12 @@ fn serve(stream: TcpStream, token: &str, tx: Sender<ControlRequest>, ctx: egui::
}
continue;
}
+ if let Some(reply) = repeat_auth_reply(&line) {
+ if write_reply(&mut out, &reply).is_err() || out.flush().is_err() {
+ break;
+ }
+ continue;
+ }
let reply = match serde_json::from_str::<Value>(&line) {
Ok(msg) => {
let id = msg.get("id").cloned().unwrap_or(Value::Null);
@@ -202,4 +208,44 @@ mod tests {
handler.join().unwrap();
server.join().unwrap();
}
+
+ #[test]
+ fn repeat_auth_reports_already_authenticated_without_dispatching() {
+ const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
+ 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();
+ serve(stream, TOKEN, tx, egui::Context::default());
+ });
+ let handler = std::thread::spawn(move || {
+ let req = rx.recv_timeout(Duration::from_secs(5)).unwrap();
+ assert_eq!(req.method, "test.after", "a repeat auth must not reach the UI dispatcher");
+ req.reply.send(json!({"ok": true, "result": "still serving"})).unwrap();
+ });
+ let mut stream = TcpStream::connect(addr).unwrap();
+ stream.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
+ let mut reader = BufReader::new(stream.try_clone().unwrap());
+ let mut line = String::new();
+ for id in ["auth", "again"] {
+ writeln!(stream, "{}", json!({"id": id, "method": "auth", "params": {"token": TOKEN}})).unwrap();
+ line.clear();
+ reader.read_line(&mut line).unwrap();
+ }
+ let again: Value = serde_json::from_str(&line).unwrap();
+ assert_eq!(again["id"], "again");
+ assert_eq!(again["ok"], false);
+ assert_eq!(again["error"], "already authenticated");
+ writeln!(stream, "{}", json!({"id": 9, "method": "test.after"})).unwrap();
+ line.clear();
+ reader.read_line(&mut line).unwrap();
+ let after: Value = serde_json::from_str(&line).unwrap();
+ assert_eq!(after["id"], 9);
+ assert_eq!(after["result"], "still serving");
+ drop(reader);
+ drop(stream);
+ handler.join().unwrap();
+ server.join().unwrap();
+ }
}
diff --git a/crates/automation/src/rpc.rs b/crates/automation/src/rpc.rs
index d513bfa88..875850460 100644
--- a/crates/automation/src/rpc.rs
+++ b/crates/automation/src/rpc.rs
@@ -30,7 +30,7 @@ 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,
+ read_bounded_line, repeat_auth_reply,
};
use crate::{AutomationError, Headless};
@@ -288,7 +288,7 @@ fn serve_tcp_connection(h: &Mutex<Headless>, stream: std::net::TcpStream, token:
LineRead::Line => {}
}
let reply = if authenticated {
- respond(h, &line)
+ repeat_auth_reply(&line).unwrap_or_else(|| respond(h, &line))
} else {
let (reply, ok) = authentication_reply(&line, token);
authenticated = ok;
@@ -780,6 +780,36 @@ mod tests {
assert!(v["result"].as_array().unwrap().iter().any(|m| m == "batch"));
}
+ #[test]
+ fn tcp_repeat_auth_reports_already_authenticated_and_keeps_serving() {
+ use std::io::{BufReader, Write as _};
+ const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
+ let h = Arc::new(Mutex::new(Headless::new()));
+ let (tx, rx) = std::sync::mpsc::channel();
+ std::thread::spawn(move || {
+ let _ = serve_tcp("127.0.0.1:0", h, TOKEN.into(), move |a| tx.send(a).unwrap());
+ });
+ let addr = rx.recv().unwrap();
+ let mut s = std::net::TcpStream::connect(addr).unwrap();
+ let mut reader = BufReader::new(s.try_clone().unwrap());
+ let mut line = String::new();
+ for id in ["auth", "again"] {
+ writeln!(s, r#"{{"id":"{id}","method":"auth","params":{{"token":"{TOKEN}"}}}}"#).unwrap();
+ line.clear();
+ reader.read_line(&mut line).unwrap();
+ }
+ let again: Value = serde_json::from_str(&line).unwrap();
+ assert_eq!(again["id"], "again");
+ assert_eq!(again["ok"], false);
+ assert_eq!(again["error"], "already authenticated");
+ writeln!(s, r#"{{"id":"m","method":"methods"}}"#).unwrap();
+ line.clear();
+ reader.read_line(&mut line).unwrap();
+ let v: Value = serde_json::from_str(&line).unwrap();
+ assert_eq!(v["id"], "m");
+ assert_eq!(v["ok"], true);
+ }
+
#[test]
fn tcp_rejects_requests_before_authentication() {
use std::io::{BufReader, Write as _};
diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs
index 075427c03..4659a3ff1 100644
--- a/crates/automation/src/security.rs
+++ b/crates/automation/src/security.rs
@@ -118,6 +118,18 @@ pub fn authentication_reply(line: &str, expected_token: &str) -> (Value, bool) {
}
}
+/// Answer a repeat `auth` frame on an already authenticated connection. Returns `None` for any
+/// other frame, which the caller dispatches as usual.
+/// Without this, a second `auth` fell through to the method dispatcher as an unknown method.
+pub fn repeat_auth_reply(line: &str) -> Option<Value> {
+ let req: Value = serde_json::from_str(line).ok()?;
+ if req.get("method").and_then(Value::as_str) != Some(AUTH_METHOD) {
+ return None;
+ }
+ let id = req.get("id").cloned().unwrap_or(Value::Null);
+ Some(json!({"id": id, "ok": false, "error": "already authenticated"}))
+}
+
fn read_token_file(path: &Path) -> Result<String, AutomationError> {
let token = std::fs::read_to_string(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?;
let token = token.trim().to_owned();
@@ -294,6 +306,17 @@ mod tests {
assert_eq!(reply["result"]["authenticated"], true);
}
+ #[test]
+ fn repeat_auth_on_an_authenticated_connection_says_so() {
+ let line = json!({"id": 3, "method": AUTH_METHOD, "params": {"token": "anything"}}).to_string();
+ let reply = repeat_auth_reply(&line).unwrap();
+ assert_eq!(reply["id"], 3);
+ assert_eq!(reply["ok"], false);
+ assert_eq!(reply["error"], "already authenticated");
+ assert!(repeat_auth_reply(r#"{"id":4,"method":"methods"}"#).is_none());
+ assert!(repeat_auth_reply("{not json").is_none());
+ }
+
#[test]
fn token_file_round_trips_between_server_and_client() {
let path = std::env::temp_dir().join(format!("photocraft-control-token-{}-{}.txt", std::process::id(), generate_token().unwrap()));
diff --git a/docs/control-protocol.md b/docs/control-protocol.md
index c73a0be6a..0d974c095 100644
--- a/docs/control-protocol.md
+++ b/docs/control-protocol.md
@@ -23,6 +23,8 @@ The first request on every TCP connection must authenticate. No other method is
{"id": "auth", "method": "auth", "params": {"token": "<64 hexadecimal characters>"}}
```
+Authenticate once per connection. A later `auth` frame on the same connection gets `{"ok": false, "error": "already authenticated"}` and the connection keeps serving.
+
After the successful authentication reply, each request is one JSON line:
```json