//! Offline end-to-end smoke of the real binary over stdio (no network): identity lifecycle, //! UID stability across rename and restart, instance lock, export/import CLI, error surfacing. use std::io::{BufRead, BufReader, Write}; use std::path::{Path, PathBuf}; use std::process::{Child, ChildStdin, Command, Stdio}; use std::sync::mpsc; use std::time::Duration; use serde_json::{json, Value}; const BIN: &str = env!("CARGO_BIN_EXE_teamspeach-core"); struct TempDir(PathBuf); impl TempDir { fn new(tag: &str) -> Self { let p = std::env::temp_dir().join(format!("teamspeach-smoke-{tag}-{}", std::process::id())); let _ = std::fs::remove_dir_all(&p); std::fs::create_dir_all(&p).unwrap(); Self(p) } } impl Drop for TempDir { fn drop(&mut self) { let _ = std::fs::remove_dir_all(&self.0); } } struct Core { child: Child, stdin: ChildStdin, lines: mpsc::Receiver, /// Every stdout line, for secret-leak checks. transcript: std::sync::Arc>, } impl Core { fn start(dir: &Path) -> Self { let mut child = Command::new(BIN) .arg("--data-dir") .arg(dir) .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()) .spawn() .expect("spawn core"); let stdin = child.stdin.take().unwrap(); let stdout = child.stdout.take().unwrap(); let (tx, lines) = mpsc::channel(); let transcript = std::sync::Arc::new(std::sync::Mutex::new(String::new())); let t = transcript.clone(); std::thread::spawn(move || { for line in BufReader::new(stdout).lines() { let line = line.unwrap(); t.lock().unwrap().push_str(&line); let v: Value = serde_json::from_str(&line).unwrap_or_else(|e| panic!("stdout is not JSON ({e}): {line}")); if tx.send(v).is_err() { break; } } }); let mut core = Self { child, stdin, lines, transcript }; let ready = core.next(); assert_eq!(ready["event"], "ready"); assert_eq!(ready["protocol"], 1); core } fn next(&mut self) -> Value { self.lines.recv_timeout(Duration::from_secs(20)).expect("core output") } fn send(&mut self, v: Value) { writeln!(self.stdin, "{v}").unwrap(); self.stdin.flush().unwrap(); } /// Send a request and return its response, collecting events seen meanwhile. fn request(&mut self, id: &str, cmd: &str, args: Value) -> (Value, Vec) { self.send(json!({ "id": id, "cmd": cmd, "args": args })); let mut events = Vec::new(); loop { let v = self.next(); if v.get("id").and_then(Value::as_str) == Some(id) { return (v, events); } events.push(v); } } fn shutdown(mut self) { let (resp, _) = self.request("bye", "shutdown", json!({})); assert_eq!(resp["ok"], true); let status = self.child.wait().unwrap(); assert!(status.success(), "exit status {status:?}"); } } fn cli(args: &[&std::ffi::OsStr]) -> (i32, Value) { let out = Command::new(BIN).args(args).output().unwrap(); let line = String::from_utf8(out.stdout).unwrap(); let v = if line.trim().is_empty() { Value::Null } else { serde_json::from_str(line.trim()).unwrap() }; (out.status.code().unwrap(), v) } #[test] fn invalid_recording_commands_leave_destination_and_status_untouched() { let profile = TempDir::new("recording-protocol"); let destination = profile.0.join("takes"); std::fs::create_dir(&destination).unwrap(); let existing = destination.join("existing.wav"); std::fs::write(&existing, b"previous take").unwrap(); let mut core = Core::start(&profile.0); for (cmd, args) in [ ("recording_start", json!({"directory":destination,"mode":4})), ("recording_stop", json!({"force":true})), ("recording_pause", json!({"track_id":0})), ("recording_resume", json!({"track_id":0})), ("recording_status", json!({"session":0})), ("recording_info", json!({"track_id":0})), ("recording_waveform", json!({"track_id":0,"from_bucket":-1})), ] { let (reply, events) = core.request(cmd, cmd, args); assert_eq!(reply["error"]["code"], "bad_request", "{cmd}: {reply}"); assert!(!events.iter().any(|e| e["event"].as_str().is_some_and(|s| s.starts_with("recording_"))), "{cmd}: {events:?}"); } let (reply, _) = core.request("status", "recording_status", json!({})); assert_eq!(reply["result"], json!({"isRecording":false,"isPaused":false})); let (reply, _) = core.request("info", "recording_info", json!({})); assert_eq!(reply["result"], json!({"isRecording":false})); core.shutdown(); assert_eq!(std::fs::read(existing).unwrap(), b"previous take"); assert_eq!(std::fs::read_dir(destination).unwrap().count(), 1); } #[test] fn identity_lifecycle_over_stdio() { let dir = TempDir::new("life"); let mut core = Core::start(&dir.0); let (r, _) = core.request("1", "profile_get", json!({})); assert_eq!(r["result"]["exists"], false); let (r, _) = core.request("2", "rename", json!({ "nickname": "Nobody" })); assert_eq!(r["error"]["code"], "profile_missing"); let (r, events) = core.request("3", "profile_create", json!({ "nickname": "TeamsPeach-Smoke" })); assert_eq!(r["ok"], true, "{r}"); let uid = r["result"]["uid"].as_str().unwrap().to_owned(); assert_eq!(r["result"]["nickname"], "TeamsPeach-Smoke"); assert!(r["result"]["security_level"].as_u64().unwrap() >= 8); assert!(events.iter().any(|e| e["event"] == "profile" && e["uid"] == uid.as_str())); // The private key (as stored, i.e. what any accidental serialization would print) must never // appear on stdout. let stored: Value = serde_json::from_slice(&std::fs::read(dir.0.join("identities.json")).unwrap()).unwrap(); let private_key = stored["identities"][0]["key"]["private_key"].as_str().unwrap().to_owned(); assert!(private_key.len() > 40); assert!(!core.transcript.lock().unwrap().contains(&private_key), "private key leaked to stdout"); let (r, _) = core.request("4", "profile_create", json!({ "nickname": "Other" })); assert_eq!(r["error"]["code"], "profile_exists"); let (r, _) = core.request("5", "rename", json!({ "nickname": "Renamed Smoke" })); assert_eq!(r["result"]["uid"], uid.as_str()); assert_eq!(r["result"]["nickname"], "Renamed Smoke"); let (r, _) = core.request("6", "rename", json!({ "nickname": "x" })); assert_eq!(r["error"]["code"], "invalid_nickname"); // Second instance on the same data dir is refused. let second = Command::new(BIN).arg("--data-dir").arg(&dir.0).stdin(Stdio::null()).output().unwrap(); assert_eq!(second.status.code(), Some(3)); assert!(second.stdout.is_empty()); // Protocol errors are surfaced. let (r, _) = core.request("7", "read_file", json!({ "path": "/etc/passwd" })); assert_eq!(r["error"]["code"], "unknown_command"); let (r, _) = core.request("8", "join_channel", json!({ "channel_id": 1 })); assert_eq!(r["error"]["code"], "not_connected"); core.send(json!({ "cmd": "audio_frame", "args": { "pcm": "AAAA" } })); let e = core.next(); assert_eq!(e["event"], "error"); assert_eq!(e["error"]["code"], "audio_format"); core.send(json!({ "cmd": "audio_frame", "args": { "pcm": base64_silence() } })); let e = core.next(); assert_eq!(e["error"]["code"], "not_connected"); core.send(json!({ "cmd": "audio_end" })); let (r, _) = core.request("9", "set_audio", json!({ "input_muted": true })); assert_eq!(r["result"], json!({ "input_muted": true, "output_muted": false, "transmitting": false })); assert!(!core.transcript.lock().unwrap().contains(&private_key), "private key leaked to stdout"); core.shutdown(); // Restart: same UID, renamed nickname persisted. let mut core = Core::start(&dir.0); let (r, _) = core.request("1", "profile_get", json!({})); assert_eq!(r["result"]["uid"], uid.as_str()); assert_eq!(r["result"]["nickname"], "Renamed Smoke"); assert!(!core.transcript.lock().unwrap().contains(&private_key), "private key leaked to stdout"); core.shutdown(); // Export (allowed while a core runs) and import into a fresh data dir. let running = Core::start(&dir.0); let export_file = dir.0.join("export.ini"); let (code, v) = cli(&["identity".as_ref(), "export".as_ref(), "--data-dir".as_ref(), dir.0.as_os_str(), "--uid".as_ref(), uid.as_ref(), "--out".as_ref(), export_file.as_os_str()]); assert_eq!(code, 0, "{v}"); assert_eq!(v["result"]["uid"], uid.as_str()); assert!(!v.to_string().contains(&private_key)); // The export carries the key (obfuscated TeamSpeak form); it must not reach stdout either. let ini = std::fs::read_to_string(&export_file).unwrap(); let exported = ini.lines().find_map(|l| l.strip_prefix("identity=\"")).unwrap().trim_end_matches('"'); let exported_key = exported.split_once('V').unwrap().1.to_owned(); assert!(!v.to_string().contains(&exported_key)); assert!(!running.transcript.lock().unwrap().contains(&exported_key)); assert!(!running.transcript.lock().unwrap().contains(&private_key)); running.shutdown(); let other = TempDir::new("import"); let (code, v) = cli(&["identity".as_ref(), "import".as_ref(), "--data-dir".as_ref(), other.0.as_os_str(), "--in".as_ref(), export_file.as_os_str()]); assert_eq!(code, 0, "{v}"); assert_eq!(v["result"]["imported"], json!([uid.as_str()])); let (code, v) = cli(&["identity".as_ref(), "import".as_ref(), "--data-dir".as_ref(), other.0.as_os_str(), "--in".as_ref(), export_file.as_os_str()]); assert_eq!(code, 0, "{v}"); assert_eq!(v["result"]["existing"], json!([uid.as_str()])); assert_eq!(v["result"]["imported"], json!([])); let mut core = Core::start(&other.0); let (r, _) = core.request("1", "profile_get", json!({})); assert_eq!(r["result"]["uid"], uid.as_str()); assert_eq!(r["result"]["nickname"], "Renamed Smoke"); core.shutdown(); } #[test] fn corrupt_identity_is_reported_not_replaced() { let dir = TempDir::new("corrupt"); let path = dir.0.join("identity.json"); std::fs::write(&path, b"{\"version\":1,\"uid\":\"broken\"").unwrap(); let mut core = Core::start(&dir.0); let (r, _) = core.request("1", "profile_get", json!({})); assert_eq!(r["error"]["code"], "identity_corrupt"); let (r, _) = core.request("2", "profile_create", json!({ "nickname": "Fresh" })); assert_eq!(r["error"]["code"], "identity_corrupt"); let (r, _) = core.request("3", "connect", json!({ "address": "127.0.0.1:9" })); assert_eq!(r["error"]["code"], "identity_corrupt"); core.shutdown(); assert_eq!(std::fs::read(&path).unwrap(), b"{\"version\":1,\"uid\":\"broken\""); } #[test] fn stdin_eof_exits_cleanly() { let dir = TempDir::new("eof"); let mut core = Core::start(&dir.0); drop(core.stdin); let status = core.child.wait().unwrap(); assert!(status.success()); } fn base64_silence() -> String { "A".repeat(2560) } /// Controlled offline subprocess fixture: no identity creation, no network connection, /// and in particular no live moderation or permission/group transaction. #[test] fn client_menu_commands_are_validated_and_never_fake_success_offline() { let dir=TempDir::new("menu-offline"); let mut core=Core::start(&dir.0); let (r,_)=core.request("ctx","client_context",json!({"client_id":42,"uid":"fixture"})); assert_eq!(r["error"]["code"],"not_connected"); for args in [json!({"client_id":0,"uid":"fixture"}),json!({"client_id":65536,"uid":"fixture"}), json!({"client_id":42,"uid":""}),json!({"client_id":42,"uid":"fixture","unexpected":true})] { let (reply,_) = core.request("invalid-context","client_context",args); assert_eq!(reply["error"]["code"],"bad_request","{reply}"); } let (r,_)=core.request("invalid-stats","client_action",json!({"client_id":42,"uid":"fixture","generation":9_007_199_254_740_992u64,"action":"connection_info"})); assert_eq!(r["error"]["code"],"bad_request","{r}"); for flag in [None,Some(json!(1)),Some(Value::Null)] { let mut args=json!({"client_id":42,"uid":"fixture","generation":1,"action":"commander"}); if let Some(flag)=flag {args["enabled"]=flag;} let (reply,_) = core.request("invalid-commander","client_action",args); assert_eq!(reply["error"]["code"],"bad_request","{reply}"); } let actions=[ json!({"action":"poke","message":"fixture"}),json!({"action":"connection_info"}), json!({"action":"commander","enabled":true}),json!({"action":"server_group","group_id":6,"enabled":true}), json!({"action":"channel_group","group_id":7,"channel_id":1}),json!({"action":"client_permissions"}), json!({"action":"channel_permissions","channel_id":1}), json!({"action":"set_client_permission","permission_id":42,"value":null,"skip":false}), json!({"action":"set_channel_permission","permission_id":42,"channel_id":1,"value":75}), json!({"action":"kick_channel","reason":"fixture"}),json!({"action":"kick_server","reason":"fixture"}), json!({"action":"ban","reason":"fixture","duration":1}),json!({"action":"volume","db":-6.0,"muted":true}), ]; for (i,mut args) in actions.into_iter().enumerate(){ args["client_id"]=json!(42);args["uid"]=json!("fixture");args["generation"]=json!(1); let (r,_)=core.request(&format!("action-{i}"),"client_action",args); assert_eq!(r["error"]["code"],"not_connected","{r}"); } for (i,args) in [ json!({"client_id":42,"uid":"fixture","generation":1,"action":"volume","value":3,"muted":false}), json!({"client_id":42,"uid":"fixture","generation":1,"action":"volume","db":10.5,"muted":false}), json!({"client_id":42,"uid":"fixture","generation":1,"action":"volume","db":-3.25,"muted":false}), json!({"client_id":42,"uid":"fixture","generation":1,"action":"set_client_permission","permission_id":1,"skip":false}), json!({"client_id":42,"uid":"fixture","generation":1,"action":"connection_info","raw":"banclient clid=1"}), json!({"client_id":42,"uid":"fixture","generation":1,"action":"client_permissions","raw":"clientdelperm cldbid=1"}), json!({"client_id":42,"uid":"fixture","generation":1,"action":"avatar","data":"AAAA"}), ].into_iter().enumerate(){ let (r,_)=core.request(&format!("invalid-{i}"),"client_action",args); assert_eq!(r["error"]["code"],"bad_request","{r}"); } core.shutdown(); } #[test] fn connect_and_disconnect_validate_arguments_before_network_io() { let dir = TempDir::new("connection-args"); let mut core = Core::start(&dir.0); for (field, value) in [ ("address", json!("x".repeat(256))), ("address", json!("localhost\n")), ("channel", json!("")), ("channel", json!("x".repeat(513))), ("nickname", json!("x".repeat(65))), ("identity_id", Value::Null), ("identity_id", json!("other")), ("server_password", json!("x".repeat(256))), ("channel_password", json!("bad\tpassword")), ] { let mut args = json!({"address":"127.0.0.1"}); args[field] = value; let (reply, events) = core.request("invalid-connect", "connect", args); assert_eq!(reply["error"]["code"], "bad_request", "{field}: {reply}"); assert!(!events.iter().any(|e| e["state"] == "connecting")); } let limit = "\u{10000}".repeat(40); for args in [json!({"message":format!("{limit}x")}), json!({"message":"\r"}), json!({"message":null})] { let (reply, _) = core.request("invalid-disconnect", "disconnect", args); assert_eq!(reply["error"]["code"], "bad_request", "{reply}"); } for valid in [json!({}), json!({"message":""}), json!({"message":limit})] { let (reply, _) = core.request("valid-disconnect", "disconnect", valid); assert_eq!(reply["error"]["code"], "not_connected", "{reply}"); } core.shutdown(); } #[test] fn talk_power_validates_its_captured_target_before_dispatch() { let dir = TempDir::new("talk-power-args"); let mut core = Core::start(&dir.0); let valid = json!({"generation":9_007_199_254_740_991u64,"client_id":65535,"uid":"peer=","grant":false}); for (field,value) in [("generation",json!(0)),("generation",json!(9_007_199_254_740_992u64)), ("client_id",json!(0)),("client_id",json!(65536)),("uid",json!("")),("grant",json!(1)),("unexpected",json!(true))] { let mut args = valid.clone(); args[field] = value; let (reply,_) = core.request("invalid", "talk_power", args); assert_eq!(reply["error"]["code"], "bad_request", "{field}: {reply}"); } let (reply,_) = core.request("valid", "talk_power", valid); assert_eq!(reply["error"]["code"], "not_connected", "{reply}"); core.shutdown(); } #[test] fn status_messages_are_optional_but_must_be_valid_when_present() { let dir=TempDir::new("status-message-args"); let mut core=Core::start(&dir.0); for (cmd, flag, max) in [("set_away", "away", 80), ("talk_request", "request", 50)] { let limit="\u{10000}".repeat(max); for (enabled,msg) in [(true,Value::Null),(true,json!(format!("{limit}x"))), (true,json!("bad\u{85}message")),(false,json!(""))] { let mut args=json!({"message":msg});args[flag]=enabled.into(); let (reply,_) = core.request("invalid-status",cmd,args); assert_eq!(reply["error"]["code"],"bad_request","{cmd}: {reply}"); } for (enabled,msg) in [(true,Some(limit)),(false,None)] { let mut args=json!({});args[flag]=enabled.into(); if let Some(msg)=msg {args["message"]=msg.into();} let (reply,_) = core.request("valid-status",cmd,args); assert_eq!(reply["error"]["code"],"not_connected","{cmd}: {reply}"); } } core.shutdown(); } #[test] fn poke_validates_utf8_bytes_before_connection_lookup() { let dir = TempDir::new("poke-args"); let mut core = Core::start(&dir.0); let exact = "\u{10000}".repeat(256); for (message, expected) in [(String::new(),"bad_request"),(format!("{exact}x"),"bad_request"), ("no\nline".into(),"bad_request"),("no\u{7f}del".into(),"bad_request"),(exact,"not_connected")] { let (reply,_) = core.request("poke", "client_action", json!({"client_id":2,"uid":"peer=","generation":1,"action":"poke","message":message})); assert_eq!(reply["error"]["code"],expected,"{reply}"); } core.shutdown(); } #[test] fn client_info_requires_explicit_client_identity() { let dir = TempDir::new("client-info-args"); let mut core = Core::start(&dir.0); for args in [json!({"client_id":0,"uid":"peer="}),json!({"client_id":65536,"uid":"peer="}),json!({"client_id":7}),json!({"client_id":7,"uid":""}),json!({"client_id":7,"uid":"peer=","unknown":true})] { let (reply,_) = core.request("invalid-info","client_info",args); assert_eq!(reply["error"]["code"],"bad_request","{reply}"); } let (reply,_) = core.request("offline-info","client_info",json!({"client_id":7,"uid":"peer="})); assert_eq!(reply["error"]["code"],"not_connected","{reply}"); core.shutdown(); } #[test] fn channel_queries_validate_arguments_before_connection_lookup() { let dir = TempDir::new("channel-query-args"); let mut core = Core::start(&dir.0); for cmd in ["channel_info", "channel_description", "channel_list"] { let valid = if cmd == "channel_list" { json!({}) } else { json!({"channel_id": 1}) }; let mut extra = valid.clone(); extra["unexpected"] = json!(true); for args in [extra, json!({"channel_id":0})] { let (reply, _) = core.request("invalid", cmd, args); assert_eq!(reply["error"]["code"], "bad_request", "{cmd}: {reply}"); } let (reply, _) = core.request("valid", cmd, valid); assert_eq!(reply["error"]["code"], "not_connected", "{cmd}: {reply}"); } core.shutdown(); } #[test] fn file_browser_rejects_invalid_list_before_connection() { let dir = TempDir::new("file-list-boundary"); let mut core = Core::start(&dir.0); for args in [json!({"channel_id":0,"path":"/"}), json!({"channel_id":9_007_199_254_740_992u64,"path":"/"}), json!({"channel_id":1,"path":"/a/../b"}), json!({"channel_id":1,"path":"/","unexpected":true})] { let (reply, _) = core.request("invalid-list", "file_list", args); assert_eq!(reply["error"]["code"], "bad_request", "{reply}"); } let (reply, _) = core.request("valid-list", "file_list", json!({"channel_id":9_007_199_254_740_991u64,"path":"/"})); assert_eq!(reply["error"]["code"], "not_connected", "{reply}"); for args in [json!({"channel_id":0,"path":"/image.png"}), json!({"channel_id":1,"path":"/images/"}), json!({"channel_id":1,"path":"/image.png","destination":"unapproved"})] { let (reply, _) = core.request("invalid-image", "file_fetch_image", args); assert_eq!(reply["error"]["code"], "bad_request", "{reply}"); } let (reply, _) = core.request("invalid-history", "file_transfers", json!({"channel_id":1})); assert_eq!(reply["error"]["code"], "bad_request", "{reply}"); let (reply, _) = core.request("offline-history", "file_transfers", json!({})); assert_eq!(reply["error"]["code"], "not_connected", "{reply}"); core.shutdown(); } #[test] fn transfer_controls_validate_the_id_before_connection_lookup() { let dir = TempDir::new("transfer-control-ids"); let mut core = Core::start(&dir.0); for cmd in ["file_cancel", "file_pause", "file_resume"] { for id in [0, u64::from(u32::MAX) + 1] { let (reply, _) = core.request("invalid-id", cmd, json!({"transfer_id":id})); assert_eq!(reply["error"]["code"], "bad_request", "{cmd}: {reply}"); } for id in [1, u32::MAX] { let (reply, _) = core.request("valid-id", cmd, json!({"transfer_id":id})); assert_eq!(reply["error"]["code"], "not_connected", "{cmd}: {reply}"); } } core.shutdown(); } #[test] fn publisher_commands_validate_through_real_stdio_without_server() { let dir = TempDir::new("publisher"); let mut core = Core::start(&dir.0); let metadata = json!({"name":"Disposable QA | stream","type":3,"accessibility":3,"mode":1,"bitrate":4500,"viewer_limit":0,"audio":false}); let mut update = metadata.clone(); update["stream_id"] = json!("qa-stream"); for (i, (command, args)) in [ ("stream_setup", metadata.clone()), ("stream_update", update), ("stream_stop", json!({"stream_id":"qa-stream"})), ("stream_respond", json!({"stream_id":"qa-stream","client_id":42,"decision":true,"offer":"v=0\r\n","message":""})), ("stream_respond", json!({"stream_id":"qa-stream","client_id":42,"decision":false,"offer":"","message":"not_authorized"})), ("stream_remove", json!({"stream_id":"qa-stream","client_id":42})), ].into_iter().enumerate() { let (r, _) = core.request(&format!("publisher-{i}"), command, args); assert_eq!(r["error"]["code"], "not_connected", "{command}: {r}"); } let mut unsupported = metadata.clone(); unsupported["mode"] = json!(2); for (i, (command, args)) in [ ("stream_setup", unsupported), ("stream_update", metadata), ("stream_remove", json!({"stream_id":"qa-stream","client_id":42,"reason":5})), ("stream_respond", json!({"stream_id":"qa-stream","client_id":42,"decision":true,"offer":"","message":""})), ].into_iter().enumerate() { let (r, _) = core.request(&format!("publisher-invalid-{i}"), command, args); assert_eq!(r["error"]["code"], "bad_request", "{command}: {r}"); } core.shutdown(); }