Skip to main content

townos_tunnel/
lib.rs

1//! Brings a Town OS overlay up using the WireGuard the host already has.
2//!
3//! The client does not implement WireGuard. It enrolls a peer, writes the
4//! wg-quick config the box hands back, and hands the work to something that can
5//! do it: `town-os-tunneld` on Linux, `wg-quick` on macOS, and the WireGuard
6//! tunnel service on Windows.
7//!
8//! Two consequences are worth stating plainly. Bringing an interface up needs
9//! root, and on Linux that privilege was granted once, to the helper, when it
10//! was installed — so nothing here ever raises an authorization prompt, and
11//! nothing here ever waits on one. macOS and Windows still ask, because neither
12//! has a helper yet. And when there is nothing on the machine to drive,
13//! [`TunnelManager::backend`] answers `None`, and the honest move is to export
14//! the config for the user to import, which [`TunnelManager::config_path`]
15//! supports.
16
17use std::path::{Path, PathBuf};
18
19mod backends;
20pub mod config;
21/// Running the host's tools. Deliberately not compiled on Linux.
22///
23/// Nothing on the Linux path shells out any more — the helper does the
24/// privileged work over a socket and the kernel answers the rest over netlink —
25/// and gating the module is what keeps it that way. A subprocess reintroduced
26/// here would be a compile error rather than something to notice in review. The
27/// platforms that still need it are the ones without a helper. See CLAUDE.md.
28#[cfg(not(target_os = "linux"))]
29pub mod exec;
30/// The client half of the helper protocol. Linux-only, because the helper is.
31#[cfg(target_os = "linux")]
32pub mod helper;
33pub mod keys;
34pub mod proto;
35/// Talking to the kernel directly. Linux only for now; the other platforms
36/// reach their WireGuard through different interfaces and get their own
37/// modules rather than a lowest common denominator here.
38#[cfg(target_os = "linux")]
39pub mod netlink;
40
41pub use config::{WgConfig, interface_name};
42pub use keys::Keypair;
43
44#[derive(Debug, thiserror::Error)]
45pub enum Error {
46    #[error("{0}")]
47    Config(String),
48
49    #[error("{what} failed{}: {message}", .status.map(|s| format!(" (exit {s})")).unwrap_or_default())]
50    Command {
51        what: String,
52        status: Option<i32>,
53        message: String,
54    },
55
56    #[error("{0} is not installed")]
57    ToolMissing(String),
58
59    /// The privileged helper could not be reached, or would not do it. Carried
60    /// as strings for the same reason as `Netlink` below: this must exist on
61    /// every platform, and the cause is prose rather than an error to chain to.
62    #[error("{what}: {cause}")]
63    Helper { what: String, cause: String },
64
65    #[error("could not run {program}: {source}")]
66    Spawn {
67        program: String,
68        #[source]
69        source: std::io::Error,
70    },
71
72    #[error("no system WireGuard found")]
73    NoBackend,
74
75    /// The cause is carried as a string rather than the netlink crate's own
76    /// error type, so this variant exists on every platform and the enum does
77    /// not change shape with the target. It is deliberately not named `source`:
78    /// thiserror reads that name as an `Error` to chain to, and this is prose.
79    #[error("{what}: {cause}")]
80    Netlink { what: String, cause: String },
81
82    #[error("{path}: {source}")]
83    Io {
84        path: PathBuf,
85        #[source]
86        source: std::io::Error,
87    },
88}
89
90pub type Result<T> = std::result::Result<T, Error>;
91
92/// Which system WireGuard a backend drives.
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94pub enum BackendKind {
95    /// `town-os-tunneld`, over its unix socket.
96    Helper,
97    /// `wg-quick`, elevated.
98    WgQuick,
99    /// The WireGuard for Windows tunnel service.
100    WindowsService,
101}
102
103/// Whether a backend can be used, and if not, what to tell the user.
104#[derive(Debug, Clone)]
105pub struct Availability {
106    pub usable: bool,
107    /// A sentence fit to show: what is missing, or what this will do.
108    pub detail: String,
109}
110
111impl Availability {
112    pub fn usable(detail: impl Into<String>) -> Availability {
113        Availability {
114            usable: true,
115            detail: detail.into(),
116        }
117    }
118
119    pub fn missing(detail: impl Into<String>) -> Availability {
120        Availability {
121            usable: false,
122            detail: detail.into(),
123        }
124    }
125}
126
127/// One overlay, ready to bring up.
128#[derive(Debug, Clone)]
129pub struct Tunnel {
130    /// The Town OS network this belongs to.
131    pub network: String,
132    /// The host interface name, from [`interface_name`].
133    pub interface: String,
134    /// Where the wg-quick config is written.
135    pub config_path: PathBuf,
136}
137
138/// What a backend can do with an interface.
139///
140/// Every method is async, and that is the point of the trait. All four are
141/// questions for something outside this process — the kernel, or the service
142/// that owns the interface — and all four are asked from the UI. Making them
143/// futures is what lets the window keep drawing while they are outstanding.
144///
145/// `up` and `down` were the last two that were not. They ran `pkexec wg-quick`,
146/// a subprocess that sits on a polkit dialog until somebody types a password,
147/// which is unbounded human-interaction time on a thread and the whole subject
148/// of CLAUDE.md. The privilege is now granted once, to a helper, and asking it
149/// to do something is a message on a socket. See [`helper`].
150#[async_trait::async_trait]
151pub trait Backend: Send + Sync {
152    fn kind(&self) -> BackendKind;
153
154    /// A name for the user, e.g. "NetworkManager".
155    fn label(&self) -> &'static str;
156
157    /// How this backend will ask for privilege, shown before it first does.
158    fn elevation(&self) -> &'static str;
159
160    /// Whether this backend is usable on this machine right now.
161    ///
162    /// Async and never called from a frame. This used to run `nmcli` on the UI
163    /// thread from inside `backend_panel`, which is a subprocess inside a
164    /// repaint — the compositor's "Application Not Responding" dialog was that,
165    /// waiting on a D-Bus call with a 25 second default timeout.
166    async fn probe(&self) -> Availability;
167
168    /// Brings the interface up.
169    async fn up(&self, tunnel: &Tunnel) -> Result<()>;
170
171    /// Takes the interface down.
172    async fn down(&self, tunnel: &Tunnel) -> Result<()>;
173
174    /// Whether the interface is currently up.
175    ///
176    /// This must not need privilege: it runs on a timer, and a status poll that
177    /// raised an authorization prompt would be unusable.
178    async fn is_up(&self, tunnel: &Tunnel) -> Result<bool>;
179}
180
181/// Owns the config files and picks a backend.
182pub struct TunnelManager {
183    state_dir: PathBuf,
184    backends: Vec<Box<dyn Backend>>,
185}
186
187impl TunnelManager {
188    /// Builds a manager storing configs under `state_dir`.
189    ///
190    /// Backends come back in preference order, most integrated first.
191    pub fn new(state_dir: impl Into<PathBuf>) -> TunnelManager {
192        TunnelManager {
193            state_dir: state_dir.into(),
194            backends: backends::for_platform(),
195        }
196    }
197
198    /// Every backend this build knows, in preference order, so the UI can show
199    /// what was found and what was not.
200    pub fn backends(&self) -> &[Box<dyn Backend>] {
201        &self.backends
202    }
203
204    /// The first usable backend, or `None` when no system WireGuard is present.
205    ///
206    /// Async because probing is: this asks each backend in turn until one says
207    /// it is usable, and a backend may have to talk to a service to know. It
208    /// must never be called from a frame — that is what froze the window.
209    pub async fn backend(&self) -> Option<&dyn Backend> {
210        for backend in &self.backends {
211            if backend.probe().await.usable {
212                return Some(backend.as_ref());
213            }
214        }
215        None
216    }
217
218    /// The backend of a given kind, without probing.
219    ///
220    /// Probing is a question for something outside this process, so it happens
221    /// once and the answer is remembered; this is how a caller that already
222    /// knows which backend was chosen gets hold of it again without asking the
223    /// system a second time. Synchronous on purpose — it is a lookup in a
224    /// `Vec`, and callers on the UI thread must be able to use it.
225    pub fn backend_of_kind(&self, kind: BackendKind) -> Option<&dyn Backend> {
226        self.backends
227            .iter()
228            .find(|b| b.kind() == kind)
229            .map(|b| b.as_ref())
230    }
231
232    /// Every backend's availability, in preference order.
233    ///
234    /// One pass for the UI to render the whole panel from, so the tunnels tab
235    /// does not probe once per backend per repaint.
236    pub async fn availability(&self) -> Vec<(&'static str, Availability)> {
237        let mut out = Vec::with_capacity(self.backends.len());
238        for backend in &self.backends {
239            out.push((backend.label(), backend.probe().await));
240        }
241        out
242    }
243
244    /// Where this network's config lives.
245    pub fn config_path(&self, network: &str) -> PathBuf {
246        self.state_dir.join(format!("{}.conf", interface_name(network)))
247    }
248
249    /// Describes a network's tunnel without touching the filesystem.
250    pub fn tunnel(&self, network: &str) -> Tunnel {
251        Tunnel {
252            network: network.to_owned(),
253            interface: interface_name(network),
254            config_path: self.config_path(network),
255        }
256    }
257
258    /// Writes the config, readable only by this user, and returns the tunnel.
259    ///
260    /// The file holds the device's private key, so the mode is not incidental:
261    /// on Unix it is created 0600, and an existing file is truncated rather than
262    /// appended so a re-enrollment cannot leave the previous key behind.
263    /// These three are futures because the caller is a frame.
264    ///
265    /// A config is a few hundred bytes in the user's own state directory, so on
266    /// a local disk this is microseconds — but a home directory is not always a
267    /// local disk, NFS and sshfs are both ordinary, and "usually fast" is what
268    /// this whole app has been getting wrong. See CLAUDE.md.
269    pub async fn install(&self, network: &str, config: &WgConfig) -> Result<Tunnel> {
270        config.validate()?;
271
272        tokio::fs::create_dir_all(&self.state_dir)
273            .await
274            .map_err(|source| Error::Io {
275                path: self.state_dir.clone(),
276                source,
277            })?;
278        restrict_dir(&self.state_dir).await;
279
280        let tunnel = self.tunnel(network);
281        write_private(&tunnel.config_path, config.render().as_bytes()).await?;
282        Ok(tunnel)
283    }
284
285    /// Reads back an installed config, if there is one.
286    pub async fn installed(&self, network: &str) -> Option<WgConfig> {
287        let text = tokio::fs::read_to_string(self.config_path(network)).await.ok()?;
288        WgConfig::parse(&text).ok()
289    }
290
291    /// Forgets a network's config. Take the tunnel down first — this only
292    /// removes the file.
293    pub async fn uninstall(&self, network: &str) -> Result<()> {
294        let path = self.config_path(network);
295        match tokio::fs::remove_file(&path).await {
296            Ok(()) => Ok(()),
297            Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
298            Err(source) => Err(Error::Io { path, source }),
299        }
300    }
301}
302
303/// Writes a file only this user can read.
304///
305/// The mode is set at creation rather than after: a file created 0644 and
306/// chmod'ed afterwards is world-readable for the window in between, and what it
307/// holds is a private key.
308async fn write_private(path: &Path, contents: &[u8]) -> Result<()> {
309    use tokio::io::AsyncWriteExt as _;
310
311    let mut options = tokio::fs::OpenOptions::new();
312    options.write(true).create(true).truncate(true);
313    #[cfg(unix)]
314    options.mode(0o600);
315
316    let mut file = options.open(path).await.map_err(|source| Error::Io {
317        path: path.to_owned(),
318        source,
319    })?;
320    file.write_all(contents).await.map_err(|source| Error::Io {
321        path: path.to_owned(),
322        source,
323    })?;
324    file.flush().await.map_err(|source| Error::Io {
325        path: path.to_owned(),
326        source,
327    })
328}
329
330/// Best-effort 0700 on the directory holding the configs.
331async fn restrict_dir(path: &Path) {
332    #[cfg(unix)]
333    {
334        use std::os::unix::fs::PermissionsExt as _;
335        let _ = tokio::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).await;
336    }
337    #[cfg(not(unix))]
338    let _ = path;
339}
340
341#[cfg(test)]
342mod tests {
343    use super::*;
344
345    fn sample_config() -> WgConfig {
346        let mut cfg = WgConfig::parse(
347            "[Interface]\nPrivateKey = REPLACE_WITH_YOUR_PRIVATE_KEY\nAddress = 10.9.0.2/32\nDNS = 10.9.0.1\n\n[Peer]\nPublicKey = pk\nAllowedIPs = 10.9.0.0/24\n",
348        )
349        .unwrap();
350        cfg.set_private_key(Keypair::generate().private_key());
351        cfg
352    }
353
354    fn temp_dir(name: &str) -> PathBuf {
355        let dir = std::env::temp_dir().join(format!("townos-tunnel-test-{name}-{}", std::process::id()));
356        let _ = std::fs::remove_dir_all(&dir);
357        dir
358    }
359
360    #[test]
361    fn config_path_follows_the_interface_name() {
362        let mgr = TunnelManager::new("/tmp/state");
363        assert_eq!(mgr.config_path("office"), Path::new("/tmp/state/townos-office.conf"));
364        assert_eq!(mgr.tunnel("office").interface, "townos-office");
365    }
366
367    #[tokio::test]
368    async fn install_writes_a_config_only_this_user_can_read() {
369        let dir = temp_dir("install");
370        let mgr = TunnelManager::new(&dir);
371        let tunnel = mgr.install("office", &sample_config()).await.unwrap();
372
373        assert!(tunnel.config_path.exists());
374        #[cfg(unix)]
375        {
376            use std::os::unix::fs::PermissionsExt as _;
377            let mode = std::fs::metadata(&tunnel.config_path).unwrap().permissions().mode();
378            assert_eq!(mode & 0o777, 0o600, "config holds a private key");
379        }
380
381        let read_back = mgr.installed("office").await.unwrap();
382        assert_eq!(read_back.address(), Some("10.9.0.2/32"));
383
384        let _ = std::fs::remove_dir_all(&dir);
385    }
386
387    #[tokio::test]
388    async fn install_refuses_a_config_that_would_run_commands_as_root() {
389        let dir = temp_dir("refuse");
390        let mgr = TunnelManager::new(&dir);
391        let cfg = WgConfig::parse(
392            "[Interface]\nPrivateKey = k\nAddress = 10.9.0.2/32\nPostUp = touch /tmp/pwned\n\n[Peer]\nPublicKey = pk\n",
393        )
394        .unwrap();
395
396        assert!(mgr.install("office", &cfg).await.is_err());
397        assert!(!mgr.config_path("office").exists(), "nothing was written");
398        let _ = std::fs::remove_dir_all(&dir);
399    }
400
401    #[tokio::test]
402    async fn reinstalling_replaces_rather_than_appends() {
403        let dir = temp_dir("replace");
404        let mgr = TunnelManager::new(&dir);
405        mgr.install("office", &sample_config()).await.unwrap();
406        let first = std::fs::read_to_string(mgr.config_path("office")).unwrap();
407
408        mgr.install("office", &sample_config()).await.unwrap();
409        let second = std::fs::read_to_string(mgr.config_path("office")).unwrap();
410
411        assert_ne!(first, second, "a fresh key was written");
412        assert_eq!(second.matches("[Interface]").count(), 1, "not appended");
413        let _ = std::fs::remove_dir_all(&dir);
414    }
415
416    #[tokio::test]
417    async fn uninstalling_something_absent_is_not_an_error() {
418        let dir = temp_dir("uninstall");
419        let mgr = TunnelManager::new(&dir);
420        assert!(mgr.uninstall("never-installed").await.is_ok());
421        assert!(mgr.installed("never-installed").await.is_none());
422    }
423
424    #[tokio::test]
425    async fn every_backend_probes_without_panicking() {
426        // Probing asks things outside this process; it must answer on a machine
427        // that has none of them, because that is exactly when the UI asks.
428        let mgr = TunnelManager::new("/tmp/state");
429        for (label, availability) in mgr.availability().await {
430            assert!(!label.is_empty());
431            assert!(!availability.detail.is_empty(), "{label} gave no reason");
432        }
433    }
434
435    #[tokio::test]
436    async fn availability_covers_every_backend_in_preference_order() {
437        // The panel renders straight from this, so it has to describe all of
438        // them and keep the order the platform put them in.
439        let mgr = TunnelManager::new("/tmp/state");
440        let reported: Vec<&str> = mgr.availability().await.into_iter().map(|(l, _)| l).collect();
441        let expected: Vec<&str> = mgr.backends().iter().map(|b| b.label()).collect();
442        assert_eq!(reported, expected);
443    }
444}