Skip to main content

townos_api/
lib.rs

1//! A client for the Town OS control plane, the HTTP API served by
2//! `systemcontroller` on port 5309.
3//!
4//! Every endpoint answers 200 on success — including the ones with no body — so
5//! anything else is a refusal and becomes an [`Error::Status`]. Authentication is
6//! a bearer token obtained from [`Client::authenticate`]; it is a 7-day JWT that
7//! slides forward on use.
8//!
9//! The module split follows the control plane's own route groups: [`dns`],
10//! [`storage`] (object storage plus the btrfs volumes underneath it), and
11//! [`networks`] (the WireGuard overlays a client enrolls into).
12
13use std::sync::{Arc, RwLock};
14use std::time::Duration;
15
16use serde::Serialize;
17use serde::de::DeserializeOwned;
18
19pub mod dns;
20mod error;
21pub mod networks;
22pub mod status;
23pub mod storage;
24mod types;
25
26pub use error::{Error, Problem, Result};
27pub use types::*;
28
29/// The port `systemcontroller` listens on unless `TOWN_OS_LISTEN` says otherwise.
30pub const DEFAULT_PORT: u16 = 5309;
31
32/// Builds the base URL for a host entered by a user.
33///
34/// Accepts a bare host (`box.local`), a host and port, or a full URL. A bare host
35/// gets `http://` and [`DEFAULT_PORT`] — the control plane serves plain HTTP and
36/// is expected to be reached over the overlay or the LAN, so defaulting to https
37/// would fail for the common case.
38pub fn base_url_for(input: &str) -> Result<String> {
39    let raw = input.trim().trim_end_matches('/');
40    if raw.is_empty() {
41        return Err(Error::BaseUrl("no address given".into()));
42    }
43
44    let candidate = if raw.contains("://") {
45        raw.to_owned()
46    } else {
47        format!("http://{raw}")
48    };
49
50    let mut url =
51        url::Url::parse(&candidate).map_err(|e| Error::BaseUrl(format!("{raw}: {e}")))?;
52
53    if url.host_str().is_none_or(str::is_empty) {
54        return Err(Error::BaseUrl(format!("{raw}: no host")));
55    }
56    // An explicit port survives; a bare host gets the control plane's own.
57    if !raw.contains("://") && !raw.rsplit('/').next().unwrap_or("").contains(':') {
58        let _ = url.set_port(Some(DEFAULT_PORT));
59    }
60    Ok(url.as_str().trim_end_matches('/').to_owned())
61}
62
63/// How long to wait for a box to accept a connection at all.
64///
65/// A box that is switched off refuses immediately and this never comes into it.
66/// A box that is not there — an address with nothing at it, a laptop that moved
67/// networks, a tunnel that is down — does not refuse, it says nothing, and the
68/// kernel will keep trying for north of two minutes before giving up. That is
69/// the wait this bounds. Five seconds is longer than any reachable box on a
70/// local network takes and short enough that a wrong address feels like an
71/// answer rather than a hang.
72const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
73
74/// How long any one control-plane call may take, connection included.
75///
76/// Deliberately not `reqwest`'s own `.timeout()`, which would apply to every
77/// request the client makes — including an archive upload that is legitimately
78/// a gigabyte and legitimately takes an hour. This one is applied in [`send`],
79/// which the JSON calls go through and the transfers do not.
80const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
81
82/// A handle on one Town OS box.
83///
84/// Cloning is cheap and shares the token, so a clone handed to a background task
85/// keeps working after the UI thread re-authenticates.
86#[derive(Clone)]
87pub struct Client {
88    base_url: Arc<str>,
89    token: Arc<RwLock<Option<String>>>,
90    http: reqwest::Client,
91}
92
93impl Client {
94    /// Builds a client for `base` (anything [`base_url_for`] accepts).
95    pub fn new(base: &str) -> Result<Self> {
96        let base_url = base_url_for(base)?;
97        let http = reqwest::Client::builder()
98            .connect_timeout(CONNECT_TIMEOUT)
99            .user_agent(concat!("town-os-desktop/", env!("CARGO_PKG_VERSION")))
100            .build()?;
101        Ok(Self {
102            base_url: base_url.into(),
103            token: Arc::new(RwLock::new(None)),
104            http,
105        })
106    }
107
108    pub fn base_url(&self) -> &str {
109        &self.base_url
110    }
111
112    pub fn set_token(&self, token: impl Into<String>) {
113        let token = token.into();
114        *self.token.write().expect("token lock") = (!token.is_empty()).then_some(token);
115    }
116
117    pub fn clear_token(&self) {
118        *self.token.write().expect("token lock") = None;
119    }
120
121    pub fn token(&self) -> Option<String> {
122        self.token.read().expect("token lock").clone()
123    }
124
125    pub fn has_token(&self) -> bool {
126        self.token.read().expect("token lock").is_some()
127    }
128
129    fn request(&self, method: reqwest::Method, path: &str) -> reqwest::RequestBuilder {
130        let req = self.http.request(method, format!("{}{path}", self.base_url));
131        match self.token() {
132            Some(t) => req.bearer_auth(t),
133            None => req,
134        }
135    }
136
137    /// Sends a control-plane request under a deadline.
138    ///
139    /// Every network call is treated as one that may never come back, because
140    /// that is what a network call is: the far side can be absent, wedged, or
141    /// on the other end of a tunnel that just went down, and none of those
142    /// produce an error — they produce silence. `connect_timeout` bounds
143    /// getting the connection; this bounds everything after it, so a box that
144    /// accepts a connection and then says nothing cannot hold a task open
145    /// indefinitely.
146    ///
147    /// `tokio::time::timeout` rather than reqwest's own: it composes with any
148    /// future, so the rule is the same shape everywhere it is applied, and the
149    /// bound is visible here rather than configured somewhere far away and
150    /// silently inherited by requests it was never meant for. Archive transfers
151    /// go through their own path and are deliberately not bounded this way.
152    async fn send(
153        &self,
154        verb: &'static str,
155        path: &str,
156        req: reqwest::RequestBuilder,
157    ) -> Result<reqwest::Response> {
158        let resp = tokio::time::timeout(REQUEST_TIMEOUT, req.send())
159            .await
160            .map_err(|_| Error::Timeout {
161                verb,
162                path: path.to_owned(),
163                after: REQUEST_TIMEOUT,
164            })??;
165
166        let status = resp.status();
167        if status != reqwest::StatusCode::OK {
168            let body = resp.text().await.unwrap_or_default();
169            return Err(Error::status(verb, path, status.as_u16(), body));
170        }
171        Ok(resp)
172    }
173
174    async fn decode<T: DeserializeOwned>(path: &str, resp: reqwest::Response) -> Result<T> {
175        let body = resp.text().await?;
176        serde_json::from_str(&body).map_err(|source| Error::Decode {
177            path: path.to_owned(),
178            source,
179        })
180    }
181
182    /// GET `path`, decoding the JSON body.
183    pub async fn get_json<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
184        let req = self.request(reqwest::Method::GET, path);
185        let resp = self.send("GET", path, req).await?;
186        Self::decode(path, resp).await
187    }
188
189    /// POST `body` to `path`, decoding the JSON answer.
190    pub async fn post_json<B: Serialize, T: DeserializeOwned>(
191        &self,
192        path: &str,
193        body: &B,
194    ) -> Result<T> {
195        let req = self.request(reqwest::Method::POST, path).json(body);
196        let resp = self.send("POST", path, req).await?;
197        Self::decode(path, resp).await
198    }
199
200    /// POST `body` to `path`, discarding the answer.
201    ///
202    /// Several endpoints answer `{"status":"ok"}` and several answer nothing at
203    /// all; neither is worth a type.
204    pub async fn post_empty<B: Serialize>(&self, path: &str, body: &B) -> Result<()> {
205        let req = self.request(reqwest::Method::POST, path).json(body);
206        self.send("POST", path, req).await?;
207        Ok(())
208    }
209
210    // --- Session ---
211
212    /// Exchanges credentials for a session token, and stores it on this client.
213    ///
214    /// Calls `POST /account/authenticate`.
215    pub async fn authenticate(&self, username: &str, password: &str) -> Result<Authenticated> {
216        let body = serde_json::json!({ "username": username, "password": password });
217        let out: Authenticated = self.post_json("/account/authenticate", &body).await?;
218        self.set_token(out.token.clone());
219        Ok(out)
220    }
221
222    /// Returns the username the current token belongs to.
223    ///
224    /// Doubles as the token liveness check on startup: a stored token that has
225    /// expired fails here, which is how the app knows to ask for a password
226    /// again rather than showing an empty dashboard.
227    ///
228    /// Calls `GET /account/me`.
229    pub async fn whoami(&self) -> Result<String> {
230        if !self.has_token() {
231            return Err(Error::Unauthenticated);
232        }
233        #[derive(serde::Deserialize)]
234        struct Me {
235            username: String,
236        }
237        let me: Me = self.get_json("/account/me").await?;
238        Ok(me.username)
239    }
240
241    /// Lists the account's active sessions. Calls `GET /account/sessions`.
242    pub async fn sessions(&self) -> Result<Vec<Session>> {
243        self.get_json("/account/sessions").await
244    }
245
246    /// Invalidates a session by id. Calls `POST /account/session/revoke`.
247    ///
248    /// The id is required. The box has no "revoke whichever session you are
249    /// calling from" spelling — an empty id is a 403 for an ordinary account and
250    /// a no-op for an administrator — so signing out uses
251    /// [`Client::current_session_id`] to name the session it is ending.
252    pub async fn revoke_session(&self, session_id: &str) -> Result<()> {
253        if session_id.is_empty() {
254            return Err(Error::BaseUrl("no session id to revoke".into()));
255        }
256        self.post_empty("/account/session/revoke", &serde_json::json!({ "session_id": session_id }))
257            .await
258    }
259
260    /// The id of the session this client holds a token for.
261    ///
262    /// Read out of the token rather than fetched: the box issues a JWT carrying
263    /// `session_id`, and `GET /account/sessions` returns every session for the
264    /// account with nothing marking which one is calling — so the token is the
265    /// only place the answer exists.
266    ///
267    /// The signature is deliberately not checked. This reads a claim out of a
268    /// credential the box gave us to decide which id to name in a request the box
269    /// will authorize on its own terms; nothing is trusted on the strength of it.
270    pub fn current_session_id(&self) -> Option<String> {
271        session_id_from_token(&self.token()?)
272    }
273
274    /// Returns the signed-in account, including its grants.
275    ///
276    /// The UI reads `admin` and the grant list to decide which controls to
277    /// disable, so a non-admin sees why an action is unavailable instead of
278    /// discovering it through a 403.
279    ///
280    /// Calls `POST /account`.
281    pub async fn account(&self, username: &str) -> Result<Account> {
282        self.post_json("/account", &serde_json::json!({ "username": username }))
283            .await
284    }
285
286    /// Changes an account's password.
287    ///
288    /// Permitted on your own account without being an administrator, which is the
289    /// only reason this is worth having in a desktop client. The box requires at
290    /// least [`MIN_PASSWORD_LENGTH`] characters.
291    ///
292    /// Calls `POST /account/update`.
293    pub async fn set_password(&self, username: &str, password: &str) -> Result<Account> {
294        self.post_json(
295            "/account/update",
296            &serde_json::json!({
297                "username": username,
298                "fields": { "password": password },
299            }),
300        )
301        .await
302    }
303}
304
305/// The shortest password the box will accept.
306pub const MIN_PASSWORD_LENGTH: usize = 8;
307
308/// Pulls the `session_id` claim out of a JWT payload.
309///
310/// A JWT is three base64url segments separated by dots; the middle one is the
311/// JSON claims. Decoded by hand because the crate needs no other JWT handling
312/// and this is not verification — see [`Client::current_session_id`].
313fn session_id_from_token(token: &str) -> Option<String> {
314    let payload = token.split('.').nth(1)?;
315    let json = base64url_decode(payload)?;
316    let claims: serde_json::Value = serde_json::from_slice(&json).ok()?;
317    claims
318        .get("session_id")?
319        .as_str()
320        .map(str::to_owned)
321        .filter(|id| !id.is_empty())
322}
323
324/// Decodes unpadded base64url, which is what a JWT segment is.
325fn base64url_decode(input: &str) -> Option<Vec<u8>> {
326    let mut out = Vec::with_capacity(input.len() * 3 / 4);
327    let mut accumulator: u32 = 0;
328    let mut bits = 0u32;
329
330    for byte in input.bytes() {
331        let value = match byte {
332            b'A'..=b'Z' => byte - b'A',
333            b'a'..=b'z' => byte - b'a' + 26,
334            b'0'..=b'9' => byte - b'0' + 52,
335            b'-' => 62,
336            b'_' => 63,
337            // A JWT segment is unpadded, but a padded one is still readable and
338            // padding carries no data.
339            b'=' => break,
340            _ => return None,
341        };
342        accumulator = (accumulator << 6) | value as u32;
343        bits += 6;
344        if bits >= 8 {
345            bits -= 8;
346            out.push((accumulator >> bits) as u8);
347        }
348    }
349    Some(out)
350}
351
352#[cfg(test)]
353mod tests {
354    use super::*;
355
356    /// An address that goes nowhere and says nothing.
357    ///
358    /// TEST-NET-1 is reserved and unrouted, so a connection to it is neither
359    /// refused nor accepted — it hangs until something gives up. That is the
360    /// exact failure this module's deadlines exist for, and the only way to
361    /// reproduce it without unplugging something.
362    const BLACK_HOLE: &str = "http://192.0.2.1:5309";
363
364    /// A client pointed at nothing, with a token so the request actually goes
365    /// out.
366    ///
367    /// The token matters: `whoami` refuses without one before it touches the
368    /// network, so a client that has not been given a token tests the guard
369    /// clause and never reaches the wire at all.
370    fn black_hole_client() -> Client {
371        let client = Client::new(BLACK_HOLE).unwrap();
372        client.set_token("a-token-nobody-will-ever-see");
373        client
374    }
375
376    #[tokio::test]
377    async fn a_box_that_never_answers_gives_up_rather_than_hanging() {
378        // Without a bound this takes as long as the kernel's TCP retry
379        // schedule, which is over two minutes. The test would not fail, it
380        // would just never finish — which is what the app did.
381        let client = black_hole_client();
382
383        let started = std::time::Instant::now();
384        let result = client.whoami().await;
385        let elapsed = started.elapsed();
386
387        assert!(result.is_err(), "an unroutable address answered");
388        assert!(
389            elapsed < CONNECT_TIMEOUT + Duration::from_secs(3),
390            "gave up after {elapsed:?}, which is not the deadline it was given"
391        );
392    }
393
394    #[tokio::test]
395    async fn not_answering_is_reported_as_unreachable_not_as_a_refusal() {
396        // The distinction the UI acts on: unreachable means keep the stored
397        // token, anything else means the box had an opinion about it.
398        let error = black_hole_client().whoami().await.unwrap_err();
399
400        assert!(error.is_unreachable(), "{error}");
401        assert!(
402            !error.is_unauthenticated(),
403            "a box that never answered has not rejected the token: {error}"
404        );
405    }
406
407    #[test]
408    fn transfers_are_not_bound_by_the_control_plane_deadline() {
409        // An archive can be a gigabyte. If this ever becomes a client-wide
410        // reqwest timeout again, a large upload dies partway through with no
411        // explanation, and this is the note that says why it was not.
412        assert!(
413            REQUEST_TIMEOUT < Duration::from_secs(120),
414            "the control-plane deadline is meant to be short"
415        );
416        assert!(
417            CONNECT_TIMEOUT < REQUEST_TIMEOUT,
418            "connecting is a smaller problem than the whole call"
419        );
420    }
421
422    #[test]
423    fn bare_host_gets_the_control_plane_port() {
424        assert_eq!(base_url_for("box.local").unwrap(), "http://box.local:5309");
425        assert_eq!(base_url_for("  box.local/ ").unwrap(), "http://box.local:5309");
426    }
427
428    #[test]
429    fn explicit_port_and_scheme_survive() {
430        assert_eq!(base_url_for("box.local:8080").unwrap(), "http://box.local:8080");
431        assert_eq!(base_url_for("https://box.local").unwrap(), "https://box.local");
432        assert_eq!(
433            base_url_for("https://box.local:9000/").unwrap(),
434            "https://box.local:9000"
435        );
436    }
437
438    #[test]
439    fn ipv4_and_ipv6_hosts() {
440        assert_eq!(base_url_for("10.9.0.1").unwrap(), "http://10.9.0.1:5309");
441        assert_eq!(base_url_for("http://[::1]:5309").unwrap(), "http://[::1]:5309");
442    }
443
444    #[test]
445    fn empty_input_is_refused() {
446        assert!(base_url_for("   ").is_err());
447    }
448
449    #[test]
450    fn problem_json_detail_wins_over_raw_body() {
451        let body = r#"{"type":"about:blank","status":403,"title":"Forbidden","detail":"administrator required"}"#;
452        let err = Error::status("POST", "/dns/tld", 403, body.into());
453        assert_eq!(err.detail(), "administrator required");
454        assert!(err.is_forbidden());
455        assert!(!err.is_unauthenticated());
456    }
457
458    #[test]
459    fn legacy_echo_message_is_read_too() {
460        let err = Error::status("GET", "/dns/status", 401, r#"{"message":"bad token"}"#.into());
461        assert_eq!(err.detail(), "bad token");
462        assert!(err.is_unauthenticated());
463    }
464
465    /// A token shaped exactly like the box's: HS256 header, the three claims it
466    /// sets, and a signature that is never checked here.
467    fn token_with(payload: &str) -> String {
468        fn encode(bytes: &[u8]) -> String {
469            const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
470            let mut out = String::new();
471            for chunk in bytes.chunks(3) {
472                let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
473                let n = (b[0] as u32) << 16 | (b[1] as u32) << 8 | b[2] as u32;
474                let take = chunk.len() + 1;
475                for i in 0..take {
476                    out.push(ALPHABET[(n >> (18 - 6 * i)) as usize & 63] as char);
477                }
478            }
479            out
480        }
481        format!(
482            "{}.{}.not-a-real-signature",
483            encode(br#"{"alg":"HS256","typ":"JWT"}"#),
484            encode(payload.as_bytes())
485        )
486    }
487
488    #[test]
489    fn the_session_id_comes_out_of_the_token() {
490        let token = token_with(
491            r#"{"session_id":"9f1c3d6e-0b22-4c5a-8f77-2a1b4c5d6e7f","username":"erikh","issued_at":1700000000}"#,
492        );
493        assert_eq!(
494            session_id_from_token(&token).as_deref(),
495            Some("9f1c3d6e-0b22-4c5a-8f77-2a1b4c5d6e7f")
496        );
497    }
498
499    #[test]
500    fn a_token_without_a_session_id_yields_nothing_rather_than_an_empty_id() {
501        assert_eq!(session_id_from_token(&token_with(r#"{"username":"erikh"}"#)), None);
502        assert_eq!(session_id_from_token(&token_with(r#"{"session_id":""}"#)), None);
503        assert_eq!(session_id_from_token("not-a-jwt"), None);
504        assert_eq!(session_id_from_token(""), None);
505        assert_eq!(session_id_from_token("a.!!!!.c"), None);
506    }
507
508    #[tokio::test]
509    async fn revoking_with_no_id_is_refused_locally_rather_than_sent() {
510        // The box answers 403 for an ordinary account and silently does nothing
511        // for an administrator, so an empty id must not reach it — the failure
512        // would be indistinguishable from a session that was really revoked.
513        let client = Client::new("box.invalid").unwrap();
514        assert!(client.revoke_session("").await.is_err());
515    }
516
517    #[test]
518    fn the_current_session_is_unknown_without_a_token() {
519        let client = Client::new("box.local").unwrap();
520        assert_eq!(client.current_session_id(), None);
521    }
522
523    #[test]
524    fn non_json_body_falls_back_to_text_then_status() {
525        assert_eq!(
526            Error::status("GET", "/x", 502, "upstream is down\n".into()).detail(),
527            "upstream is down"
528        );
529        assert_eq!(Error::status("GET", "/x", 500, String::new()).detail(), "status 500");
530    }
531}