townos-api 0.0.2

Client for the Town OS control plane (systemcontroller) HTTP API
Documentation
//! WireGuard overlays, and the enrollment this client joins one through.
//!
//! The flow a desktop client uses is: generate a keypair locally, POST the
//! **public** half to [`Client::add_peer`], and receive a ready-to-import
//! wg-quick config. The private key never leaves the machine — the API will
//! generate a keypair for a caller that sends no public key, and answer with the
//! private half, but a client that can generate its own should, so the secret
//! exists in exactly one place.
//!
//! Enrollment is not permanent. A non-admin account's peer carries a TTL
//! (`peer_ttl`, two hours unless the operator changed it) and the enrolling
//! client is expected to call [`Client::refresh_peer`] before it elapses;
//! otherwise the reaper removes the peer and the overlay address is reclaimed.
//! An admin's peer has no expiry.

use chrono::{DateTime, Utc};
use serde::Deserialize;

use crate::{Client, Error, Result};

#[derive(Debug, Clone, Default, Deserialize)]
pub struct Network {
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub tld: String,
    #[serde(default)]
    pub subnet: String,
    #[serde(default)]
    pub address: String,
    #[serde(default)]
    pub public_key: String,
    #[serde(default)]
    pub listen_port: u16,
    #[serde(default)]
    pub enabled: bool,
    #[serde(default)]
    pub peer_count: u64,
    #[serde(default)]
    pub interface: String,
    #[serde(default)]
    pub running: bool,
}

impl Network {
    /// Whether this network can carry a tunnel at all.
    ///
    /// The default `home` network is a DNS-only scope with no overlay, so it can
    /// never have peers and must not be offered as somewhere to enroll.
    pub fn is_overlay(&self) -> bool {
        !self.subnet.is_empty() && self.listen_port != 0
    }
}

#[derive(Debug, Clone, Default, Deserialize)]
pub struct Peer {
    #[serde(default)]
    pub network: String,
    #[serde(default)]
    pub public_key: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub allowed_ip: String,
    #[serde(default)]
    pub endpoint: String,
    /// Whether this peer runs its own rolodex DNS server on its overlay address.
    /// Enrolling one is an administrator's call: it makes the peer a forwarder
    /// for the whole network's TLD.
    #[serde(default)]
    pub rolodex: bool,
    #[serde(default)]
    pub created_by: Option<String>,
    /// When the enrollment lapses. `None` means it never does.
    #[serde(default)]
    pub expires_at: Option<DateTime<Utc>>,
    #[serde(default)]
    pub created_at: Option<DateTime<Utc>>,
}

/// A peer joined with live tunnel state read from the kernel (admin only).
#[derive(Debug, Clone, Deserialize)]
pub struct ConnectedPeer {
    #[serde(default)]
    pub network: String,
    #[serde(default)]
    pub tld: String,
    #[serde(default)]
    pub interface: String,
    #[serde(default)]
    pub public_key: String,
    #[serde(default)]
    pub name: String,
    #[serde(default)]
    pub account: Option<String>,
    #[serde(default)]
    pub allowed_ip: String,
    #[serde(default)]
    pub endpoint: Option<String>,
    #[serde(default)]
    pub rolodex: bool,
    /// A handshake inside WireGuard's 180s window — the only liveness the
    /// protocol offers.
    #[serde(default)]
    pub connected: bool,
    /// Absent when the peer has never handshaken, which is distinct from having
    /// handshaken long ago.
    #[serde(default)]
    pub last_handshake: Option<DateTime<Utc>>,
    #[serde(default)]
    pub rx_bytes: u64,
    #[serde(default)]
    pub tx_bytes: u64,
    #[serde(default)]
    pub expires_at: Option<DateTime<Utc>>,
}

/// What [`Client::add_peer`] answers with.
#[derive(Debug, Clone, Deserialize)]
pub struct Enrollment {
    pub peer: Peer,
    /// Filled only when the server generated the keypair — that is, when the
    /// caller sent no public key.
    #[serde(default)]
    pub private_key: Option<String>,
    /// A wg-quick config for this device, with the box's public key, endpoint,
    /// overlay subnet and DNS server already filled in.
    #[serde(default)]
    pub config: String,
}

/// The new expiry after a heartbeat, so the client can pace the next one.
#[derive(Debug, Clone, Deserialize)]
pub struct RefreshedPeer {
    #[serde(default)]
    pub network: String,
    #[serde(default)]
    pub public_key: String,
    pub expires_at: DateTime<Utc>,
}

impl Client {
    /// Calls `GET /networks`.
    pub async fn networks(&self) -> Result<Vec<Network>> {
        self.get_json("/networks").await
    }

    /// Calls `GET /networks/peers`.
    pub async fn peers(&self, network: &str) -> Result<Vec<Peer>> {
        self.get_json(&format!("/networks/peers?network={}", enc(network)))
            .await
    }

    /// Every peer across every overlay, joined with kernel state (admin only).
    ///
    /// Calls `GET /networks/peers/connected`.
    pub async fn connected_peers(&self) -> Result<Vec<ConnectedPeer>> {
        self.get_json("/networks/peers/connected").await
    }

    /// Enrolls a device.
    ///
    /// Pass `public_key` to keep the private half local; pass `None` to let the
    /// server generate the pair and hand back the private key in
    /// [`Enrollment::private_key`].
    ///
    /// `endpoint` is where *other* peers should dial this one, `host:port`. Empty
    /// is right for a laptop behind NAT — it dials out and the box learns the
    /// address from the handshake — and wrong for a machine that is supposed to
    /// be reachable, which needs a name or address that resolves from the
    /// overlay. [`validate_endpoint`] is the same check the box applies.
    ///
    /// Calls `POST /networks/peers/add`. Permitted for an administrator or an
    /// account holding the `wireguard` grant on this network.
    pub async fn add_peer(
        &self,
        network: &str,
        name: &str,
        public_key: Option<&str>,
        endpoint: &str,
    ) -> Result<Enrollment> {
        self.post_json(
            "/networks/peers/add",
            &serde_json::json!({
                "network": network,
                "name": name,
                "public_key": public_key.unwrap_or(""),
                "endpoint": endpoint,
                // Enrolling a peer that serves DNS for the whole network's TLD is
                // an administrator's decision about what the network resolves,
                // not something a client asks for on its own behalf.
                "rolodex": false,
            }),
        )
        .await
    }

    /// Slides this peer's TTL forward — the heartbeat that keeps a long-lived
    /// enrollment alive. The server computes the new expiry; the caller does not
    /// choose it.
    ///
    /// Calls `POST /networks/peers/refresh`.
    pub async fn refresh_peer(&self, network: &str, public_key: &str) -> Result<RefreshedPeer> {
        self.post_json(
            "/networks/peers/refresh",
            &serde_json::json!({ "network": network, "public_key": public_key }),
        )
        .await
    }

    /// Calls `POST /networks/peers/remove` (admin).
    pub async fn remove_peer(&self, network: &str, public_key: &str) -> Result<()> {
        self.post_empty(
            "/networks/peers/remove",
            &serde_json::json!({ "network": network, "public_key": public_key }),
        )
        .await
    }

    /// Calls `POST /networks/enable` (admin). Brings the overlay's interface up.
    pub async fn enable_network(&self, name: &str) -> Result<()> {
        self.post_empty("/networks/enable", &serde_json::json!({ "name": name }))
            .await
    }

    /// Calls `POST /networks/disable` (admin). Takes the overlay down; local DNS
    /// and services keep running.
    pub async fn disable_network(&self, name: &str) -> Result<()> {
        self.post_empty("/networks/disable", &serde_json::json!({ "name": name }))
            .await
    }
}

/// Checks a peer endpoint the way the box does, so a mistake is reported beside
/// the field rather than as a 400 after the form is submitted.
///
/// Empty is valid and means "not reachable from outside" — the common case. Any
/// other value must be `host:port` with an IPv6 host bracketed, which is both
/// what `net.SplitHostPort` accepts on the box and what wg-quick expects.
pub fn validate_endpoint(endpoint: &str) -> Result<()> {
    let endpoint = endpoint.trim();
    if endpoint.is_empty() {
        return Ok(());
    }
    // A newline would let the value smuggle a second directive into the wg-quick
    // config, which is eval'd as root. The box refuses it; so does this.
    if endpoint.contains(['\n', '\r']) {
        return Err(Error::BaseUrl("an endpoint cannot contain a newline".into()));
    }

    let (host, port) = match endpoint.strip_prefix('[') {
        Some(rest) => {
            let (host, tail) = rest
                .split_once(']')
                .ok_or_else(|| Error::BaseUrl("a bracketed IPv6 endpoint is missing its ]".into()))?;
            let port = tail
                .strip_prefix(':')
                .ok_or_else(|| Error::BaseUrl(format!("{endpoint:?} has no port")))?;
            (host, port)
        }
        None => endpoint
            .rsplit_once(':')
            .ok_or_else(|| Error::BaseUrl(format!("{endpoint:?} has no port — write host:port")))?,
    };

    if host.is_empty() {
        return Err(Error::BaseUrl("an endpoint needs a host".into()));
    }
    if host.contains(':') && !endpoint.starts_with('[') {
        return Err(Error::BaseUrl(
            "an IPv6 endpoint must be bracketed, as [2001:db8::1]:51820".into(),
        ));
    }
    if !port.chars().all(|c| c.is_ascii_digit()) || !(1..=65535).contains(&port.parse::<u32>().unwrap_or(0))
    {
        return Err(Error::BaseUrl(format!("{port:?} is not a port")));
    }
    Ok(())
}

fn enc(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for byte in value.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
                out.push(byte as char)
            }
            other => out.push_str(&format!("%{other:02X}")),
        }
    }
    out
}

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

    #[test]
    fn dns_only_networks_are_not_offered_for_enrollment() {
        let home = Network {
            name: "home".into(),
            subnet: String::new(),
            listen_port: 0,
            ..Default::default()
        };
        assert!(!home.is_overlay());

        let office = Network {
            name: "office".into(),
            subnet: "10.9.0.0/24".into(),
            listen_port: 51820,
            ..Default::default()
        };
        assert!(office.is_overlay());
    }

    #[test]
    fn a_peer_with_no_expiry_is_permanent() {
        let peer: Peer = serde_json::from_str(
            r#"{"network":"office","public_key":"k","allowed_ip":"10.9.0.2/32"}"#,
        )
        .unwrap();
        assert!(peer.expires_at.is_none());
    }

    #[test]
    fn an_empty_endpoint_is_the_laptop_behind_nat_case() {
        assert!(validate_endpoint("").is_ok());
        assert!(validate_endpoint("   ").is_ok());
    }

    #[test]
    fn endpoints_are_host_and_port() {
        assert!(validate_endpoint("branch.example.com:51820").is_ok());
        assert!(validate_endpoint("10.9.0.5:51820").is_ok());
        assert!(validate_endpoint("[2001:db8::1]:51820").is_ok());
    }

    #[test]
    fn a_bare_host_is_refused_with_the_shape_it_wanted() {
        let err = validate_endpoint("branch.example.com").unwrap_err().detail();
        assert!(err.contains("host:port"), "{err}");
    }

    #[test]
    fn an_unbracketed_ipv6_endpoint_is_refused() {
        // rsplit finds a colon, so this parses as host "2001:db8:" port "1" — the
        // check has to catch it explicitly or the box would.
        let err = validate_endpoint("2001:db8::1:51820").unwrap_err().detail();
        assert!(err.contains("bracketed"), "{err}");
    }

    #[test]
    fn nonsense_ports_are_refused() {
        assert!(validate_endpoint("host:0").is_err());
        assert!(validate_endpoint("host:70000").is_err());
        assert!(validate_endpoint("host:wireguard").is_err());
        assert!(validate_endpoint("host:").is_err());
        assert!(validate_endpoint(":51820").is_err());
    }

    #[test]
    fn an_endpoint_carrying_a_newline_is_refused() {
        // wg-quick evals PostUp as root and decides what a hook is from the
        // file's own content, so a newline in a rendered value is a root shell.
        let err = validate_endpoint("host:51820\nPostUp = sh -c evil")
            .unwrap_err()
            .detail();
        assert!(err.contains("newline"), "{err}");
    }

    #[test]
    fn enrollment_without_a_server_key_reports_none() {
        let e: Enrollment = serde_json::from_str(
            r#"{"peer":{"network":"office","public_key":"k"},"config":"[Interface]\n"}"#,
        )
        .unwrap();
        assert!(e.private_key.is_none());
        assert_eq!(e.peer.network, "office");
    }
}