Files
client/core/tests/bridge_smoke.rs
T
omar 1fe5baba05 test: verify scoped native tab requests
- Run the existing two-tab Client Info smoke against the disposable loopback fixture.
- Verify unknown commands and malformed arguments over real stdio and record typed profile and stale-response evidence.
2026-11-28 14:19:14 +03:00

722 lines
33 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 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 (unknown, _) = core.request("unknown", "unknown_request_qa", json!({}));
assert_eq!(unknown["ok"], false);
assert_eq!(unknown["error"]["code"], "unknown_command");
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":"move_to_own_channel","expected_channel_id":9_007_199_254_740_991u64}),
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":"move_to_own_channel","expected_channel_id":0}),
json!({"client_id":42,"uid":"fixture","generation":1,"action":"move_to_own_channel","expected_channel_id":9_007_199_254_740_992u64}),
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 database_list_rejects_invalid_pages_before_connection_lookup() {
let dir = TempDir::new("database-pages");
let mut core = Core::start(&dir.0);
for (args, expected) in [
(json!({"start":0,"duration":1}), "not_connected"),
(json!({"start":u32::MAX,"duration":200}), "not_connected"),
(json!({"start":0,"duration":0}), "bad_request"),
(json!({"start":0,"duration":201}), "bad_request"),
(json!({"start":4294967296_u64,"duration":1}), "bad_request"),
(json!({"start":0,"duration":1,"unexpected":false}), "bad_request"),
] {
let (reply, _) = core.request("page", "client_database_list", args);
assert_eq!(reply["error"]["code"], expected, "{reply}");
}
core.shutdown();
}
#[test]
fn client_database_text_bounds_count_unicode_scalars_before_dispatch() {
let dir=TempDir::new("database-text-limits");
let mut core=Core::start(&dir.0);
for (cmd,field,max,mut args) in [
("client_database_find","pattern",255,json!({"uid":false})),
("client_database_id","uid",128,json!({})),
("client_info","uid",128,json!({"client_id":1})),
("server_group_member_add_uid","uid",128,json!({"generation":1,"group_id":1})),
] {
let limit="я".repeat(max-1)+"\u{1f3b5}";
for (value,expected) in [(limit.clone(),"not_connected"),(format!("{limit}x"),"bad_request"),
(String::new(),"bad_request"),("a\u{85}b".into(),"bad_request")] {
args[field]=json!(value);
let (reply,_)=core.request("text-boundary",cmd,args.clone());
assert_eq!(reply["error"]["code"],expected,"{cmd}.{field}: {reply}");
}
}
core.shutdown();
}
#[test]
fn unicode_group_names_are_validated_before_connecting() {
let dir=TempDir::new("unicode-group-names");
let mut core=Core::start(&dir.0);
let limit="я".repeat(127)+"\u{1f3b5}";
for (cmd,mut args) in [("group_add",json!({"generation":1,"kind":"server","type":1})),
("group_rename",json!({"generation":1,"kind":"channel","group_id":3}))] {
for (name,code) in [(limit.clone(),"not_connected"),(format!("{limit}x"),"bad_request"),("line\nbreak".into(),"bad_request")] {
args["name"]=json!(name);
let (reply,_)=core.request("group-name",cmd,args.clone());
assert_eq!(reply["error"]["code"],code,"{cmd}: {reply}");
}
}
core.shutdown();
}
#[test]
fn admin_ids_and_log_offsets_respect_the_safe_integer_boundary_before_connecting() {
let dir=TempDir::new("admin-integer-boundary");
let mut core=Core::start(&dir.0);
const MAX:u64=(1<<53)-1;
for (cmd,property,mut args) in [
("channel_create","channel_order",json!({"generation":1,"parent_id":0,"properties":{"channel_name":"Fixture"}})),
("channel_edit","channel_order",json!({"generation":1,"channel_id":2,"properties":{}})),
("server_edit","virtualserver_download_quota",json!({"generation":1,"confirm":"Fixture","properties":{}})),
("server_edit","virtualserver_default_server_group",json!({"generation":1,"confirm":"Fixture","properties":{}})),
] {
for (value,expected) in [(MAX,"not_connected"),(MAX+1,"bad_request")] {
args["properties"][property]=json!(value);
let (reply,_)=core.request("property-boundary",cmd,args.clone());
assert_eq!(reply["error"]["code"],expected,"{property}: {reply}");
}
}
for (cmd, field, mut args) in [
("channel_description", "channel_id", json!({})),
("channel_move", "parent_id", json!({"generation":1,"channel_id":2})),
("channel_move", "order", json!({"generation":1,"channel_id":2,"parent_id":0})),
("channel_create", "parent_id", json!({"generation":1,"properties":{"channel_name":"Fixture"}})),
("channel_info", "channel_id", json!({})),
("server_group_perm_list", "group_id", json!({})),
("temp_password_add", "channel_id", json!({"generation":1,"password":"fixture","duration_s":60})),
("server_log", "begin_pos", json!({"lines":1,"reverse":false,"instance":false})),
] {
for (value,expected) in [(MAX,"not_connected"),(MAX+1,"bad_request")] {
args[field]=json!(value);
let (reply,_)=core.request("boundary",cmd,args.clone());
assert_eq!(reply["error"]["code"],expected,"{cmd}.{field}: {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 transmit_stdio_distinguishes_missing_fields_from_null() {
let dir = TempDir::new("transmit-args");
let mut core = Core::start(&dir.0);
for mode in ["direct", "vad"] {
for field in ["detector", "sensitivity", "level_db"] {
let mut args = json!({"mode":mode});
args[field] = Value::Null;
let (reply, _) = core.request("invalid-transmit", "set_transmit", args);
assert_eq!(reply["error"]["code"], "bad_request", "{mode}.{field}: {reply}");
}
}
for (args, expected) in [
(json!({"mode":"direct"}), json!({"mode":"direct"})),
(json!({"mode":"vad"}), json!({"mode":"vad","detector":"automatic","sensitivity":"normal"})),
(json!({"mode":"vad","detector":"volume_gate","level_db":12.5}), json!({"mode":"vad","detector":"volume_gate","level_db":12.5})),
] {
let (reply, _) = core.request("valid-transmit", "set_transmit", args);
assert_eq!(reply["result"], expected, "{reply}");
}
core.shutdown();
}
#[test]
fn playback_dsp_stdio_requires_an_explicit_boolean_agc() {
let dir = TempDir::new("playback-dsp-args");
let mut core = Core::start(&dir.0);
for args in [json!({}), json!({"agc": null}), json!({"agc": 1}), json!({"agc": "false"}), json!({"agc": true, "gain": 1})] {
let (reply, _) = core.request("invalid-dsp", "set_playback_dsp", args);
assert_eq!(reply["error"]["code"], "bad_request", "{reply}");
}
for enabled in [true, false] {
let (reply, _) = core.request("valid-dsp", "set_playback_dsp", json!({"agc": enabled}));
assert_eq!(reply["ok"], true, "{reply}");
assert_eq!(reply["result"]["agc"], enabled);
}
core.shutdown();
}
#[test]
fn audio_flag_updates_are_partial_and_reject_explicit_null() {
let dir = TempDir::new("audio-flag-args");
let mut core = Core::start(&dir.0);
for (args, muted, deafened) in [(json!({"input_muted":true}), true, false),
(json!({"output_muted":true}), true, true), (json!({"input_muted":false}), false, true)] {
let (reply, _) = core.request("set", "set_audio", args);
assert_eq!(reply["result"], json!({"input_muted":muted,"output_muted":deafened,"transmitting":false}));
}
for invalid in [json!({"input_muted":null,"output_muted":false}),json!({"output_muted":null}),json!({"input_muted":"false"})] {
let (reply, _) = core.request("invalid", "set_audio", invalid);
assert_eq!(reply["error"]["code"], "bad_request");
}
let (reply, events) = core.request("read", "set_audio", json!({}));
assert_eq!(reply["result"], json!({"input_muted":false,"output_muted":true,"transmitting":false}));
assert!(events.iter().any(|e| e["event"]=="audio_state" && e["input_muted"]==false && e["output_muted"]==true));
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 stdio_requires_objects_without_dispatching_positional_commands() {
let dir = TempDir::new("object-envelope");
let mut core = Core::start(&dir.0);
for (cmd, args) in [("profile_create", json!(["Positional"])), ("channel_description", json!([1])),
("admin_context", json!([])), ("shutdown", Value::Null)] {
let (reply, _) = core.request("invalid", cmd, args);
assert_eq!(reply["error"]["code"], "bad_request", "{cmd}: {reply}");
}
for input in [json!(["unexpected", "shutdown", {}]), json!({"id":"ignored", "cmd":"audio_end", "args":[]})] {
core.send(input);
let event = core.next();
assert_eq!(event["event"], "error", "{event}");
assert_eq!(event["error"]["code"], "bad_request");
assert!(event.get("id").is_none());
}
core.send(json!({"id":"alive", "cmd":"profile_get"}));
let profile = core.next();
assert_eq!(profile["id"], "alive");
assert_eq!(profile["ok"], true, "{profile}");
assert_eq!(profile["result"]["exists"], false, "{profile}");
core.shutdown();
}
#[test]
fn whisper_commands_reject_invalid_epochs_and_targets_before_connection_lookup() {
let dir = TempDir::new("whisper-args");
let mut core = Core::start(&dir.0);
let target = json!({"kind":"ids", "clients":[], "channel_ids":[1]});
for (cmd, args) in [
("whisper_start", json!({"epoch":0,"target":target})),
("whisper_start", json!({"epoch":1,"target":{"kind":"ids","clients":[],"channel_ids":[],"extra":true}})),
("whisper_stop", json!({"epoch":0})),
("whisper_stop", json!({"epoch":4294967296_u64})),
("whisper_stop", json!({"epoch":1,"extra":true})),
] {
let (reply, _) = core.request("invalid", cmd, args);
assert_eq!(reply["error"]["code"], "bad_request", "{cmd}: {reply}");
}
let (reply, _) = core.request("unheld", "whisper_stop", json!({"epoch":u32::MAX}));
assert_eq!(reply["result"], json!({"epoch":u32::MAX,"stopped":false}));
core.shutdown();
}
#[test]
fn channel_subscriptions_validate_arguments_before_connection_lookup() {
const SINGLE: &str = "channel_subscribe";
const ALL: &str = "channel_subscribe_all";
const MAX_CHANNEL_ID: u64 = (1 << 53) - 1;
let dir = TempDir::new("channel-subscription-args");
let mut core = Core::start(&dir.0);
for (cmd, args) in [
(SINGLE, json!({"channel_id": 1, "subscribe": true})),
(SINGLE, json!({"channel_id": MAX_CHANNEL_ID, "subscribe": false})),
(ALL, json!({"subscribe": true})),
(ALL, json!({"subscribe": false})),
] {
let (reply, _) = core.request("valid-subscription", cmd, args);
assert_eq!(reply["ok"], false, "{cmd}: {reply}");
assert_eq!(reply["error"]["code"], "not_connected", "{cmd}: {reply}");
}
for (cmd, args) in [
(SINGLE, json!({"subscribe": true})),
(SINGLE, json!({"channel_id": 0, "subscribe": true})),
(SINGLE, json!({"channel_id": -1, "subscribe": false})),
(SINGLE, json!({"channel_id": 1.5, "subscribe": true})),
(SINGLE, json!({"channel_id": "1", "subscribe": true})),
(SINGLE, json!({"channel_id": MAX_CHANNEL_ID + 1, "subscribe": false})),
(SINGLE, json!({"channel_id": 1})),
(SINGLE, json!({"channel_id": 1, "subscribe": null})),
(SINGLE, json!({"channel_id": 1, "subscribe": 1})),
(SINGLE, json!({"channel_id": 1, "subscribe": "false"})),
(SINGLE, json!({"channel_id": 1, "subscribe": false, "generation": 1})),
(SINGLE, json!([1, false])),
(ALL, json!({})),
(ALL, json!({"subscribe": null})),
(ALL, json!({"subscribe": 0})),
(ALL, json!({"subscribe": "true"})),
(ALL, json!({"channel_id": 1, "subscribe": false})),
(ALL, json!([true])),
] {
let (reply, _) = core.request("invalid-subscription", cmd, args.clone());
assert_eq!(reply["ok"], false, "{cmd} with {args}: {reply}");
assert_eq!(reply["error"]["code"], "bad_request", "{cmd} with {args}: {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();
}