nmrs 2.3.0

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
use uuid::Uuid;

use super::device::DeviceState;

/// VPN connection type.
///
/// Identifies the VPN protocol/technology used for the connection.
/// Currently only WireGuard is supported.
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum VpnType {
    /// WireGuard - modern, high-performance VPN protocol.
    WireGuard,
}

/// VPN Credentials for establishing a VPN connection.
///
/// Stores the necessary information to configure and connect to a VPN.
/// Currently supports WireGuard VPN connections.
///
/// # Fields
///
/// - `vpn_type`: The type of VPN (currently only WireGuard)
/// - `name`: Unique identifier for the connection
/// - `gateway`: VPN gateway endpoint (e.g., "vpn.example.com:51820")
/// - `private_key`: Client's WireGuard private key
/// - `address`: Client's IP address with CIDR notation (e.g., "10.0.0.2/24")
/// - `peers`: List of WireGuard peers to connect to
/// - `dns`: Optional DNS servers to use (e.g., ["1.1.1.1", "8.8.8.8"])
/// - `mtu`: Optional Maximum Transmission Unit
/// - `uuid`: Optional UUID for the connection (auto-generated if not provided)
///
/// # Example
///
/// ```rust
/// use nmrs::{VpnCredentials, VpnType, WireGuardPeer};
///
/// let peer = WireGuardPeer::new(
///     "server_public_key",
///     "vpn.home.com:51820",
///     vec!["0.0.0.0/0".into()],
/// ).with_persistent_keepalive(25);
///
/// let creds = VpnCredentials::new(
///     VpnType::WireGuard,
///     "HomeVPN",
///     "vpn.home.com:51820",
///     "aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789=",
///     "10.0.0.2/24",
///     vec![peer],
/// ).with_dns(vec!["1.1.1.1".into()]);
/// ```
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct VpnCredentials {
    /// The type of VPN (currently only WireGuard).
    pub vpn_type: VpnType,
    /// Unique name for the connection profile.
    pub name: String,
    /// VPN gateway endpoint (e.g., "vpn.example.com:51820").
    pub gateway: String,
    /// Client's WireGuard private key (base64 encoded).
    pub private_key: String,
    /// Client's IP address with CIDR notation (e.g., "10.0.0.2/24").
    pub address: String,
    /// List of WireGuard peers to connect to.
    pub peers: Vec<WireGuardPeer>,
    /// Optional DNS servers to use when connected.
    pub dns: Option<Vec<String>>,
    /// Optional Maximum Transmission Unit size.
    pub mtu: Option<u32>,
    /// Optional UUID for the connection (auto-generated if not provided).
    pub uuid: Option<Uuid>,
}

impl VpnCredentials {
    /// Creates new `VpnCredentials` with the required fields.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::{VpnCredentials, VpnType, WireGuardPeer};
    ///
    /// let peer = WireGuardPeer::new(
    ///     "server_public_key",
    ///     "vpn.example.com:51820",
    ///     vec!["0.0.0.0/0".into()],
    /// );
    ///
    /// let creds = VpnCredentials::new(
    ///     VpnType::WireGuard,
    ///     "MyVPN",
    ///     "vpn.example.com:51820",
    ///     "client_private_key",
    ///     "10.0.0.2/24",
    ///     vec![peer],
    /// );
    /// ```
    pub fn new(
        vpn_type: VpnType,
        name: impl Into<String>,
        gateway: impl Into<String>,
        private_key: impl Into<String>,
        address: impl Into<String>,
        peers: Vec<WireGuardPeer>,
    ) -> Self {
        Self {
            vpn_type,
            name: name.into(),
            gateway: gateway.into(),
            private_key: private_key.into(),
            address: address.into(),
            peers,
            dns: None,
            mtu: None,
            uuid: None,
        }
    }

    /// Creates a new `VpnCredentials` builder.
    ///
    /// This provides a more ergonomic way to construct VPN credentials with a fluent API,
    /// making it harder to mix up parameter order and easier to see what each value represents.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::{VpnCredentials, VpnType, WireGuardPeer};
    ///
    /// let peer = WireGuardPeer::new(
    ///     "server_public_key",
    ///     "vpn.example.com:51820",
    ///     vec!["0.0.0.0/0".into()],
    /// );
    ///
    /// let creds = VpnCredentials::builder()
    ///     .name("MyVPN")
    ///     .wireguard()
    ///     .gateway("vpn.example.com:51820")
    ///     .private_key("client_private_key")
    ///     .address("10.0.0.2/24")
    ///     .add_peer(peer)
    ///     .with_dns(vec!["1.1.1.1".into()])
    ///     .build();
    /// ```
    #[must_use]
    pub fn builder() -> VpnCredentialsBuilder {
        VpnCredentialsBuilder::default()
    }

    /// Sets the DNS servers to use when connected.
    #[must_use]
    pub fn with_dns(mut self, dns: Vec<String>) -> Self {
        self.dns = Some(dns);
        self
    }

    /// Sets the MTU (Maximum Transmission Unit) size.
    #[must_use]
    pub fn with_mtu(mut self, mtu: u32) -> Self {
        self.mtu = Some(mtu);
        self
    }

    /// Sets the UUID for the connection.
    #[must_use]
    pub fn with_uuid(mut self, uuid: Uuid) -> Self {
        self.uuid = Some(uuid);
        self
    }
}

/// Builder for constructing `VpnCredentials` with a fluent API.
///
/// This builder provides a more ergonomic way to create VPN credentials,
/// making the code more readable and less error-prone compared to the
/// traditional constructor with many positional parameters.
///
/// # Examples
///
/// ## Basic WireGuard VPN
///
/// ```rust
/// use nmrs::{VpnCredentials, WireGuardPeer};
///
/// let peer = WireGuardPeer::new(
///     "HIgo9xNzJMWLKAShlKl6/bUT1VI9Q0SDBXGtLXkPFXc=",
///     "vpn.example.com:51820",
///     vec!["0.0.0.0/0".into()],
/// );
///
/// let creds = VpnCredentials::builder()
///     .name("HomeVPN")
///     .wireguard()
///     .gateway("vpn.example.com:51820")
///     .private_key("YBk6X3pP8KjKz7+HFWzVHNqL3qTZq8hX9VxFQJ4zVmM=")
///     .address("10.0.0.2/24")
///     .add_peer(peer)
///     .build();
/// ```
///
/// ## With Optional DNS and MTU
///
/// ```rust
/// use nmrs::{VpnCredentials, WireGuardPeer};
///
/// let peer = WireGuardPeer::new(
///     "server_public_key",
///     "vpn.example.com:51820",
///     vec!["0.0.0.0/0".into()],
/// ).with_persistent_keepalive(25);
///
/// let creds = VpnCredentials::builder()
///     .name("CorpVPN")
///     .wireguard()
///     .gateway("vpn.corp.com:51820")
///     .private_key("private_key_here")
///     .address("10.8.0.2/24")
///     .add_peer(peer)
///     .with_dns(vec!["1.1.1.1".into(), "8.8.8.8".into()])
///     .with_mtu(1420)
///     .build();
/// ```
#[derive(Debug, Default)]
pub struct VpnCredentialsBuilder {
    vpn_type: Option<VpnType>,
    name: Option<String>,
    gateway: Option<String>,
    private_key: Option<String>,
    address: Option<String>,
    peers: Vec<WireGuardPeer>,
    dns: Option<Vec<String>>,
    mtu: Option<u32>,
    uuid: Option<Uuid>,
}

impl VpnCredentialsBuilder {
    /// Sets the VPN type to WireGuard.
    ///
    /// Currently, WireGuard is the only supported VPN type.
    #[must_use]
    pub fn wireguard(mut self) -> Self {
        self.vpn_type = Some(VpnType::WireGuard);
        self
    }

    /// Sets the VPN type.
    ///
    /// For most use cases, prefer using [`wireguard()`](Self::wireguard) instead.
    #[must_use]
    pub fn vpn_type(mut self, vpn_type: VpnType) -> Self {
        self.vpn_type = Some(vpn_type);
        self
    }

    /// Sets the connection name.
    ///
    /// This is the unique identifier for the VPN connection profile.
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Sets the VPN gateway endpoint.
    ///
    /// Should be in "host:port" format (e.g., "vpn.example.com:51820").
    #[must_use]
    pub fn gateway(mut self, gateway: impl Into<String>) -> Self {
        self.gateway = Some(gateway.into());
        self
    }

    /// Sets the client's WireGuard private key.
    ///
    /// The private key should be base64 encoded.
    #[must_use]
    pub fn private_key(mut self, private_key: impl Into<String>) -> Self {
        self.private_key = Some(private_key.into());
        self
    }

    /// Sets the client's IP address with CIDR notation.
    ///
    /// # Examples
    ///
    /// - "10.0.0.2/24" for a /24 subnet
    /// - "192.168.1.10/32" for a single IP
    #[must_use]
    pub fn address(mut self, address: impl Into<String>) -> Self {
        self.address = Some(address.into());
        self
    }

    /// Adds a WireGuard peer to the connection.
    ///
    /// Multiple peers can be added by calling this method multiple times.
    #[must_use]
    pub fn add_peer(mut self, peer: WireGuardPeer) -> Self {
        self.peers.push(peer);
        self
    }

    /// Sets all WireGuard peers at once.
    ///
    /// This replaces any previously added peers.
    #[must_use]
    pub fn peers(mut self, peers: Vec<WireGuardPeer>) -> Self {
        self.peers = peers;
        self
    }

    /// Sets the DNS servers to use when connected.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::VpnCredentials;
    ///
    /// let builder = VpnCredentials::builder()
    ///     .with_dns(vec!["1.1.1.1".into(), "8.8.8.8".into()]);
    /// ```
    #[must_use]
    pub fn with_dns(mut self, dns: Vec<String>) -> Self {
        self.dns = Some(dns);
        self
    }

    /// Sets the MTU (Maximum Transmission Unit) size.
    ///
    /// Typical values are 1420 for WireGuard over standard networks.
    #[must_use]
    pub fn with_mtu(mut self, mtu: u32) -> Self {
        self.mtu = Some(mtu);
        self
    }

    /// Sets a specific UUID for the connection.
    ///
    /// If not set, NetworkManager will generate one automatically.
    #[must_use]
    pub fn with_uuid(mut self, uuid: Uuid) -> Self {
        self.uuid = Some(uuid);
        self
    }

    /// Builds the `VpnCredentials` from the configured values.
    ///
    /// # Panics
    ///
    /// Panics if any required field is missing:
    /// - `vpn_type` (use [`wireguard()`](Self::wireguard))
    /// - `name` (use [`name()`](Self::name))
    /// - `gateway` (use [`gateway()`](Self::gateway))
    /// - `private_key` (use [`private_key()`](Self::private_key))
    /// - `address` (use [`address()`](Self::address))
    /// - At least one peer must be added (use [`add_peer()`](Self::add_peer))
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::{VpnCredentials, WireGuardPeer};
    ///
    /// let peer = WireGuardPeer::new(
    ///     "public_key",
    ///     "vpn.example.com:51820",
    ///     vec!["0.0.0.0/0".into()],
    /// );
    ///
    /// let creds = VpnCredentials::builder()
    ///     .name("MyVPN")
    ///     .wireguard()
    ///     .gateway("vpn.example.com:51820")
    ///     .private_key("private_key")
    ///     .address("10.0.0.2/24")
    ///     .add_peer(peer)
    ///     .build();
    /// ```
    #[must_use]
    pub fn build(self) -> VpnCredentials {
        VpnCredentials {
            vpn_type: self
                .vpn_type
                .expect("vpn_type is required (use .wireguard())"),
            name: self.name.expect("name is required (use .name())"),
            gateway: self.gateway.expect("gateway is required (use .gateway())"),
            private_key: self
                .private_key
                .expect("private_key is required (use .private_key())"),
            address: self.address.expect("address is required (use .address())"),
            peers: {
                if self.peers.is_empty() {
                    panic!("at least one peer is required (use .add_peer())");
                }
                self.peers
            },
            dns: self.dns,
            mtu: self.mtu,
            uuid: self.uuid,
        }
    }
}

/// WireGuard peer configuration.
///
/// Represents a single WireGuard peer (server) to connect to.
///
/// # Fields
///
/// - `public_key`: The peer's WireGuard public key
/// - `gateway`: Peer endpoint in "host:port" format (e.g., "vpn.example.com:51820")
/// - `allowed_ips`: List of IP ranges allowed through this peer (e.g., ["0.0.0.0/0"])
/// - `preshared_key`: Optional pre-shared key for additional security
/// - `persistent_keepalive`: Optional keepalive interval in seconds (e.g., 25)
///
/// # Example
///
/// ```rust
/// use nmrs::WireGuardPeer;
///
/// let peer = WireGuardPeer::new(
///     "aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789=",
///     "vpn.example.com:51820",
///     vec!["0.0.0.0/0".into(), "::/0".into()],
/// );
/// ```
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct WireGuardPeer {
    /// The peer's WireGuard public key (base64 encoded).
    pub public_key: String,
    /// Peer endpoint in "host:port" format.
    pub gateway: String,
    /// IP ranges to route through this peer (e.g., ["0.0.0.0/0"]).
    pub allowed_ips: Vec<String>,
    /// Optional pre-shared key for additional security.
    pub preshared_key: Option<String>,
    /// Optional keepalive interval in seconds (e.g., 25).
    pub persistent_keepalive: Option<u32>,
}

impl WireGuardPeer {
    /// Creates a new `WireGuardPeer` with the required fields.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use nmrs::WireGuardPeer;
    ///
    /// let peer = WireGuardPeer::new(
    ///     "aBcDeFgHiJkLmNoPqRsTuVwXyZ0123456789=",
    ///     "vpn.example.com:51820",
    ///     vec!["0.0.0.0/0".into()],
    /// );
    /// ```
    pub fn new(
        public_key: impl Into<String>,
        gateway: impl Into<String>,
        allowed_ips: Vec<String>,
    ) -> Self {
        Self {
            public_key: public_key.into(),
            gateway: gateway.into(),
            allowed_ips,
            preshared_key: None,
            persistent_keepalive: None,
        }
    }

    /// Sets the pre-shared key for additional security.
    #[must_use]
    pub fn with_preshared_key(mut self, psk: impl Into<String>) -> Self {
        self.preshared_key = Some(psk.into());
        self
    }

    /// Sets the persistent keepalive interval in seconds.
    #[must_use]
    pub fn with_persistent_keepalive(mut self, interval: u32) -> Self {
        self.persistent_keepalive = Some(interval);
        self
    }
}

/// VPN Connection information.
///
/// Represents a VPN connection managed by NetworkManager, including both
/// saved and active connections.
///
/// # Fields
///
/// - `name`: The connection name/identifier
/// - `vpn_type`: The type of VPN (WireGuard, etc.)
/// - `state`: Current connection state (for active connections)
/// - `interface`: Network interface name (e.g., "wg0") when active
///
/// # Example
///
/// ```no_run
/// # use nmrs::{VpnConnection, VpnType, DeviceState};
/// # // This struct is returned by the library, not constructed directly
/// # let vpn: VpnConnection = todo!();
/// println!("VPN: {}, State: {:?}", vpn.name, vpn.state);
/// ```
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct VpnConnection {
    /// The connection name/identifier.
    pub name: String,
    /// The type of VPN (WireGuard, etc.).
    pub vpn_type: VpnType,
    /// Current connection state.
    pub state: DeviceState,
    /// Network interface name when active (e.g., "wg0").
    pub interface: Option<String>,
}

/// Detailed VPN connection information and statistics.
///
/// Provides comprehensive information about an active VPN connection,
/// including IP configuration and connection details.
///
/// # Example
///
/// ```no_run
/// # use nmrs::{VpnConnectionInfo, VpnType, DeviceState};
/// # // This struct is returned by the library, not constructed directly
/// # let info: VpnConnectionInfo = todo!();
/// if let Some(ip) = &info.ip4_address {
///     println!("VPN IPv4: {}", ip);
/// }
/// if let Some(ip) = &info.ip6_address {
///     println!("VPN IPv6: {}", ip);
/// }
/// ```
#[non_exhaustive]
#[derive(Debug, Clone)]
pub struct VpnConnectionInfo {
    /// The connection name/identifier.
    pub name: String,
    /// The type of VPN (WireGuard, etc.).
    pub vpn_type: VpnType,
    /// Current connection state.
    pub state: DeviceState,
    /// Network interface name when active (e.g., "wg0").
    pub interface: Option<String>,
    /// VPN gateway endpoint address.
    pub gateway: Option<String>,
    /// Assigned IPv4 address with CIDR notation.
    pub ip4_address: Option<String>,
    /// Assigned IPv6 address with CIDR notation.
    pub ip6_address: Option<String>,
    /// DNS servers configured for this VPN.
    pub dns_servers: Vec<String>,
}