1use 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
29pub const DEFAULT_PORT: u16 = 5309;
31
32pub 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 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
63const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
73
74const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
81
82#[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 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 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 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 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 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 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 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 pub async fn sessions(&self) -> Result<Vec<Session>> {
243 self.get_json("/account/sessions").await
244 }
245
246 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 pub fn current_session_id(&self) -> Option<String> {
271 session_id_from_token(&self.token()?)
272 }
273
274 pub async fn account(&self, username: &str) -> Result<Account> {
282 self.post_json("/account", &serde_json::json!({ "username": username }))
283 .await
284 }
285
286 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
305pub const MIN_PASSWORD_LENGTH: usize = 8;
307
308fn 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
324fn 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 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 const BLACK_HOLE: &str = "http://192.0.2.1:5309";
363
364 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 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 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 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 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 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}