townos-api 0.0.2

Client for the Town OS control plane (systemcontroller) HTTP API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
//! A client for the Town OS control plane, the HTTP API served by
//! `systemcontroller` on port 5309.
//!
//! Every endpoint answers 200 on success — including the ones with no body — so
//! anything else is a refusal and becomes an [`Error::Status`]. Authentication is
//! a bearer token obtained from [`Client::authenticate`]; it is a 7-day JWT that
//! slides forward on use.
//!
//! The module split follows the control plane's own route groups: [`dns`],
//! [`storage`] (object storage plus the btrfs volumes underneath it), and
//! [`networks`] (the WireGuard overlays a client enrolls into).

use std::sync::{Arc, RwLock};
use std::time::Duration;

use serde::Serialize;
use serde::de::DeserializeOwned;

pub mod dns;
mod error;
pub mod networks;
pub mod status;
pub mod storage;
mod types;

pub use error::{Error, Problem, Result};
pub use types::*;

/// The port `systemcontroller` listens on unless `TOWN_OS_LISTEN` says otherwise.
pub const DEFAULT_PORT: u16 = 5309;

/// Builds the base URL for a host entered by a user.
///
/// Accepts a bare host (`box.local`), a host and port, or a full URL. A bare host
/// gets `http://` and [`DEFAULT_PORT`] — the control plane serves plain HTTP and
/// is expected to be reached over the overlay or the LAN, so defaulting to https
/// would fail for the common case.
pub fn base_url_for(input: &str) -> Result<String> {
    let raw = input.trim().trim_end_matches('/');
    if raw.is_empty() {
        return Err(Error::BaseUrl("no address given".into()));
    }

    let candidate = if raw.contains("://") {
        raw.to_owned()
    } else {
        format!("http://{raw}")
    };

    let mut url =
        url::Url::parse(&candidate).map_err(|e| Error::BaseUrl(format!("{raw}: {e}")))?;

    if url.host_str().is_none_or(str::is_empty) {
        return Err(Error::BaseUrl(format!("{raw}: no host")));
    }
    // An explicit port survives; a bare host gets the control plane's own.
    if !raw.contains("://") && !raw.rsplit('/').next().unwrap_or("").contains(':') {
        let _ = url.set_port(Some(DEFAULT_PORT));
    }
    Ok(url.as_str().trim_end_matches('/').to_owned())
}

/// How long to wait for a box to accept a connection at all.
///
/// A box that is switched off refuses immediately and this never comes into it.
/// A box that is not there — an address with nothing at it, a laptop that moved
/// networks, a tunnel that is down — does not refuse, it says nothing, and the
/// kernel will keep trying for north of two minutes before giving up. That is
/// the wait this bounds. Five seconds is longer than any reachable box on a
/// local network takes and short enough that a wrong address feels like an
/// answer rather than a hang.
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);

/// How long any one control-plane call may take, connection included.
///
/// Deliberately not `reqwest`'s own `.timeout()`, which would apply to every
/// request the client makes — including an archive upload that is legitimately
/// a gigabyte and legitimately takes an hour. This one is applied in [`send`],
/// which the JSON calls go through and the transfers do not.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);

/// A handle on one Town OS box.
///
/// Cloning is cheap and shares the token, so a clone handed to a background task
/// keeps working after the UI thread re-authenticates.
#[derive(Clone)]
pub struct Client {
    base_url: Arc<str>,
    token: Arc<RwLock<Option<String>>>,
    http: reqwest::Client,
}

impl Client {
    /// Builds a client for `base` (anything [`base_url_for`] accepts).
    pub fn new(base: &str) -> Result<Self> {
        let base_url = base_url_for(base)?;
        let http = reqwest::Client::builder()
            .connect_timeout(CONNECT_TIMEOUT)
            .user_agent(concat!("town-os-desktop/", env!("CARGO_PKG_VERSION")))
            .build()?;
        Ok(Self {
            base_url: base_url.into(),
            token: Arc::new(RwLock::new(None)),
            http,
        })
    }

    pub fn base_url(&self) -> &str {
        &self.base_url
    }

    pub fn set_token(&self, token: impl Into<String>) {
        let token = token.into();
        *self.token.write().expect("token lock") = (!token.is_empty()).then_some(token);
    }

    pub fn clear_token(&self) {
        *self.token.write().expect("token lock") = None;
    }

    pub fn token(&self) -> Option<String> {
        self.token.read().expect("token lock").clone()
    }

    pub fn has_token(&self) -> bool {
        self.token.read().expect("token lock").is_some()
    }

    fn request(&self, method: reqwest::Method, path: &str) -> reqwest::RequestBuilder {
        let req = self.http.request(method, format!("{}{path}", self.base_url));
        match self.token() {
            Some(t) => req.bearer_auth(t),
            None => req,
        }
    }

    /// Sends a control-plane request under a deadline.
    ///
    /// Every network call is treated as one that may never come back, because
    /// that is what a network call is: the far side can be absent, wedged, or
    /// on the other end of a tunnel that just went down, and none of those
    /// produce an error — they produce silence. `connect_timeout` bounds
    /// getting the connection; this bounds everything after it, so a box that
    /// accepts a connection and then says nothing cannot hold a task open
    /// indefinitely.
    ///
    /// `tokio::time::timeout` rather than reqwest's own: it composes with any
    /// future, so the rule is the same shape everywhere it is applied, and the
    /// bound is visible here rather than configured somewhere far away and
    /// silently inherited by requests it was never meant for. Archive transfers
    /// go through their own path and are deliberately not bounded this way.
    async fn send(
        &self,
        verb: &'static str,
        path: &str,
        req: reqwest::RequestBuilder,
    ) -> Result<reqwest::Response> {
        let resp = tokio::time::timeout(REQUEST_TIMEOUT, req.send())
            .await
            .map_err(|_| Error::Timeout {
                verb,
                path: path.to_owned(),
                after: REQUEST_TIMEOUT,
            })??;

        let status = resp.status();
        if status != reqwest::StatusCode::OK {
            let body = resp.text().await.unwrap_or_default();
            return Err(Error::status(verb, path, status.as_u16(), body));
        }
        Ok(resp)
    }

    async fn decode<T: DeserializeOwned>(path: &str, resp: reqwest::Response) -> Result<T> {
        let body = resp.text().await?;
        serde_json::from_str(&body).map_err(|source| Error::Decode {
            path: path.to_owned(),
            source,
        })
    }

    /// GET `path`, decoding the JSON body.
    pub async fn get_json<T: DeserializeOwned>(&self, path: &str) -> Result<T> {
        let req = self.request(reqwest::Method::GET, path);
        let resp = self.send("GET", path, req).await?;
        Self::decode(path, resp).await
    }

    /// POST `body` to `path`, decoding the JSON answer.
    pub async fn post_json<B: Serialize, T: DeserializeOwned>(
        &self,
        path: &str,
        body: &B,
    ) -> Result<T> {
        let req = self.request(reqwest::Method::POST, path).json(body);
        let resp = self.send("POST", path, req).await?;
        Self::decode(path, resp).await
    }

    /// POST `body` to `path`, discarding the answer.
    ///
    /// Several endpoints answer `{"status":"ok"}` and several answer nothing at
    /// all; neither is worth a type.
    pub async fn post_empty<B: Serialize>(&self, path: &str, body: &B) -> Result<()> {
        let req = self.request(reqwest::Method::POST, path).json(body);
        self.send("POST", path, req).await?;
        Ok(())
    }

    // --- Session ---

    /// Exchanges credentials for a session token, and stores it on this client.
    ///
    /// Calls `POST /account/authenticate`.
    pub async fn authenticate(&self, username: &str, password: &str) -> Result<Authenticated> {
        let body = serde_json::json!({ "username": username, "password": password });
        let out: Authenticated = self.post_json("/account/authenticate", &body).await?;
        self.set_token(out.token.clone());
        Ok(out)
    }

    /// Returns the username the current token belongs to.
    ///
    /// Doubles as the token liveness check on startup: a stored token that has
    /// expired fails here, which is how the app knows to ask for a password
    /// again rather than showing an empty dashboard.
    ///
    /// Calls `GET /account/me`.
    pub async fn whoami(&self) -> Result<String> {
        if !self.has_token() {
            return Err(Error::Unauthenticated);
        }
        #[derive(serde::Deserialize)]
        struct Me {
            username: String,
        }
        let me: Me = self.get_json("/account/me").await?;
        Ok(me.username)
    }

    /// Lists the account's active sessions. Calls `GET /account/sessions`.
    pub async fn sessions(&self) -> Result<Vec<Session>> {
        self.get_json("/account/sessions").await
    }

    /// Invalidates a session by id. Calls `POST /account/session/revoke`.
    ///
    /// The id is required. The box has no "revoke whichever session you are
    /// calling from" spelling — an empty id is a 403 for an ordinary account and
    /// a no-op for an administrator — so signing out uses
    /// [`Client::current_session_id`] to name the session it is ending.
    pub async fn revoke_session(&self, session_id: &str) -> Result<()> {
        if session_id.is_empty() {
            return Err(Error::BaseUrl("no session id to revoke".into()));
        }
        self.post_empty("/account/session/revoke", &serde_json::json!({ "session_id": session_id }))
            .await
    }

    /// The id of the session this client holds a token for.
    ///
    /// Read out of the token rather than fetched: the box issues a JWT carrying
    /// `session_id`, and `GET /account/sessions` returns every session for the
    /// account with nothing marking which one is calling — so the token is the
    /// only place the answer exists.
    ///
    /// The signature is deliberately not checked. This reads a claim out of a
    /// credential the box gave us to decide which id to name in a request the box
    /// will authorize on its own terms; nothing is trusted on the strength of it.
    pub fn current_session_id(&self) -> Option<String> {
        session_id_from_token(&self.token()?)
    }

    /// Returns the signed-in account, including its grants.
    ///
    /// The UI reads `admin` and the grant list to decide which controls to
    /// disable, so a non-admin sees why an action is unavailable instead of
    /// discovering it through a 403.
    ///
    /// Calls `POST /account`.
    pub async fn account(&self, username: &str) -> Result<Account> {
        self.post_json("/account", &serde_json::json!({ "username": username }))
            .await
    }

    /// Changes an account's password.
    ///
    /// Permitted on your own account without being an administrator, which is the
    /// only reason this is worth having in a desktop client. The box requires at
    /// least [`MIN_PASSWORD_LENGTH`] characters.
    ///
    /// Calls `POST /account/update`.
    pub async fn set_password(&self, username: &str, password: &str) -> Result<Account> {
        self.post_json(
            "/account/update",
            &serde_json::json!({
                "username": username,
                "fields": { "password": password },
            }),
        )
        .await
    }
}

/// The shortest password the box will accept.
pub const MIN_PASSWORD_LENGTH: usize = 8;

/// Pulls the `session_id` claim out of a JWT payload.
///
/// A JWT is three base64url segments separated by dots; the middle one is the
/// JSON claims. Decoded by hand because the crate needs no other JWT handling
/// and this is not verification — see [`Client::current_session_id`].
fn session_id_from_token(token: &str) -> Option<String> {
    let payload = token.split('.').nth(1)?;
    let json = base64url_decode(payload)?;
    let claims: serde_json::Value = serde_json::from_slice(&json).ok()?;
    claims
        .get("session_id")?
        .as_str()
        .map(str::to_owned)
        .filter(|id| !id.is_empty())
}

/// Decodes unpadded base64url, which is what a JWT segment is.
fn base64url_decode(input: &str) -> Option<Vec<u8>> {
    let mut out = Vec::with_capacity(input.len() * 3 / 4);
    let mut accumulator: u32 = 0;
    let mut bits = 0u32;

    for byte in input.bytes() {
        let value = match byte {
            b'A'..=b'Z' => byte - b'A',
            b'a'..=b'z' => byte - b'a' + 26,
            b'0'..=b'9' => byte - b'0' + 52,
            b'-' => 62,
            b'_' => 63,
            // A JWT segment is unpadded, but a padded one is still readable and
            // padding carries no data.
            b'=' => break,
            _ => return None,
        };
        accumulator = (accumulator << 6) | value as u32;
        bits += 6;
        if bits >= 8 {
            bits -= 8;
            out.push((accumulator >> bits) as u8);
        }
    }
    Some(out)
}

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

    /// An address that goes nowhere and says nothing.
    ///
    /// TEST-NET-1 is reserved and unrouted, so a connection to it is neither
    /// refused nor accepted — it hangs until something gives up. That is the
    /// exact failure this module's deadlines exist for, and the only way to
    /// reproduce it without unplugging something.
    const BLACK_HOLE: &str = "http://192.0.2.1:5309";

    /// A client pointed at nothing, with a token so the request actually goes
    /// out.
    ///
    /// The token matters: `whoami` refuses without one before it touches the
    /// network, so a client that has not been given a token tests the guard
    /// clause and never reaches the wire at all.
    fn black_hole_client() -> Client {
        let client = Client::new(BLACK_HOLE).unwrap();
        client.set_token("a-token-nobody-will-ever-see");
        client
    }

    #[tokio::test]
    async fn a_box_that_never_answers_gives_up_rather_than_hanging() {
        // Without a bound this takes as long as the kernel's TCP retry
        // schedule, which is over two minutes. The test would not fail, it
        // would just never finish — which is what the app did.
        let client = black_hole_client();

        let started = std::time::Instant::now();
        let result = client.whoami().await;
        let elapsed = started.elapsed();

        assert!(result.is_err(), "an unroutable address answered");
        assert!(
            elapsed < CONNECT_TIMEOUT + Duration::from_secs(3),
            "gave up after {elapsed:?}, which is not the deadline it was given"
        );
    }

    #[tokio::test]
    async fn not_answering_is_reported_as_unreachable_not_as_a_refusal() {
        // The distinction the UI acts on: unreachable means keep the stored
        // token, anything else means the box had an opinion about it.
        let error = black_hole_client().whoami().await.unwrap_err();

        assert!(error.is_unreachable(), "{error}");
        assert!(
            !error.is_unauthenticated(),
            "a box that never answered has not rejected the token: {error}"
        );
    }

    #[test]
    fn transfers_are_not_bound_by_the_control_plane_deadline() {
        // An archive can be a gigabyte. If this ever becomes a client-wide
        // reqwest timeout again, a large upload dies partway through with no
        // explanation, and this is the note that says why it was not.
        assert!(
            REQUEST_TIMEOUT < Duration::from_secs(120),
            "the control-plane deadline is meant to be short"
        );
        assert!(
            CONNECT_TIMEOUT < REQUEST_TIMEOUT,
            "connecting is a smaller problem than the whole call"
        );
    }

    #[test]
    fn bare_host_gets_the_control_plane_port() {
        assert_eq!(base_url_for("box.local").unwrap(), "http://box.local:5309");
        assert_eq!(base_url_for("  box.local/ ").unwrap(), "http://box.local:5309");
    }

    #[test]
    fn explicit_port_and_scheme_survive() {
        assert_eq!(base_url_for("box.local:8080").unwrap(), "http://box.local:8080");
        assert_eq!(base_url_for("https://box.local").unwrap(), "https://box.local");
        assert_eq!(
            base_url_for("https://box.local:9000/").unwrap(),
            "https://box.local:9000"
        );
    }

    #[test]
    fn ipv4_and_ipv6_hosts() {
        assert_eq!(base_url_for("10.9.0.1").unwrap(), "http://10.9.0.1:5309");
        assert_eq!(base_url_for("http://[::1]:5309").unwrap(), "http://[::1]:5309");
    }

    #[test]
    fn empty_input_is_refused() {
        assert!(base_url_for("   ").is_err());
    }

    #[test]
    fn problem_json_detail_wins_over_raw_body() {
        let body = r#"{"type":"about:blank","status":403,"title":"Forbidden","detail":"administrator required"}"#;
        let err = Error::status("POST", "/dns/tld", 403, body.into());
        assert_eq!(err.detail(), "administrator required");
        assert!(err.is_forbidden());
        assert!(!err.is_unauthenticated());
    }

    #[test]
    fn legacy_echo_message_is_read_too() {
        let err = Error::status("GET", "/dns/status", 401, r#"{"message":"bad token"}"#.into());
        assert_eq!(err.detail(), "bad token");
        assert!(err.is_unauthenticated());
    }

    /// A token shaped exactly like the box's: HS256 header, the three claims it
    /// sets, and a signature that is never checked here.
    fn token_with(payload: &str) -> String {
        fn encode(bytes: &[u8]) -> String {
            const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
            let mut out = String::new();
            for chunk in bytes.chunks(3) {
                let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
                let n = (b[0] as u32) << 16 | (b[1] as u32) << 8 | b[2] as u32;
                let take = chunk.len() + 1;
                for i in 0..take {
                    out.push(ALPHABET[(n >> (18 - 6 * i)) as usize & 63] as char);
                }
            }
            out
        }
        format!(
            "{}.{}.not-a-real-signature",
            encode(br#"{"alg":"HS256","typ":"JWT"}"#),
            encode(payload.as_bytes())
        )
    }

    #[test]
    fn the_session_id_comes_out_of_the_token() {
        let token = token_with(
            r#"{"session_id":"9f1c3d6e-0b22-4c5a-8f77-2a1b4c5d6e7f","username":"erikh","issued_at":1700000000}"#,
        );
        assert_eq!(
            session_id_from_token(&token).as_deref(),
            Some("9f1c3d6e-0b22-4c5a-8f77-2a1b4c5d6e7f")
        );
    }

    #[test]
    fn a_token_without_a_session_id_yields_nothing_rather_than_an_empty_id() {
        assert_eq!(session_id_from_token(&token_with(r#"{"username":"erikh"}"#)), None);
        assert_eq!(session_id_from_token(&token_with(r#"{"session_id":""}"#)), None);
        assert_eq!(session_id_from_token("not-a-jwt"), None);
        assert_eq!(session_id_from_token(""), None);
        assert_eq!(session_id_from_token("a.!!!!.c"), None);
    }

    #[tokio::test]
    async fn revoking_with_no_id_is_refused_locally_rather_than_sent() {
        // The box answers 403 for an ordinary account and silently does nothing
        // for an administrator, so an empty id must not reach it — the failure
        // would be indistinguishable from a session that was really revoked.
        let client = Client::new("box.invalid").unwrap();
        assert!(client.revoke_session("").await.is_err());
    }

    #[test]
    fn the_current_session_is_unknown_without_a_token() {
        let client = Client::new("box.local").unwrap();
        assert_eq!(client.current_session_id(), None);
    }

    #[test]
    fn non_json_body_falls_back_to_text_then_status() {
        assert_eq!(
            Error::status("GET", "/x", 502, "upstream is down\n".into()).detail(),
            "upstream is down"
        );
        assert_eq!(Error::status("GET", "/x", 500, String::new()).detail(), "status 500");
    }
}