Apply saved whisper policy before a native session connects

- Serialize preference changes with preflight acknowledgement, without holding the policy lock through the network handshake.
This commit is contained in:
omar committed 2026-11-26 18:08:07 +03:00
1 parent 3b5c49e329
commit a153511710
5 files changed
+84 -4

No files matched your search

+2
View File
@@ -68,6 +68,8 @@ pub struct RuntimeServices {
pub audio_configuration:tokio::sync::Mutex<()>,
pub microphone_test_resume:Mutex<Option<(Option<SessionKey>,bool,bool)>>,
pub transmission:Mutex<TransmissionState>,
// Serializes saved receive-mode changes against pre-connect core initialization.
pub(super) whisper_receive:tokio::sync::RwLock<()>,
pub(super) notification_clock:super::notification_actions::NotificationClock,
pub system_scheme:Mutex<Option<crate::services::themes::ColorScheme>>,
pub installed:bool,
-1
View File
@@ -13,7 +13,6 @@ async fn control(ctx:&Arc<RuntimeServices>,event:ConnectionEvent)->Result<()> {
chat_actions::on_control(ctx.clone(),key.clone(),(*value).clone()).await?;
match value["event"].as_str(){
Some("state") if value["state"]=="connected"=>{
let receive=ctx.profile()?.whispers.receive_command();ctx.request(&key,receive).await?;
let volumes=ctx.profile()?.volumes.replace_command()?;ctx.request(&key,volumes).await?;
},
Some("state") if value["state"]!="connected"=>{
@@ -56,6 +56,7 @@ async fn connect_with_audio(ctx:&Arc<RuntimeServices>,key:&SessionKey,args:Conne
let address=args.address.clone();
let (input_muted,output_muted)=*ctx.audio_defaults.lock().map_err(|_|bad("Audio defaults are unavailable"))?;
ctx.request(key,Command::SetAudio{input_muted:Some(input_override.unwrap_or(input_muted)),output_muted:Some(output_muted)}).await?;
initialize_whisper_receive(ctx,key,ui_generation).await?;
ctx.require_ui_generation(ui_generation)?;
ctx.require_key(key,false)?;
if let Some(bookmark)=bookmark{check_bookmark(&*ctx.profile()?,bookmark)?;}
@@ -81,6 +82,14 @@ async fn connect_with_audio(ctx:&Arc<RuntimeServices>,key:&SessionKey,args:Conne
ctx.mutate(move|p|{p.prefs.set(json!({"lastAddress":address}))?;Ok(())}).await?;
Ok(())
}
async fn initialize_whisper_receive(ctx:&RuntimeServices,key:&SessionKey,ui_generation:u64)->Result<Value>{
// Wait for a concurrent edit to reach both storage and the ready cores. Do not hold
// the guard through Connect: live edits also update ready cores that are still joining.
let _mode=ctx.whisper_receive.read().await;
ctx.require_ui_generation(ui_generation)?;
let receive=ctx.profile()?.whispers.receive_command();
ctx.request(key,receive).await
}
pub async fn bookmark(ctx:&Arc<RuntimeServices>,target:&Target,startup:bool)->Result<WorkflowResult>{
if !ctx.network_enabled{return Err(ServiceError::new("network_disabled","Network connections are disabled in this isolated runtime"))}
let generation=ctx.current_ui_generation()?;
@@ -141,3 +150,43 @@ async fn join(ctx:&Arc<RuntimeServices>,target:Target,values:Values)->Result<()>
joined?;restored?;Ok(())
}
async fn channel_password(ctx:&RuntimeServices,target:&Target)->Result<String>{let mut editor=form(ctx,target,Operation::ConfirmPassword)?;editor.fields.retain(|field|field.id=="password");let values=input(ctx,editor,Values::new()).await?;let secret=SecretString::new(text(&values,"password")?)?;Ok(secret.expose(ExplicitSecretAccess::ConnectByUser).to_owned())}
#[cfg(test)]
#[tokio::test(flavor = "current_thread")]
async fn whisper_preflight_acknowledges_mode_from_concurrent_settings_edit(){
use crate::{AppConfig, AppRuntime, services::{profile_import::initialize_native_root, whisper::{ReceiveMode,WhisperStore}}, ui::settings::{Field,SettingValue,SettingsAction}};
use std::{pin::pin,time::Duration};
use super::super::{isolated_settings,model::BootstrapState};
let temp=tempfile::tempdir().unwrap();
let root=temp.path().join("profile");
initialize_native_root(&root).unwrap();
ProfileServices::open(&root).unwrap().identities.onboard("Whisper policy test").unwrap();
let runtime=AppRuntime::start(AppConfig::isolated(root.clone())).unwrap();
let ui_generation=runtime.next_ui_generation();
let mut updates=runtime.subscribe();
let timeout=Duration::from_secs(5);
let ready=tokio::time::timeout(timeout,updates.wait_for(|state|{
state.bootstrap==BootstrapState::Ready&&state.settings.loaded&&!state.connections.connections.is_empty()
})).await.unwrap().unwrap().clone();
let key=&ready.connections.connections[0].key;
let ctx=runtime.services.lock().unwrap().upgrade().unwrap();
assert_eq!(ctx.profile().unwrap().whispers.get().receive_mode,ReceiveMode::AllowAll);
// Queue the real settings writer ahead of preflight without relying on timing.
// Tokio's fair lock will not let a later reader overtake the waiting writer.
let blocker=ctx.whisper_receive.read().await;
let mut edit=pin!(isolated_settings(ctx.clone(),SettingsAction::Edit{
field:Field::WhisperReceive,value:SettingValue::Text("deny_all".into()),
}));
assert!(futures::poll!(edit.as_mut()).is_pending());
let mut preflight=pin!(initialize_whisper_receive(&ctx,key,ui_generation));
assert!(futures::poll!(preflight.as_mut()).is_pending());
drop(blocker);
let (edited,applied)=tokio::time::timeout(timeout,async{tokio::join!(edit,preflight)}).await.unwrap();
assert!(edited.is_ok());
assert_eq!(applied.unwrap()["mode"],"deny_all");
assert_eq!(WhisperStore::open(&root).unwrap().get().receive_mode,ReceiveMode::DenyAll);
assert!(!ctx.connected.connections.snapshot().any_active());
runtime.shutdown().await.unwrap();
}
+1
View File
@@ -74,6 +74,7 @@ async fn construct(config:&AppConfig,profile:ProfileServices,runtime:Weak<AppRun
file_workflows:Default::default(),chat_workflows:Default::default(),stream_workflows:Default::default(),local_workflows:Default::default(),
audio_input_active:AtomicBool::new(false),audio_output_active:AtomicBool::new(false),
applied_audio_selections:Mutex::new(None),audio_configuration:Default::default(),microphone_test_resume:Mutex::new(None),
whisper_receive:Default::default(),
transmission:Default::default(),notification_clock:notification_actions::NotificationClock::new(),system_scheme:Mutex::new(None),installed,
microphone_granted:AtomicBool::new(false),output_granted:AtomicBool::new(false),policy,
network_enabled:config.network_enabled,version:config.build_version,runtime:runtime.clone(),
@@ -32,9 +32,7 @@ pub(super) async fn edit(ctx:Arc<RuntimeServices>,field:Field,value:SettingValue
Field::KeyBindingGlobal{profile,binding}=>{let global=boolean(value)?;keys::edit_binding(&ctx,profile,binding,move|b|{b.global=global;Ok(())}).await?;},
Field::WhisperReceive=>{
let mode=match text(value)?.as_str(){"allow_all"=>ReceiveMode::AllowAll,"deny_all"=>ReceiveMode::DenyAll,_=>return Err(bad("Unknown whisper receive mode"))};
let keys=ctx.connected.connections.snapshot().connections.iter().filter(|c|c.is_connected()).map(|c|c.key.clone()).collect::<Vec<_>>();
for key in &keys{ctx.request(key,teamspeach_core::protocol::Command::Whisper(teamspeach_core::whisper::WhisperCommand::SetReceive{deny:mode==ReceiveMode::DenyAll})).await?;ctx.require_key(key,true)?;}
ctx.mutate(move|p|p.whispers.set_receive_mode(mode)).await?;
update_whisper_receive(&ctx,mode).await?;
},
Field::Whisper{list,field}=>{edit_whisper(&ctx,list,move|l|{match field{WhisperField::Name=>l.name=text(value)?,WhisperField::Kind=>l.kind=choice_number(value,1,2)?,WhisperField::GroupType=>l.group_type=choice_number(value,0,3)?,WhisperField::GroupTargetMode=>l.group_target_mode=choice_number(value,0,6)?,WhisperField::ServerUid=>{l.target_server_uuid=text(value)?;l.target_server_name.clear();l.target_group_id="0".into();l.target_group_name.clear();},WhisperField::GroupId=>{l.target_group_id=text(value)?;l.target_group_name.clear();}}Ok(())}).await?;},
Field::NotificationState(id)=>notification(&ctx,id,choice_number(value,0,2)?).await?,
@@ -59,6 +57,37 @@ pub(super) async fn edit(ctx:Arc<RuntimeServices>,field:Field,value:SettingValue
Field::IdentityTarget(_)|Field::NewIdentityName|Field::NewKeyProfileName|Field::NewWhisperName=>return Err(bad("Invalid draft value")),
}done()
}
async fn update_whisper_receive(ctx:&Arc<RuntimeServices>,mode:ReceiveMode)->Result<()>{
use crate::app::connections::CoreStatus;
use teamspeach_core::{protocol::Command,whisper::WhisperCommand};
let _update=ctx.whisper_receive.write().await;
let deny=mode==ReceiveMode::DenyAll;
// Never let a core allow whispers while Deny All is still saved. Conversely, do not
// save Deny All until every ready core has acknowledged the restriction.
if !deny{ctx.mutate(move|p|p.whispers.set_receive_mode(mode)).await?;}
let snapshot=ctx.connected.connections.snapshot();
let mut failure=None;
for tab in snapshot.connections.iter().filter(|tab|tab.status==CoreStatus::Ready){
if let Err(error)=ctx.request(&tab.key,Command::Whisper(WhisperCommand::SetReceive{deny})).await{
failure.get_or_insert(error);
}
}
if let Some(mut error)=failure{
let status=if deny{"Deny All was not saved; some server tabs may already be blocking whispers"}
else{"Allow All was saved, but some server tabs could not confirm the change"};
error.message=format!("{status}: {}",error.message);
return Err(error)
}
if deny{
ctx.mutate(move|p|p.whispers.set_receive_mode(mode)).await.map_err(|mut error|{
error.message=format!("Server tabs were told to block whispers, but saving Deny All could not be confirmed: {}",error.message);
error
})?;
}
Ok(())
}
fn choice_number(value:SettingValue,min:u8,max:u8)->Result<u8>{let value=match value{SettingValue::Text(v)=>v.parse::<u8>().map_err(|_|bad("Invalid choice"))?,v=>integer(v,min.into(),max.into())? as u8};if value<min||value>max{return Err(bad("Choice outside range"))}Ok(value)}
fn save_notification(prefs: &mut Prefs, current: &NotificationPrefs, key: &str, state: u8) -> Result<()> {
let next = current.with_state(key, state)?;