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::*;
pub const DEFAULT_PORT: u16 = 5309;
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")));
}
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())
}
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
const REQUEST_TIMEOUT: Duration = Duration::from_secs(30);
#[derive(Clone)]
pub struct Client {
base_url: Arc<str>,
token: Arc<RwLock<Option<String>>>,
http: reqwest::Client,
}
impl Client {
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,
}
}
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,
})
}
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
}
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
}
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(())
}
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)
}
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)
}
pub async fn sessions(&self) -> Result<Vec<Session>> {
self.get_json("/account/sessions").await
}
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
}
pub fn current_session_id(&self) -> Option<String> {
session_id_from_token(&self.token()?)
}
pub async fn account(&self, username: &str) -> Result<Account> {
self.post_json("/account", &serde_json::json!({ "username": username }))
.await
}
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
}
pub async fn update_details(
&self,
username: &str,
details: AccountDetails,
) -> Result<Option<Account>> {
let mut fields = serde_json::Map::new();
if let Some(email) = details.email {
fields.insert("email".into(), email.into());
}
if let Some(phone) = details.phone {
fields.insert("phone".into(), phone.into());
}
if let Some(real_name) = details.real_name {
fields.insert("real_name".into(), real_name.into());
}
if fields.is_empty() {
return Ok(None);
}
self.post_json(
"/account/update",
&serde_json::json!({ "username": username, "fields": fields }),
)
.await
.map(Some)
}
}
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct AccountDetails {
pub email: Option<String>,
pub phone: Option<String>,
pub real_name: Option<String>,
}
impl AccountDetails {
pub fn changed_from(before: &Account, email: &str, phone: &str, real_name: &str) -> Self {
AccountDetails {
email: (email != before.email).then(|| email.to_owned()),
phone: (phone != before.phone).then(|| phone.to_owned()),
real_name: (real_name != before.real_name).then(|| real_name.to_owned()),
}
}
pub fn is_empty(&self) -> bool {
self.email.is_none() && self.phone.is_none() && self.real_name.is_none()
}
}
pub const MIN_PASSWORD_LENGTH: usize = 8;
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())
}
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,
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::*;
fn account_with(email: &str, phone: &str, real_name: &str) -> Account {
Account {
username: "erikh".into(),
email: email.into(),
phone: phone.into(),
real_name: real_name.into(),
..Default::default()
}
}
#[test]
fn only_the_fields_that_changed_are_sent() {
let before = account_with("old@example.com", "555", "Erik");
let changes = AccountDetails::changed_from(&before, "new@example.com", "555", "Erik");
assert_eq!(changes.email.as_deref(), Some("new@example.com"));
assert_eq!(changes.phone, None, "an untouched field must not be sent");
assert_eq!(changes.real_name, None);
}
#[test]
fn clearing_a_field_is_a_change_and_not_a_no_op() {
let before = account_with("e@example.com", "555", "Erik");
let changes = AccountDetails::changed_from(&before, "e@example.com", "", "Erik");
assert_eq!(changes.phone.as_deref(), Some(""), "clearing must be sent");
assert!(!changes.is_empty());
}
#[test]
fn changing_nothing_produces_nothing_to_send() {
let before = account_with("e@example.com", "555", "Erik");
let changes = AccountDetails::changed_from(&before, "e@example.com", "555", "Erik");
assert!(changes.is_empty());
assert_eq!(changes, AccountDetails::default());
}
#[tokio::test]
async fn an_empty_update_makes_no_request_at_all() {
let client = Client::new(BLACK_HOLE).unwrap();
client.set_token("a-token-nobody-will-ever-see");
let started = std::time::Instant::now();
let answer = client
.update_details("erikh", AccountDetails::default())
.await
.expect("an empty update is not a failure");
assert!(answer.is_none(), "nothing changed, so there is no new account");
assert!(
started.elapsed() < Duration::from_millis(250),
"a request went out for an update with no fields in it"
);
}
const BLACK_HOLE: &str = "http://192.0.2.1:5309";
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() {
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() {
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() {
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());
}
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() {
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");
}
}