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 pub async fn update_details(
316 &self,
317 username: &str,
318 details: AccountDetails,
319 ) -> Result<Option<Account>> {
320 let mut fields = serde_json::Map::new();
321 if let Some(email) = details.email {
322 fields.insert("email".into(), email.into());
323 }
324 if let Some(phone) = details.phone {
325 fields.insert("phone".into(), phone.into());
326 }
327 if let Some(real_name) = details.real_name {
328 fields.insert("real_name".into(), real_name.into());
329 }
330
331 if fields.is_empty() {
332 return Ok(None);
333 }
334
335 self.post_json(
336 "/account/update",
337 &serde_json::json!({ "username": username, "fields": fields }),
338 )
339 .await
340 .map(Some)
341 }
342}
343
344#[derive(Debug, Default, Clone, PartialEq, Eq)]
351pub struct AccountDetails {
352 pub email: Option<String>,
353 pub phone: Option<String>,
354 pub real_name: Option<String>,
355}
356
357impl AccountDetails {
358 pub fn changed_from(before: &Account, email: &str, phone: &str, real_name: &str) -> Self {
360 AccountDetails {
361 email: (email != before.email).then(|| email.to_owned()),
362 phone: (phone != before.phone).then(|| phone.to_owned()),
363 real_name: (real_name != before.real_name).then(|| real_name.to_owned()),
364 }
365 }
366
367 pub fn is_empty(&self) -> bool {
368 self.email.is_none() && self.phone.is_none() && self.real_name.is_none()
369 }
370}
371
372pub const MIN_PASSWORD_LENGTH: usize = 8;
374
375fn session_id_from_token(token: &str) -> Option<String> {
381 let payload = token.split('.').nth(1)?;
382 let json = base64url_decode(payload)?;
383 let claims: serde_json::Value = serde_json::from_slice(&json).ok()?;
384 claims
385 .get("session_id")?
386 .as_str()
387 .map(str::to_owned)
388 .filter(|id| !id.is_empty())
389}
390
391fn base64url_decode(input: &str) -> Option<Vec<u8>> {
393 let mut out = Vec::with_capacity(input.len() * 3 / 4);
394 let mut accumulator: u32 = 0;
395 let mut bits = 0u32;
396
397 for byte in input.bytes() {
398 let value = match byte {
399 b'A'..=b'Z' => byte - b'A',
400 b'a'..=b'z' => byte - b'a' + 26,
401 b'0'..=b'9' => byte - b'0' + 52,
402 b'-' => 62,
403 b'_' => 63,
404 b'=' => break,
407 _ => return None,
408 };
409 accumulator = (accumulator << 6) | value as u32;
410 bits += 6;
411 if bits >= 8 {
412 bits -= 8;
413 out.push((accumulator >> bits) as u8);
414 }
415 }
416 Some(out)
417}
418
419#[cfg(test)]
420mod tests {
421 use super::*;
422
423 fn account_with(email: &str, phone: &str, real_name: &str) -> Account {
424 Account {
425 username: "erikh".into(),
426 email: email.into(),
427 phone: phone.into(),
428 real_name: real_name.into(),
429 ..Default::default()
430 }
431 }
432
433 #[test]
434 fn only_the_fields_that_changed_are_sent() {
435 let before = account_with("old@example.com", "555", "Erik");
439 let changes = AccountDetails::changed_from(&before, "new@example.com", "555", "Erik");
440
441 assert_eq!(changes.email.as_deref(), Some("new@example.com"));
442 assert_eq!(changes.phone, None, "an untouched field must not be sent");
443 assert_eq!(changes.real_name, None);
444 }
445
446 #[test]
447 fn clearing_a_field_is_a_change_and_not_a_no_op() {
448 let before = account_with("e@example.com", "555", "Erik");
452 let changes = AccountDetails::changed_from(&before, "e@example.com", "", "Erik");
453
454 assert_eq!(changes.phone.as_deref(), Some(""), "clearing must be sent");
455 assert!(!changes.is_empty());
456 }
457
458 #[test]
459 fn changing_nothing_produces_nothing_to_send() {
460 let before = account_with("e@example.com", "555", "Erik");
461 let changes = AccountDetails::changed_from(&before, "e@example.com", "555", "Erik");
462
463 assert!(changes.is_empty());
464 assert_eq!(changes, AccountDetails::default());
465 }
466
467 #[tokio::test]
468 async fn an_empty_update_makes_no_request_at_all() {
469 let client = Client::new(BLACK_HOLE).unwrap();
473 client.set_token("a-token-nobody-will-ever-see");
474
475 let started = std::time::Instant::now();
476 let answer = client
477 .update_details("erikh", AccountDetails::default())
478 .await
479 .expect("an empty update is not a failure");
480
481 assert!(answer.is_none(), "nothing changed, so there is no new account");
482 assert!(
483 started.elapsed() < Duration::from_millis(250),
484 "a request went out for an update with no fields in it"
485 );
486 }
487
488 const BLACK_HOLE: &str = "http://192.0.2.1:5309";
495
496 fn black_hole_client() -> Client {
503 let client = Client::new(BLACK_HOLE).unwrap();
504 client.set_token("a-token-nobody-will-ever-see");
505 client
506 }
507
508 #[tokio::test]
509 async fn a_box_that_never_answers_gives_up_rather_than_hanging() {
510 let client = black_hole_client();
514
515 let started = std::time::Instant::now();
516 let result = client.whoami().await;
517 let elapsed = started.elapsed();
518
519 assert!(result.is_err(), "an unroutable address answered");
520 assert!(
521 elapsed < CONNECT_TIMEOUT + Duration::from_secs(3),
522 "gave up after {elapsed:?}, which is not the deadline it was given"
523 );
524 }
525
526 #[tokio::test]
527 async fn not_answering_is_reported_as_unreachable_not_as_a_refusal() {
528 let error = black_hole_client().whoami().await.unwrap_err();
531
532 assert!(error.is_unreachable(), "{error}");
533 assert!(
534 !error.is_unauthenticated(),
535 "a box that never answered has not rejected the token: {error}"
536 );
537 }
538
539 #[test]
540 fn transfers_are_not_bound_by_the_control_plane_deadline() {
541 assert!(
545 REQUEST_TIMEOUT < Duration::from_secs(120),
546 "the control-plane deadline is meant to be short"
547 );
548 assert!(
549 CONNECT_TIMEOUT < REQUEST_TIMEOUT,
550 "connecting is a smaller problem than the whole call"
551 );
552 }
553
554 #[test]
555 fn bare_host_gets_the_control_plane_port() {
556 assert_eq!(base_url_for("box.local").unwrap(), "http://box.local:5309");
557 assert_eq!(base_url_for(" box.local/ ").unwrap(), "http://box.local:5309");
558 }
559
560 #[test]
561 fn explicit_port_and_scheme_survive() {
562 assert_eq!(base_url_for("box.local:8080").unwrap(), "http://box.local:8080");
563 assert_eq!(base_url_for("https://box.local").unwrap(), "https://box.local");
564 assert_eq!(
565 base_url_for("https://box.local:9000/").unwrap(),
566 "https://box.local:9000"
567 );
568 }
569
570 #[test]
571 fn ipv4_and_ipv6_hosts() {
572 assert_eq!(base_url_for("10.9.0.1").unwrap(), "http://10.9.0.1:5309");
573 assert_eq!(base_url_for("http://[::1]:5309").unwrap(), "http://[::1]:5309");
574 }
575
576 #[test]
577 fn empty_input_is_refused() {
578 assert!(base_url_for(" ").is_err());
579 }
580
581 #[test]
582 fn problem_json_detail_wins_over_raw_body() {
583 let body = r#"{"type":"about:blank","status":403,"title":"Forbidden","detail":"administrator required"}"#;
584 let err = Error::status("POST", "/dns/tld", 403, body.into());
585 assert_eq!(err.detail(), "administrator required");
586 assert!(err.is_forbidden());
587 assert!(!err.is_unauthenticated());
588 }
589
590 #[test]
591 fn legacy_echo_message_is_read_too() {
592 let err = Error::status("GET", "/dns/status", 401, r#"{"message":"bad token"}"#.into());
593 assert_eq!(err.detail(), "bad token");
594 assert!(err.is_unauthenticated());
595 }
596
597 fn token_with(payload: &str) -> String {
600 fn encode(bytes: &[u8]) -> String {
601 const ALPHABET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
602 let mut out = String::new();
603 for chunk in bytes.chunks(3) {
604 let b = [chunk[0], *chunk.get(1).unwrap_or(&0), *chunk.get(2).unwrap_or(&0)];
605 let n = (b[0] as u32) << 16 | (b[1] as u32) << 8 | b[2] as u32;
606 let take = chunk.len() + 1;
607 for i in 0..take {
608 out.push(ALPHABET[(n >> (18 - 6 * i)) as usize & 63] as char);
609 }
610 }
611 out
612 }
613 format!(
614 "{}.{}.not-a-real-signature",
615 encode(br#"{"alg":"HS256","typ":"JWT"}"#),
616 encode(payload.as_bytes())
617 )
618 }
619
620 #[test]
621 fn the_session_id_comes_out_of_the_token() {
622 let token = token_with(
623 r#"{"session_id":"9f1c3d6e-0b22-4c5a-8f77-2a1b4c5d6e7f","username":"erikh","issued_at":1700000000}"#,
624 );
625 assert_eq!(
626 session_id_from_token(&token).as_deref(),
627 Some("9f1c3d6e-0b22-4c5a-8f77-2a1b4c5d6e7f")
628 );
629 }
630
631 #[test]
632 fn a_token_without_a_session_id_yields_nothing_rather_than_an_empty_id() {
633 assert_eq!(session_id_from_token(&token_with(r#"{"username":"erikh"}"#)), None);
634 assert_eq!(session_id_from_token(&token_with(r#"{"session_id":""}"#)), None);
635 assert_eq!(session_id_from_token("not-a-jwt"), None);
636 assert_eq!(session_id_from_token(""), None);
637 assert_eq!(session_id_from_token("a.!!!!.c"), None);
638 }
639
640 #[tokio::test]
641 async fn revoking_with_no_id_is_refused_locally_rather_than_sent() {
642 let client = Client::new("box.invalid").unwrap();
646 assert!(client.revoke_session("").await.is_err());
647 }
648
649 #[test]
650 fn the_current_session_is_unknown_without_a_token() {
651 let client = Client::new("box.local").unwrap();
652 assert_eq!(client.current_session_id(), None);
653 }
654
655 #[test]
656 fn non_json_body_falls_back_to_text_then_status() {
657 assert_eq!(
658 Error::status("GET", "/x", 502, "upstream is down\n".into()).detail(),
659 "upstream is down"
660 );
661 assert_eq!(Error::status("GET", "/x", 500, String::new()).detail(), "status 500");
662 }
663}