feat(network): integrate nmrs for VPN, airplane mode, and secret agent

Replace cosmic-settings-network-manager-subscription channel-based
NetworkManager calls with direct nmrs API calls:
- VPN list: nm.list_saved_connections() instead of hand-walking
  NetworkManagerSettings over D-Bus.
- VPN connect/disconnect: nm.connect_vpn_by_uuid / disconnect_vpn_by_uuid.
- Forget Wi-Fi: nm.forget(&ssid).
- Wi-Fi radio toggle: nm.set_wireless_enabled.
- Airplane mode: nm.set_airplane_mode, dropping
  cosmic-settings-airplane-mode-subscription.
- Secret agent: nmrs::agent::SecretAgent registered per-popup,
  replacing nm-secret-agent-manager. VPN secrets are replied via
  responder.vpn_secrets(...); the applets own Authenticate flow still
  drives Wi-Fi password handoff and releases NM with NoSecrets.
This commit is contained in:
Akrm Al-Hakimi 2026-04-25 01:04:18 -04:00 • committed by Ashley Wulber
parent 65a9e142b5
commit 8d84396e57
3 changed files with 387 additions and 402 deletions

64
Cargo.lock generated
View file

@ -1221,7 +1221,6 @@ dependencies = [
"anyhow", "anyhow",
"async-fn-stream", "async-fn-stream",
"cosmic-dbus-networkmanager", "cosmic-dbus-networkmanager",
"cosmic-settings-airplane-mode-subscription",
"cosmic-settings-network-manager-subscription", "cosmic-settings-network-manager-subscription",
"futures", "futures",
"futures-util", "futures-util",
@ -1229,7 +1228,7 @@ dependencies = [
"i18n-embed-fl", "i18n-embed-fl",
"indexmap 2.14.0", "indexmap 2.14.0",
"libcosmic", "libcosmic",
"nm-secret-agent-manager", "nmrs",
"rust-embed", "rust-embed",
"rustc-hash 2.1.2", "rustc-hash 2.1.2",
"secure-string", "secure-string",
@ -1576,18 +1575,6 @@ dependencies = [
"zbus", "zbus",
] ]
[[package]]
name = "cosmic-settings-airplane-mode-subscription"
version = "1.0.7"
source = "git+https://github.com/pop-os/cosmic-settings#703a934b096b8681b1b8d16d8625118c8073151a"
dependencies = [
"futures",
"iced_futures",
"log",
"rustix 1.1.4",
"tokio",
]
[[package]] [[package]]
name = "cosmic-settings-config" name = "cosmic-settings-config"
version = "0.1.0" version = "0.1.0"
@ -2054,7 +2041,7 @@ dependencies = [
"libc", "libc",
"option-ext", "option-ext",
"redox_users", "redox_users",
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@ -2252,7 +2239,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
dependencies = [ dependencies = [
"libc", "libc",
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@ -2640,6 +2627,12 @@ version = "0.3.32"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
[[package]]
name = "futures-timer"
version = "3.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f288b0a4f20f9a56b5d1da57e2227c661b7b16168e2f72365f57b63326e29b24"
[[package]] [[package]]
name = "futures-util" name = "futures-util"
version = "0.3.32" version = "0.3.32"
@ -3894,7 +3887,7 @@ dependencies = [
"portable-atomic", "portable-atomic",
"portable-atomic-util", "portable-atomic-util",
"serde_core", "serde_core",
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@ -4045,7 +4038,7 @@ version = "1.4.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7a1886916523694cd6ea3d175f03a1e5010699a2a4cc13696d83d7bea1d80638" checksum = "7a1886916523694cd6ea3d175f03a1e5010699a2a4cc13696d83d7bea1d80638"
dependencies = [ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@ -4615,6 +4608,26 @@ dependencies = [
"zbus", "zbus",
] ]
[[package]]
name = "nmrs"
version = "3.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e7e844f47ab7f54da2a16de939f5b52ad6c84b844be68e9338e3d32160ddcd68"
dependencies = [
"async-trait",
"base64",
"bitflags 2.11.1",
"futures",
"futures-timer",
"log",
"serde",
"thiserror 2.0.18",
"tokio",
"uuid",
"zbus",
"zvariant",
]
[[package]] [[package]]
name = "nom" name = "nom"
version = "7.1.3" version = "7.1.3"
@ -4667,7 +4680,7 @@ version = "0.50.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5"
dependencies = [ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@ -5857,7 +5870,7 @@ dependencies = [
"errno", "errno",
"libc", "libc",
"linux-raw-sys 0.12.1", "linux-raw-sys 0.12.1",
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@ -6091,6 +6104,12 @@ dependencies = [
"syn", "syn",
] ]
[[package]]
name = "sha1_smol"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bbfa15b3dddfee50a0fff136974b3e1bde555604ba463834a7eb7deb6417705d"
[[package]] [[package]]
name = "sha2" name = "sha2"
version = "0.10.9" version = "0.10.9"
@ -6463,7 +6482,7 @@ dependencies = [
"getrandom 0.4.2", "getrandom 0.4.2",
"once_cell", "once_cell",
"rustix 1.1.4", "rustix 1.1.4",
"windows-sys 0.61.2", "windows-sys 0.59.0",
] ]
[[package]] [[package]]
@ -7026,6 +7045,7 @@ dependencies = [
"getrandom 0.4.2", "getrandom 0.4.2",
"js-sys", "js-sys",
"serde_core", "serde_core",
"sha1_smol",
"wasm-bindgen", "wasm-bindgen",
] ]
@ -7532,7 +7552,7 @@ version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [ dependencies = [
"windows-sys 0.61.2", "windows-sys 0.48.0",
] ]
[[package]] [[package]]

View file

@ -26,16 +26,13 @@ tracing-log.workspace = true
tracing-subscriber.workspace = true tracing-subscriber.workspace = true
tracing.workspace = true tracing.workspace = true
zbus.workspace = true zbus.workspace = true
nm-secret-agent-manager = { git = "https://github.com/pop-os/dbus-settings-bindings/" }
indexmap = "2.13.0" indexmap = "2.13.0"
secure-string = "0.3.0" secure-string = "0.3.0"
uuid = { version = "1.21.0", features = ["v4"] } uuid = { version = "1.21.0", features = ["v4"] }
nmrs = "3.0"
[dependencies.cosmic-settings-network-manager-subscription] [dependencies.cosmic-settings-network-manager-subscription]
git = "https://github.com/pop-os/cosmic-settings/" git = "https://github.com/pop-os/cosmic-settings/"
# path = "../../cosmic-settings/subscriptions/network-manager" # path = "../../cosmic-settings/subscriptions/network-manager"
[dependencies.cosmic-settings-airplane-mode-subscription]
git = "https://github.com/pop-os/cosmic-settings/"
# path = "../../cosmic-settings/subscriptions/airplane-mode"

View file

@ -1,21 +1,21 @@
use anyhow::Context; use anyhow::Context;
use cosmic_dbus_networkmanager::settings::{NetworkManagerSettings, connection::Settings};
use cosmic_settings_network_manager_subscription::{ use cosmic_settings_network_manager_subscription::{
self as network_manager, NetworkManagerState, UUID, self as network_manager, NetworkManagerState, UUID,
active_conns::active_conns_subscription,
available_wifi::{AccessPoint, NetworkType}, available_wifi::{AccessPoint, NetworkType},
current_networks::ActiveConnectionInfo, current_networks::ActiveConnectionInfo,
hw_address::HwAddress, hw_address::HwAddress,
nm_secret_agent::{self, PasswordFlag, SecretSender},
}; };
use indexmap::IndexMap; use indexmap::IndexMap;
use nmrs::{
NetworkManager as NmrsManager, SettingsSummary,
agent::{SecretAgent, SecretAgentCapabilities, SecretRequest, SecretResponder, SecretSetting},
};
use rustc_hash::FxHashSet; use rustc_hash::FxHashSet;
use secure_string::SecureString; use secure_string::SecureString;
use std::{ use std::{
borrow::Cow, borrow::Cow,
collections::{BTreeMap, BTreeSet}, collections::{BTreeMap, HashMap},
sync::{Arc, LazyLock}, sync::{Arc, LazyLock},
time::Duration,
}; };
use cosmic::{ use cosmic::{
@ -33,18 +33,17 @@ use cosmic::{
}, },
surface, theme, surface, theme,
widget::{ widget::{
Column, Id, Row, button, column, container, divider, Id, button, column, container, divider,
icon::{self, from_name}, icon::{self, from_name},
row, scrollable, secure_input, text, text_input, toggler, row, scrollable, secure_input, text, text_input, toggler,
}, },
}; };
use cosmic_dbus_networkmanager::interface::{ use cosmic_dbus_networkmanager::interface::enums::{
access_point, ActiveConnectionState, DeviceState, NmConnectivityState,
enums::{ActiveConnectionState, DeviceState, NmConnectivityState, NmState},
}; };
use futures::{StreamExt, channel::mpsc::TrySendError}; use futures::{StreamExt, lock::Mutex as AsyncMutex};
use zbus::{Connection, zvariant::ObjectPath}; use zbus::Connection;
use crate::{config, fl}; use crate::{config, fl};
@ -74,14 +73,6 @@ impl NewConnectionState {
} }
.ssid .ssid
} }
pub fn hw_address(&self) -> HwAddress {
match self {
Self::EnterPassword { access_point, .. } => access_point,
Self::Waiting(ap) => ap,
Self::Failure(ap) => ap,
}
.hw_address
}
} }
impl From<NewConnectionState> for AccessPoint { impl From<NewConnectionState> for AccessPoint {
@ -101,51 +92,53 @@ pub struct MyNetworkState {
pub known_vpns: IndexMap<UUID, ConnectionSettings>, pub known_vpns: IndexMap<UUID, ConnectionSettings>,
pub ssid_to_uuid: BTreeMap<Box<str>, Box<str>>, pub ssid_to_uuid: BTreeMap<Box<str>, Box<str>>,
pub devices: Vec<Arc<network_manager::devices::DeviceInfo>>, pub devices: Vec<Arc<network_manager::devices::DeviceInfo>>,
pub password: Option<Password>,
pub connecting: BTreeSet<network_manager::SSID>,
pub nm_state: NetworkManagerState, pub nm_state: NetworkManagerState,
pub requested_vpn: Option<RequestedVpn>, pub requested_vpn: Option<RequestedVpn>,
} }
/// Shared, take-once handle to an `nmrs` [`SecretResponder`]. Cloned freely
/// across `Message` boundaries; the first consumer to `lock().take()` it owns
/// the reply to NetworkManager.
pub type SecretResponderHandle = Arc<AsyncMutex<Option<SecretResponder>>>;
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct RequestedVpn { pub struct RequestedVpn {
name: String,
uuid: Arc<str>, uuid: Arc<str>,
description: Option<String>, description: Option<String>,
password: SecureString, password: SecureString,
password_hidden: bool, password_hidden: bool,
tx: SecretSender, responder: SecretResponderHandle,
/// VPN secret keys NM hinted as needed (e.g. `["password"]`). When empty,
/// `"password"` is used as a fallback.
secret_keys: Vec<String>,
} }
#[derive(Clone, Debug)] #[derive(Clone, Debug)]
pub enum ConnectionSettings { pub enum ConnectionSettings {
Vpn(VpnConnectionSettings), Vpn { id: String },
Wireguard { id: String }, Wireguard { id: String },
} }
#[derive(Clone, Debug, Default)] /// Local mirror of the secret-agent events the applet cares about. Sourced
pub struct VpnConnectionSettings { /// from `nmrs::agent` instead of the previous `nm_secret_agent` subscription.
id: String, #[derive(Debug, Clone)]
username: Option<String>, pub enum NmAgentEvent {
connection_type: Option<ConnectionType>, RequestSecret {
password_flag: Option<PasswordFlag>, connection_uuid: String,
connection_id: String,
setting: AgentSetting,
responder: SecretResponderHandle,
},
CancelGetSecrets,
Failed(String),
} }
#[derive(Clone, Debug, Eq, PartialEq)] #[derive(Debug, Clone)]
enum ConnectionType { pub enum AgentSetting {
Password, WifiPsk { ssid: String },
} WifiEap,
Vpn { secret_keys: Vec<String> },
impl VpnConnectionSettings { Other,
fn password_flag(&self) -> Option<PasswordFlag> {
self.connection_type
.as_ref()
.is_some_and(|ct| match ct {
ConnectionType::Password => true,
})
.then_some(self.password_flag)
.flatten()
}
} }
#[derive(Default)] #[derive(Default)]
@ -157,7 +150,6 @@ struct CosmicNetworkApplet {
// NM state // NM state
nm_sender: Option<futures::channel::mpsc::UnboundedSender<network_manager::Request>>, nm_sender: Option<futures::channel::mpsc::UnboundedSender<network_manager::Request>>,
nm_task: Option<tokio::sync::oneshot::Sender<()>>, nm_task: Option<tokio::sync::oneshot::Sender<()>>,
secret_tx: Option<tokio::sync::mpsc::Sender<nm_secret_agent::Request>>,
nm_state: MyNetworkState, nm_state: MyNetworkState,
// UI state // UI state
@ -264,8 +256,9 @@ fn vpn_section<'a>(
if show_available_vpns { if show_available_vpns {
for (uuid, connection) in &nm_state.known_vpns { for (uuid, connection) in &nm_state.known_vpns {
let id = match connection { let id = match connection {
ConnectionSettings::Vpn(connection) => connection.id.as_str(), ConnectionSettings::Vpn { id } | ConnectionSettings::Wireguard { id } => {
ConnectionSettings::Wireguard { id } => id.as_str(), id.as_str()
}
}; };
// Check if this VPN is currently active // Check if this VPN is currently active
let is_active = nm_state.nm_state.active_conns.iter().any( let is_active = nm_state.nm_state.active_conns.iter().any(
@ -366,15 +359,12 @@ impl CosmicNetworkApplet {
} }
fn update_togglers(&mut self, state: &NetworkManagerState) { fn update_togglers(&mut self, state: &NetworkManagerState) {
let mut changed = false;
if self.nm_state.nm_state.wifi_enabled != state.wifi_enabled { if self.nm_state.nm_state.wifi_enabled != state.wifi_enabled {
self.nm_state.nm_state.wifi_enabled = state.wifi_enabled; self.nm_state.nm_state.wifi_enabled = state.wifi_enabled;
changed = true;
} }
if self.nm_state.nm_state.airplane_mode != state.airplane_mode { if self.nm_state.nm_state.airplane_mode != state.airplane_mode {
self.nm_state.nm_state.airplane_mode = state.airplane_mode; self.nm_state.nm_state.airplane_mode = state.airplane_mode;
changed = true;
} }
} }
@ -397,53 +387,88 @@ impl CosmicNetworkApplet {
} }
fn connect_vpn(&mut self, uuid: Arc<str>) -> Task<cosmic::Action<Message>> { fn connect_vpn(&mut self, uuid: Arc<str>) -> Task<cosmic::Action<Message>> {
if let Some((tx, conn)) = self.nm_sender.clone().zip(self.conn.clone()) {
cosmic::task::future(async move { cosmic::task::future(async move {
// Find the connection by UUID match NmrsManager::new().await {
if let Ok(nm_settings) = NetworkManagerSettings::new(&conn).await { Ok(nm) => match nm.connect_vpn_by_uuid(&uuid).await {
if let Ok(connections) = nm_settings.list_connections().await { Ok(()) => Message::Refresh,
for connection in connections { Err(e) => Message::Error(format!("activate VPN {uuid}: {e}")),
if let Ok(settings) = connection.get_settings().await { },
let settings = Settings::new(settings); Err(e) => Message::Error(format!("nmrs init: {e}")),
if let Some(conn_settings) = &settings.connection { }
if conn_settings.uuid.as_ref().is_some_and(|conn_uuid| { })
conn_uuid.as_str() == uuid.as_ref() }
}) {
let path = connection.inner().path().clone().to_owned();
if let Err(err) =
tx.unbounded_send(network_manager::Request::Activate(
ObjectPath::try_from("/").unwrap(),
path,
))
{
if err.is_disconnected() {
return zbus::Connection::system()
.await
.context(
"failed to create system dbus connection",
)
.map_or_else(
|why| Message::Error(why.to_string()),
Message::NetworkManagerConnect,
);
} }
tracing::error!("{err:?}"); /// Registers an `nmrs` secret agent on the system bus and yields its
/// requests + cancellations as [`NmAgentEvent`] for the applet to handle.
fn secret_agent_task(identifier: String) -> Task<NmAgentEvent> {
cosmic::Task::stream(async_fn_stream::fn_stream(move |emitter| async move {
let registration = SecretAgent::builder()
.with_identifier(identifier)
.with_capabilities(SecretAgentCapabilities::VPN_HINTS)
.register()
.await;
let (mut handle, mut requests) = match registration {
Ok(pair) => pair,
Err(e) => {
let _ = emitter.emit(NmAgentEvent::Failed(e.to_string())).await;
return;
} }
break; };
loop {
tokio::select! {
req = requests.next() => match req {
Some(req) => {
let event = secret_request_to_event(req);
let _ = emitter.emit(event).await;
}
None => break,
},
cancel = handle.cancellations().next() => match cancel {
Some(_reason) => {
let _ = emitter.emit(NmAgentEvent::CancelGetSecrets).await;
}
None => break,
},
} }
} }
if let Err(e) = handle.unregister().await {
tracing::warn!("failed to unregister secret agent: {e}");
}
}))
}
fn secret_request_to_event(req: SecretRequest) -> NmAgentEvent {
let setting = match req.setting {
SecretSetting::WifiPsk { ssid } => AgentSetting::WifiPsk { ssid },
SecretSetting::WifiEap { .. } => AgentSetting::WifiEap,
SecretSetting::Vpn { .. } => AgentSetting::Vpn {
secret_keys: req.hints.clone(),
},
_ => AgentSetting::Other,
};
NmAgentEvent::RequestSecret {
connection_uuid: req.connection_uuid,
connection_id: req.connection_id,
setting,
responder: Arc::new(AsyncMutex::new(Some(req.responder))),
} }
} }
/// Reply with [`NoSecrets`](nmrs::agent::SecretResponder::no_secrets) to free
/// NetworkManager when the applet decides not to use the responder. Dropping
/// it would also auto-reply, but doing it explicitly keeps the log clean.
fn release_responder(responder: SecretResponderHandle) -> Task<cosmic::Action<Message>> {
cosmic::task::future(async move {
if let Some(r) = responder.lock().await.take() {
let _ = r.no_secrets().await;
} }
} Message::NoOp
Message::Refresh
}) })
} else {
tracing::warn!("No sender available to activate VPN.");
Task::none()
}
}
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
@ -460,12 +485,13 @@ pub(crate) enum Message {
TogglePasswordVisibility, TogglePasswordVisibility,
FocusSecureInput, FocusSecureInput,
NoOp, NoOp,
#[allow(dead_code)] // required by `cosmic::applet` surface path; not always emitted
Surface(surface::Action), Surface(surface::Action),
ActivateVpn(Arc<str>), // UUID of VPN to activate ActivateVpn(Arc<str>), // UUID of VPN to activate
DeactivateVpn(Arc<str>), // UUID of VPN to deactivate DeactivateVpn(Arc<str>), // UUID of VPN to deactivate
ToggleVpnList, // Show/hide available VPNs ToggleVpnList, // Show/hide available VPNs
/// An update from the secret agent /// An update from the secret agent
SecretAgent(network_manager::nm_secret_agent::Event), SecretAgent(NmAgentEvent),
/// Connect to a WiFi network access point. /// Connect to a WiFi network access point.
Connect(network_manager::SSID, HwAddress), Connect(network_manager::SSID, HwAddress),
/// Connect with a password /// Connect with a password
@ -501,16 +527,6 @@ pub(crate) enum Message {
SelectDevice(Option<Arc<network_manager::devices::DeviceInfo>>), SelectDevice(Option<Arc<network_manager::devices::DeviceInfo>>),
} }
#[derive(Debug, Clone)]
struct Password {
ssid: network_manager::SSID,
hw_address: HwAddress,
identity: Option<String>,
password: SecureString,
password_hidden: bool,
tx: SecretSender,
}
fn connection_settings(conn: zbus::Connection) -> Task<Message> { fn connection_settings(conn: zbus::Connection) -> Task<Message> {
let settings = async move { let settings = async move {
let settings = network_manager::dbus::settings::NetworkManagerSettings::new(&conn).await?; let settings = network_manager::dbus::settings::NetworkManagerSettings::new(&conn).await?;
@ -634,109 +650,30 @@ impl CosmicNetworkApplet {
} }
} }
fn load_vpns(conn: zbus::Connection) -> Task<crate::app::Message> { fn load_vpns(_conn: zbus::Connection) -> Task<crate::app::Message> {
let settings = async move { cosmic::task::future(async move {
let settings = network_manager::dbus::settings::NetworkManagerSettings::new(&conn).await?; let nm = match NmrsManager::new().await {
Ok(nm) => nm,
_ = settings.load_connections(&[]).await; Err(e) => return Message::Error(format!("nmrs init: {e}")),
let settings = settings
// Get a list of known connections.
.list_connections()
.await?
// Prepare for wrapping in a concurrent stream.
.into_iter()
.map(|conn| async move { conn })
// Create a concurrent stream for each connection.
.apply(futures::stream::FuturesOrdered::from_iter)
// Concurrently fetch settings for each connection, and filter for VPN.
.filter_map(|conn| async move {
let settings = conn.get_settings().await.ok()?;
let connection = settings.get("connection")?;
match connection
.get("type")?
.downcast_ref::<String>()
.ok()?
.as_str()
{
"vpn" => (),
"wireguard" => {
let id = connection.get("id")?.downcast_ref::<String>().ok()?;
let uuid = connection.get("uuid")?.downcast_ref::<String>().ok()?;
return Some((Arc::from(uuid), ConnectionSettings::Wireguard { id }));
}
_ => return None,
}
let vpn = settings.get("vpn")?;
let id = connection.get("id")?.downcast_ref::<String>().ok()?;
let uuid = connection.get("uuid")?.downcast_ref::<String>().ok()?;
let (connection_type, username, password_flag) = vpn
.get("data")
.and_then(|data| data.downcast_ref::<zbus::zvariant::Dict>().ok())
.map(|dict| {
let (mut connection_type, mut password_flag) = (None, None);
let mut username = vpn
.get("user-name")
.and_then(|u| u.downcast_ref::<String>().ok());
if dict
.get::<String, String>(&String::from("connection-type"))
.ok()
.flatten()
.as_deref()
// may be "password" or "password-tls"
.is_some_and(|p| p.starts_with("password"))
{
connection_type = Some(ConnectionType::Password);
username = Some(username.unwrap_or_default());
password_flag = dict
.get::<String, String>(&String::from("password-flags"))
.ok()
.flatten()
.and_then(|value| match value.as_str() {
"0" => Some(PasswordFlag::None),
"1" => Some(PasswordFlag::AgentOwned),
"2" => Some(PasswordFlag::NotSaved),
"4" => Some(PasswordFlag::NotRequired),
_ => None,
});
}
(connection_type, username, password_flag)
})
.unwrap_or_default();
Some((
Arc::from(uuid),
ConnectionSettings::Vpn(VpnConnectionSettings {
id,
connection_type,
password_flag,
username,
}),
))
})
// Reduce the settings list into
.fold(IndexMap::new(), |mut set, (uuid, data)| async move {
set.insert(uuid, data);
set
})
.await;
Ok::<_, zbus::Error>(settings)
}; };
cosmic::task::future(async move { let saved = match nm.list_saved_connections().await {
settings.await.map_or_else( Ok(saved) => saved,
|why| Message::Error(why.to_string()), Err(e) => return Message::Error(format!("list saved connections: {e}")),
Message::KnownConnections, };
)
let mut map: IndexMap<UUID, ConnectionSettings> = IndexMap::new();
for c in saved {
let uuid: UUID = Arc::from(c.uuid.as_str());
let entry = match c.summary {
SettingsSummary::WireGuard { .. } => ConnectionSettings::Wireguard { id: c.id },
SettingsSummary::Vpn { .. } => ConnectionSettings::Vpn { id: c.id },
_ => continue,
};
map.insert(uuid, entry);
}
Message::KnownConnections(map)
}) })
} }
@ -759,7 +696,7 @@ impl cosmic::Application for CosmicNetworkApplet {
const APP_ID: &'static str = config::APP_ID; const APP_ID: &'static str = config::APP_ID;
fn init(core: cosmic::app::Core, _flags: ()) -> (Self, app::Task<Message>) { fn init(core: cosmic::app::Core, _flags: ()) -> (Self, app::Task<Message>) {
let mut applet = Self { let applet = Self {
core, core,
icon_name: "network-wired-disconnected-symbolic".to_string(), icon_name: "network-wired-disconnected-symbolic".to_string(),
token_tx: None, token_tx: None,
@ -789,19 +726,11 @@ impl cosmic::Application for CosmicNetworkApplet {
tasks.push(update_state(conn.clone())); tasks.push(update_state(conn.clone()));
tasks.push(update_devices(conn.clone())); tasks.push(update_devices(conn.clone()));
tasks.push(load_vpns(conn)); tasks.push(load_vpns(conn));
let (tx, rx) = tokio::sync::mpsc::channel(4);
self.secret_tx = Some(tx);
let my_id = format!( let my_id = format!(
"com.system76.CosmicSettings.Applet.{}.NetworkManager.SecretAgent", "com.system76.CosmicSettings.Applet.{}.NetworkManager.SecretAgent",
uuid::Uuid::new_v4() uuid::Uuid::new_v4()
); );
tasks.push( tasks.push(secret_agent_task(my_id).map(Message::SecretAgent));
cosmic::Task::stream(nm_secret_agent::secret_agent_stream(
my_id.clone(),
rx,
))
.map(Message::SecretAgent),
);
} }
// TODO request update of state maybe // TODO request update of state maybe
let new_id = window::Id::unique(); let new_id = window::Id::unique();
@ -823,17 +752,20 @@ impl cosmic::Application for CosmicNetworkApplet {
} }
Message::ToggleAirplaneMode(enabled) => { Message::ToggleAirplaneMode(enabled) => {
self.toggle_wifi_ctr += 1; self.toggle_wifi_ctr += 1;
if let Some(tx) = self.nm_sender.as_mut() { self.nm_state.nm_state.airplane_mode = enabled;
if let Err(err) = return cosmic::task::future(async move {
tx.unbounded_send(network_manager::Request::SetAirplaneMode(enabled)) match NmrsManager::new().await {
{ Ok(nm) => match nm.set_airplane_mode(enabled).await {
if err.is_disconnected() { Ok(()) => Message::Refresh,
return system_conn().map(cosmic::Action::App); Err(e) => {
} tracing::warn!("set_airplane_mode partial failure: {e}");
Message::Refresh
tracing::error!("{err:?}");
} }
},
Err(e) => Message::Error(format!("nmrs init: {e}")),
} }
})
.map(cosmic::Action::App);
} }
Message::SelectWirelessAccessPoint(access_point) => { Message::SelectWirelessAccessPoint(access_point) => {
let Some(tx) = self.nm_sender.as_ref() else { let Some(tx) = self.nm_sender.as_ref() else {
@ -845,7 +777,7 @@ impl cosmic::Application for CosmicNetworkApplet {
tx.unbounded_send(network_manager::Request::SelectAccessPoint( tx.unbounded_send(network_manager::Request::SelectAccessPoint(
access_point.ssid.clone(), access_point.ssid.clone(),
access_point.network_type, access_point.network_type,
self.secret_tx.clone(), None,
self.active_device.as_ref().map(|d| d.interface.clone()), self.active_device.as_ref().map(|d| d.interface.clone()),
)) ))
{ {
@ -862,12 +794,11 @@ impl cosmic::Application for CosmicNetworkApplet {
.nm_state .nm_state
.known_access_points .known_access_points
.contains(&access_point) .contains(&access_point)
{ && let Err(err) =
if let Err(err) =
tx.unbounded_send(network_manager::Request::SelectAccessPoint( tx.unbounded_send(network_manager::Request::SelectAccessPoint(
access_point.ssid.clone(), access_point.ssid.clone(),
access_point.network_type, access_point.network_type,
self.secret_tx.clone(), None,
self.active_device.as_ref().map(|d| d.interface.clone()), self.active_device.as_ref().map(|d| d.interface.clone()),
)) ))
{ {
@ -877,7 +808,6 @@ impl cosmic::Application for CosmicNetworkApplet {
tracing::error!("{err:?}"); tracing::error!("{err:?}");
} }
}
self.new_connection = Some(NewConnectionState::EnterPassword { self.new_connection = Some(NewConnectionState::EnterPassword {
access_point, access_point,
description: None, description: None,
@ -915,7 +845,6 @@ impl cosmic::Application for CosmicNetworkApplet {
_ = cancel.send(()); _ = cancel.send(());
} }
self.secret_tx = None;
return system_conn().map(cosmic::Action::App); return system_conn().map(cosmic::Action::App);
} }
} }
@ -981,19 +910,23 @@ impl cosmic::Application for CosmicNetworkApplet {
tracing::warn!("Failed to find known access point with ssid: {}", ssid); tracing::warn!("Failed to find known access point with ssid: {}", ssid);
return Task::none(); return Task::none();
}; };
if let Some(tx) = self.nm_sender.as_ref() {
if let Err(err) =
tx.unbounded_send(network_manager::Request::Forget(ssid.into()))
{
if err.is_disconnected() {
return system_conn().map(cosmic::Action::App);
}
tracing::error!("{err:?}");
}
self.show_visible_networks = true; self.show_visible_networks = true;
return self.update(Message::SelectWirelessAccessPoint(ap)); let ssid_for_task = ssid.clone();
let forget_task = cosmic::task::future(async move {
match NmrsManager::new().await {
Ok(nm) => match nm.forget(&ssid_for_task).await {
Ok(()) => Message::Refresh,
Err(e) => {
tracing::warn!("forget {ssid_for_task} failed: {e}");
Message::Refresh
} }
},
Err(e) => Message::Error(format!("nmrs init: {e}")),
}
})
.map(cosmic::Action::App);
let reconnect_task = self.update(Message::SelectWirelessAccessPoint(ap));
return Task::batch(vec![forget_task, reconnect_task]);
} }
Message::Surface(a) => { Message::Surface(a) => {
return cosmic::task::message(cosmic::Action::Cosmic( return cosmic::task::message(cosmic::Action::Cosmic(
@ -1003,17 +936,17 @@ impl cosmic::Application for CosmicNetworkApplet {
Message::ActivateVpn(uuid) => { Message::ActivateVpn(uuid) => {
return self.connect_vpn(uuid.clone()); return self.connect_vpn(uuid.clone());
} }
Message::DeactivateVpn(name) => { Message::DeactivateVpn(uuid) => {
if let Some(tx) = self.nm_sender.as_ref() { return cosmic::task::future(async move {
if let Err(err) = tx.unbounded_send(network_manager::Request::Deactivate(name)) match NmrsManager::new().await {
{ Ok(nm) => match nm.disconnect_vpn_by_uuid(&uuid).await {
if err.is_disconnected() { Ok(()) => Message::Refresh,
return system_conn().map(cosmic::Action::App); Err(e) => Message::Error(format!("disconnect VPN {uuid}: {e}")),
} },
Err(e) => Message::Error(format!("nmrs init: {e}")),
tracing::error!("{err:?}");
}
} }
})
.map(cosmic::Action::App);
} }
Message::ToggleVpnList => { Message::ToggleVpnList => {
self.show_available_vpns = !self.show_available_vpns; self.show_available_vpns = !self.show_available_vpns;
@ -1038,7 +971,7 @@ impl cosmic::Application for CosmicNetworkApplet {
if let Err(err) = tx.unbounded_send(network_manager::Request::SelectAccessPoint( if let Err(err) = tx.unbounded_send(network_manager::Request::SelectAccessPoint(
ssid, ssid,
network_type, network_type,
self.secret_tx.clone(), None,
self.active_device.as_ref().map(|d| d.interface.clone()), self.active_device.as_ref().map(|d| d.interface.clone()),
)) { )) {
if err.is_disconnected() { if err.is_disconnected() {
@ -1067,7 +1000,7 @@ impl cosmic::Application for CosmicNetworkApplet {
ssid: access_point.ssid.to_string(), ssid: access_point.ssid.to_string(),
identity: is_enterprise.then(|| identity.clone()), identity: is_enterprise.then(|| identity.clone()),
password, password,
secret_tx: self.secret_tx.clone(), secret_tx: None,
interface: self.active_device.as_ref().map(|d| d.interface.clone()), interface: self.active_device.as_ref().map(|d| d.interface.clone()),
}) { }) {
if err.is_disconnected() { if err.is_disconnected() {
@ -1153,9 +1086,9 @@ impl cosmic::Application for CosmicNetworkApplet {
} => { } => {
if let network_manager::Request::SelectAccessPoint( if let network_manager::Request::SelectAccessPoint(
ssid, ssid,
hw_address, _hw_address,
_network_type, _network_type,
secret_tx, _secret_tx,
) = &req ) = &req
{ {
let conn_match = self let conn_match = self
@ -1167,15 +1100,7 @@ impl cosmic::Application for CosmicNetworkApplet {
if let Some(ActiveConnectionInfo::WiFi { state, .. }) = state if let Some(ActiveConnectionInfo::WiFi { state, .. }) = state
.active_conns .active_conns
.iter_mut() .iter_mut()
.find(|ap| { .find(|ap| ap.name().as_str() == ssid.as_ref())
let ap_hw_address = match ap {
ActiveConnectionInfo::Wired { hw_address, .. }
| ActiveConnectionInfo::WiFi { hw_address, .. } => {
HwAddress::from_str(&hw_address).unwrap()
}
ActiveConnectionInfo::Vpn { .. } => HwAddress::default(),
};
ap.name().as_str() == ssid.as_ref()})
{ {
*state = ActiveConnectionState::Activated; *state = ActiveConnectionState::Activated;
} }
@ -1192,8 +1117,8 @@ impl cosmic::Application for CosmicNetworkApplet {
ssid, ssid,
identity: _, identity: _,
password: _, password: _,
secret_tx, secret_tx: _,
interface interface: _,
} = &req } = &req
{ {
if let Some(NewConnectionState::Waiting(access_point)) = if let Some(NewConnectionState::Waiting(access_point)) =
@ -1207,15 +1132,14 @@ impl cosmic::Application for CosmicNetworkApplet {
} else { } else {
self.show_visible_networks = false; self.show_visible_networks = false;
} }
} else if let Some(NewConnectionState::EnterPassword { } else if let Some(NewConnectionState::EnterPassword { access_point, .. }) =
access_point, .. self.new_connection.as_ref()
}) = self.new_connection.as_ref() && success
&& ssid.as_str() == access_point.ssid.as_ref()
{ {
if success && ssid.as_str() == access_point.ssid.as_ref() {
self.new_connection = None; self.new_connection = None;
self.show_visible_networks = false; self.show_visible_networks = false;
} }
}
} else if self } else if self
.new_connection .new_connection
.as_ref() .as_ref()
@ -1246,9 +1170,9 @@ impl cosmic::Application for CosmicNetworkApplet {
} }
} }
cosmic_settings_network_manager_subscription::Event::WiFiCredentials { cosmic_settings_network_manager_subscription::Event::WiFiCredentials {
ssid, ssid: _,
password, password: _,
security_type, security_type: _,
} => {} } => {}
}, },
Message::NetworkManagerConnect(connection) => { Message::NetworkManagerConnect(connection) => {
@ -1271,72 +1195,91 @@ impl cosmic::Application for CosmicNetworkApplet {
self.nm_state.devices = device_infos.into_iter().map(Arc::new).collect(); self.nm_state.devices = device_infos.into_iter().map(Arc::new).collect();
} }
Message::WiFiEnable(enable) => { Message::WiFiEnable(enable) => {
if let Some(sender) = self.nm_sender.as_mut() { self.nm_state.nm_state.wifi_enabled = enable;
if let Err(err) = return cosmic::task::future(async move {
sender.unbounded_send(network_manager::Request::SetWiFi(enable)) match NmrsManager::new().await {
{ Ok(nm) => match nm.set_wireless_enabled(enable).await {
if err.is_disconnected() { Ok(()) => Message::Refresh,
return system_conn().map(cosmic::Action::App); Err(e) => Message::Error(format!("set_wireless_enabled: {e}")),
} },
Err(e) => Message::Error(format!("nmrs init: {e}")),
tracing::error!("{err:?}");
}
if let Err(err) = sender.unbounded_send(network_manager::Request::Reload) {
if err.is_disconnected() {
return system_conn().map(cosmic::Action::App);
}
tracing::error!("{err:?}");
}
} }
})
.map(cosmic::Action::App);
} }
Message::SecretAgent(agent_event) => match agent_event { Message::SecretAgent(agent_event) => match agent_event {
nm_secret_agent::Event::RequestSecret { NmAgentEvent::RequestSecret {
uuid, connection_uuid,
name, connection_id,
description, setting,
previous, responder,
tx,
..
} => { } => {
let description = (!connection_id.is_empty()).then_some(connection_id);
let known_vpn = self
.nm_state
.known_vpns
.contains_key(connection_uuid.as_str());
let mut consumed = false;
if let Some(state) = self.new_connection.as_mut() { if let Some(state) = self.new_connection.as_mut() {
match state { match state {
NewConnectionState::EnterPassword { access_point, .. } NewConnectionState::EnterPassword { access_point, .. }
| NewConnectionState::Waiting(access_point) | NewConnectionState::Waiting(access_point)
| NewConnectionState::Failure(access_point) => { | NewConnectionState::Failure(access_point) => {
if self let matches_ssid = matches!(
&setting,
AgentSetting::WifiPsk { ssid }
if ssid == access_point.ssid.as_ref()
);
let matches_uuid = self
.nm_state .nm_state
.ssid_to_uuid .ssid_to_uuid
.get(access_point.ssid.as_ref()) .get(access_point.ssid.as_ref())
.is_some_and(|ap_uuid| ap_uuid.as_ref() == uuid.as_str()) .is_some_and(|ap_uuid| {
{ ap_uuid.as_ref() == connection_uuid.as_str()
});
if matches_ssid || matches_uuid {
*state = NewConnectionState::EnterPassword { *state = NewConnectionState::EnterPassword {
access_point: access_point.clone(), access_point: access_point.clone(),
description, description: description.clone(),
identity: String::new(), identity: String::new(),
password: String::new().into(), password: String::new().into(),
password_hidden: true, password_hidden: true,
};
} }
} }
} }
} } else if known_vpn {
} else if self.nm_state.known_vpns.contains_key(uuid.as_str()) { let secret_keys = match &setting {
AgentSetting::Vpn { secret_keys } => secret_keys.clone(),
_ => Vec::new(),
};
self.nm_state.requested_vpn = Some(RequestedVpn { self.nm_state.requested_vpn = Some(RequestedVpn {
name, uuid: connection_uuid.into(),
uuid: uuid.into(),
description, description,
password: previous, password: SecureString::from(String::new()),
password_hidden: true, password_hidden: true,
tx, responder: responder.clone(),
secret_keys,
}); });
consumed = true;
}
// The applet's Wi-Fi flow re-issues the password through
// `Authenticate` rather than the agent. Free NM with
// `NoSecrets` so it doesn't sit on a stalled GetSecrets call.
if !consumed {
return release_responder(responder);
} }
} }
nm_secret_agent::Event::CancelGetSecrets { .. } => { NmAgentEvent::CancelGetSecrets => {
self.new_connection = None; self.new_connection = None;
self.nm_state.requested_vpn = None; self.nm_state.requested_vpn = None;
} }
nm_secret_agent::Event::Failed(error) => { NmAgentEvent::Failed(error) => {
tracing::error!("Error from secret agent: {error:?}"); tracing::error!("Error from secret agent: {error}");
} }
}, },
Message::KnownConnections(index_map) => { Message::KnownConnections(index_map) => {
@ -1358,12 +1301,30 @@ impl cosmic::Application for CosmicNetworkApplet {
} }
} }
Message::ConnectVPNWithPassword => { Message::ConnectVPNWithPassword => {
if let Some(RequestedVpn { password, tx, .. }) = self.nm_state.requested_vpn.take() if let Some(RequestedVpn {
password,
responder,
secret_keys,
..
}) = self.nm_state.requested_vpn.take()
{ {
return Task::future(async move { return Task::future(async move {
let mut guard = tx.lock().await; let Some(responder) = responder.lock().await.take() else {
if let Some(tx) = guard.take() { return Message::Refresh;
let _ = tx.send(password); };
let mut secrets: HashMap<String, String> = HashMap::new();
let value = password.unsecure().to_owned();
if secret_keys.is_empty() {
secrets.insert("password".to_owned(), value);
} else {
for key in secret_keys {
secrets.insert(key, value.clone());
}
}
if let Err(e) = responder.vpn_secrets(secrets).await {
tracing::error!("vpn secret reply failed: {e}");
} }
Message::Refresh Message::Refresh
}) })
@ -1376,7 +1337,15 @@ impl cosmic::Application for CosmicNetworkApplet {
} }
} }
Message::CancelVPNConnection => { Message::CancelVPNConnection => {
self.nm_state.requested_vpn = None; if let Some(req) = self.nm_state.requested_vpn.take() {
return Task::future(async move {
if let Some(responder) = req.responder.lock().await.take() {
let _ = responder.cancel().await;
}
Message::NoOp
})
.map(cosmic::Action::App);
}
} }
} }
Task::none() Task::none()
@ -1441,7 +1410,7 @@ impl cosmic::Application for CosmicNetworkApplet {
} }
ActiveConnectionInfo::Wired { ActiveConnectionInfo::Wired {
name, name,
hw_address, hw_address: _,
speed, speed,
ip_addresses, ip_addresses,
} => { } => {
@ -1561,7 +1530,7 @@ impl cosmic::Application for CosmicNetworkApplet {
.icon_size(16) .icon_size(16)
.on_press(Message::ResetFailedKnownSsid( .on_press(Message::ResetFailedKnownSsid(
name.clone(), name.clone(),
HwAddress::from_str(&hw_address).unwrap(), HwAddress::from_str(hw_address).unwrap(),
)) ))
.into(), .into(),
); );
@ -1576,7 +1545,7 @@ impl cosmic::Application for CosmicNetworkApplet {
) )
.on_press(Message::Disconnect( .on_press(Message::Disconnect(
Arc::from(name.as_str()), Arc::from(name.as_str()),
HwAddress::from_str(&hw_address).unwrap(), HwAddress::from_str(hw_address).unwrap(),
)), )),
)]) )])
.align_x(Alignment::Center), .align_x(Alignment::Center),
@ -1733,15 +1702,14 @@ impl cosmic::Application for CosmicNetworkApplet {
} }
for known in &self.nm_state.nm_state.known_access_points { for known in &self.nm_state.nm_state.known_access_points {
if let Some(active_device) = self.active_device.as_ref() { if let Some(active_device) = self.active_device.as_ref()
if active_device && active_device
.known_connections .known_connections
.iter() .iter()
.all(|c| &c.id != known.ssid.as_ref()) .all(|c| c.id != *known.ssid)
{ {
continue; continue;
} }
}
let mut btn_content = Vec::with_capacity(2); let mut btn_content = Vec::with_capacity(2);
let ssid = text::body(known.ssid.as_ref()).width(Length::Fill); let ssid = text::body(known.ssid.as_ref()).width(Length::Fill);
if known.working { if known.working {
@ -1872,12 +1840,10 @@ impl cosmic::Application for CosmicNetworkApplet {
content = content.push(id); content = content.push(id);
let is_enterprise = matches!(access_point.network_type, NetworkType::EAP); let is_enterprise = matches!(access_point.network_type, NetworkType::EAP);
let enter_password_col = let enter_password_col = cosmic::widget::column::with_capacity(4)
cosmic::widget::column::with_capacity(4)
.push_maybe(is_enterprise.then(|| text::body(fl!("identity")))) .push_maybe(is_enterprise.then(|| text::body(fl!("identity"))))
.push_maybe(is_enterprise.then(|| { .push_maybe(is_enterprise.then(|| {
text_input::text_input("", identity) text_input::text_input("", identity).on_input(Message::IdentityUpdate)
.on_input(|i| Message::IdentityUpdate(i))
})) }))
.push(text::body(fl!("enter-password"))) .push(text::body(fl!("enter-password")))
.push_maybe(description.as_ref().map(|d| text::body(d.clone()))) .push_maybe(description.as_ref().map(|d| text::body(d.clone())))
@ -1893,9 +1859,11 @@ impl cosmic::Application for CosmicNetworkApplet {
.on_paste(|s| Message::PasswordUpdate(SecureString::from(s))) .on_paste(|s| Message::PasswordUpdate(SecureString::from(s)))
.on_submit(|_| Message::ConnectWithPassword), .on_submit(|_| Message::ConnectWithPassword),
) )
.push_maybe(access_point.wps_push.then(|| { .push_maybe(
access_point.wps_push.then(|| {
container(text::body(fl!("router-wps-button"))).padding(8) container(text::body(fl!("router-wps-button"))).padding(8)
})) }),
)
.push( .push(
row::with_children([ row::with_children([
Element::from( Element::from(
@ -1987,7 +1955,7 @@ impl cosmic::Application for CosmicNetworkApplet {
.filter(|ap| { .filter(|ap| {
let among_active = self.nm_state.nm_state.active_conns.iter().any(|a| { let among_active = self.nm_state.nm_state.active_conns.iter().any(|a| {
let hw_address = active_conn_hw_address(a); let hw_address = active_conn_hw_address(a);
ap.ssid.as_ref() == &a.name() && ap.hw_address == hw_address ap.ssid.as_ref() == a.name() && ap.hw_address == hw_address
}); });
let among_known = let among_known =
self.nm_state self.nm_state