Validate join targets and bind subscription menus to current channel state

This commit is contained in:
omar committed 2026-11-27 07:03:56 +03:00
1 parent 0ef6447971
commit 2af19bcfcf
9 files changed
+291 -25

No files matched your search

+156 -3
View File
@@ -5,6 +5,7 @@
//! Pass `--channel-order` to check sibling readback on insertion and expiry only.
//! Pass `--client-database-id` to compare UID lookup and nickname search without modifying the server.
//! Pass `--client-info` to read the guest's own variables and reject a mismatched UID.
//! Pass `--channel-subscriptions` to check this guest's channel subscriptions.
use std::fs;
use std::io::{BufRead, BufReader, Write};
@@ -167,10 +168,14 @@ impl Core {
self.request(cmd, args, Instant::now() + CONTROL)?.require(cmd)
}
fn wire_request(&mut self, cmd: &str, args: Value, timeout: Duration) -> Result<Reply> {
fn wait_wire_spacing(&self) {
if let Some(last) = self.last_wire {
thread::sleep((last + WIRE_SPACING).saturating_duration_since(Instant::now()));
}
}
fn wire_request(&mut self, cmd: &str, args: Value, timeout: Duration) -> Result<Reply> {
self.wait_wire_spacing();
let reply = self.request(cmd, args, Instant::now() + timeout);
self.last_wire = Some(Instant::now());
reply
@@ -490,7 +495,153 @@ fn exercise_order(core: &mut Core, name: &str, lobby: u64, generation: u64, own:
Ok(())
}
enum Scenario { ChannelAdmin, ChannelOrder, DatabaseId, ClientInfo }
fn subscription_step(
core: &mut Core, label: &str, target: Option<u64>, subscribe: bool,
matches: impl Fn(&Value) -> bool,
) -> Result<()> {
let (cmd, args) = match target {
Some(id) => ("channel_subscribe", json!({"channel_id": id, "subscribe": subscribe})),
None => ("channel_subscribe_all", json!({"subscribe": subscribe})),
};
let before = core.snapshot["rev"].as_u64().ok_or("missing snapshot revision")?;
// Cleanup may already be at the expected state. Test transitions are not.
let already_matches = matches(&core.snapshot);
match core.wire_request(cmd, args, CONTROL)? {
Reply::Accepted(_) => core.wait_for(label, |s| {
(already_matches || s["rev"].as_u64().is_some_and(|rev| rev > before)) && matches(s)
}).map_err(|error| {
let flags: Vec<_> = core.snapshot["channels"].as_array().into_iter().flatten()
.filter_map(|row| Some((row["id"].as_u64()?, row["subscribed"].as_bool()?))).collect();
format!("{error}; command acknowledged; snapshot revision {before} -> {}, channel subscription flags {flags:?}", core.snapshot["rev"])
}),
Reply::Refused(error) if permission_denied(&error) => {
Err(format!("{label}: unverified (server permission refusal, TS {PERMISSION_DENIED})"))
}
Reply::Refused(error) => Err(rejection(label, &error)),
}
}
fn exercise_subscriptions(core: &mut Core, name: &str, lobby: u64, generation: u64, own: u64) -> Result<()> {
ensure(valid_parent(&core.snapshot, lobby), "subscription target must be the original permanent lobby")?;
let lobby_name = snapshot_channel(&core.snapshot, lobby).and_then(|row| row["name"].as_str())
.ok_or("original lobby name missing")?.to_owned();
let list = core.call("channel_list", json!({}))?;
let existing = rows(&list)?;
ensure(existing.iter().any(|row| wire_id(row) == Some(lobby) && row["channel_name"] == lobby_name.as_str())
&& existing.iter().all(|row| wire_id(row).is_some() && row["channel_name"] != name),
"channel list did not verify the original lobby and unique temporary name")?;
let created = core.wire_call("channel_create", json!({"generation": generation, "parent_id": 0,
"properties": {"channel_name": name}}))?;
let id = created["channel_id"].as_u64().filter(|id| *id != 0 && existing.iter().all(|row| wire_id(row) != Some(*id)))
.ok_or("create did not return a new temporary channel ID")?;
let same_session = |s: &Value| s["generation"].as_u64() == Some(generation);
let temporary = |s: &Value| same_session(s) && snapshot_channel(s, id).is_some_and(|row| {
row["channel_type"] == "temporary" && row["name"] == name && row["parent_id"] == 0
});
core.wait_for("generated temporary channel", temporary)?;
if own_channel(&core.snapshot, own) != Some(id) {
core.wire_call("join_channel", json!({"channel_id": id}))?;
core.wait_for("enter generated temporary channel", |s| temporary(s) && own_channel(s, own) == Some(id))?;
}
// Let the connect-time subscribe-all and the move's book events settle
// before taking the baseline. The local read drains queued snapshots.
core.wait_wire_spacing();
core.call("channel_list", json!({}))?;
// The only client in the lobby at connect was us. Hold the temporary
// channel open while probing the now non-own lobby. Do not edit the lobby.
let in_scope = |s: &Value| temporary(s) && own_channel(s, own) == Some(id) && valid_parent(s, lobby)
&& snapshot_channel(s, lobby).is_some_and(|row| row["name"] == lobby_name.as_str())
&& s["clients"].as_array().is_some_and(|clients| clients.iter().all(|c| c["id"].as_u64() == Some(own)));
ensure(in_scope(&core.snapshot), "subscription target was not the empty original lobby in the same session")?;
let baseline: Vec<_> = core.snapshot["channels"].as_array().ok_or("missing snapshot channels")?.iter()
.filter(|row| row["id"].as_u64() != Some(id))
.map(|row| Ok((row["id"].as_u64().ok_or("missing channel ID")?,
row["subscribed"].as_bool().ok_or("missing channel subscription state")?)))
.collect::<Result<_>>()?;
let lobby_subscribed = baseline.iter().find(|(cid, _)| *cid == lobby).map(|(_, subscribed)| *subscribed)
.ok_or("subscription baseline did not include the original lobby")?;
let matches = |s: &Value, target: Option<u64>, value: bool| in_scope(s)
&& s["channels"].as_array().is_some_and(|channels| {
// Compare the stable ordered channel list; disappearance or a new
// channel makes this snapshot unsuitable as readback.
let others = channels.iter().filter(|row| row["id"].as_u64() != Some(id));
channels.len() == baseline.len() + 1 && others.zip(&baseline).all(|(row, &(cid, initial))| {
let expected = if target.is_none_or(|target| target == cid) { value } else { initial };
row["id"].as_u64() == Some(cid) && row["subscribed"].as_bool() == Some(expected)
})
});
let mut automatic = true; // The disposable core sends subscribe-all on connect.
let cases = (|| {
// Leaving the initially occupied lobby can leave a false book flag even while
// subscribe-all is active. Establish the starting server mode explicitly.
if !lobby_subscribed {
automatic = false;
subscription_step(core, "establish unsubscribed lobby", None, false, |s| matches(s, None, false))?;
for &(cid, subscribed) in &baseline {
if subscribed {
subscription_step(core, "restore other baseline subscription", Some(cid), true, |s| in_scope(s)
&& snapshot_channel(s, cid).is_some_and(|row| row["subscribed"] == true))?;
}
}
}
for subscribe in [!lobby_subscribed, lobby_subscribed] {
let label = if subscribe { "channelsubscribe" } else { "channelunsubscribe" };
let expected = |s: &Value| matches(s, Some(lobby), subscribe);
ensure(in_scope(&core.snapshot) && !expected(&core.snapshot), "no valid single-channel transition to observe")?;
subscription_step(core, label, Some(lobby), subscribe, expected)?;
println!("{label}: original non-own lobby subscribed={subscribe} in a new snapshot");
}
if baseline.len() > 1 {
println!("single-channel scope: {} other non-own channel(s) retained their initial flags", baseline.len() - 1);
} else {
println!("single-channel scope: isolation unverified (no second non-own channel)");
}
// Start with a direction that must change at least one visible channel.
let first_all = !baseline.iter().any(|&(_, subscribed)| subscribed);
for subscribe in [first_all, !first_all] {
let label = if subscribe { "channelsubscribeall" } else { "channelunsubscribeall" };
let expected = |s: &Value| matches(s, None, subscribe);
ensure(in_scope(&core.snapshot) && !expected(&core.snapshot), "no valid all-channel transition to observe")?;
automatic = subscribe;
subscription_step(core, label, None, subscribe, expected)?;
println!("{label}: subscribed={subscribe} for all {} observed non-own channel(s) in a new snapshot", baseline.len());
}
Ok(())
})();
let restore = (|| {
if cases.is_err() && core.state == Some("connected") {
core.wait_wire_spacing();
core.call("channel_list", json!({}))?;
}
ensure(core.state == Some("connected") && in_scope(&core.snapshot), "cannot restore subscriptions: fixture scope changed")?;
if !automatic {
subscription_step(core, "restore automatic subscriptions", None, true, |s| matches(s, None, true))?;
}
for &(cid, initial) in &baseline {
let expected = |s: &Value| in_scope(s) && snapshot_channel(s, cid).is_some_and(|row| row["subscribed"].as_bool() == Some(initial));
if !expected(&core.snapshot) {
subscription_step(core, "restore initial channel subscription", Some(cid), initial, expected)?;
}
}
ensure(matches(&core.snapshot, Some(lobby), lobby_subscribed), "initial non-own subscriptions were not restored")?;
println!("subscription cleanup: initial non-own flags restored");
Ok(())
})();
let leave = (|| {
ensure(core.state == Some("connected") && same_session(&core.snapshot) && valid_parent(&core.snapshot, lobby)
&& snapshot_channel(&core.snapshot, lobby).is_some_and(|row| row["name"] == lobby_name.as_str()),
"cannot return to the original lobby: fixture scope changed")?;
core.wire_call("join_channel", json!({"channel_id": lobby}))?;
core.wait_for("return to original lobby and observe temporary expiry", |s| {
same_session(s) && own_channel(s, own) == Some(lobby) && snapshot_channel(s, id).is_none()
})?;
println!("temporary channel cleanup: ok (left channel; server expired it)");
Ok(())
})();
combine(combine(cases, restore), leave)
}
enum Scenario { ChannelAdmin, ChannelOrder, ChannelSubscriptions, DatabaseId, ClientInfo }
fn exercise_client_info(core: &mut Core, own: u64, uid: &str) -> Result<()> {
let info = core.wire_call("client_info", json!({"client_id":own,"uid":uid}))?;
@@ -553,6 +704,7 @@ fn exercise(core: &mut Core, name: &str, scenario: Scenario) -> Result<()> {
return exercise_client_info(core, own, &uid);
}
Scenario::ChannelOrder => return exercise_order(core, name, lobby, generation, own),
Scenario::ChannelSubscriptions => return exercise_subscriptions(core, name, lobby, generation, own),
Scenario::DatabaseId => {
let uid = snapshot["clients"][0]["uid"].as_str().filter(|s|!s.is_empty()).ok_or("own roster UID missing")?.to_owned();
return exercise_database_id(core, name, &uid);
@@ -658,9 +810,10 @@ fn run() -> Result<()> {
let scenario = match (args.next(),args.next()) {
(None,None)=>Scenario::ChannelAdmin,
(Some(arg),None) if arg=="--channel-order"=>Scenario::ChannelOrder,
(Some(arg),None) if arg=="--channel-subscriptions"=>Scenario::ChannelSubscriptions,
(Some(arg),None) if arg=="--client-database-id"=>Scenario::DatabaseId,
(Some(arg),None) if arg=="--client-info"=>Scenario::ClientInfo,
_=>return Err("usage: channel_admin_qa [--channel-order | --client-database-id | --client-info]".into()),
_=>return Err("usage: channel_admin_qa [--channel-order | --channel-subscriptions | --client-database-id | --client-info]".into()),
};
let exe = std::env::var_os("TEAMSPEACH_QA_CORE").map(PathBuf::from)
.filter(|path| path.is_absolute() && path.is_file() && path.file_name().and_then(|n| n.to_str())
+13 -1
View File
@@ -592,7 +592,10 @@ pub fn validate_command(mut command: Command) -> Result<ValidatedCommand, ErrorO
check_opt("identity_id", &a.identity_id)?;
}
Command::Disconnect { message } => check_opt("message", message)?,
Command::JoinChannel { password, .. } => check_opt("password", password)?,
Command::JoinChannel { channel_id, password } => {
if *channel_id == 0 { return Err(bad("channel_id must be positive")); }
check_opt("password", password)?;
}
Command::SendText { target, client_id, expected_client_uid, expected_channel_id, message } => {
if expected_channel_id.is_some_and(|id| id == 0 || *target != TextTarget::Channel) {
return Err(bad("expected_channel_id must be positive and is only allowed for target channel"));
@@ -803,6 +806,15 @@ mod tests {
assert_eq!(validate_command(command).unwrap_err().code, ErrorCode::BadRequest);
}
#[test]
fn join_requires_a_positive_channel_in_both_transports() {
let join = |channel_id| Command::JoinChannel { channel_id, password: None };
let Input::Invalid { error, .. } = parse_line(r#"{"id":"j","cmd":"join_channel","args":{"channel_id":0}}"#) else { panic!("zero channel accepted") };
assert_eq!(error.code, ErrorCode::BadRequest);
assert_eq!(error, validate_command(join(0)).unwrap_err());
assert_eq!(validate_command(join(1)).unwrap().into_inner(), join(1));
}
#[test]
fn direct_private_text_requires_exact_target_and_uid() {
let private = |client_id, expected_client_uid| Command::SendText {
+4
View File
@@ -59,6 +59,10 @@ async fn native_requests_validate_before_session_dispatch() {
use teamspeach_core::protocol::{ErrorCode, TextTarget};
let profile = Profile::new();
let (core, _events) = spawn(profile.config(1)).unwrap();
for (id, expected) in [(0, ErrorCode::BadRequest), (1, ErrorCode::NotConnected)] {
let error = core.request(Command::JoinChannel { channel_id: id, password: None }).await.unwrap_err();
assert_eq!(error.code, expected);
}
let error = core.request(Command::SendText { target: TextTarget::Client, client_id: None,
expected_client_uid: None, expected_channel_id: None, message: "private".into() }).await.unwrap_err();
assert_eq!(error.code, ErrorCode::BadRequest);