Skip to main content

townos_api/
types.rs

1use chrono::{DateTime, Utc};
2use serde::{Deserialize, Serialize};
3
4/// The grant that permits enrolling and refreshing WireGuard peers.
5pub const GRANT_WIREGUARD: &str = "wireguard";
6/// The grant that permits administering object storage.
7pub const GRANT_GFEH: &str = "gfeh";
8
9#[derive(Debug, Clone, Deserialize)]
10pub struct Authenticated {
11    pub token: String,
12    #[serde(default)]
13    pub account: Option<Account>,
14}
15
16#[derive(Debug, Clone, Default, Deserialize)]
17pub struct Account {
18    pub username: String,
19    #[serde(default)]
20    pub email: String,
21    #[serde(default)]
22    pub phone: String,
23    #[serde(default)]
24    pub real_name: String,
25    #[serde(default)]
26    pub admin: bool,
27    #[serde(default)]
28    pub disabled: bool,
29    /// Named capabilities. Empty means an ordinary dashboard account; an
30    /// administrator holds every grant implicitly and stores none.
31    #[serde(default)]
32    pub grants: Vec<String>,
33    /// Networks a granted account may act on. Meaningful only alongside
34    /// `grants`, and never empty then.
35    #[serde(default)]
36    pub networks: Vec<String>,
37}
38
39impl Account {
40    /// Whether this account may exercise `grant`.
41    ///
42    /// An administrator answers true for everything without storing anything,
43    /// which is why this is a method rather than a `contains` at each call site.
44    pub fn holds(&self, grant: &str) -> bool {
45        self.admin || self.grants.iter().any(|g| g == grant)
46    }
47
48    /// Whether this account may act on `network`. An unscoped ordinary account
49    /// (no grants) is not restricted by scope; a granted one is.
50    pub fn may_use_network(&self, network: &str) -> bool {
51        self.admin || self.networks.is_empty() || self.networks.iter().any(|n| n == network)
52    }
53}
54
55#[derive(Debug, Clone, Deserialize)]
56pub struct Session {
57    #[serde(default)]
58    pub id: String,
59    #[serde(default)]
60    pub username: String,
61    #[serde(default)]
62    pub created_at: Option<DateTime<Utc>>,
63    #[serde(default)]
64    pub last_used: Option<DateTime<Utc>>,
65}
66
67/// The system overview from `GET /status/ping`.
68#[derive(Debug, Clone, Default, Deserialize)]
69pub struct Ping {
70    #[serde(default)]
71    pub status: String,
72    #[serde(default)]
73    pub filesystems: u64,
74    #[serde(default)]
75    pub repositories: u64,
76    #[serde(default)]
77    pub packages: u64,
78    #[serde(default)]
79    pub installed: u64,
80    #[serde(default)]
81    pub accounts: u64,
82    #[serde(default)]
83    pub admins: u64,
84    #[serde(default)]
85    pub units: Option<UnitCounts>,
86    #[serde(default)]
87    pub recent_errors: u64,
88    #[serde(default)]
89    pub needs_setup: bool,
90    #[serde(default)]
91    pub upgrades_available: u64,
92    /// Server UTC offset in minutes (positive east).
93    #[serde(default)]
94    pub timezone_offset: i32,
95}
96
97#[derive(Debug, Clone, Default, Deserialize)]
98pub struct UnitCounts {
99    #[serde(default)]
100    pub total: u64,
101    #[serde(default)]
102    pub running: u64,
103    #[serde(default)]
104    pub failed: u64,
105}
106
107/// A core system service and its container state, from `GET /system-services`.
108#[derive(Debug, Clone, Deserialize)]
109pub struct SystemService {
110    #[serde(default)]
111    pub key: String,
112    #[serde(default)]
113    pub display_name: String,
114    #[serde(default)]
115    pub image: String,
116    #[serde(default)]
117    pub port: String,
118    #[serde(rename = "Name", default)]
119    pub unit_name: String,
120    #[serde(rename = "ActiveState", default)]
121    pub active_state: String,
122    #[serde(rename = "SubState", default)]
123    pub sub_state: String,
124}
125
126impl SystemService {
127    pub fn running(&self) -> bool {
128        self.active_state == "active"
129    }
130
131    /// A name to show, preferring the human one the server supplies.
132    pub fn label(&self) -> &str {
133        if self.display_name.is_empty() {
134            &self.key
135        } else {
136            &self.display_name
137        }
138    }
139}
140
141/// A btrfs subvolume. Object storage partitions are backed by these, and the
142/// tab shows them together so a quota is legible next to what fills it.
143#[derive(Debug, Clone, Default, Serialize, Deserialize)]
144pub struct Filesystem {
145    pub name: String,
146    /// Bytes; 0 means unlimited.
147    #[serde(default)]
148    pub quota: u64,
149    #[serde(default, skip_serializing_if = "String::is_empty")]
150    pub state: String,
151}
152
153/// One page of `POST /storage`.
154#[derive(Debug, Clone, Default, Deserialize)]
155pub struct FilesystemPage {
156    #[serde(default)]
157    pub entries: Vec<Filesystem>,
158    #[serde(default)]
159    pub has_more: bool,
160    #[serde(default)]
161    pub total_pages: u64,
162    #[serde(default)]
163    pub total_count: u64,
164}
165
166/// Renders a byte count the way an operator reads a quota, with 0 meaning
167/// unlimited rather than empty.
168pub fn format_bytes(bytes: u64) -> String {
169    if bytes == 0 {
170        return "unlimited".into();
171    }
172    const UNITS: [&str; 6] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"];
173    let mut value = bytes as f64;
174    let mut unit = 0;
175    while value >= 1024.0 && unit < UNITS.len() - 1 {
176        value /= 1024.0;
177        unit += 1;
178    }
179    if unit == 0 {
180        format!("{bytes} B")
181    } else if value >= 100.0 {
182        format!("{value:.0} {}", UNITS[unit])
183    } else {
184        format!("{value:.1} {}", UNITS[unit])
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::*;
191
192    #[test]
193    fn admin_holds_every_grant_without_storing_any() {
194        let admin = Account {
195            admin: true,
196            ..Default::default()
197        };
198        assert!(admin.holds(GRANT_WIREGUARD));
199        assert!(admin.holds(GRANT_GFEH));
200        assert!(admin.may_use_network("anything"));
201    }
202
203    #[test]
204    fn granted_account_is_confined_to_its_scope() {
205        let acct = Account {
206            grants: vec![GRANT_WIREGUARD.into()],
207            networks: vec!["office".into()],
208            ..Default::default()
209        };
210        assert!(acct.holds(GRANT_WIREGUARD));
211        assert!(!acct.holds(GRANT_GFEH));
212        assert!(acct.may_use_network("office"));
213        assert!(!acct.may_use_network("home"));
214    }
215
216    #[test]
217    fn zero_quota_reads_as_unlimited() {
218        assert_eq!(format_bytes(0), "unlimited");
219        assert_eq!(format_bytes(512), "512 B");
220        assert_eq!(format_bytes(1024), "1.0 KiB");
221        assert_eq!(format_bytes(10 * 1024 * 1024 * 1024), "10.0 GiB");
222    }
223}