856f865cf98d
bridge.rs
//! Client for the desktop app's JSON-lines control protocol
//! (`docs/control-protocol.md`): one JSON request per line, replies matched
//! by `id`. Keeps one connection, reconnecting after a failure or a call
//! dropped before its reply โ or before a call, once the connection has been
//! idle long enough that the app (which closes idle control connections after
//! [`IO_TIMEOUT`](crate::security::IO_TIMEOUT)) may already have closed it.
//!
//! Each connection authenticates with the challenge handshake (NV-6): the client connects to
//! the literal loopback address it was given (never a name lookup that may pick another
//! listener) and the server must prove it holds the control token before the client sends its
//! own proof. The token itself is never sent, so a process that took the port gets nothing.
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::atomic::{AtomicU64, Ordering};
use std::time::{Duration, Instant};
use serde_json::{Value, json};
use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader};
use tokio::net::TcpStream;
use tokio::sync::Mutex;
use crate::AutomationError;
use crate::budgets::MAX_RESPONSE_BYTES;
use crate::security::{
AUTH_METHOD, CHALLENGE_METHOD, IO_TIMEOUT, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, is_hex256, proof_matches, validate_token,
};
type Conn = (BufReader<tokio::net::tcp::OwnedReadHalf>, tokio::net::tcp::OwnedWriteHalf);
/// Reconnect before sending when the cached connection has been idle this long: the app
/// drops idle control connections after [`IO_TIMEOUT`], and reconnecting before the send
/// keeps the request out of the "was it applied?" state. The margin covers a request
/// still in flight when the idle clock runs out.
const IDLE_RECONNECT: Duration = IO_TIMEOUT.saturating_sub(Duration::from_secs(5));
/// The default call timeout sits strictly below the app's 60s reply deadline, so this
/// client's error โ not the app's deadline reply, not the caller's own cutoff โ is the
/// one the caller sees.
pub const DEFAULT_CALL_TIMEOUT: Duration = Duration::from_secs(55);
const NO_REPLY_CAUSES: &str =
"the command may still be running, or the app was not drawing frames (display asleep, window fully occluded, or a long operation blocked the frame loop)";
pub struct BridgeClient {
addr: String,
/// Where to connect: `addr` parsed, with `localhost` taken as 127.0.0.1.
socket: SocketAddr,
token: String,
conn: Mutex<Option<(Conn, Instant)>>,
next_id: AtomicU64,
timeout: Duration,
idle_reconnect: Duration,
}
impl BridgeClient {
/// `addr` such as `127.0.0.1:7878`. Only loopback addresses are accepted,
/// matching the server, which binds to loopback only.
pub fn new(addr: impl Into<String>, token: impl Into<String>) -> Result<Self, AutomationError> {
let addr = addr.into();
let token = token.into();
let socket = loopback_socket(&addr)?;
validate_token(&token)?;
Ok(BridgeClient {
addr,
socket,
token: token.to_ascii_lowercase(),
conn: Mutex::new(None),
next_id: AtomicU64::new(1),
timeout: DEFAULT_CALL_TIMEOUT,
idle_reconnect: IDLE_RECONNECT,
})
}
pub fn with_timeout(mut self, t: Duration) -> Self {
self.timeout = t;
self
}
/// Shrink the idle-reconnect threshold; tests use it to run the reconnect path quickly.
pub fn with_idle_reconnect(mut self, t: Duration) -> Self {
self.idle_reconnect = t;
self
}
pub fn addr(&self) -> &str {
&self.addr
}
/// Call a control method; returns its `result` or the app's error. Never resends after
/// a transport failure: the request may have been applied (#1007).
pub async fn call(&self, method: &str, params: Value) -> Result<Value, AutomationError> {
self.dispatch(method, ¶ms, false).await
}
/// [`Self::call`] for a method the caller knows only reads state. A transport failure
/// applied nothing, so one fresh attempt is made on a new connection.
pub async fn call_read(&self, method: &str, params: Value) -> Result<Value, AutomationError> {
self.dispatch(method, ¶ms, true).await
}
async fn dispatch(&self, method: &str, params: &Value, read: bool) -> Result<Value, AutomationError> {
match self.attempt(method, params).await {
Ok(v) => Ok(v),
// A dropped socket or an unsent request applied nothing: safe to retry once,
// and only for a call the caller vouched is a read.
Err(Failure::NotSent(_)) | Err(Failure::Transport(_)) if read => match self.attempt(method, params).await {
Ok(v) => Ok(v),
Err(retry) => Err(self.failure(method, retry, read)),
},
Err(f) => Err(self.failure(method, f, read)),
}
}
/// The message for a failed attempt, worded by what the failure proves.
fn failure(&self, method: &str, f: Failure, read: bool) -> AutomationError {
match f {
Failure::NotSent(e) => AutomationError::Bridge(format!("`{method}` failed: {e}; the request was not sent")),
Failure::Transport(e) => AutomationError::Bridge(format!("`{method}` failed: {e}; operation may have completed; inspect state before retrying")),
Failure::TimedOut(_) => {
let what = if read { "a read may be retried safely" } else { "operation may have completed; inspect state before retrying" };
AutomationError::Bridge(format!("`{method}` timed out after {:?}; {NO_REPLY_CAUSES}; {what}", self.timeout))
}
Failure::Definite(e) => e,
}
}
/// One exchange over one connection, reconnecting first when the cached one may be dead.
async fn attempt(&self, method: &str, params: &Value) -> Result<Value, Failure> {
let mut guard = self.conn.lock().await;
if let Some((_, last_used)) = guard.as_ref()
&& last_used.elapsed() >= self.idle_reconnect
{
// The request below goes to a fresh socket, not one the app may have dropped.
*guard = None;
}
if guard.is_none() {
let s = tokio::time::timeout(Duration::from_secs(5), TcpStream::connect(self.socket))
.await
.map_err(|_| Failure::NotSent(format!("timed out connecting to {}", self.addr)))?
.map_err(|e| {
Failure::NotSent(format!(
"cannot connect to {} ({e}); start the app with `photocraft --control <port>` and matching control credentials",
self.addr
))
})?;
let (r, w) = s.into_split();
let mut conn = (BufReader::new(r), w);
let auth = tokio::time::timeout(Duration::from_secs(5), self.authenticate(&mut conn))
.await
.map_err(|_| Failure::NotSent("control authentication timed out".into()))?
.map_err(|e| Failure::NotSent(e.to_string()))?;
if let Err(e) = auth {
return Err(Failure::Definite(e));
}
*guard = Some((conn, Instant::now()));
}
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
// Out of the cache until answered: a call dropped mid-exchange (a cancelled wait) closes
// its connection, so no later call shares a socket with a half-sent request or a reply
// the app is still working on.
let Some((mut conn, _)) = guard.take() else {
return Err(Failure::NotSent(format!("not connected to {}", self.addr)));
};
let outcome = tokio::time::timeout(self.timeout, exchange(&mut conn, id, method, params)).await;
match outcome {
// An oversized frame leaves unread bytes. Drop this connection and
// report the budget failure without retrying a possibly completed edit.
Ok(Ok(Err(error @ AutomationError::BadRequest(_)))) => Err(Failure::Definite(error)),
Ok(Ok(Ok(v))) => {
*guard = Some((conn, Instant::now()));
Ok(v)
}
Ok(Ok(Err(e))) => {
// The app answered: the operation did not apply โ except the app's own
// deadline reply, which fires while the command may still be running.
*guard = Some((conn, Instant::now()));
Err(Failure::Definite(e))
}
// A failed write or lost reply does not prove the edit was not applied.
// Reconnect on the next call; only a vouched read may resend (#1007).
Ok(Err(e)) => Err(Failure::Transport(e.to_string())),
Err(_) => Err(Failure::TimedOut(())),
}
}
}
impl BridgeClient {
/// Challenge authentication on a fresh connection. The server must prove it holds the token
/// before the client sends its own proof; the token itself is never sent (NV-6).
/// Outer `Err` = transport failure; inner = refused.
async fn authenticate(&self, conn: &mut Conn) -> Result<Result<(), AutomationError>, AutomationError> {
let client_nonce = generate_nonce()?;
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
let challenge = match exchange(conn, id, CHALLENGE_METHOD, &json!({"clientNonce": client_nonce})).await? {
Ok(challenge) => challenge,
Err(AutomationError::App(e)) => {
return Ok(Err(AutomationError::Bridge(format!(
"{} refused challenge authentication ({e}): it is not PhotoCraft, or a PhotoCraft too old to support it (update the app); the control token was not sent",
self.addr
))));
}
Err(e) => return Ok(Err(e)),
};
let field = |key: &str| challenge.get(key).and_then(Value::as_str).filter(|v| is_hex256(v));
let server_nonce = match (field("serverNonce"), field("serverProof")) {
(Some(nonce), Some(proof)) if proof_matches(&self.token, ProofRole::Server, &client_nonce, nonce, proof) => nonce,
_ => {
return Ok(Err(AutomationError::Bridge(format!(
"{} did not prove it holds this control token: the token does not match the app's, or the listener is not that PhotoCraft app; the control token was not sent",
self.addr
))));
}
};
let proof = handshake_proof(&self.token, ProofRole::Client, &client_nonce, server_nonce)?;
let id = self.next_id.fetch_add(1, Ordering::Relaxed);
Ok(exchange(conn, id, AUTH_METHOD, &json!({"proof": proof})).await?.map(|_| ()))
}
}
/// The literal loopback socket address for `addr`: `127.0.0.1:<port>` or `[::1]:<port>`, with
/// `localhost:<port>` meaning 127.0.0.1, the address the app binds. The name is never looked up,
/// since a lookup may return `[::1]` first and reach another process listening there (NV-6).
fn loopback_socket(addr: &str) -> Result<SocketAddr, AutomationError> {
let refuse = || AutomationError::BadRequest(format!("bridge address must be loopback `127.0.0.1:<port>` or `[::1]:<port>`, got `{addr}`"));
let socket = match addr.strip_prefix("localhost:") {
Some(port) => SocketAddr::from((Ipv4Addr::LOCALHOST, port.parse::<u16>().map_err(|_| refuse())?)),
None => addr.parse::<SocketAddr>().map_err(|_| refuse())?,
};
if socket.ip() == IpAddr::V4(Ipv4Addr::LOCALHOST) || socket.ip() == IpAddr::V6(Ipv6Addr::LOCALHOST) { Ok(socket) } else { Err(refuse()) }
}
/// How a single attempt failed, deciding the retry and the wording above.
enum Failure {
/// The connection could not be established or authenticated: nothing was sent.
NotSent(String),
/// The request was sent and the reply was lost: the outcome is uncertain.
Transport(String),
/// The call's own timeout elapsed. Retrying would only double the wait.
TimedOut(()),
/// The app answered (ok or error) or the request was refused before it was sent.
Definite(AutomationError),
}
/// Outer `Err` = transport failure with an uncertain outcome; inner = app-level result.
async fn exchange(conn: &mut Conn, id: u64, method: &str, params: &Value) -> Result<Result<Value, AutomationError>, AutomationError> {
let mut line = serde_json::to_string(&json!({"id": id, "method": method, "params": params})).map_err(|e| AutomationError::Other(e.to_string()))?;
line.push('\n');
if line.len() > MAX_REQUEST_BYTES {
return Ok(Err(AutomationError::BadRequest(format!("request is {} bytes; maximum is {MAX_REQUEST_BYTES}", line.len()))));
}
let io = |e: std::io::Error| AutomationError::Bridge(e.to_string());
conn.1.write_all(line.as_bytes()).await.map_err(io)?;
conn.1.flush().await.map_err(io)?;
let mut buf = Vec::new();
loop {
buf.clear();
// Read raw bytes so truncation inside a UTF-8 character still reports the
// budget error instead of a decoding/transport error.
let n = (&mut conn.0).take((MAX_RESPONSE_BYTES + 1) as u64).read_until(b'\n', &mut buf).await.map_err(io)?;
if n > MAX_RESPONSE_BYTES {
return Ok(Err(AutomationError::BadRequest(format!("bridge response exceeds {MAX_RESPONSE_BYTES} bytes; operation may have completed"))));
}
if n == 0 {
return Err(AutomationError::Bridge("connection closed by the app".into()));
}
let Ok(v) = serde_json::from_slice::<Value>(&buf) else {
continue;
};
if v.get("id").and_then(Value::as_u64) != Some(id) {
continue; // stale reply from an earlier, timed-out request
}
return Ok(reply_result(&v));
}
}
/// An app reply as the caller's result. A failed reply can still carry a `result`: a cancelled
/// Batch lists the outputs it already wrote, so the error keeps it rather than dropping it.
fn reply_result(v: &Value) -> Result<Value, AutomationError> {
if v.get("ok").and_then(Value::as_bool) == Some(true) {
return Ok(v.get("result").cloned().unwrap_or(Value::Null));
}
let error = v.get("error").and_then(Value::as_str).unwrap_or("unknown error");
Err(AutomationError::App(match v.get("result") {
Some(result) if !result.is_null() => format!("{error}; partial result: {result}"),
_ => error.to_owned(),
}))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_failed_reply_keeps_its_partial_result() {
assert_eq!(reply_result(&json!({"ok": true, "result": {"files": ["a.png"]}})).unwrap(), json!({"files": ["a.png"]}));
let Err(AutomationError::App(message)) = reply_result(&json!({"ok": false, "error": "cancelled", "result": {"files": ["a.png"], "cancelled": true}}))
else {
panic!("a failed reply is an app error")
};
assert!(message.starts_with("cancelled; partial result: ") && message.contains("a.png"), "{message}");
let Err(AutomationError::App(message)) = reply_result(&json!({"ok": false, "error": "cancelled"})) else { panic!("a failed reply is an app error") };
assert_eq!(message, "cancelled");
}
#[test]
fn the_call_timeout_stays_below_the_app_reply_deadline() {
// At or above the app's 60s deadline, callers would see their own cutoff first.
assert!(DEFAULT_CALL_TIMEOUT < Duration::from_secs(60));
}
/// NV-6: `localhost` is the IPv4 loopback the app binds, never a name lookup.
#[test]
fn bridge_addresses_are_literal_loopback_sockets() {
assert_eq!(loopback_socket("localhost:7878").unwrap(), SocketAddr::from((Ipv4Addr::LOCALHOST, 7878)));
assert_eq!(loopback_socket("127.0.0.1:7878").unwrap(), SocketAddr::from((Ipv4Addr::LOCALHOST, 7878)));
assert_eq!(loopback_socket("[::1]:7878").unwrap(), SocketAddr::from((Ipv6Addr::LOCALHOST, 7878)));
for bad in ["10.0.0.5:7878", "127.0.0.2:7878", "localhost", "localhost:", "localhost:99999", "::1:7878", "example.com:7878", "127.0.0.1"] {
assert!(loopback_socket(bad).is_err(), "{bad}");
}
}
#[test]
fn idle_reconnect_stays_below_the_app_idle_cutoff() {
// Reconnecting later than IO_TIMEOUT would send into a socket the app dropped.
assert!(IDLE_RECONNECT < IO_TIMEOUT);
}
}
No file is open. Choose one in the tree, or press Ctrl+O (โO on a Mac) to find one by name.
Syntax highlighting could not load. The unmodified read-only text remains available above.