Skip to main content

townos_api/
networks.rs

1//! WireGuard overlays, and the enrollment this client joins one through.
2//!
3//! The flow a desktop client uses is: generate a keypair locally, POST the
4//! **public** half to [`Client::add_peer`], and receive a ready-to-import
5//! wg-quick config. The private key never leaves the machine — the API will
6//! generate a keypair for a caller that sends no public key, and answer with the
7//! private half, but a client that can generate its own should, so the secret
8//! exists in exactly one place.
9//!
10//! Enrollment is not permanent. A non-admin account's peer carries a TTL
11//! (`peer_ttl`, two hours unless the operator changed it) and the enrolling
12//! client is expected to call [`Client::refresh_peer`] before it elapses;
13//! otherwise the reaper removes the peer and the overlay address is reclaimed.
14//! An admin's peer has no expiry.
15
16use chrono::{DateTime, Utc};
17use serde::Deserialize;
18
19use crate::{Client, Error, Result};
20
21#[derive(Debug, Clone, Default, Deserialize)]
22pub struct Network {
23    #[serde(default)]
24    pub name: String,
25    #[serde(default)]
26    pub tld: String,
27    #[serde(default)]
28    pub subnet: String,
29    #[serde(default)]
30    pub address: String,
31    #[serde(default)]
32    pub public_key: String,
33    #[serde(default)]
34    pub listen_port: u16,
35    #[serde(default)]
36    pub enabled: bool,
37    #[serde(default)]
38    pub peer_count: u64,
39    #[serde(default)]
40    pub interface: String,
41    #[serde(default)]
42    pub running: bool,
43}
44
45impl Network {
46    /// Whether this network can carry a tunnel at all.
47    ///
48    /// The default `home` network is a DNS-only scope with no overlay, so it can
49    /// never have peers and must not be offered as somewhere to enroll.
50    pub fn is_overlay(&self) -> bool {
51        !self.subnet.is_empty() && self.listen_port != 0
52    }
53}
54
55#[derive(Debug, Clone, Default, Deserialize)]
56pub struct Peer {
57    #[serde(default)]
58    pub network: String,
59    #[serde(default)]
60    pub public_key: String,
61    #[serde(default)]
62    pub name: String,
63    #[serde(default)]
64    pub allowed_ip: String,
65    #[serde(default)]
66    pub endpoint: String,
67    /// Whether this peer runs its own rolodex DNS server on its overlay address.
68    /// Enrolling one is an administrator's call: it makes the peer a forwarder
69    /// for the whole network's TLD.
70    #[serde(default)]
71    pub rolodex: bool,
72    #[serde(default)]
73    pub created_by: Option<String>,
74    /// When the enrollment lapses. `None` means it never does.
75    #[serde(default)]
76    pub expires_at: Option<DateTime<Utc>>,
77    #[serde(default)]
78    pub created_at: Option<DateTime<Utc>>,
79}
80
81/// A peer joined with live tunnel state read from the kernel (admin only).
82#[derive(Debug, Clone, Deserialize)]
83pub struct ConnectedPeer {
84    #[serde(default)]
85    pub network: String,
86    #[serde(default)]
87    pub tld: String,
88    #[serde(default)]
89    pub interface: String,
90    #[serde(default)]
91    pub public_key: String,
92    #[serde(default)]
93    pub name: String,
94    #[serde(default)]
95    pub account: Option<String>,
96    #[serde(default)]
97    pub allowed_ip: String,
98    #[serde(default)]
99    pub endpoint: Option<String>,
100    #[serde(default)]
101    pub rolodex: bool,
102    /// A handshake inside WireGuard's 180s window — the only liveness the
103    /// protocol offers.
104    #[serde(default)]
105    pub connected: bool,
106    /// Absent when the peer has never handshaken, which is distinct from having
107    /// handshaken long ago.
108    #[serde(default)]
109    pub last_handshake: Option<DateTime<Utc>>,
110    #[serde(default)]
111    pub rx_bytes: u64,
112    #[serde(default)]
113    pub tx_bytes: u64,
114    #[serde(default)]
115    pub expires_at: Option<DateTime<Utc>>,
116}
117
118/// What [`Client::add_peer`] answers with.
119#[derive(Debug, Clone, Deserialize)]
120pub struct Enrollment {
121    pub peer: Peer,
122    /// Filled only when the server generated the keypair — that is, when the
123    /// caller sent no public key.
124    #[serde(default)]
125    pub private_key: Option<String>,
126    /// A wg-quick config for this device, with the box's public key, endpoint,
127    /// overlay subnet and DNS server already filled in.
128    #[serde(default)]
129    pub config: String,
130}
131
132/// The new expiry after a heartbeat, so the client can pace the next one.
133#[derive(Debug, Clone, Deserialize)]
134pub struct RefreshedPeer {
135    #[serde(default)]
136    pub network: String,
137    #[serde(default)]
138    pub public_key: String,
139    pub expires_at: DateTime<Utc>,
140}
141
142impl Client {
143    /// Calls `GET /networks`.
144    pub async fn networks(&self) -> Result<Vec<Network>> {
145        self.get_json("/networks").await
146    }
147
148    /// Calls `GET /networks/peers`.
149    pub async fn peers(&self, network: &str) -> Result<Vec<Peer>> {
150        self.get_json(&format!("/networks/peers?network={}", enc(network)))
151            .await
152    }
153
154    /// Every peer across every overlay, joined with kernel state (admin only).
155    ///
156    /// Calls `GET /networks/peers/connected`.
157    pub async fn connected_peers(&self) -> Result<Vec<ConnectedPeer>> {
158        self.get_json("/networks/peers/connected").await
159    }
160
161    /// Enrolls a device.
162    ///
163    /// Pass `public_key` to keep the private half local; pass `None` to let the
164    /// server generate the pair and hand back the private key in
165    /// [`Enrollment::private_key`].
166    ///
167    /// `endpoint` is where *other* peers should dial this one, `host:port`. Empty
168    /// is right for a laptop behind NAT — it dials out and the box learns the
169    /// address from the handshake — and wrong for a machine that is supposed to
170    /// be reachable, which needs a name or address that resolves from the
171    /// overlay. [`validate_endpoint`] is the same check the box applies.
172    ///
173    /// Calls `POST /networks/peers/add`. Permitted for an administrator or an
174    /// account holding the `wireguard` grant on this network.
175    pub async fn add_peer(
176        &self,
177        network: &str,
178        name: &str,
179        public_key: Option<&str>,
180        endpoint: &str,
181    ) -> Result<Enrollment> {
182        self.post_json(
183            "/networks/peers/add",
184            &serde_json::json!({
185                "network": network,
186                "name": name,
187                "public_key": public_key.unwrap_or(""),
188                "endpoint": endpoint,
189                // Enrolling a peer that serves DNS for the whole network's TLD is
190                // an administrator's decision about what the network resolves,
191                // not something a client asks for on its own behalf.
192                "rolodex": false,
193            }),
194        )
195        .await
196    }
197
198    /// Slides this peer's TTL forward — the heartbeat that keeps a long-lived
199    /// enrollment alive. The server computes the new expiry; the caller does not
200    /// choose it.
201    ///
202    /// Calls `POST /networks/peers/refresh`.
203    pub async fn refresh_peer(&self, network: &str, public_key: &str) -> Result<RefreshedPeer> {
204        self.post_json(
205            "/networks/peers/refresh",
206            &serde_json::json!({ "network": network, "public_key": public_key }),
207        )
208        .await
209    }
210
211    /// Calls `POST /networks/peers/remove` (admin).
212    pub async fn remove_peer(&self, network: &str, public_key: &str) -> Result<()> {
213        self.post_empty(
214            "/networks/peers/remove",
215            &serde_json::json!({ "network": network, "public_key": public_key }),
216        )
217        .await
218    }
219
220    /// Calls `POST /networks/enable` (admin). Brings the overlay's interface up.
221    pub async fn enable_network(&self, name: &str) -> Result<()> {
222        self.post_empty("/networks/enable", &serde_json::json!({ "name": name }))
223            .await
224    }
225
226    /// Calls `POST /networks/disable` (admin). Takes the overlay down; local DNS
227    /// and services keep running.
228    pub async fn disable_network(&self, name: &str) -> Result<()> {
229        self.post_empty("/networks/disable", &serde_json::json!({ "name": name }))
230            .await
231    }
232}
233
234/// Checks a peer endpoint the way the box does, so a mistake is reported beside
235/// the field rather than as a 400 after the form is submitted.
236///
237/// Empty is valid and means "not reachable from outside" — the common case. Any
238/// other value must be `host:port` with an IPv6 host bracketed, which is both
239/// what `net.SplitHostPort` accepts on the box and what wg-quick expects.
240pub fn validate_endpoint(endpoint: &str) -> Result<()> {
241    let endpoint = endpoint.trim();
242    if endpoint.is_empty() {
243        return Ok(());
244    }
245    // A newline would let the value smuggle a second directive into the wg-quick
246    // config, which is eval'd as root. The box refuses it; so does this.
247    if endpoint.contains(['\n', '\r']) {
248        return Err(Error::BaseUrl("an endpoint cannot contain a newline".into()));
249    }
250
251    let (host, port) = match endpoint.strip_prefix('[') {
252        Some(rest) => {
253            let (host, tail) = rest
254                .split_once(']')
255                .ok_or_else(|| Error::BaseUrl("a bracketed IPv6 endpoint is missing its ]".into()))?;
256            let port = tail
257                .strip_prefix(':')
258                .ok_or_else(|| Error::BaseUrl(format!("{endpoint:?} has no port")))?;
259            (host, port)
260        }
261        None => endpoint
262            .rsplit_once(':')
263            .ok_or_else(|| Error::BaseUrl(format!("{endpoint:?} has no port — write host:port")))?,
264    };
265
266    if host.is_empty() {
267        return Err(Error::BaseUrl("an endpoint needs a host".into()));
268    }
269    if host.contains(':') && !endpoint.starts_with('[') {
270        return Err(Error::BaseUrl(
271            "an IPv6 endpoint must be bracketed, as [2001:db8::1]:51820".into(),
272        ));
273    }
274    if !port.chars().all(|c| c.is_ascii_digit()) || !(1..=65535).contains(&port.parse::<u32>().unwrap_or(0))
275    {
276        return Err(Error::BaseUrl(format!("{port:?} is not a port")));
277    }
278    Ok(())
279}
280
281fn enc(value: &str) -> String {
282    let mut out = String::with_capacity(value.len());
283    for byte in value.bytes() {
284        match byte {
285            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
286                out.push(byte as char)
287            }
288            other => out.push_str(&format!("%{other:02X}")),
289        }
290    }
291    out
292}
293
294#[cfg(test)]
295mod tests {
296    use super::*;
297
298    #[test]
299    fn dns_only_networks_are_not_offered_for_enrollment() {
300        let home = Network {
301            name: "home".into(),
302            subnet: String::new(),
303            listen_port: 0,
304            ..Default::default()
305        };
306        assert!(!home.is_overlay());
307
308        let office = Network {
309            name: "office".into(),
310            subnet: "10.9.0.0/24".into(),
311            listen_port: 51820,
312            ..Default::default()
313        };
314        assert!(office.is_overlay());
315    }
316
317    #[test]
318    fn a_peer_with_no_expiry_is_permanent() {
319        let peer: Peer = serde_json::from_str(
320            r#"{"network":"office","public_key":"k","allowed_ip":"10.9.0.2/32"}"#,
321        )
322        .unwrap();
323        assert!(peer.expires_at.is_none());
324    }
325
326    #[test]
327    fn an_empty_endpoint_is_the_laptop_behind_nat_case() {
328        assert!(validate_endpoint("").is_ok());
329        assert!(validate_endpoint("   ").is_ok());
330    }
331
332    #[test]
333    fn endpoints_are_host_and_port() {
334        assert!(validate_endpoint("branch.example.com:51820").is_ok());
335        assert!(validate_endpoint("10.9.0.5:51820").is_ok());
336        assert!(validate_endpoint("[2001:db8::1]:51820").is_ok());
337    }
338
339    #[test]
340    fn a_bare_host_is_refused_with_the_shape_it_wanted() {
341        let err = validate_endpoint("branch.example.com").unwrap_err().detail();
342        assert!(err.contains("host:port"), "{err}");
343    }
344
345    #[test]
346    fn an_unbracketed_ipv6_endpoint_is_refused() {
347        // rsplit finds a colon, so this parses as host "2001:db8:" port "1" — the
348        // check has to catch it explicitly or the box would.
349        let err = validate_endpoint("2001:db8::1:51820").unwrap_err().detail();
350        assert!(err.contains("bracketed"), "{err}");
351    }
352
353    #[test]
354    fn nonsense_ports_are_refused() {
355        assert!(validate_endpoint("host:0").is_err());
356        assert!(validate_endpoint("host:70000").is_err());
357        assert!(validate_endpoint("host:wireguard").is_err());
358        assert!(validate_endpoint("host:").is_err());
359        assert!(validate_endpoint(":51820").is_err());
360    }
361
362    #[test]
363    fn an_endpoint_carrying_a_newline_is_refused() {
364        // wg-quick evals PostUp as root and decides what a hook is from the
365        // file's own content, so a newline in a rendered value is a root shell.
366        let err = validate_endpoint("host:51820\nPostUp = sh -c evil")
367            .unwrap_err()
368            .detail();
369        assert!(err.contains("newline"), "{err}");
370    }
371
372    #[test]
373    fn enrollment_without_a_server_key_reports_none() {
374        let e: Enrollment = serde_json::from_str(
375            r#"{"peer":{"network":"office","public_key":"k"},"config":"[Interface]\n"}"#,
376        )
377        .unwrap();
378        assert!(e.private_key.is_none());
379        assert_eq!(e.peer.network, "office");
380    }
381}