223 lines
8.7 KiB
Rust
223 lines
8.7 KiB
Rust
//! 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<Value>,
|
|
/// Every stdout line, for secret-leak checks.
|
|
transcript: std::sync::Arc<std::sync::Mutex<String>>,
|
|
}
|
|
|
|
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<Value>) {
|
|
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 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("identity.json")).unwrap()).unwrap();
|
|
let private_key = stored["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(), "--out".as_ref(), export_file.as_os_str()]);
|
|
assert_eq!(code, 0, "{v}");
|
|
assert_eq!(v["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["uid"], 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, 1);
|
|
assert_eq!(v["error"]["code"], "profile_exists");
|
|
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) }
|