Validate manager requests before revoking the current capture route

This commit is contained in:
omar committed 2026-11-27 14:04:46 +03:00
1 parent f41e064ea6
commit 389e26dc89
6 files changed
+126 -27

No files matched your search

+2
View File
@@ -2,6 +2,8 @@
## Unreleased ## Unreleased
- Invalid connection requests no longer revoke the current microphone route or trigger a default identity lookup. The manager forwards validated commands to the embedded core without parsing them again.
- Validate connect and disconnect string lengths and selected identity IDs before dispatch. The JSON bridge rejects explicitly null fields instead of treating them as omitted. - Validate connect and disconnect string lengths and selected identity IDs before dispatch. The JSON bridge rejects explicitly null fields instead of treating them as omitted.
- Partial snapshot imports now list acknowledged changes alongside failures. Property and permission rows identify the object and field without displaying its value. Reusing an existing icon does not count as an upload. - Partial snapshot imports now list acknowledged changes alongside failures. Property and permission rows identify the object and field without displaying its value. Reusing an existing icon does not count as an upload.
+35 -2
View File
@@ -104,6 +104,10 @@ impl ErrorObj {
fn bad(msg: impl Into<String>) -> ErrorObj { ErrorObj::new(ErrorCode::BadRequest, msg) } fn bad(msg: impl Into<String>) -> ErrorObj { ErrorObj::new(ErrorCode::BadRequest, msg) }
fn check_identity_id(uid: &str) -> Result<(), ErrorObj> {
if crate::profile::valid_uid(uid) { Ok(()) } else { Err(bad("invalid identity_id")) }
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "snake_case")] #[serde(rename_all = "snake_case")]
pub enum TextTarget { pub enum TextTarget {
@@ -190,12 +194,23 @@ impl Command {
} }
/// A command whose transport-independent arguments have been checked and normalized. /// A command whose transport-independent arguments have been checked and normalized.
/// Only the core can unwrap it; callers must use [`validate_command`]. /// Callers can inspect it without changing it; only the core can unwrap it.
#[derive(Clone, Debug, PartialEq)] #[derive(Clone, Debug, PartialEq)]
pub struct ValidatedCommand(Command); pub struct ValidatedCommand(Command);
impl ValidatedCommand { impl ValidatedCommand {
pub fn name(&self) -> &'static str { self.0.name() } pub fn name(&self) -> &'static str { self.0.name() }
pub fn as_command(&self) -> &Command { &self.0 }
/// Bind the selected default to a connect that did not specify an identity.
pub fn bind_default_identity(&mut self, uid: &str) -> Result<(), ErrorObj> {
let Command::Connect(args) = &mut self.0 else { return Err(bad("identity binding requires connect")); };
if args.identity_id.is_some() { return Err(bad("identity_id is already set")); }
check_identity_id(uid)?;
args.identity_id = Some(uid.to_owned());
Ok(())
}
pub(crate) fn into_inner(self) -> Command { self.0 } pub(crate) fn into_inner(self) -> Command { self.0 }
} }
@@ -621,7 +636,7 @@ pub fn validate_command(mut command: Command) -> Result<ValidatedCommand, ErrorO
] { ] {
if value.is_some_and(|s| !bounded_text(s, min, max, false)) { return Err(bad(format!("invalid {field}"))); } if value.is_some_and(|s| !bounded_text(s, min, max, false)) { return Err(bad(format!("invalid {field}"))); }
} }
if a.identity_id.as_deref().is_some_and(|uid| !crate::profile::valid_uid(uid)) { return Err(bad("invalid identity_id")); } if let Some(uid) = a.identity_id.as_deref() { check_identity_id(uid)?; }
} }
Command::Disconnect { message } => { Command::Disconnect { message } => {
if message.as_deref().is_some_and(|s| !bounded_text(s, 0, 80, false)) { return Err(bad("invalid disconnect message")); } if message.as_deref().is_some_and(|s| !bounded_text(s, 0, 80, false)) { return Err(bad("invalid disconnect message")); }
@@ -808,6 +823,24 @@ mod tests {
assert_bad(Command::Connect(args)); assert_bad(Command::Connect(args));
} }
#[test]
fn default_identity_binding_requires_a_valid_uid_and_omission() {
let args = ConnectArgs { address: "localhost".into(), server_password: None, channel: None,
channel_password: None, identity_id: None, nickname: None };
let mut command = validate_command(Command::Connect(args.clone())).unwrap();
assert_eq!(command.bind_default_identity("").unwrap_err().code, ErrorCode::BadRequest);
assert_eq!(command.as_command(), &Command::Connect(args.clone()));
let uid = "test/9PZ9vww/Bpf5vJxtJhpz80=";
let chosen = Command::Connect(ConnectArgs { identity_id: Some(uid.into()), ..args });
command.bind_default_identity(uid).unwrap();
assert_eq!(command.as_command(), &chosen);
assert_eq!(command.bind_default_identity(uid).unwrap_err().code, ErrorCode::BadRequest);
let mut explicit = validate_command(chosen.clone()).unwrap();
assert_eq!(explicit.bind_default_identity(uid).unwrap_err().code, ErrorCode::BadRequest);
assert_eq!(explicit.as_command(), &chosen);
}
#[test] #[test]
fn connect_rejects_non_string_nickname_overrides() { fn connect_rejects_non_string_nickname_overrides() {
let parse = |args: Value| parse_line(&serde_json::json!({"id":"c","cmd":"connect","args":args}).to_string()); let parse = |args: Value| parse_line(&serde_json::json!({"id":"c","cmd":"connect","args":args}).to_string());
+6 -2
View File
@@ -2,7 +2,7 @@
use std::{collections::HashMap, path::PathBuf, sync::{Arc, Mutex, atomic::{AtomicU64, Ordering}}, thread}; use std::{collections::HashMap, path::PathBuf, sync::{Arc, Mutex, atomic::{AtomicU64, Ordering}}, thread};
use serde_json::Value; use serde_json::Value;
use tokio::sync::{mpsc, oneshot}; use tokio::sync::{mpsc, oneshot};
use crate::{audio::{AudioIn, AudioInQueue, CapturedFrame}, locks, output::{Out, PlaybackReceiver}, profile::Store, protocol::{validate_command, Command, ErrorCode, ErrorObj, Input}, session::Session}; use crate::{audio::{AudioIn, AudioInQueue, CapturedFrame}, locks, output::{Out, PlaybackReceiver}, profile::Store, protocol::{validate_command, Command, ErrorCode, ErrorObj, Input, ValidatedCommand}, session::Session};
pub struct CoreConfig { pub data_dir: PathBuf, pub connection_dir: PathBuf } pub struct CoreConfig { pub data_dir: PathBuf, pub connection_dir: PathBuf }
#[derive(Debug, thiserror::Error)] #[derive(Debug, thiserror::Error)]
@@ -43,7 +43,11 @@ impl Drop for PendingRequest {
impl CoreHandle { impl CoreHandle {
pub async fn request(&self, command: Command) -> Result<Value, ErrorObj> { pub async fn request(&self, command: Command) -> Result<Value, ErrorObj> {
let command = validate_command(command)?; self.request_validated(validate_command(command)?).await
}
/// Send a command that has already passed shared protocol validation.
pub async fn request_validated(&self, command: ValidatedCommand) -> Result<Value, ErrorObj> {
let commands = self.commands.as_ref().ok_or_else(stopped)?; let commands = self.commands.as_ref().ok_or_else(stopped)?;
let id = self.next_request.fetch_add(1, Ordering::Relaxed).to_string(); let id = self.next_request.fetch_add(1, Ordering::Relaxed).to_string();
let (reply, receiver) = oneshot::channel(); let (reply, receiver) = oneshot::channel();
+2
View File
@@ -4,6 +4,8 @@
## Возврат к разработке на ПК, 2026-11-26 ## Возврат к разработке на ПК, 2026-11-26
Windows, база `f41e064`: менеджер вкладок проверяет запрос до изменения маршрута микрофона. Неверные connect/disconnect оставили действительными прежнюю сессию, владельца и разрешение; ядро приняло следующий сгенерированный PCM-кадр с тем же разрешением. Прошли 20 тестов ядра и 13 тестов менеджера. Физические устройства и переключение микрофона через Slint между живыми подключениями не проверялись.
Windows, база `c12cf21`: ограничения полей connect/disconnect сверены с историческим валидатором. Ядро отклоняет неверные строки и UID до подключения. Прошли 18 тестов протокола и профиля и один тест stdio. Проверка двух вкладок с переключением микрофона из Slint остаётся открытой. Windows, база `c12cf21`: ограничения полей connect/disconnect сверены с историческим валидатором. Ядро отклоняет неверные строки и UID до подключения. Прошли 18 тестов протокола и профиля и один тест stdio. Проверка двух вкладок с переключением микрофона из Slint остаётся открытой.
Windows, база `6bf4de7`: закрыт `current-contract:snapshot-partial`. Частичный отчёт перечисляет подтверждённые изменения без значений свойств и разрешений. Отказ и отмена загрузки иконки проверены на уровне сервиса. На beta14 режим Skip показал один пропуск и ноль изменений. Прошли 32 теста; стенд остановлен. Windows, база `6bf4de7`: закрыт `current-contract:snapshot-partial`. Частичный отчёт перечисляет подтверждённые изменения без значений свойств и разрешений. Отказ и отмена загрузки иконки проверены на уровне сервиса. На beta14 режим Skip показал один пропуск и ноль изменений. Прошли 32 теста; стенд остановлен.
+28 -21
View File
@@ -13,7 +13,7 @@ use serde_json::Value;
use teamspeach_core::{ use teamspeach_core::{
audio::CapturedFrame, audio::CapturedFrame,
output::PlaybackFrame, output::PlaybackFrame,
protocol::{Command, ErrorObj}, protocol::{Command, ErrorCode, ErrorObj, TextTarget, ValidatedCommand, validate_command},
runtime::{self, CoreConfig, CoreEvents, CoreHandle}, runtime::{self, CoreConfig, CoreEvents, CoreHandle},
vad::GateMode, vad::GateMode,
whisper::WhisperCommand, whisper::WhisperCommand,
@@ -268,6 +268,7 @@ impl ConnectionManager {
self.capture.lock().expect("capture route poisoned").revoke(None); self.capture.lock().expect("capture route poisoned").revoke(None);
} }
pub async fn request(&self, key: &SessionKey, command: Command) -> Result<Value, ConnectionError> { pub async fn request(&self, key: &SessionKey, command: Command) -> Result<Value, ConnectionError> {
let command = validate_command(command)?;
self.call(|reply| Operation::Request(key.clone(), command, reply)).await self.call(|reply| Operation::Request(key.clone(), command, reply)).await
} }
pub async fn close(&self, key: &SessionKey) -> Result<(), ConnectionError> { pub async fn close(&self, key: &SessionKey) -> Result<(), ConnectionError> {
@@ -309,7 +310,7 @@ enum Operation {
SelectChannel(SessionKey, u64, Reply<()>), SelectChannel(SessionKey, u64, Reply<()>),
Workflow(WorkflowSettings, Reply<()>), Workflow(WorkflowSettings, Reply<()>),
SetInput(Option<SessionKey>, InputConfiguration, Reply<Option<CapturePermit>>), SetInput(Option<SessionKey>, InputConfiguration, Reply<Option<CapturePermit>>),
Request(SessionKey, Command, Reply<Value>), Request(SessionKey, ValidatedCommand, Reply<Value>),
Close(SessionKey, Reply<()>), Close(SessionKey, Reply<()>),
Restart(SessionKey, Reply<SessionKey>), Restart(SessionKey, Reply<SessionKey>),
#[cfg(test)] #[cfg(test)]
@@ -449,7 +450,9 @@ impl Actor {
self.sink.on_event(ConnectionEvent::InputReset); self.sink.on_event(ConnectionEvent::InputReset);
if let Some(index) = index { if let Some(index) = index {
if let Some(epoch) = self.entries[index].whisper.take() { if let Some(epoch) = self.entries[index].whisper.take() {
self.dispatch(index, self.entries[index].key(), Command::Whisper(WhisperCommand::Stop { epoch }), CompletionKind::ReleaseWhisper); let command = validate_command(Command::Whisper(WhisperCommand::Stop { epoch }))
.expect("tracked whisper epoch came from a validated start");
self.dispatch(index, self.entries[index].key(), command, CompletionKind::ReleaseWhisper);
} }
} }
revision revision
@@ -499,7 +502,7 @@ impl Actor {
if let Ok(index) = self.index(&next) { self.configure_input(index, self.entries[index].key(), None); } if let Ok(index) = self.index(&next) { self.configure_input(index, self.entries[index].key(), None); }
} }
} }
fn dispatch(&mut self, index: usize, key: SessionKey, mut command: Command, mut kind: CompletionKind) { fn dispatch(&mut self, index: usize, key: SessionKey, mut command: ValidatedCommand, mut kind: CompletionKind) {
let session_clock = self.entries[index].session_clock.clone(); let session_clock = self.entries[index].session_clock.clone();
let capture = self.capture.clone(); let capture = self.capture.clone();
let request = self.next_request; let request = self.next_request;
@@ -513,24 +516,22 @@ impl Actor {
// Resolve only the public UID, never identity private material. This also binds a // Resolve only the public UID, never identity private material. This also binds a
// default-identity connect if another session changes the default while awaiting it. // default-identity connect if another session changes the default while awaiting it.
if let CompletionKind::Request { guard: Guard::Connect { identity, .. }, .. } = &mut kind { if let CompletionKind::Request { guard: Guard::Connect { identity, .. }, .. } = &mut kind {
if identity.as_ref().is_none_or(|identity| identity.is_empty()) {
let profile = core.request(Command::ProfileGet).await.map_err(ConnectionError::from)?;
*identity = profile.get("uid").and_then(Value::as_str).map(str::to_owned);
if identity.is_none() { if identity.is_none() {
return Err(ConnectionError::Core(ErrorObj::new(teamspeach_core::protocol::ErrorCode::ProfileMissing, "profile has no identity"))); let mut profile = core.request(Command::ProfileGet).await?;
} let Some(Value::String(uid)) = profile.as_object_mut().and_then(|profile| profile.remove("uid")) else {
return Err(ErrorObj::new(ErrorCode::ProfileMissing, "profile has no identity").into());
};
if core.connection_generation() != key.generation || session_clock.load(Ordering::Acquire) != key.session { return Err(ConnectionError::TargetChanged); } if core.connection_generation() != key.generation || session_clock.load(Ordering::Acquire) != key.session { return Err(ConnectionError::TargetChanged); }
command.bind_default_identity(&uid)?;
*identity = Some(uid);
} }
} }
if let (Command::Connect(args), CompletionKind::Request { guard: Guard::Connect { identity, .. }, .. }) = (&mut command, &kind) {
args.identity_id = identity.clone();
}
if let CompletionKind::Request { capture_revision: Some(revision), .. } = &kind { if let CompletionKind::Request { capture_revision: Some(revision), .. } = &kind {
if capture.lock().expect("capture route poisoned").revision != *revision { if capture.lock().expect("capture route poisoned").revision != *revision {
return Err(ConnectionError::TargetChanged); return Err(ConnectionError::TargetChanged);
} }
} }
core.request(command).await.map_err(ConnectionError::from) core.request_validated(command).await.map_err(ConnectionError::from)
}.await; }.await;
drop(core); drop(core);
let _ = completions.send(Completion { request, key, result, kind }).await; let _ = completions.send(Completion { request, key, result, kind }).await;
@@ -613,6 +614,11 @@ impl Actor {
Ok(index) => index, Ok(index) => index,
Err(error) => { let _ = reply.send(Err(error)); return; } Err(error) => { let _ = reply.send(Err(error)); return; }
}; };
if index.is_some() {
if let Err(error) = validate_command(Command::SetTransmit { vad: config.vad }) {
let _ = reply.send(Err(error.into())); return;
}
}
self.revoke(); self.revoke();
self.choose_input(key.as_ref().map(|key| key.connection_id.clone())); self.choose_input(key.as_ref().map(|key| key.connection_id.clone()));
if let (Some(index), Some(key)) = (index, key) { if let (Some(index), Some(key)) = (index, key) {
@@ -629,30 +635,31 @@ impl Actor {
if self.entries[index].worker.as_ref().expect("checked live worker").requests.len() >= COMMAND_CAPACITY { if self.entries[index].worker.as_ref().expect("checked live worker").requests.len() >= COMMAND_CAPACITY {
let _ = reply.send(Err(ConnectionError::Busy)); return; let _ = reply.send(Err(ConnectionError::Busy)); return;
} }
if matches!(command, Command::Shutdown) { let request = command.as_command();
if matches!(request, Command::Shutdown) {
let _ = reply.send(Err(ConnectionError::Worker("use close, restart or shutdown to join the core".into()))); return; let _ = reply.send(Err(ConnectionError::Worker("use close, restart or shutdown to join the core".into()))); return;
} }
let channel_lease=if matches!(command,Command::JoinChannel{..}|Command::SendText{target:teamspeach_core::protocol::TextTarget::Channel,..}){ let channel_lease=if matches!(request,Command::JoinChannel{..}|Command::SendText{target:TextTarget::Channel,..}){
match self.entries[index].worker.as_ref().expect("checked live worker").channel_request.clone().try_lock_owned(){Ok(lease)=>Some(lease),Err(_)=>{let _=reply.send(Err(ConnectionError::Busy));return}} match self.entries[index].worker.as_ref().expect("checked live worker").channel_request.clone().try_lock_owned(){Ok(lease)=>Some(lease),Err(_)=>{let _=reply.send(Err(ConnectionError::Busy));return}}
}else{None}; }else{None};
if let Command::SendText { target:teamspeach_core::protocol::TextTarget::Channel, expected_channel_id:Some(channel), .. }=&command { if let Command::SendText { target:TextTarget::Channel, expected_channel_id:Some(channel), .. }=request {
if !self.entries[index].snapshot.is_connected() || self.entries[index].snapshot.server.as_deref().and_then(|s|s["own_channel_id"].as_u64())!=Some(*channel){let _=reply.send(Err(ConnectionError::TargetChanged));return} if !self.entries[index].snapshot.is_connected() || self.entries[index].snapshot.server.as_deref().and_then(|s|s["own_channel_id"].as_u64())!=Some(*channel){let _=reply.send(Err(ConnectionError::TargetChanged));return}
} }
let guard = match &command { let guard = match request {
Command::Connect(args) => Guard::Connect { address: args.address.clone(), identity: args.identity_id.clone() }, Command::Connect(args) => Guard::Connect { address: args.address.clone(), identity: args.identity_id.clone() },
Command::Disconnect { .. } => Guard::Disconnect, Command::Disconnect { .. } => Guard::Disconnect,
_ => Guard::Strict, _ => Guard::Strict,
}; };
let boundary = matches!(command, Command::Connect(_) | Command::Disconnect { .. } | Command::JoinChannel { .. } let boundary = matches!(request, Command::Connect(_) | Command::Disconnect { .. } | Command::JoinChannel { .. }
| Command::SetAudio { .. } | Command::SetTransmit { .. } | Command::Whisper(WhisperCommand::Start { .. } | WhisperCommand::Stop { .. })); | Command::SetAudio { .. } | Command::SetTransmit { .. } | Command::Whisper(WhisperCommand::Start { .. } | WhisperCommand::Stop { .. }));
let capture_revision = if boundary { let capture_revision = if boundary {
let revision = if self.input.as_ref() == Some(&key.connection_id) { Some(self.revoke()) } else { None }; let revision = if self.input.as_ref() == Some(&key.connection_id) { Some(self.revoke()) } else { None };
self.entries[index].worker.as_ref().expect("checked live worker").core.invalidate_audio(); self.entries[index].worker.as_ref().expect("checked live worker").core.invalidate_audio();
revision revision
} else { None }; } else { None };
let changes_config = matches!(command, Command::SetAudio { .. } | Command::SetTransmit { .. }); let changes_config = matches!(request, Command::SetAudio { .. } | Command::SetTransmit { .. });
if let Some(config) = &mut self.entries[index].config { if let Some(config) = &mut self.entries[index].config {
match &command { match request {
Command::SetTransmit { vad } => config.vad = *vad, Command::SetTransmit { vad } => config.vad = *vad,
Command::SetAudio { input_muted, output_muted } => { Command::SetAudio { input_muted, output_muted } => {
if let Some(muted) = input_muted { config.input_muted = *muted; } if let Some(muted) = input_muted { config.input_muted = *muted; }
@@ -661,7 +668,7 @@ impl Actor {
_ => {} _ => {}
} }
} }
if let Command::Whisper(WhisperCommand::Start { epoch, .. }) = &command { self.entries[index].whisper = Some(*epoch); } if let Command::Whisper(WhisperCommand::Start { epoch, .. }) = request { self.entries[index].whisper = Some(*epoch); }
self.dispatch(index, key, command, CompletionKind::Request { guard, capture_revision, changes_config, channel_lease, reply }); self.dispatch(index, key, command, CompletionKind::Request { guard, capture_revision, changes_config, channel_lease, reply });
self.publish(); self.publish();
} }
+53 -2
View File
@@ -1,6 +1,7 @@
//! Reducer fixtures deliberately exercise presentation/session bookkeeping, not network success. //! Reducer fixtures deliberately exercise presentation/session bookkeeping, not network success.
use super::*; use super::*;
use serde_json::json; use serde_json::json;
use teamspeach_core::protocol::{ConnectArgs, ErrorCode};
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
static NEXT: AtomicU64 = AtomicU64::new(0); static NEXT: AtomicU64 = AtomicU64::new(0);
@@ -106,7 +107,7 @@ async fn real_reply_arriving_after_session_boundary_is_rejected() {
let key = actor.create().unwrap(); let key = actor.create().unwrap();
actor.entries[0].worker.as_ref().unwrap().core.request(Command::ProfileCreate { nickname: "Real reply".into() }).await.unwrap(); actor.entries[0].worker.as_ref().unwrap().core.request(Command::ProfileCreate { nickname: "Real reply".into() }).await.unwrap();
let (reply, response) = oneshot::channel(); let (reply, response) = oneshot::channel();
actor.dispatch(0, key, Command::ProfileGet, CompletionKind::Request { actor.dispatch(0, key, validate_command(Command::ProfileGet).unwrap(), CompletionKind::Request {
guard: Guard::Strict, capture_revision: None, changes_config: false, reply, channel_lease:None, guard: Guard::Strict, capture_revision: None, changes_config: false, reply, channel_lease:None,
}); });
let completion = tokio::time::timeout(Duration::from_secs(10), async { let completion = tokio::time::timeout(Duration::from_secs(10), async {
@@ -173,6 +174,56 @@ async fn capture_ingress_distinguishes_frame_expiry_from_revocation() {
manager.shutdown().await.unwrap(); manager.shutdown().await.unwrap();
} }
#[tokio::test(flavor = "current_thread")]
async fn malformed_connection_requests_preserve_acknowledged_capture() {
let profile = Profile::new();
let manager = ConnectionManager::start(profile.0.clone(), Arc::new(|_: ConnectionEvent| {})).unwrap();
let key = manager.create().await.unwrap();
let viewed = manager.create().await.unwrap();
// A nonnumeric channel ID fails after identity selection, but before the core can dial.
let connect = ConnectArgs {
address: "127.0.0.1".into(), channel: Some("cid:not-a-number".into()),
identity_id: None, nickname: None, server_password: None, channel_password: None,
};
assert!(matches!(manager.request(&key, Command::Connect(connect.clone())).await,
Err(ConnectionError::Core(ErrorObj { code: ErrorCode::ProfileMissing, .. }))));
manager.request(&key, Command::ProfileCreate { nickname: "Default identity".into() }).await.unwrap();
// Only the connected snapshot is synthetic; input configuration and ingress use the real offline core.
manager.fixture_control(&key, snapshot(1, &[1])).await.unwrap();
manager.view(&viewed).await.unwrap();
let permit = manager.set_input(Some(&key), InputConfiguration::default()).await.unwrap().unwrap();
assert_eq!(manager.snapshot().capture.as_ref(), Some(&permit));
for (expected, command) in [
("invalid address", Command::Connect(ConnectArgs { address: String::new(), ..connect.clone() })),
("invalid identity_id", Command::Connect(ConnectArgs { identity_id: Some(String::new()), ..connect.clone() })),
("invalid disconnect message", Command::Disconnect { message: Some("x".repeat(81)) }),
] {
let error = manager.request(&key, command).await.unwrap_err();
let ConnectionError::Core(error) = error else { panic!("expected {expected}, got {error:?}") };
assert_eq!(error.code, ErrorCode::BadRequest, "{error:?}");
assert_eq!(error.message, expected);
let current = manager.snapshot();
let entry = current.get(&key.connection_id).unwrap();
assert_eq!(entry.key, key);
assert!(entry.is_connected());
assert_eq!(current.viewed_id.as_ref(), Some(&viewed.connection_id));
assert_eq!(current.input_id.as_ref(), Some(&key.connection_id));
assert_eq!(current.capture.as_ref(), Some(&permit));
assert_eq!(manager.push_audio(&key, CapturedFrame {
pcm: [1; 960], captured_at: Instant::now(), capture_epoch: permit.capture_epoch,
connection_generation: permit.key.generation, whisper: None,
}), CaptureIngress::Accepted, "{expected}");
}
let error = manager.request(&key, Command::Connect(connect)).await.unwrap_err();
let ConnectionError::Core(error) = error else { panic!("expected an offline channel error, got {error:?}") };
assert_eq!(error.code, ErrorCode::BadRequest, "{error:?}");
assert_eq!(error.message, "channel \"cid:<n>\" needs a number");
manager.shutdown().await.unwrap();
}
#[tokio::test(flavor = "current_thread")] #[tokio::test(flavor = "current_thread")]
async fn microphone_handoff_waits_for_ack_while_another_tab_is_viewed() { async fn microphone_handoff_waits_for_ack_while_another_tab_is_viewed() {
async fn input_ack(actor: &mut Actor, owner: &SessionKey) -> Internal { async fn input_ack(actor: &mut Actor, owner: &SessionKey) -> Internal {
@@ -334,7 +385,7 @@ async fn restart_discards_an_outstanding_response_from_the_previous_worker() {
let key = actor.create().unwrap(); let key = actor.create().unwrap();
let other = actor.create().unwrap(); let other = actor.create().unwrap();
let (reply, pending) = oneshot::channel(); let (reply, pending) = oneshot::channel();
actor.operation(Operation::Request(key.clone(), Command::ProfileGet, reply)); actor.operation(Operation::Request(key.clone(), validate_command(Command::ProfileGet).unwrap(), reply));
let response = tokio::time::timeout(Duration::from_secs(5), async { let response = tokio::time::timeout(Duration::from_secs(5), async {
loop { loop {
let message = actor.events.recv().await.unwrap(); let message = actor.events.recv().await.unwrap();