townos-api 0.0.3

Client for the Town OS control plane (systemcontroller) HTTP API
Documentation
use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};

/// The grant that permits enrolling and refreshing WireGuard peers.
pub const GRANT_WIREGUARD: &str = "wireguard";
/// The grant that permits administering object storage.
pub const GRANT_GFEH: &str = "gfeh";

#[derive(Debug, Clone, Deserialize)]
pub struct Authenticated {
    pub token: String,
    #[serde(default)]
    pub account: Option<Account>,
}

#[derive(Debug, Clone, Default, Deserialize)]
pub struct Account {
    pub username: String,
    #[serde(default)]
    pub email: String,
    #[serde(default)]
    pub phone: String,
    #[serde(default)]
    pub real_name: String,
    #[serde(default)]
    pub admin: bool,
    #[serde(default)]
    pub disabled: bool,
    /// Named capabilities. Empty means an ordinary dashboard account; an
    /// administrator holds every grant implicitly and stores none.
    #[serde(default)]
    pub grants: Vec<String>,
    /// Networks a granted account may act on. Meaningful only alongside
    /// `grants`, and never empty then.
    #[serde(default)]
    pub networks: Vec<String>,
}

impl Account {
    /// Whether this account may exercise `grant`.
    ///
    /// An administrator answers true for everything without storing anything,
    /// which is why this is a method rather than a `contains` at each call site.
    pub fn holds(&self, grant: &str) -> bool {
        self.admin || self.grants.iter().any(|g| g == grant)
    }

    /// Whether this account may act on `network`. An unscoped ordinary account
    /// (no grants) is not restricted by scope; a granted one is.
    pub fn may_use_network(&self, network: &str) -> bool {
        self.admin || self.networks.is_empty() || self.networks.iter().any(|n| n == network)
    }
}

#[derive(Debug, Clone, Deserialize)]
pub struct Session {
    #[serde(default)]
    pub id: String,
    #[serde(default)]
    pub username: String,
    #[serde(default)]
    pub created_at: Option<DateTime<Utc>>,
    #[serde(default)]
    pub last_used: Option<DateTime<Utc>>,
}

/// The system overview from `GET /status/ping`.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Ping {
    #[serde(default)]
    pub status: String,
    #[serde(default)]
    pub filesystems: u64,
    #[serde(default)]
    pub repositories: u64,
    #[serde(default)]
    pub packages: u64,
    #[serde(default)]
    pub installed: u64,
    #[serde(default)]
    pub accounts: u64,
    #[serde(default)]
    pub admins: u64,
    #[serde(default)]
    pub units: Option<UnitCounts>,
    #[serde(default)]
    pub recent_errors: u64,
    #[serde(default)]
    pub needs_setup: bool,
    #[serde(default)]
    pub upgrades_available: u64,
    /// Server UTC offset in minutes (positive east).
    #[serde(default)]
    pub timezone_offset: i32,
}

#[derive(Debug, Clone, Default, Deserialize)]
pub struct UnitCounts {
    #[serde(default)]
    pub total: u64,
    #[serde(default)]
    pub running: u64,
    #[serde(default)]
    pub failed: u64,
}

/// A core system service and its container state, from `GET /system-services`.
#[derive(Debug, Clone, Deserialize)]
pub struct SystemService {
    #[serde(default)]
    pub key: String,
    #[serde(default)]
    pub display_name: String,
    #[serde(default)]
    pub image: String,
    #[serde(default)]
    pub port: String,
    #[serde(rename = "Name", default)]
    pub unit_name: String,
    #[serde(rename = "ActiveState", default)]
    pub active_state: String,
    #[serde(rename = "SubState", default)]
    pub sub_state: String,
}

impl SystemService {
    pub fn running(&self) -> bool {
        self.active_state == "active"
    }

    /// A name to show, preferring the human one the server supplies.
    pub fn label(&self) -> &str {
        if self.display_name.is_empty() {
            &self.key
        } else {
            &self.display_name
        }
    }
}

/// A btrfs subvolume. Object storage partitions are backed by these, and the
/// tab shows them together so a quota is legible next to what fills it.
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Filesystem {
    pub name: String,
    /// Bytes; 0 means unlimited.
    #[serde(default)]
    pub quota: u64,
    #[serde(default, skip_serializing_if = "String::is_empty")]
    pub state: String,
}

/// One page of `POST /storage`.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct FilesystemPage {
    #[serde(default)]
    pub entries: Vec<Filesystem>,
    #[serde(default)]
    pub has_more: bool,
    #[serde(default)]
    pub total_pages: u64,
    #[serde(default)]
    pub total_count: u64,
}

/// Renders a byte count the way an operator reads a quota, with 0 meaning
/// unlimited rather than empty.
pub fn format_bytes(bytes: u64) -> String {
    if bytes == 0 {
        return "unlimited".into();
    }
    const UNITS: [&str; 6] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"];
    let mut value = bytes as f64;
    let mut unit = 0;
    while value >= 1024.0 && unit < UNITS.len() - 1 {
        value /= 1024.0;
        unit += 1;
    }
    if unit == 0 {
        format!("{bytes} B")
    } else if value >= 100.0 {
        format!("{value:.0} {}", UNITS[unit])
    } else {
        format!("{value:.1} {}", UNITS[unit])
    }
}

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

    #[test]
    fn admin_holds_every_grant_without_storing_any() {
        let admin = Account {
            admin: true,
            ..Default::default()
        };
        assert!(admin.holds(GRANT_WIREGUARD));
        assert!(admin.holds(GRANT_GFEH));
        assert!(admin.may_use_network("anything"));
    }

    #[test]
    fn granted_account_is_confined_to_its_scope() {
        let acct = Account {
            grants: vec![GRANT_WIREGUARD.into()],
            networks: vec!["office".into()],
            ..Default::default()
        };
        assert!(acct.holds(GRANT_WIREGUARD));
        assert!(!acct.holds(GRANT_GFEH));
        assert!(acct.may_use_network("office"));
        assert!(!acct.may_use_network("home"));
    }

    #[test]
    fn zero_quota_reads_as_unlimited() {
        assert_eq!(format_bytes(0), "unlimited");
        assert_eq!(format_bytes(512), "512 B");
        assert_eq!(format_bytes(1024), "1.0 KiB");
        assert_eq!(format_bytes(10 * 1024 * 1024 * 1024), "10.0 GiB");
    }
}