//! Shared parser, fixture, and JSONL helpers for the scripted peer harness. #![allow(clippy::missing_errors_doc)] use std::{ fmt::Write as _, net::SocketAddr, path::{Path, PathBuf}, time::Duration, }; use eyre::{Context, OptionExt}; use lanspread_peer::{ CallToPlayLocalIntent, PeerEndpoint, PeerId, ScopedProcess, UnpackFuture, Unpacker, }; use serde::Serialize; use serde_json::{Value, json}; use tokio_util::sync::CancellationToken; pub const DEFAULT_FIXTURE_VERSION: &str = "20250101"; const EXTERNAL_UNRAR_CAPTURE_LIMIT: usize = 64 * 1024; #[derive(Debug, Clone, PartialEq, Eq)] pub struct CommandEnvelope { pub request_id: Option, pub command: CliCommand, } #[derive(Debug, Clone, PartialEq, Eq)] pub enum CliCommand { Status, ListPeers, ListGames, ListCallToPlay, PublishCallToPlay { intent: CallToPlayLocalIntent, }, SetCallToPlayDisplayName { display_name: String, }, SetGameDir { path: PathBuf, }, Download { game_id: String, install_after_download: bool, }, StreamInstall { game_id: String, account_name: Option, language: Option, persona_name: Option, }, CancelDownload { game_id: String, }, Install { game_id: String, }, Uninstall { game_id: String, }, Play { game_id: String, username: String, language: Option, }, WaitPeers { count: usize, timeout: Duration, }, Connect { endpoint: PeerEndpoint, }, Shutdown, } impl CliCommand { #[must_use] pub fn name(&self) -> &'static str { match self { Self::Status => "status", Self::ListPeers => "list-peers", Self::ListGames => "list-games", Self::ListCallToPlay => "list-call-to-play", Self::PublishCallToPlay { .. } => "publish-call-to-play", Self::SetCallToPlayDisplayName { .. } => "set-call-to-play-display-name", Self::SetGameDir { .. } => "set-game-dir", Self::Download { .. } => "download", Self::StreamInstall { .. } => "stream-install", Self::CancelDownload { .. } => "cancel-download", Self::Install { .. } => "install", Self::Uninstall { .. } => "uninstall", Self::Play { .. } => "play", Self::WaitPeers { .. } => "wait-peers", Self::Connect { .. } => "connect", Self::Shutdown => "shutdown", } } } pub fn parse_command_line(line: &str) -> eyre::Result { let value = serde_json::from_str::(line).wrap_err("command must be a JSON object")?; parse_command_value(&value) } pub fn parse_command_value(value: &Value) -> eyre::Result { let object = value .as_object() .ok_or_eyre("command must be a JSON object")?; let request_id = object.get("id").cloned(); let command_name = object .get("cmd") .or_else(|| object.get("command")) .and_then(Value::as_str) .ok_or_eyre("command object must include a string cmd")?; let command_name = command_name.replace('_', "-"); let command = match command_name.as_str() { "status" => CliCommand::Status, "list-peers" => CliCommand::ListPeers, "list-games" => CliCommand::ListGames, "list-call-to-play" => CliCommand::ListCallToPlay, "publish-call-to-play" => CliCommand::PublishCallToPlay { intent: serde_json::from_value( object .get("intent") .cloned() .ok_or_eyre("publish-call-to-play must include intent")?, ) .wrap_err("invalid Call to Play intent")?, }, "set-call-to-play-display-name" => CliCommand::SetCallToPlayDisplayName { display_name: required_str(object, "display_name")?, }, "set-game-dir" => CliCommand::SetGameDir { path: PathBuf::from(required_str(object, "path")?), }, "download" => CliCommand::Download { game_id: game_id(object)?, install_after_download: install_after_download(object)?, }, "stream-install" => CliCommand::StreamInstall { game_id: game_id(object)?, account_name: optional_str(object, "account_name")?, language: optional_str(object, "language")?, persona_name: optional_str(object, "persona_name")?, }, "cancel-download" => CliCommand::CancelDownload { game_id: game_id(object)?, }, "install" => CliCommand::Install { game_id: game_id(object)?, }, "uninstall" => CliCommand::Uninstall { game_id: game_id(object)?, }, "play" => CliCommand::Play { game_id: game_id(object)?, username: required_str(object, "username")?, language: object .get("language") .and_then(Value::as_str) .map(ToOwned::to_owned), }, "wait-peers" => CliCommand::WaitPeers { count: required_u64(object, "count")? .try_into() .wrap_err("count does not fit in usize")?, timeout: Duration::from_millis(required_u64(object, "timeout_ms")?), }, "connect" | "direct-connect" => { let peer_id = required_str(object, "peer_id")? .parse::() .wrap_err("peer_id is not a canonical peer ID")?; let addr = required_str(object, "addr")? .parse::() .wrap_err("addr must be a socket address like 127.0.0.1:12345")?; CliCommand::Connect { endpoint: PeerEndpoint::new(peer_id, addr), } } "shutdown" => CliCommand::Shutdown, other => eyre::bail!("unknown command: {other}"), }; Ok(CommandEnvelope { request_id, command, }) } fn required_str( object: &serde_json::Map, field: &'static str, ) -> eyre::Result { object .get(field) .and_then(Value::as_str) .map(ToOwned::to_owned) .ok_or_else(|| eyre::eyre!("missing string field {field}")) } fn optional_str( object: &serde_json::Map, field: &'static str, ) -> eyre::Result> { object .get(field) .map(|value| { value .as_str() .map(ToOwned::to_owned) .ok_or_else(|| eyre::eyre!("{field} must be a string when provided")) }) .transpose() } fn required_u64(object: &serde_json::Map, field: &'static str) -> eyre::Result { object .get(field) .and_then(Value::as_u64) .ok_or_else(|| eyre::eyre!("missing integer field {field}")) } fn game_id(object: &serde_json::Map) -> eyre::Result { object .get("game_id") .or_else(|| object.get("game")) .and_then(Value::as_str) .map(ToOwned::to_owned) .ok_or_eyre("game commands must include string game_id") } fn install_after_download(object: &serde_json::Map) -> eyre::Result { if let Some(value) = object.get("install") { return value .as_bool() .ok_or_eyre("install must be boolean when provided"); } if let Some(value) = object.get("no_install") { return value .as_bool() .map(|no_install| !no_install) .ok_or_eyre("no_install must be boolean when provided"); } Ok(true) } #[derive(Debug, Clone, PartialEq, Eq, Serialize)] pub struct FixtureSeed { pub game_id: String, pub game_root: PathBuf, pub archive: PathBuf, } pub fn seed_fixture_game(game_dir: &Path, fixture_name: &str) -> eyre::Result { let game_id = fixture_name.to_string(); let game_root = game_dir.join(&game_id); std::fs::create_dir_all(&game_root)?; let version_path = game_root.join("version.ini"); std::fs::write(version_path, DEFAULT_FIXTURE_VERSION.as_bytes())?; let archive = game_root.join(format!("{game_id}.eti")); std::fs::write( &archive, format!("fixture archive for {game_id}\n").as_bytes(), )?; Ok(FixtureSeed { game_id, game_root, archive, }) } pub struct FixtureUnpacker; impl Unpacker for FixtureUnpacker { fn unpack<'a>( &'a self, archive: &'a Path, dest: &'a Path, cancel_token: CancellationToken, ) -> UnpackFuture<'a> { Box::pin(async move { if cancel_token.is_cancelled() { eyre::bail!("fixture extraction for {} was cancelled", archive.display()); } // These fixture files are deliberately tiny. Keep each operation // lexical: selecting against Tokio's filesystem helpers could drop // their futures while blocking-pool work still touches staging. std::fs::create_dir_all(dest)?; if cancel_token.is_cancelled() { eyre::bail!("fixture extraction for {} was cancelled", archive.display()); } let payload = std::fs::read(archive)?; if cancel_token.is_cancelled() { eyre::bail!("fixture extraction for {} was cancelled", archive.display()); } std::fs::write(dest.join("fixture-payload.txt"), payload)?; Ok(()) }) } } pub struct ExternalUnrarUnpacker { program: PathBuf, } impl ExternalUnrarUnpacker { #[must_use] pub fn new(program: PathBuf) -> Self { Self { program } } } impl Unpacker for ExternalUnrarUnpacker { fn unpack<'a>( &'a self, archive: &'a Path, dest: &'a Path, cancel_token: CancellationToken, ) -> UnpackFuture<'a> { Box::pin(async move { if cancel_token.is_cancelled() { eyre::bail!("unrar extraction for {} was cancelled", archive.display()); } // Directory creation is small and synchronous; keeping it lexical // prevents a dropped Tokio fs future from outliving rollback. std::fs::create_dir_all(dest)?; if cancel_token.is_cancelled() { eyre::bail!("unrar extraction for {} was cancelled", archive.display()); } let process = ScopedProcess::spawn( &self.program, [ std::ffi::OsString::from("x"), std::ffi::OsString::from("-o+"), std::ffi::OsString::from("-p-"), // Skip symbolic links inside the archive; the install // transaction also audits the extracted tree for links. std::ffi::OsString::from("-ol-"), archive.as_os_str().to_owned(), dest.as_os_str().to_owned(), ], &cancel_token, EXTERNAL_UNRAR_CAPTURE_LIMIT, )?; let output = process.wait().await?; if !output.status.success() { eyre::bail!( "unrar failed for {} with status {}: {}", archive.display(), output.status, format_captured_process_output( &output.stderr, output.stderr_truncated, "stderr" ) ); } Ok(()) }) } } fn format_captured_process_output(bytes: &[u8], truncated: bool, stream: &str) -> String { let mut output = String::from_utf8_lossy(bytes).into_owned(); if truncated { let _ = write!(output, "\n[{stream} truncated]"); } output } pub fn result_line(id: &Option, command: &str, data: Value) -> eyre::Result { output_line(json!({ "type": "result", "id": id, "command": command, "ok": true, "data": data, })) } pub fn error_line(id: &Option, command: Option<&str>, error: &str) -> eyre::Result { output_line(json!({ "type": "error", "id": id, "command": command, "error": error, })) } pub fn event_line(event: &str, data: Value) -> eyre::Result { output_line(json!({ "type": "event", "event": event, "data": data, })) } fn output_line(value: Value) -> eyre::Result { serde_json::to_string(&value).wrap_err("failed to serialize JSONL output") } #[cfg(test)] mod tests { #[cfg(unix)] use std::os::unix::fs::PermissionsExt as _; use std::sync::Arc; use super::*; struct TempDir(PathBuf); impl TempDir { fn new(name: &str) -> Self { let path = std::env::temp_dir().join(format!( "{name}-{}", std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .expect("system clock should be after unix epoch") .as_nanos() )); std::fs::create_dir_all(&path).expect("temp dir should be created"); Self(path) } fn path(&self) -> &Path { &self.0 } } impl Drop for TempDir { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } #[test] fn parses_download_command_with_correlation_id() { let parsed = parse_command_line( r#"{"id":"req-1","cmd":"download","game_id":"fixture-one","install":false}"#, ) .expect("command should parse"); assert_eq!(parsed.request_id, Some(json!("req-1"))); assert_eq!( parsed.command, CliCommand::Download { game_id: "fixture-one".to_string(), install_after_download: false, } ); } #[test] fn formats_result_lines() { let line = result_line(&Some(json!(7)), "status", json!({"peer_count": 0})) .expect("line should serialize"); let parsed = serde_json::from_str::(&line).expect("line should be json"); assert_eq!(parsed["type"], "result"); assert_eq!(parsed["id"], 7); assert_eq!(parsed["data"]["peer_count"], 0); } #[test] fn captured_process_output_marks_truncation() { assert_eq!( format_captured_process_output(b"partial", true, "stderr"), "partial\n[stderr truncated]" ); } #[test] fn parses_stream_install_command() { let parsed = parse_command_line(r#"{"cmd":"stream-install","game_id":"cnctw"}"#) .expect("command should parse"); assert_eq!( parsed.command, CliCommand::StreamInstall { game_id: "cnctw".to_string(), account_name: None, language: None, persona_name: None, } ); } #[test] fn parses_optional_stream_install_settings_without_sanitizing_them() { let parsed = parse_command_line( r#"{"cmd":"stream-install","game_id":"cnctw","account_name":" Alice% ","language":"DE","persona_name":" Player% "}"#, ) .expect("command should parse"); assert_eq!( parsed.command, CliCommand::StreamInstall { game_id: "cnctw".to_string(), account_name: Some(" Alice% ".to_string()), language: Some("DE".to_string()), persona_name: Some(" Player% ".to_string()), } ); } #[test] fn parses_cancel_download_command() { let parsed = parse_command_line(r#"{"cmd":"cancel-download","game_id":"cnctw"}"#) .expect("command should parse"); assert_eq!( parsed.command, CliCommand::CancelDownload { game_id: "cnctw".to_string(), } ); } #[test] fn parses_connect_as_an_authenticated_peer_endpoint() { let parsed = parse_command_line( r#"{"cmd":"connect","peer_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","addr":"127.0.0.1:34567"}"#, ) .expect("authenticated connect command should parse"); assert_eq!( parsed.command, CliCommand::Connect { endpoint: PeerEndpoint::new( PeerId::from_bytes([0; 32]), "127.0.0.1:34567" .parse() .expect("test socket address should parse"), ), } ); } #[test] fn rejects_address_only_connect() { let error = parse_command_line(r#"{"cmd":"connect","addr":"127.0.0.1:34567"}"#) .expect_err("connect must require an authenticated peer identity"); assert!(error.to_string().contains("missing string field peer_id")); } #[test] fn rejects_noncanonical_connect_peer_id() { let error = parse_command_line( r#"{"cmd":"connect","peer_id":"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","addr":"127.0.0.1:34567"}"#, ) .expect_err("connect must reject noncanonical peer IDs"); assert!(error.to_string().contains("canonical peer ID")); } #[test] fn parses_intent_only_call_to_play_command() { let parsed = parse_command_line( r#"{"cmd":"publish-call-to-play","intent":{"call_id":null,"action":{"Create":{"game_id":"game-1","max_players":4,"scheduled_for":null,"deadline":61000}}}}"#, ) .expect("command should parse"); let CliCommand::PublishCallToPlay { intent } = parsed.command else { panic!("expected PublishCallToPlay"); }; assert!(intent.call_id.is_none()); assert!(matches!( intent.action, lanspread_peer::CallToPlayLocalAction::Create { game_id, max_players: 4, scheduled_for: None, deadline: 61_000, } if game_id == "game-1" )); } #[test] fn parses_existing_call_rsvp_and_chat_intents_used_by_late_join_scenarios() { let call_id = format!("{}.{}", "a".repeat(52), "ab".repeat(16)); let rsvp = parse_command_line(&format!( r#"{{"cmd":"publish-call-to-play","intent":{{"call_id":"{call_id}","action":"Rsvp"}}}}"#, )) .expect("RSVP intent should parse"); let chat = parse_command_line(&format!( r#"{{"cmd":"publish-call-to-play","intent":{{"call_id":"{call_id}","action":{{"SendMessage":{{"text":"I am in"}}}}}}}}"#, )) .expect("chat intent should parse"); let CliCommand::PublishCallToPlay { intent: rsvp } = rsvp.command else { panic!("expected RSVP PublishCallToPlay"); }; let CliCommand::PublishCallToPlay { intent: chat } = chat.command else { panic!("expected chat PublishCallToPlay"); }; assert_eq!(rsvp.call_id, chat.call_id); assert!(matches!( rsvp.action, lanspread_peer::CallToPlayLocalAction::Rsvp )); assert!(matches!( chat.action, lanspread_peer::CallToPlayLocalAction::SendMessage { text } if text == "I am in" )); } #[test] fn rejects_client_authored_call_to_play_event_fields() { let error = parse_command_line( r#"{"cmd":"publish-call-to-play","intent":{"call_id":null,"id":"event-1","at":1000,"action":{"Rsvp":null}}}"#, ) .expect_err("client-authored event identity and time must be rejected"); assert!(error.to_string().contains("invalid Call to Play intent")); } #[tokio::test] async fn fixture_unpacker_creates_install_payload() { let temp = TempDir::new("lanspread-peer-cli-fixture"); let seed = seed_fixture_game(temp.path(), "fixture-one").expect("fixture should seed"); let dest = temp.path().join("staging"); Arc::new(FixtureUnpacker) .unpack(&seed.archive, &dest, CancellationToken::new()) .await .expect("fixture archive should unpack"); let payload = std::fs::read_to_string(dest.join("fixture-payload.txt")) .expect("payload should be written"); assert!(payload.contains("fixture-one")); } #[cfg(unix)] fn controlled_unrar(temp: &TempDir) -> (Arc, PathBuf, PathBuf) { let program = temp.path().join("controlled-unrar"); std::fs::write( &program, r#"#!/bin/sh set -eu [ "$3" = "-p-" ] [ "$4" = "-ol-" ] dest=$6 printf '%s' "$$" > "$dest/child.pid" printf 'started' > "$dest/started" while [ ! -e "$dest/release" ]; do :; done printf 'late' > "$dest/late-canary" "#, ) .expect("controlled unrar should be written"); let mut permissions = std::fs::metadata(&program) .expect("controlled unrar metadata should be readable") .permissions(); permissions.set_mode(0o700); std::fs::set_permissions(&program, permissions) .expect("controlled unrar should be executable"); let archive = temp.path().join("archive.eti"); std::fs::write(&archive, b"fixture").expect("archive should be written"); let destination = temp.path().join("destination"); ( Arc::new(ExternalUnrarUnpacker::new(program)), archive, destination, ) } #[cfg(unix)] async fn wait_for_path(path: &Path) { tokio::time::timeout(std::time::Duration::from_secs(2), async { while !path.exists() { tokio::time::sleep(std::time::Duration::from_millis(5)).await; } }) .await .expect("controlled child marker should appear"); } #[cfg(target_os = "linux")] async fn wait_for_process_exit(pid: u32) { let process = PathBuf::from(format!("/proc/{pid}")); tokio::time::timeout(std::time::Duration::from_secs(2), async { while process.exists() { tokio::time::sleep(std::time::Duration::from_millis(5)).await; } }) .await .expect("controlled child should no longer exist"); } #[cfg(target_os = "linux")] fn controlled_child_pid(destination: &Path) -> u32 { std::fs::read_to_string(destination.join("child.pid")) .expect("controlled child pid should be readable") .parse() .expect("controlled child pid should be numeric") } #[cfg(unix)] #[tokio::test] async fn external_unrar_cancellation_kills_and_reaps_before_return() { let temp = TempDir::new("lanspread-peer-cli-unrar-cancel"); let (unpacker, archive, destination) = controlled_unrar(&temp); let cancel_token = CancellationToken::new(); let task_cancel_token = cancel_token.clone(); let task_destination = destination.clone(); let task = tokio::spawn(async move { unpacker .unpack(&archive, &task_destination, task_cancel_token) .await }); wait_for_path(&destination.join("started")).await; #[cfg(target_os = "linux")] let pid = controlled_child_pid(&destination); cancel_token.cancel(); let error = tokio::time::timeout(std::time::Duration::from_secs(2), task) .await .expect("cancelled unpack should settle") .expect("unpack task should not panic") .expect_err("cancelled unpack should fail"); assert!(error.to_string().contains("cancelled")); #[cfg(target_os = "linux")] wait_for_process_exit(pid).await; std::fs::write(destination.join("release"), b"").expect("release marker should be written"); tokio::time::sleep(std::time::Duration::from_millis(25)).await; assert!(!destination.join("late-canary").exists()); } #[cfg(unix)] #[tokio::test] async fn dropping_external_unrar_future_kills_child() { let temp = TempDir::new("lanspread-peer-cli-unrar-drop"); let (unpacker, archive, destination) = controlled_unrar(&temp); let task_destination = destination.clone(); let task = tokio::spawn(async move { unpacker .unpack(&archive, &task_destination, CancellationToken::new()) .await }); wait_for_path(&destination.join("started")).await; #[cfg(target_os = "linux")] let pid = controlled_child_pid(&destination); task.abort(); task.await .expect_err("aborted unpack task should be cancelled"); #[cfg(target_os = "linux")] wait_for_process_exit(pid).await; std::fs::write(destination.join("release"), b"").expect("release marker should be written"); tokio::time::sleep(std::time::Duration::from_millis(25)).await; assert!(!destination.join("late-canary").exists()); } }