nmrs 3.5.7

A Rust library for NetworkManager over D-Bus
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
//! Secret agent builder, handle, and lifecycle management.

use std::collections::HashMap;
use std::sync::atomic::AtomicU64;
use std::sync::{Arc, Mutex};

use futures::channel::mpsc;
use log::debug;
use zbus::Connection;

use crate::ConnectionError;
use crate::dbus::AgentManagerProxy;

use super::iface::SecretAgentInterface;
use super::request::{CancelReason, SecretAgentCapabilities, SecretRequest, SecretStoreEvent};

const DEFAULT_IDENTIFIER: &str = "com.system76.CosmicApplets.nmrs.secret_agent";
const DEFAULT_OBJECT_PATH: &str = "/org/freedesktop/NetworkManager/SecretAgent";
const DEFAULT_QUEUE_DEPTH: usize = 32;
const AGENT_MANAGER_ERROR_PREFIX: &str = "org.freedesktop.NetworkManager.AgentManager.";

#[derive(Debug, PartialEq, Eq)]
enum AgentManagerFailure {
    AlreadyRegistered,
    Registration,
    NotRegistered,
    Other,
}

fn classify_agent_manager_failure(name: &str, detail: Option<&str>) -> AgentManagerFailure {
    if !name.starts_with(AGENT_MANAGER_ERROR_PREFIX) {
        return AgentManagerFailure::Other;
    }

    match name.strip_prefix(AGENT_MANAGER_ERROR_PREFIX) {
        Some("PermissionDenied")
            if detail.is_some_and(|detail| {
                detail.to_ascii_lowercase().contains("already registered")
            }) =>
        {
            AgentManagerFailure::AlreadyRegistered
        }
        Some("NotRegistered") => AgentManagerFailure::NotRegistered,
        _ => AgentManagerFailure::Registration,
    }
}

fn classify_zbus_agent_manager_failure(error: &zbus::Error) -> AgentManagerFailure {
    match error {
        zbus::Error::MethodError(name, detail, _) => {
            classify_agent_manager_failure(name.as_str(), detail.as_deref())
        }
        _ => AgentManagerFailure::Other,
    }
}

fn registration_error(error: zbus::Error, operation: &str) -> ConnectionError {
    match classify_zbus_agent_manager_failure(&error) {
        AgentManagerFailure::AlreadyRegistered => ConnectionError::AgentAlreadyRegistered,
        AgentManagerFailure::Registration | AgentManagerFailure::NotRegistered => {
            ConnectionError::AgentRegistration {
                context: format!("{operation}: {error}"),
            }
        }
        AgentManagerFailure::Other => ConnectionError::DbusOperation {
            context: operation.into(),
            source: error,
        },
    }
}

fn unregistration_error(error: zbus::Error) -> ConnectionError {
    if classify_zbus_agent_manager_failure(&error) == AgentManagerFailure::NotRegistered {
        ConnectionError::AgentNotRegistered
    } else {
        ConnectionError::DbusOperation {
            context: "unregistering secret agent".into(),
            source: error,
        }
    }
}

/// Entry point for creating a NetworkManager secret agent.
///
/// A secret agent receives credential requests from NetworkManager over D-Bus
/// whenever a connection needs secrets the system does not already have (Wi-Fi
/// password forgotten, VPN token expired, etc.).
///
/// Use [`SecretAgent::builder()`] to configure and register the agent.
///
/// # Example
///
/// ```no_run
/// use futures::StreamExt;
/// use nmrs::agent::{SecretAgent, SecretSetting};
///
/// # async fn example() -> nmrs::Result<()> {
/// let (handle, mut requests) = SecretAgent::builder().register().await?;
///
/// while let Some(req) = requests.next().await {
///     if let SecretSetting::WifiPsk { ref ssid } = req.setting {
///         println!("password requested for {ssid}");
///         req.responder.wifi_psk("my-password").await?;
///     }
/// }
/// # Ok(())
/// # }
/// ```
pub struct SecretAgent;

impl SecretAgent {
    /// Returns a builder for configuring and registering a secret agent.
    #[must_use]
    pub fn builder() -> SecretAgentBuilder {
        SecretAgentBuilder::default()
    }
}

/// Builder for configuring and registering a [`SecretAgent`].
///
/// Use the `with_*` methods to override defaults, then call
/// [`register()`](Self::register) to connect to the system bus and start
/// serving.
///
/// # Defaults
///
/// | Setting | Default |
/// |---------|---------|
/// | identifier | `com.system76.CosmicApplets.nmrs.secret_agent` |
/// | capabilities | [`SecretAgentCapabilities::VPN_HINTS`] |
/// | object path | `/org/freedesktop/NetworkManager/SecretAgent` |
/// | queue depth | 32 |
#[derive(Debug)]
pub struct SecretAgentBuilder {
    identifier: String,
    capabilities: SecretAgentCapabilities,
    object_path: String,
    queue_depth: usize,
}

impl Default for SecretAgentBuilder {
    fn default() -> Self {
        Self {
            identifier: DEFAULT_IDENTIFIER.into(),
            capabilities: SecretAgentCapabilities::VPN_HINTS,
            object_path: DEFAULT_OBJECT_PATH.into(),
            queue_depth: DEFAULT_QUEUE_DEPTH,
        }
    }
}

impl SecretAgentBuilder {
    /// Sets the identifier passed to NetworkManager for this agent.
    ///
    /// This is not a D-Bus bus name and `nmrs` will not try to own it on the
    /// system bus. NetworkManager requires it to be unique within the user's
    /// agent session and to follow D-Bus bus-name formatting rules, except
    /// that `:` is not allowed.
    #[must_use]
    pub fn with_identifier(mut self, identifier: impl Into<String>) -> Self {
        self.identifier = identifier.into();
        self
    }

    /// Sets the capabilities advertised to NetworkManager.
    ///
    /// Defaults to [`SecretAgentCapabilities::VPN_HINTS`].
    #[must_use]
    pub fn with_capabilities(mut self, capabilities: SecretAgentCapabilities) -> Self {
        self.capabilities = capabilities;
        self
    }

    /// Sets the D-Bus object path where the agent interface is served.
    ///
    /// NetworkManager calls secret agents at
    /// `/org/freedesktop/NetworkManager/SecretAgent`; overriding this is only
    /// useful for tests or custom callers that use the same non-standard path.
    #[must_use]
    pub fn with_object_path(mut self, path: impl Into<String>) -> Self {
        self.object_path = path.into();
        self
    }

    /// Sets the maximum number of `GetSecrets` requests to buffer before
    /// back-pressure kicks in. Defaults to 32.
    #[must_use]
    pub fn with_queue_depth(mut self, depth: usize) -> Self {
        self.queue_depth = depth;
        self
    }

    /// Connects to the system bus, registers the agent with NetworkManager,
    /// and returns a handle and a stream of incoming secret requests.
    ///
    /// The returned [`mpsc::Receiver`](futures::channel::mpsc::Receiver)
    /// implements [`Stream`](futures::Stream) and yields
    /// [`SecretRequest`] items as they arrive from NetworkManager.
    ///
    /// # Errors
    ///
    /// - [`ConnectionError::AgentRegistration`] if NetworkManager rejected
    ///   the registration.
    /// - [`ConnectionError::Dbus`] for other D-Bus failures.
    pub async fn register(
        self,
    ) -> crate::Result<(SecretAgentHandle, mpsc::Receiver<SecretRequest>)> {
        let (request_tx, request_rx) = mpsc::channel(self.queue_depth);
        let (cancel_tx, cancel_rx) = mpsc::unbounded();
        let (store_tx, store_rx) = mpsc::unbounded();

        let iface = SecretAgentInterface {
            request_tx,
            cancel_tx,
            store_tx,
            pending: Arc::new(Mutex::new(HashMap::new())),
            next_request_id: AtomicU64::new(1),
            response_timeout: crate::types::constants::timeouts::secret_agent_response_timeout(),
        };

        let conn = Connection::system()
            .await
            .map_err(|e| ConnectionError::DbusOperation {
                context: "connecting to system bus for secret agent".into(),
                source: e,
            })?;

        conn.object_server()
            .at(&*self.object_path, iface)
            .await
            .map_err(|e| ConnectionError::DbusOperation {
                context: format!("serving SecretAgent interface at {}", self.object_path),
                source: e,
            })?;

        debug!(
            "Serving secret agent '{}' at '{}'",
            self.identifier, self.object_path
        );

        let agent_proxy =
            AgentManagerProxy::new(&conn)
                .await
                .map_err(|e| ConnectionError::DbusOperation {
                    context: "creating AgentManager proxy".into(),
                    source: e,
                })?;

        agent_proxy
            .register_with_capabilities(&self.identifier, self.capabilities.bits())
            .await
            .map_err(|error| {
                registration_error(error, "registering secret agent with NetworkManager")
            })?;

        debug!(
            "Registered secret agent '{}' with capabilities {:?}",
            self.identifier, self.capabilities
        );

        let handle = SecretAgentHandle {
            conn,
            identifier: self.identifier,
            capabilities: self.capabilities,
            object_path: self.object_path,
            cancel_rx,
            store_rx,
        };

        Ok((handle, request_rx))
    }
}

/// Handle to a running secret agent.
///
/// Provides methods to re-register after a NetworkManager restart, access
/// the cancellation and store-event streams, and shut the agent down.
///
/// GUI apps should keep this handle alive for as long as they want to answer
/// NetworkManager credential prompts. Dropping the handle drops the D-Bus
/// connection that serves the secret-agent object.
pub struct SecretAgentHandle {
    conn: Connection,
    identifier: String,
    capabilities: SecretAgentCapabilities,
    object_path: String,
    cancel_rx: mpsc::UnboundedReceiver<CancelReason>,
    store_rx: mpsc::UnboundedReceiver<SecretStoreEvent>,
}

impl std::fmt::Debug for SecretAgentHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SecretAgentHandle")
            .field("identifier", &self.identifier)
            .field("object_path", &self.object_path)
            .finish_non_exhaustive()
    }
}

impl SecretAgentHandle {
    /// Re-registers the agent with NetworkManager.
    ///
    /// Call this after detecting that NetworkManager restarted (e.g. its
    /// D-Bus name owner changed). Calling it while the agent is still registered
    /// returns [`ConnectionError::AgentAlreadyRegistered`]. The same long-lived
    /// handle can be kept and re-registered whenever NetworkManager comes back.
    ///
    /// # Errors
    ///
    /// Returns an error if the D-Bus call to `RegisterWithCapabilities` fails.
    pub async fn reregister(&self) -> crate::Result<()> {
        let proxy = AgentManagerProxy::new(&self.conn).await.map_err(|e| {
            ConnectionError::DbusOperation {
                context: "creating AgentManager proxy for re-registration".into(),
                source: e,
            }
        })?;
        proxy
            .register_with_capabilities(&self.identifier, self.capabilities.bits())
            .await
            .map_err(|error| {
                registration_error(error, "re-registering secret agent with NetworkManager")
            })?;
        debug!("Re-registered secret agent '{}'", self.identifier);
        Ok(())
    }

    /// Unregisters the agent from NetworkManager and stops serving its object.
    ///
    /// After this call, the request stream returned by
    /// [`SecretAgentBuilder::register`] will complete and the agent's object
    /// path is released, even if NetworkManager is no longer reachable.
    ///
    /// # Errors
    ///
    /// Returns an error if the D-Bus `Unregister` call fails or if the agent's
    /// object could not be removed from the object server.
    pub async fn unregister(self) -> crate::Result<()> {
        let unregistered = async {
            let proxy = AgentManagerProxy::new(&self.conn).await.map_err(|e| {
                ConnectionError::DbusOperation {
                    context: "creating AgentManager proxy for unregistration".into(),
                    source: e,
                }
            })?;
            proxy.unregister().await.map_err(unregistration_error)
        }
        .await;

        self.conn
            .object_server()
            .remove::<SecretAgentInterface, _>(&*self.object_path)
            .await
            .map_err(|e| ConnectionError::DbusOperation {
                context: format!("removing SecretAgent interface at {}", self.object_path),
                source: e,
            })?;

        unregistered?;
        debug!("Unregistered secret agent '{}'", self.identifier);
        Ok(())
    }

    /// Returns a mutable reference to the cancellation stream.
    ///
    /// Yields [`CancelReason`] items when NetworkManager calls
    /// `CancelGetSecrets` for an in-flight request. By the time the
    /// consumer receives this event, the agent has already replied to
    /// NetworkManager.
    ///
    /// Use with [`StreamExt::next()`](futures::StreamExt::next):
    ///
    /// ```ignore
    /// while let Some(reason) = handle.cancellations().next().await {
    ///     println!("cancelled: {}", reason.setting_name);
    /// }
    /// ```
    pub fn cancellations(&mut self) -> &mut mpsc::UnboundedReceiver<CancelReason> {
        &mut self.cancel_rx
    }

    /// Returns a mutable reference to the save/delete event stream.
    ///
    /// Yields [`SecretStoreEvent`] items when NetworkManager sends
    /// `SaveSecrets` or `DeleteSecrets`. These are informational — the agent
    /// always acknowledges them immediately.
    pub fn store_events(&mut self) -> &mut mpsc::UnboundedReceiver<SecretStoreEvent> {
        &mut self.store_rx
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn agent_manager_errors_map_to_public_lifecycle_failures() {
        let cases = [
            (
                "org.freedesktop.NetworkManager.AgentManager.PermissionDenied",
                Some("An agent with this ID is already registered for this user."),
                AgentManagerFailure::AlreadyRegistered,
            ),
            (
                "org.freedesktop.NetworkManager.AgentManager.PermissionDenied",
                Some("Not authorized"),
                AgentManagerFailure::Registration,
            ),
            (
                "org.freedesktop.NetworkManager.AgentManager.InvalidIdentifier",
                Some("Identifier contains invalid character ':'"),
                AgentManagerFailure::Registration,
            ),
            (
                "org.freedesktop.NetworkManager.AgentManager.NotRegistered",
                None,
                AgentManagerFailure::NotRegistered,
            ),
            (
                "org.freedesktop.DBus.Error.NoReply",
                Some("timed out"),
                AgentManagerFailure::Other,
            ),
        ];

        for (name, detail, expected) in cases {
            assert_eq!(classify_agent_manager_failure(name, detail), expected);
        }
    }

    #[test]
    fn defaults_match_networkmanager_secret_agent_contract() {
        let builder = SecretAgentBuilder::default();

        assert_eq!(builder.object_path, DEFAULT_OBJECT_PATH);
        assert_eq!(builder.identifier, DEFAULT_IDENTIFIER);
        assert_eq!(builder.capabilities, SecretAgentCapabilities::VPN_HINTS);
        assert_eq!(builder.queue_depth, DEFAULT_QUEUE_DEPTH);
    }

    #[test]
    fn builder_methods_replace_every_registration_option() {
        let builder = SecretAgent::builder()
            .with_identifier("org.example.nmrs.agent")
            .with_capabilities(SecretAgentCapabilities::empty())
            .with_object_path("/org/example/nmrs/Agent")
            .with_queue_depth(7);

        assert_eq!(builder.identifier, "org.example.nmrs.agent");
        assert_eq!(builder.capabilities, SecretAgentCapabilities::empty());
        assert_eq!(builder.object_path, "/org/example/nmrs/Agent");
        assert_eq!(builder.queue_depth, 7);
    }

    /// A private peer-to-peer connection pair over a socketpair, so the tests
    /// never depend on the host's session bus. The agent serves its object on
    /// the first connection; the second stands in for the bus and answers
    /// anything it does not serve with a D-Bus error.
    async fn connection_pair() -> (Connection, Connection) {
        let (agent_socket, peer_socket) =
            std::os::unix::net::UnixStream::pair().expect("socketpair");
        // Serving an interface at build time makes `build()` wait until the
        // peer's object server is listening, so a call can't arrive before it
        // subscribes and be dropped without a reply.
        let peer = zbus::connection::Builder::unix_stream(peer_socket)
            .server(zbus::Guid::generate())
            .expect("p2p server guid")
            .p2p()
            .serve_at("/", StandInBus)
            .expect("serving the stand-in bus")
            .build();
        let agent = zbus::connection::Builder::unix_stream(agent_socket)
            .p2p()
            .method_timeout(std::time::Duration::from_secs(5))
            .build();
        let (peer, agent) = futures::join!(peer, agent);
        let peer = peer.expect("p2p server connection");
        let agent = agent.expect("p2p client connection");
        (agent, peer)
    }

    struct StandInBus;

    #[zbus::interface(name = "org.freedesktop.nmrs.test.StandInBus")]
    impl StandInBus {}

    async fn serve_agent(conn: &Connection, object_path: &str) -> SecretAgentHandle {
        let (request_tx, _request_rx) = mpsc::channel(DEFAULT_QUEUE_DEPTH);
        let (cancel_tx, cancel_rx) = mpsc::unbounded();
        let (store_tx, store_rx) = mpsc::unbounded();

        conn.object_server()
            .at(
                object_path,
                SecretAgentInterface {
                    request_tx,
                    cancel_tx,
                    store_tx,
                    pending: Arc::new(Mutex::new(HashMap::new())),
                    next_request_id: AtomicU64::new(1),
                    response_timeout:
                        crate::types::constants::timeouts::secret_agent_response_timeout(),
                },
            )
            .await
            .expect("serving the agent interface");

        SecretAgentHandle {
            conn: conn.clone(),
            identifier: DEFAULT_IDENTIFIER.to_owned(),
            capabilities: SecretAgentCapabilities::VPN_HINTS,
            object_path: object_path.to_owned(),
            cancel_rx,
            store_rx,
        }
    }

    /// Whether the agent interface is currently served at `path` on `conn`.
    async fn agent_served_at(conn: &Connection, path: &str) -> bool {
        conn.object_server()
            .interface::<_, SecretAgentInterface>(path)
            .await
            .is_ok()
    }

    /// Introspects `path` on the agent connection from its peer. Calling
    /// `Introspect` on the connection that serves the object hangs
    /// intermittently on zbus 5 when several tests do it concurrently.
    async fn introspect(peer: &Connection, path: &str) -> String {
        zbus::fdo::IntrospectableProxy::builder(peer)
            .destination("org.freedesktop.NetworkManager.nmrs.Agent")
            .expect("destination")
            .path(path.to_owned())
            .expect("object path")
            .build()
            .await
            .expect("introspectable proxy")
            .introspect()
            .await
            .unwrap_or_default()
    }

    async fn exported_nodes(peer: &Connection) -> Vec<String> {
        introspect(peer, "/")
            .await
            .lines()
            .filter(|line| line.trim_start().starts_with("<node name="))
            .map(|line| line.trim().to_owned())
            .collect()
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn unregister_releases_the_agent_object_path() {
        let (conn, _peer) = connection_pair().await;
        let handle = serve_agent(&conn, DEFAULT_OBJECT_PATH).await;
        assert!(agent_served_at(&conn, DEFAULT_OBJECT_PATH).await);

        // The peer is not NetworkManager, so `Unregister` fails; the object
        // path must be released regardless.
        assert!(handle.unregister().await.is_err());

        assert!(!agent_served_at(&conn, DEFAULT_OBJECT_PATH).await);
    }

    // zbus 5 removes the agent interface but leaves the auto-created ancestor
    // nodes (`/org`, `/org/freedesktop`, ...) in the object tree. zbus 6 prunes
    // them (z-galaxy/zbus#1916); enable this once nmrs is on zbus 6.
    #[ignore = "needs zbus 6: ObjectServer::remove prunes empty ancestor nodes"]
    #[tokio::test(flavor = "multi_thread")]
    async fn unregister_leaves_no_objects_exported_on_the_agent_connection() {
        let (conn, peer) = connection_pair().await;
        let handle = serve_agent(&conn, DEFAULT_OBJECT_PATH).await;

        assert!(handle.unregister().await.is_err());

        assert_eq!(exported_nodes(&peer).await, Vec::<String>::new());
    }

    #[tokio::test(flavor = "multi_thread")]
    async fn unregister_releases_a_custom_object_path() {
        let (conn, _peer) = connection_pair().await;
        let handle = serve_agent(&conn, "/org/example/nmrs/Agent").await;
        assert!(agent_served_at(&conn, "/org/example/nmrs/Agent").await);

        assert!(handle.unregister().await.is_err());

        assert!(!agent_served_at(&conn, "/org/example/nmrs/Agent").await);
    }
}