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    /// Changes an account's contact details.
305    ///
306    /// The same endpoint as [`Client::set_password`] and the same `fields`
307    /// object, which is why both are one call rather than three.
308    ///
309    /// Only the fields that changed are sent. That is not an optimisation: the
310    /// box merges what it is given, so sending every field on every save means
311    /// a stale value read into the form minutes ago overwrites a change made
312    /// somewhere else in between. Sending nothing sends no request at all.
313    ///
314    /// Calls `POST /account/update`.
315    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/// The contact details an account can change about itself.
345///
346/// Each is `None` for "leave this alone" rather than empty-for-unchanged,
347/// because empty is a value somebody may legitimately want to store: clearing a
348/// phone number is a change, not a no-op, and the two must not be the same
349/// request.
350#[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    /// What changed between the account as loaded and the form as edited.
359    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
372/// The shortest password the box will accept.
373pub const MIN_PASSWORD_LENGTH: usize = 8;
374
375/// Pulls the `session_id` claim out of a JWT payload.
376///
377/// A JWT is three base64url segments separated by dots; the middle one is the
378/// JSON claims. Decoded by hand because the crate needs no other JWT handling
379/// and this is not verification — see [`Client::current_session_id`].
380fn 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
391/// Decodes unpadded base64url, which is what a JWT segment is.
392fn 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            // A JWT segment is unpadded, but a padded one is still readable and
405            // padding carries no data.
406            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        // The box merges what it is given. Sending every field on every save
436        // means a value read into the form minutes ago silently overwrites a
437        // change somebody made elsewhere in between.
438        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        // The distinction the whole `Option` exists for: empty is a value
449        // somebody may want stored. Deleting a phone number has to reach the
450        // box, and must not be confused with leaving it alone.
451        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        // Pointed at an address that goes nowhere: if this sent a request it
470        // would have to wait out the connect deadline and then fail. Answering
471        // `Ok(None)` immediately is the assertion.
472        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    /// An address that goes nowhere and says nothing.
489    ///
490    /// TEST-NET-1 is reserved and unrouted, so a connection to it is neither
491    /// refused nor accepted — it hangs until something gives up. That is the
492    /// exact failure this module's deadlines exist for, and the only way to
493    /// reproduce it without unplugging something.
494    const BLACK_HOLE: &str = "http://192.0.2.1:5309";
495
496    /// A client pointed at nothing, with a token so the request actually goes
497    /// out.
498    ///
499    /// The token matters: `whoami` refuses without one before it touches the
500    /// network, so a client that has not been given a token tests the guard
501    /// clause and never reaches the wire at all.
502    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        // Without a bound this takes as long as the kernel's TCP retry
511        // schedule, which is over two minutes. The test would not fail, it
512        // would just never finish — which is what the app did.
513        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        // The distinction the UI acts on: unreachable means keep the stored
529        // token, anything else means the box had an opinion about it.
530        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        // An archive can be a gigabyte. If this ever becomes a client-wide
542        // reqwest timeout again, a large upload dies partway through with no
543        // explanation, and this is the note that says why it was not.
544        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    /// A token shaped exactly like the box's: HS256 header, the three claims it
598    /// sets, and a signature that is never checked here.
599    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        // The box answers 403 for an ordinary account and silently does nothing
643        // for an administrator, so an empty id must not reach it — the failure
644        // would be indistinguishable from a session that was really revoked.
645        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}