mirror of
https://github.com/storytold/craft-launcher.git
synced 2026-12-02 20:22:35 -05:00
Merge pull request #869 from dylanmtaylor/security/single-instance-challenge-response
fix(security): implement mutual challenge-response for single-instance IPC
This commit is contained in:
1 file changed
+232
-99
@@ -26,22 +26,26 @@ use artcraft_launcher_core::version::{self, Version};
|
||||
const PORT: u16 = 47_413;
|
||||
/// What launchers before the version handshake send (and still the answer to an unknown peer).
|
||||
const SHOW: &[u8] = b"artcraft-launcher:show";
|
||||
/// `hello <version> <token>`: a second start introduces itself and proves it is the same OS user.
|
||||
/// `hello <version> <nonce>`: a second start introduces itself with its version and client nonce.
|
||||
const HELLO: &str = "artcraft-launcher:hello ";
|
||||
/// `challenge <nonce> <proof>`: running instance challenges newcomer to prove knowledge of token.
|
||||
const CHALLENGE: &str = "artcraft-launcher:challenge ";
|
||||
/// `auth <proof>`: newcomer's response proving possession of token.
|
||||
const AUTH: &str = "artcraft-launcher:auth ";
|
||||
/// `running <version>`: the first instance's answer.
|
||||
const RUNNING: &str = "artcraft-launcher:running ";
|
||||
/// How long a newer start waits for the old one to quit and free the port.
|
||||
const TAKE_OVER_WITHIN: Duration = Duration::from_secs(10);
|
||||
/// How large a greeting may be, now that it carries a token as well as a version.
|
||||
const MAX_GREETING: usize = 128;
|
||||
/// How large a greeting or challenge-response line may be.
|
||||
const MAX_GREETING: usize = 256;
|
||||
|
||||
/// A per-user secret that proves a hello comes from this OS account.
|
||||
///
|
||||
/// The fixed loopback port is reachable by any local process, so a `hello` alone can't be trusted
|
||||
/// to decide the launcher's lifecycle: another local user could send a newer version and make an
|
||||
/// idle launcher quit (CWE-862). The token lives in the user's own data folder, readable only by
|
||||
/// this account, so a peer that echoes it must be able to read that file — i.e. be the same user.
|
||||
/// It is read once, created on first use with owner-only permissions.
|
||||
/// this account. Mutual challenge-response uses this secret without ever sending it across the wire
|
||||
/// (CWE-522, CWE-287).
|
||||
fn token() -> Option<String> {
|
||||
use std::io::Read;
|
||||
let dir =
|
||||
@@ -153,16 +157,38 @@ pub fn claim(wake: Wake) -> Instance {
|
||||
}
|
||||
}
|
||||
|
||||
fn compute_proof(role: &str, token: &str, client_nonce: &str, server_nonce: &str) -> String {
|
||||
use sha2::{Digest, Sha256};
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(b"artcraft-launcher:auth:v1:");
|
||||
hasher.update(role.as_bytes());
|
||||
hasher.update(b":");
|
||||
hasher.update(token.as_bytes());
|
||||
hasher.update(b":");
|
||||
hasher.update(client_nonce.as_bytes());
|
||||
hasher.update(b":");
|
||||
hasher.update(server_nonce.as_bytes());
|
||||
let hash = hasher.finalize();
|
||||
format!("{hash:x}")
|
||||
}
|
||||
|
||||
fn constant_time_eq(a: &str, b: &str) -> bool {
|
||||
if a.len() != b.len() {
|
||||
return false;
|
||||
}
|
||||
let mut diff = 0u8;
|
||||
for (&x, &y) in a.as_bytes().iter().zip(b.as_bytes()) {
|
||||
diff |= x ^ y;
|
||||
}
|
||||
core::hint::black_box(diff) == 0
|
||||
}
|
||||
|
||||
/// Answers other starts on `listener` until the receiver is dropped.
|
||||
fn listen(listener: TcpListener, ours: Option<Version>, token: Option<String>, wake: Wake) -> Receiver<Request> {
|
||||
let (tx, rx) = channel();
|
||||
std::thread::spawn(move || {
|
||||
for mut stream in listener.incoming().flatten() {
|
||||
let message = read_message(&mut stream);
|
||||
let Some((request, reply)) = answer(&message, ours.as_ref(), token.as_deref()) else { continue };
|
||||
if let Some(reply) = reply {
|
||||
let _ = stream.write_all(reply.as_bytes());
|
||||
}
|
||||
let Some(request) = handle_incoming(&mut stream, ours.as_ref(), token.as_deref()) else { continue };
|
||||
drop(stream);
|
||||
if tx.send(request).is_err() {
|
||||
break;
|
||||
@@ -175,99 +201,159 @@ fn listen(listener: TcpListener, ours: Option<Version>, token: Option<String>, w
|
||||
rx
|
||||
}
|
||||
|
||||
/// Reads a greeting through EOF, at most [`MAX_GREETING`] bytes and one second in total. New
|
||||
/// starts close their write half to delimit the message; older starts keep it open while waiting
|
||||
/// for a reply, so a read timeout also ends their greeting.
|
||||
/// Reads a line or message up to `\n` or EOF, at most [`MAX_GREETING`] bytes and one second in total.
|
||||
fn read_message(stream: &mut TcpStream) -> Vec<u8> {
|
||||
let deadline = Instant::now() + Duration::from_secs(1);
|
||||
let mut message = Vec::new();
|
||||
let mut buf = [0u8; MAX_GREETING];
|
||||
while message.len() < buf.len() {
|
||||
let mut byte = [0u8; 1];
|
||||
while message.len() < MAX_GREETING {
|
||||
let remaining = deadline.saturating_duration_since(Instant::now());
|
||||
if remaining.is_zero() || stream.set_read_timeout(Some(remaining)).is_err() {
|
||||
break;
|
||||
}
|
||||
let available = buf.len() - message.len();
|
||||
let Some(room) = buf.get_mut(..available) else { break };
|
||||
match stream.read(room) {
|
||||
match stream.read(&mut byte) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => {
|
||||
if let Some(bytes) = room.get(..n) {
|
||||
message.extend_from_slice(bytes);
|
||||
Ok(_) => {
|
||||
if byte[0] == b'\n' {
|
||||
break;
|
||||
}
|
||||
message.push(byte[0]);
|
||||
}
|
||||
Err(e) if e.kind() == ErrorKind::Interrupted => continue,
|
||||
Err(_) => break,
|
||||
}
|
||||
}
|
||||
if message.ends_with(b"\r") {
|
||||
message.pop();
|
||||
}
|
||||
message
|
||||
}
|
||||
|
||||
/// The running launcher's side: what `message` asks for, and what to answer.
|
||||
///
|
||||
/// A `Replace` (which can make the launcher quit) is only granted when the greeting carries this
|
||||
/// user's token: the fixed loopback port is reachable by any local account, so an unauthenticated
|
||||
/// peer may bring the window forward (`Show`, harmless) but may not end the launcher (CWE-862).
|
||||
fn answer(message: &[u8], ours: Option<&Version>, token: Option<&str>) -> Option<(Request, Option<String>)> {
|
||||
if message == SHOW {
|
||||
return Some((Request::Show, None));
|
||||
/// The running launcher's side: handles a newcomer's greeting, performing challenge-response
|
||||
/// authentication before authorizing replacement (CWE-287, CWE-522, F-016, F-017).
|
||||
fn handle_incoming(stream: &mut TcpStream, ours: Option<&Version>, token: Option<&str>) -> Option<Request> {
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_secs(1)));
|
||||
let _ = stream.set_write_timeout(Some(Duration::from_secs(1)));
|
||||
let message = read_message(stream);
|
||||
if message.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let rest = std::str::from_utf8(message).ok()?.strip_prefix(HELLO)?;
|
||||
// `hello <version> <token>`; the token is optional (legacy peers omit it).
|
||||
let (theirs, their_token) = match rest.split_once(' ') {
|
||||
Some((v, t)) => (v, Some(t.trim())),
|
||||
None => (rest, None),
|
||||
};
|
||||
let authenticated = match (token, their_token) {
|
||||
(Some(ours_tok), Some(theirs_tok)) => !ours_tok.is_empty() && ours_tok == theirs_tok,
|
||||
if message == SHOW {
|
||||
return Some(Request::Show);
|
||||
}
|
||||
let text = std::str::from_utf8(&message).ok()?;
|
||||
let rest = text.strip_prefix(HELLO)?;
|
||||
let mut parts = rest.split_whitespace();
|
||||
let theirs_str = parts.next()?;
|
||||
let client_nonce = parts.next();
|
||||
let theirs_ver = version::parse(theirs_str);
|
||||
|
||||
let newer = match (&theirs_ver, ours) {
|
||||
(Some(theirs), Some(ours)) => version::is_newer(theirs, ours),
|
||||
_ => false,
|
||||
};
|
||||
let newer = match (version::parse(theirs), ours) {
|
||||
(Some(theirs), Some(ours)) => version::is_newer(&theirs, ours),
|
||||
_ => false,
|
||||
|
||||
let reply_running = format!("{RUNNING}{}\n", ours.map_or_else(|| "unknown".to_string(), ToString::to_string));
|
||||
|
||||
if !newer {
|
||||
let _ = stream.write_all(reply_running.as_bytes());
|
||||
return Some(Request::Show);
|
||||
}
|
||||
|
||||
// Newcomer is newer and asks to replace us.
|
||||
// Mutual challenge-response: require proof of token possession before granting Replace.
|
||||
let Some(ours_token) = token.filter(|t| !t.is_empty()) else {
|
||||
let _ = stream.write_all(reply_running.as_bytes());
|
||||
return Some(Request::Show);
|
||||
};
|
||||
let reply = format!("{RUNNING}{}", ours.map_or_else(|| "unknown".to_string(), ToString::to_string));
|
||||
// Only a newer start from the same user may replace us; anything else just shows the window.
|
||||
let request = if newer && authenticated { Request::Replace } else { Request::Show };
|
||||
Some((request, Some(reply)))
|
||||
|
||||
let Some(client_nonce) = client_nonce else {
|
||||
let _ = stream.write_all(reply_running.as_bytes());
|
||||
return Some(Request::Show);
|
||||
};
|
||||
|
||||
let Some(server_nonce) = fresh_secret() else {
|
||||
let _ = stream.write_all(reply_running.as_bytes());
|
||||
return Some(Request::Show);
|
||||
};
|
||||
|
||||
let server_proof = compute_proof("server", ours_token, client_nonce, &server_nonce);
|
||||
let challenge_msg = format!("{CHALLENGE}{server_nonce} {server_proof}\n");
|
||||
if stream.write_all(challenge_msg.as_bytes()).is_err() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let auth_msg = read_message(stream);
|
||||
let auth_text = std::str::from_utf8(&auth_msg).unwrap_or("");
|
||||
let client_proof = auth_text.strip_prefix(AUTH).map(str::trim).unwrap_or("");
|
||||
let expected_client_proof = compute_proof("client", ours_token, client_nonce, &server_nonce);
|
||||
|
||||
let _ = stream.write_all(reply_running.as_bytes());
|
||||
|
||||
if constant_time_eq(client_proof, &expected_client_proof) { Some(Request::Replace) } else { Some(Request::Show) }
|
||||
}
|
||||
|
||||
/// The new start's side: says hello to whatever holds the port and reads the answer.
|
||||
fn ask(addr: SocketAddr, ours: Option<&Version>, token: Option<&str>) -> std::io::Result<Answer> {
|
||||
let Some(ours) = ours else {
|
||||
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(1))?;
|
||||
// Can't compare without our own version: ask it to show itself, as before.
|
||||
stream.write_all(SHOW)?;
|
||||
return Ok(Answer::Defer);
|
||||
};
|
||||
let greeting = match token {
|
||||
Some(tok) if !tok.is_empty() => format!("{HELLO}{ours} {tok}"),
|
||||
_ => format!("{HELLO}{ours}"),
|
||||
};
|
||||
let answer = ask_once(addr, ours, &greeting)?;
|
||||
// Launchers from before the token handshake (0.1.4 to 0.6.1) try to parse the whole greeting
|
||||
// after `hello ` as a version and hang up when a space + token follows. Retry once without the
|
||||
// token so an upgrade over such a running copy still replaces it.
|
||||
if matches!(answer, Answer::Legacy) && matches!(token, Some(tok) if !tok.is_empty()) {
|
||||
return ask_once(addr, ours, &format!("{HELLO}{ours}"));
|
||||
let answer = ask_once(addr, ours, token, true)?;
|
||||
// Older running copies (0.1.4 to 0.6.1) hang up when a space follows the version.
|
||||
// Retry once without client nonce so an upgrade over such a copy still replaces it.
|
||||
if matches!(answer, Answer::Legacy) {
|
||||
return ask_once(addr, ours, token, false);
|
||||
}
|
||||
Ok(answer)
|
||||
}
|
||||
|
||||
fn ask_once(addr: SocketAddr, ours: &Version, greeting: &str) -> std::io::Result<Answer> {
|
||||
fn ask_once(addr: SocketAddr, ours: &Version, token: Option<&str>, with_nonce: bool) -> std::io::Result<Answer> {
|
||||
let mut stream = TcpStream::connect_timeout(&addr, Duration::from_secs(1))?;
|
||||
stream.write_all(greeting.as_bytes())?;
|
||||
stream.shutdown(std::net::Shutdown::Write)?;
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_secs(2)));
|
||||
let mut reply = Vec::new();
|
||||
match (&mut stream).take(MAX_GREETING as u64).read_to_end(&mut reply) {
|
||||
Ok(_) => {}
|
||||
// An old launcher may reset the connection rather than close it.
|
||||
Err(e) if reply.is_empty() && matches!(e.kind(), ErrorKind::ConnectionReset | ErrorKind::ConnectionAborted) => {}
|
||||
// No answer in time: leave the running one be.
|
||||
Err(_) if reply.is_empty() => return Ok(Answer::Defer),
|
||||
Err(_) => {}
|
||||
let _ = stream.set_write_timeout(Some(Duration::from_secs(1)));
|
||||
|
||||
let client_nonce = if with_nonce { fresh_secret() } else { None };
|
||||
let greeting = match (&client_nonce, token) {
|
||||
(Some(nonce), Some(tok)) if !tok.is_empty() => format!("{HELLO}{ours} {nonce}\n"),
|
||||
_ => format!("{HELLO}{ours}\n"),
|
||||
};
|
||||
stream.write_all(greeting.as_bytes())?;
|
||||
|
||||
let reply = read_message(&mut stream);
|
||||
if reply.is_empty() {
|
||||
return Ok(Answer::Legacy);
|
||||
}
|
||||
|
||||
let reply_str = match std::str::from_utf8(&reply) {
|
||||
Ok(s) => s.trim(),
|
||||
Err(_) => return Ok(Answer::Defer),
|
||||
};
|
||||
|
||||
if let Some(challenge_rest) = reply_str.strip_prefix(CHALLENGE) {
|
||||
let mut parts = challenge_rest.split_whitespace();
|
||||
let server_nonce = parts.next().unwrap_or("");
|
||||
let server_proof = parts.next().unwrap_or("");
|
||||
let (Some(client_nonce), Some(tok)) = (client_nonce.as_deref(), token) else {
|
||||
return Ok(Answer::Defer);
|
||||
};
|
||||
let expected_server_proof = compute_proof("server", tok, client_nonce, server_nonce);
|
||||
if !constant_time_eq(server_proof, &expected_server_proof) {
|
||||
// Server failed to prove it knows the shared token (untrusted peer).
|
||||
// Do NOT disclose client proof; abort immediately.
|
||||
return Ok(Answer::Defer);
|
||||
}
|
||||
|
||||
// Server is authentic. Prove our identity to server:
|
||||
let client_proof = compute_proof("client", tok, client_nonce, server_nonce);
|
||||
let auth_msg = format!("{AUTH}{client_proof}\n");
|
||||
stream.write_all(auth_msg.as_bytes())?;
|
||||
|
||||
let final_reply = read_message(&mut stream);
|
||||
return Ok(verdict(&final_reply, ours));
|
||||
}
|
||||
|
||||
Ok(verdict(&reply, ours))
|
||||
}
|
||||
|
||||
@@ -276,7 +362,8 @@ fn verdict(reply: &[u8], ours: &Version) -> Answer {
|
||||
if reply.is_empty() {
|
||||
return Answer::Legacy;
|
||||
}
|
||||
let running = std::str::from_utf8(reply).ok().and_then(|r| r.strip_prefix(RUNNING)).and_then(version::parse);
|
||||
let trimmed = std::str::from_utf8(reply).ok().map(str::trim);
|
||||
let running = trimmed.and_then(|r| r.strip_prefix(RUNNING)).and_then(version::parse);
|
||||
match running {
|
||||
Some(running) if version::is_newer(ours, &running) => Answer::TakeOver,
|
||||
_ => Answer::Defer,
|
||||
@@ -304,8 +391,6 @@ mod tests {
|
||||
rx.recv_timeout(Duration::from_secs(5)).unwrap()
|
||||
}
|
||||
|
||||
// Issue #29: 0.1.2 started while 0.1.0 sat in the tray, and the 0.1.0 window came up
|
||||
// offering 0.1.1. A newer start must replace the older one, not show it.
|
||||
#[test]
|
||||
fn a_newer_start_replaces_an_older_running_launcher() {
|
||||
let (addr, rx) = primary("0.1.0");
|
||||
@@ -315,12 +400,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_replace_requires_the_same_users_token() {
|
||||
// A local peer on the fixed port with the right (newer) version but no/invalid token can
|
||||
// only bring the window forward, never make the launcher quit (CWE-862).
|
||||
// A local peer on the fixed port with the right (newer) version but invalid token can
|
||||
// only bring the window forward, never make the launcher quit (CWE-862, CWE-287).
|
||||
let (addr, rx) = primary("0.1.0");
|
||||
let mut s = TcpStream::connect(addr).unwrap();
|
||||
s.write_all(format!("{HELLO}9.9.9 not-the-token").as_bytes()).unwrap();
|
||||
s.shutdown(std::net::Shutdown::Write).unwrap();
|
||||
s.write_all(format!("{HELLO}9.9.9 not-the-token\n").as_bytes()).unwrap();
|
||||
let mut reply = Vec::new();
|
||||
s.read_to_end(&mut reply).unwrap();
|
||||
assert_eq!(next(&rx), Request::Show, "an unauthenticated peer must not replace us");
|
||||
@@ -328,27 +412,88 @@ mod tests {
|
||||
// And one with no token at all.
|
||||
let (addr, rx) = primary("0.1.0");
|
||||
let mut s = TcpStream::connect(addr).unwrap();
|
||||
s.write_all(format!("{HELLO}9.9.9").as_bytes()).unwrap();
|
||||
s.shutdown(std::net::Shutdown::Write).unwrap();
|
||||
s.write_all(format!("{HELLO}9.9.9\n").as_bytes()).unwrap();
|
||||
let mut reply = Vec::new();
|
||||
s.read_to_end(&mut reply).unwrap();
|
||||
assert_eq!(next(&rx), Request::Show);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fragmented_greeting_waits_for_the_complete_version() {
|
||||
fn token_is_never_transmitted_over_the_wire() {
|
||||
// F-016: The client must never send the persistent bearer token to an unauthenticated listener.
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let handle = std::thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let mut buf = [0u8; 512];
|
||||
let n = stream.read(&mut buf).unwrap_or(0);
|
||||
buf[..n].to_vec()
|
||||
});
|
||||
|
||||
let secret = "super-secret-persistent-bearer-token";
|
||||
let _ = ask(addr, Some(&v("0.1.2")), Some(secret));
|
||||
let wire_bytes = handle.join().unwrap();
|
||||
let wire_str = String::from_utf8_lossy(&wire_bytes);
|
||||
assert!(!wire_str.contains(secret), "bearer token must never be sent in the clear");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rogue_server_failing_proof_receives_no_client_credentials() {
|
||||
// F-016 / F-017: If the listening process cannot prove it knows the token, client aborts.
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let handle = std::thread::spawn(move || {
|
||||
let (mut stream, _) = listener.accept().unwrap();
|
||||
let _ = read_message(&mut stream);
|
||||
// Rogue server sends fake challenge with forged proof
|
||||
let _ = stream.write_all(b"artcraft-launcher:challenge fake-nonce forged-proof\n");
|
||||
let mut next = [0u8; 128];
|
||||
stream.read(&mut next).unwrap_or(0)
|
||||
});
|
||||
|
||||
let ans = ask(addr, Some(&v("0.1.2")), Some(TOK)).unwrap();
|
||||
assert_eq!(ans, Answer::Defer);
|
||||
let bytes_received = handle.join().unwrap();
|
||||
assert_eq!(bytes_received, 0, "client must immediately disconnect and send no auth proof");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn replaying_an_old_auth_response_is_rejected() {
|
||||
// F-017: Replay attacks across connections must be rejected because server nonces are fresh.
|
||||
let (addr, rx) = primary("0.1.0");
|
||||
|
||||
// Stale proof generated with a different nonce
|
||||
let fake_client_nonce = "1111111111111111111111111111111111111111111111111111111111111111";
|
||||
let fake_server_nonce = "2222222222222222222222222222222222222222222222222222222222222222";
|
||||
let replayed_proof = compute_proof("client", TOK, fake_client_nonce, fake_server_nonce);
|
||||
|
||||
let mut stream = TcpStream::connect(addr).unwrap();
|
||||
stream.write_all(format!("{HELLO}9.9.9 {fake_client_nonce}\n").as_bytes()).unwrap();
|
||||
|
||||
let challenge = read_message(&mut stream);
|
||||
assert!(std::str::from_utf8(&challenge).unwrap().starts_with(CHALLENGE));
|
||||
|
||||
// Replay stale proof
|
||||
stream.write_all(format!("{AUTH}{replayed_proof}\n").as_bytes()).unwrap();
|
||||
|
||||
let reply = read_message(&mut stream);
|
||||
assert!(std::str::from_utf8(&reply).unwrap().starts_with(RUNNING));
|
||||
assert_eq!(next(&rx), Request::Show, "replayed auth proof must not authorize Replace");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fragmented_greeting_waits_for_the_complete_message() {
|
||||
for (running, first, rest, version) in [("0.1.0", "", "0.1.2", "0.1.2"), ("0.1.2", "0.1.1", "0", "0.1.10")] {
|
||||
let (addr, rx) = primary(running);
|
||||
let mut stream = TcpStream::connect(addr).unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
stream.write_all(format!("{HELLO}{first}").as_bytes()).unwrap();
|
||||
assert!(rx.recv_timeout(Duration::from_millis(100)).is_err(), "an incomplete greeting must not show the old launcher");
|
||||
stream.write_all(format!("{rest} {TOK}").as_bytes()).unwrap();
|
||||
stream.shutdown(std::net::Shutdown::Write).unwrap();
|
||||
stream.write_all(format!("{rest}\n").as_bytes()).unwrap();
|
||||
let mut reply = Vec::new();
|
||||
stream.read_to_end(&mut reply).unwrap();
|
||||
assert_eq!(verdict(&reply, &v(version)), Answer::TakeOver);
|
||||
assert_eq!(next(&rx), Request::Replace);
|
||||
assert_eq!(next(&rx), Request::Show);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -357,11 +502,11 @@ mod tests {
|
||||
let (addr, rx) = primary("0.1.0");
|
||||
let mut stream = TcpStream::connect(addr).unwrap();
|
||||
stream.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
|
||||
stream.write_all(format!("{HELLO}0.1.2 {TOK}").as_bytes()).unwrap();
|
||||
stream.write_all(format!("{HELLO}0.1.2\n").as_bytes()).unwrap();
|
||||
let mut reply = Vec::new();
|
||||
stream.read_to_end(&mut reply).unwrap();
|
||||
assert_eq!(verdict(&reply, &v("0.1.2")), Answer::TakeOver);
|
||||
assert_eq!(next(&rx), Request::Replace);
|
||||
assert_eq!(next(&rx), Request::Show);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -408,8 +553,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_running_launcher_from_before_the_handshake_is_recognised() {
|
||||
// What 0.1.0 to 0.1.3 do with a message they don't know: read it and hang up (on both the
|
||||
// initial token-bearing greeting and the tokenless retry).
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let old = std::thread::spawn(move || {
|
||||
@@ -426,7 +569,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_tokenless_retry_replaces_a_running_launcher_from_before_the_token_handshake() {
|
||||
// What 0.1.4 to 0.6.1 do: reject `hello <ver> <tok>` with no reply, then accept `hello <ver>`.
|
||||
let listener = TcpListener::bind((Ipv4Addr::LOCALHOST, 0)).unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let old = std::thread::spawn(move || {
|
||||
@@ -436,7 +578,7 @@ mod tests {
|
||||
if let Some(ver) = std::str::from_utf8(&msg).ok().and_then(|m| m.strip_prefix(HELLO)).and_then(version::parse)
|
||||
&& version::is_newer(&ver, &v("0.6.1"))
|
||||
{
|
||||
let _ = s.write_all(b"artcraft-launcher:running 0.6.1");
|
||||
let _ = s.write_all(b"artcraft-launcher:running 0.6.1\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -455,20 +597,11 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn answers_are_read_defensively() {
|
||||
let tok = Some(TOK);
|
||||
// A newer version replaces us only with a matching token; without it, it just shows.
|
||||
assert_eq!(answer(format!("artcraft-launcher:hello 9.9.9 {TOK}").as_bytes(), Some(&v("0.1.0")), tok).map(|a| a.0), Some(Request::Replace));
|
||||
assert_eq!(answer(b"artcraft-launcher:hello 9.9.9 wrong", Some(&v("0.1.0")), tok).map(|a| a.0), Some(Request::Show));
|
||||
assert_eq!(answer(b"artcraft-launcher:hello 9.9.9", Some(&v("0.1.0")), tok).map(|a| a.0), Some(Request::Show));
|
||||
assert_eq!(answer(b"artcraft-launcher:hello nonsense", Some(&v("0.1.0")), tok).map(|a| a.0), Some(Request::Show));
|
||||
assert_eq!(answer(format!("artcraft-launcher:hello 9.9.9 {TOK}").as_bytes(), None, tok).map(|a| a.0), Some(Request::Show));
|
||||
assert_eq!(answer(b"hello", Some(&v("0.1.0")), tok), None);
|
||||
assert_eq!(answer(&[0xff, 0xfe], Some(&v("0.1.0")), tok), None);
|
||||
assert_eq!(verdict(b"artcraft-launcher:running 0.1.0", &v("0.1.2")), Answer::TakeOver);
|
||||
assert_eq!(verdict(b"artcraft-launcher:running 0.1.2", &v("0.1.2")), Answer::Defer);
|
||||
assert_eq!(verdict(b"artcraft-launcher:running unknown", &v("0.1.2")), Answer::Defer);
|
||||
assert_eq!(verdict(b"garbage", &v("0.1.2")), Answer::Defer);
|
||||
fn verdict_reads_defensively() {
|
||||
assert_eq!(verdict(b"artcraft-launcher:running 0.1.0\n", &v("0.1.2")), Answer::TakeOver);
|
||||
assert_eq!(verdict(b"artcraft-launcher:running 0.1.2\n", &v("0.1.2")), Answer::Defer);
|
||||
assert_eq!(verdict(b"artcraft-launcher:running unknown\n", &v("0.1.2")), Answer::Defer);
|
||||
assert_eq!(verdict(b"garbage\n", &v("0.1.2")), Answer::Defer);
|
||||
assert_eq!(verdict(b"", &v("0.1.2")), Answer::Legacy);
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user