Skip to main content

vector_core/
blossom_error.rs

1//! What a Blossom server said when it refused — as data, not prose.
2//!
3//! Magnitude answers every refusal three ways at once: `X-Error-Code`, a
4//! stable identifier that is a header so a BUD-06 `HEAD` preflight carries it
5//! too; `X-Retry`, one of `never` / `later` / `elsewhere` / `sign_again` / `fix_clock`; and a JSON body
6//! `{error, message, retry, status, ...}` whose extra fields hold the numbers
7//! behind the sentence (`limit`, `used`, `retry_after`, `mime`). A server that
8//! speaks that vocabulary is routed on it. One that does not falls back to the
9//! status-and-keyword heuristics in `blossom_capabilities`, which is all a
10//! plain BUD-02 server gives us to go on.
11//!
12//! The difference matters most where the heuristics are wrong in a way only
13//! the code can reveal: a quota refusal is a 413, and a 413 read as "the blob
14//! is too big" would demote the server for every file of that size for days;
15//! an expired signature is a 401, and a 401 read as "this server will never
16//! take our uploads" would bury a good server under a clock skew.
17
18use reqwest::header::HeaderMap;
19use serde_json::{json, Map, Value};
20use std::time::Duration;
21
22/// A server's advice on what to do with a refused request.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum Retry {
25    /// The request is wrong. Sending it again changes nothing.
26    Never,
27    /// This server may accept it later.
28    Later,
29    /// This server will not accept it, but another might.
30    Elsewhere,
31    /// The same request with a freshly signed authorization will do.
32    SignAgain,
33    /// This device's clock is off by `clock_offset_secs`; signing again on it changes nothing.
34    FixClock,
35}
36
37impl Retry {
38    fn parse(s: &str) -> Option<Self> {
39        match s.trim() {
40            "never" => Some(Retry::Never),
41            "later" => Some(Retry::Later),
42            "elsewhere" => Some(Retry::Elsewhere),
43            "sign_again" => Some(Retry::SignAgain),
44            "fix_clock" => Some(Retry::FixClock),
45            _ => None,
46        }
47    }
48}
49
50/// A non-2xx answer to an upload, preflight, or mirror request.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct Refusal {
53    pub status: u16,
54    /// The server's stable identifier for this refusal, when it sent one.
55    /// `None` means a server without the vocabulary, to be read by status.
56    pub code: Option<String>,
57    pub retry: Option<Retry>,
58    /// For a person: the body's `message`, else `X-Reason`, else the raw body.
59    pub message: String,
60    /// The numbers behind the message: `limit`, `used`, `retry_after`, `mime`.
61    pub details: Map<String, Value>,
62}
63
64/// A code is a short snake_case word; anything else in the header is noise.
65fn valid_code(s: &str) -> bool {
66    !s.is_empty()
67        && s.len() <= 48
68        && s.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
69}
70
71impl Refusal {
72    /// Read a refusal out of a response. `body` may be empty (a `HEAD` has
73    /// none), in which case the headers carry everything Magnitude sends.
74    pub fn from_response(status: u16, headers: &HeaderMap, body: &str) -> Self {
75        let header = |name: &str| {
76            headers
77                .get(name)
78                .and_then(|v| v.to_str().ok())
79                .map(|s| s.trim().to_string())
80                .filter(|s| !s.is_empty())
81        };
82        let mut json: Option<Map<String, Value>> = serde_json::from_str::<Value>(body)
83            .ok()
84            .and_then(|v| v.as_object().cloned());
85        let json_str = |j: &Option<Map<String, Value>>, key: &str| {
86            j.as_ref()
87                .and_then(|m| m.get(key))
88                .and_then(|v| v.as_str())
89                .map(|s| s.to_string())
90        };
91
92        let code = header("x-error-code")
93            .or_else(|| json_str(&json, "error"))
94            .filter(|c| valid_code(c));
95        let retry = header("x-retry")
96            .as_deref()
97            .and_then(Retry::parse)
98            .or_else(|| json_str(&json, "retry").as_deref().and_then(Retry::parse));
99        let message = json_str(&json, "message")
100            .or_else(|| header("x-reason"))
101            .or_else(|| {
102                let trimmed = body.trim();
103                (!trimmed.is_empty()).then(|| trimmed.to_string())
104            })
105            .unwrap_or_else(|| format!("HTTP {}", status));
106
107        let mut details = json
108            .take()
109            .map(|mut m| {
110                for k in ["error", "message", "retry", "status"] {
111                    m.remove(k);
112                }
113                m
114            })
115            .unwrap_or_default();
116        if let Some(secs) = header("retry-after").and_then(|s| s.parse::<u64>().ok()) {
117            details.entry("retry_after").or_insert(json!(secs));
118        }
119
120        let refusal = Self { status, code, retry, message, details };
121        if refusal.blames_clock() {
122            crate::clock::resync_soon();
123        }
124        refusal
125    }
126
127    /// How far the server finds this device's clock from its own, in seconds (negative is behind).
128    pub fn clock_offset_secs(&self) -> Option<i64> {
129        self.details.get("clock_offset_secs").and_then(|v| v.as_i64())
130    }
131
132    /// The server says the clock that signed this is wrong.
133    pub fn blames_clock(&self) -> bool {
134        self.retry == Some(Retry::FixClock) || self.code() == Some("auth_from_the_future")
135    }
136
137    pub fn code(&self) -> Option<&str> {
138        self.code.as_deref()
139    }
140
141    fn detail_u64(&self, key: &str) -> Option<u64> {
142        self.details.get(key).and_then(|v| v.as_u64())
143    }
144
145    /// The per-file limit the server named, for a `blob_too_large`.
146    pub fn limit(&self) -> Option<u64> {
147        self.detail_u64("limit")
148    }
149
150    pub fn retry_after(&self) -> Option<Duration> {
151        self.detail_u64("retry_after").map(Duration::from_secs)
152    }
153
154    /// The file is bigger than this server takes — a property of the file's
155    /// size, so worth remembering. A quota refusal is deliberately NOT this:
156    /// it shares the 413 but says nothing about size.
157    pub fn is_size_limit(&self) -> bool {
158        match self.code() {
159            Some(c) => c == "blob_too_large",
160            None => self.status == 413,
161        }
162    }
163
164    /// This server does not take this kind of file — worth remembering.
165    pub fn is_mime(&self) -> bool {
166        match self.code() {
167            Some(c) => c == "unsupported_media_type",
168            None => crate::blossom_capabilities::is_mime_rejection(Some(self.status), &self.message),
169        }
170    }
171
172    /// Whether sending the same request to the same server again, right now,
173    /// has any chance. A coded server is believed; an uncoded one is retried
174    /// unless the status is one that never changes on a retry.
175    pub fn worth_retrying_here(&self) -> bool {
176        match self.code() {
177            // `later` covers tomorrow's quota as much as a 2 s rate limit, so
178            // only the codes where "later" plausibly means "in a moment".
179            Some("rate_limited") => self
180                .retry_after()
181                .is_none_or(|d| d <= MAX_RETRY_AFTER),
182            Some("internal") | Some("mirror_source_unreachable") => true,
183            // Each attempt signs afresh.
184            Some(_) if self.retry == Some(Retry::SignAgain) => true,
185            Some(_) => false,
186            None => {
187                !self.is_mime()
188                    && !self.is_size_limit()
189                    && !is_gateway_status(self.status)
190            }
191        }
192    }
193
194    /// One sentence for the person waiting on the upload.
195    pub fn describe(&self, host: &str) -> String {
196        let bytes = crate::crypto::format_bytes;
197        match self.code() {
198            Some("quota_daily_exceeded") => match (self.detail_u64("used"), self.limit()) {
199                (Some(used), Some(limit)) => format!(
200                    "Today's {} upload allowance on {} is used up ({} uploaded so far). It resets at midnight UTC.",
201                    bytes(limit), host, bytes(used),
202                ),
203                _ => format!("Today's upload allowance on {} is used up. It resets at midnight UTC.", host),
204            },
205            Some("quota_storage_exceeded") => match (self.detail_u64("used"), self.limit()) {
206                (Some(used), Some(limit)) => format!(
207                    "Your storage on {} is full ({} of {}). Delete some files there, or use another server.",
208                    host, bytes(used), bytes(limit),
209                ),
210                _ => format!("Your storage on {} is full.", host),
211            },
212            Some("blob_too_large") => match self.limit() {
213                Some(limit) => format!("{} allows files up to {} for your account.", host, bytes(limit)),
214                None => format!("{} won't accept a file this large.", host),
215            },
216            Some("unsupported_media_type") => match self.details.get("mime").and_then(|v| v.as_str()) {
217                Some(mime) => format!("{} doesn't accept {} files.", host, mime),
218                None => format!("{} doesn't accept this kind of file.", host),
219            },
220            Some("client_not_permitted") => format!(
221                "{} only takes uploads from Vector accounts it recognises. {}",
222                host, self.message,
223            ),
224            Some("rate_limited") => match self.retry_after() {
225                Some(d) => format!("{} is rate-limiting you; try again in {}s.", host, d.as_secs()),
226                None => format!("{} is rate-limiting you; try again shortly.", host),
227            },
228            Some("server_full") => format!("{} is out of space.", host),
229            Some("blob_blocked") => format!("{} has blocked this file.", host),
230            Some("auth_expired") | Some("auth_from_the_future") => match self.clock_offset_secs() {
231                Some(off) if self.blames_clock() => format!(
232                    "{} says this device's clock is about {} {}. {}",
233                    host,
234                    crate::clock::describe_span(off.unsigned_abs()),
235                    if off < 0 { "slow" } else { "fast" },
236                    if crate::clock::is_decentralised() {
237                        "Vector is checking the time with your relays; try again in a moment."
238                    } else {
239                        "Turn on Decentralised Clock in Settings, or set this device's clock to update automatically."
240                    },
241                ),
242                _ => format!("{} rejected the upload signature's timestamp — this device's clock may be wrong.", host),
243            },
244            Some(c) if c.starts_with("auth_") => {
245                format!("{} rejected the upload authorization ({}).", host, self.message)
246            }
247            Some("internal") => format!("{} hit an internal error.", host),
248            Some(_) => format!("{}: {}", host, self.message),
249            None => match self.status {
250                413 => format!("{} won't accept a file this large.", host),
251                415 => format!("{} doesn't accept this kind of file.", host),
252                401 | 402 => format!("{} refused Vector's upload signature ({}).", host, self.message),
253                429 => format!("{} is rate-limiting you; try again shortly.", host),
254                s if s >= 500 => format!("{} is having trouble (HTTP {}).", host, s),
255                s => format!("{}: HTTP {} {}", host, s, self.message),
256            },
257        }
258    }
259}
260
261/// A `later` this much later is still "now" to someone watching a spinner.
262const MAX_RETRY_AFTER: Duration = Duration::from_secs(15);
263
264/// 502 / 503 / 504 and the Cloudflare 52x family: the origin behind a proxy
265/// cannot ingest the upload, and the next attempt hits the same wall.
266pub fn is_gateway_status(status: u16) -> bool {
267    matches!(status, 502 | 503 | 504 | 520..=526)
268}
269
270/// Why one upload attempt did not produce a blob.
271#[derive(Debug, Clone, PartialEq, Eq)]
272pub enum UploadFailure {
273    /// The user stopped it.
274    Cancelled,
275    /// The server answered, and the answer was no.
276    Refused(Refusal),
277    /// The bytes never fully arrived: connection dropped, stalled, refused.
278    Transport(String),
279    /// The server ACKed a different hash than was sent — it re-encoded the
280    /// blob, which is fatal for ciphertext.
281    Integrity(String),
282    /// Something before or after the wire: signing, URL, parsing.
283    Other(String),
284    /// The network changed under the upload, or is still connecting.
285    Network(String),
286}
287
288impl UploadFailure {
289    pub fn refusal(&self) -> Option<&Refusal> {
290        match self {
291            UploadFailure::Refused(r) => Some(r),
292            _ => None,
293        }
294    }
295
296    /// The connection went away with the body in flight. Above a few MB this
297    /// is almost always a size policy enforced by dropping, not a blip.
298    pub fn is_mid_stream_drop(&self) -> bool {
299        let UploadFailure::Transport(msg) = self else {
300            return false;
301        };
302        [
303            "Upload request failed",
304            "error sending request",
305            "connection reset",
306            "connection closed",
307            "connection refused",
308            "body write",
309            "IncompleteMessage",
310            "broken pipe",
311        ]
312        .iter()
313        .any(|needle| msg.contains(needle))
314    }
315
316    /// One sentence for the person waiting on the upload.
317    pub fn describe(&self, host: &str) -> String {
318        match self {
319            UploadFailure::Cancelled => "Upload cancelled".to_string(),
320            UploadFailure::Refused(r) => r.describe(host),
321            UploadFailure::Transport(m) if m.starts_with("Upload stalled") => {
322                format!("{} stopped accepting the file mid-way.", host)
323            }
324            UploadFailure::Transport(_) => format!("{} could not be reached.", host),
325            UploadFailure::Integrity(_) => format!("{} altered the file instead of storing it.", host),
326            UploadFailure::Other(m) | UploadFailure::Network(m) => m.clone(),
327        }
328    }
329}
330
331impl std::fmt::Display for UploadFailure {
332    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
333        match self {
334            UploadFailure::Cancelled => write!(f, "Upload cancelled"),
335            // The "with status N" shape is load-bearing: `parse_status_from_error`
336            // reads it wherever this crosses into a String.
337            UploadFailure::Refused(r) => match r.code() {
338                Some(c) => write!(f, "Upload failed with status {} [{}]: {}", r.status, c, r.message),
339                None => write!(f, "Upload failed with status {}: {}", r.status, r.message),
340            },
341            UploadFailure::Transport(m) | UploadFailure::Integrity(m) | UploadFailure::Other(m) | UploadFailure::Network(m) => {
342                write!(f, "{}", m)
343            }
344        }
345    }
346}
347
348impl From<UploadFailure> for String {
349    fn from(e: UploadFailure) -> String {
350        e.to_string()
351    }
352}
353
354/// The host a server URL names, for messages: `magnitude.jskitty.com`, not
355/// `https://magnitude.jskitty.com/`.
356pub fn host_of(server_url: &str) -> String {
357    url::Url::parse(server_url)
358        .ok()
359        .and_then(|u| u.host_str().map(|h| h.to_string()))
360        .unwrap_or_else(|| server_url.trim_end_matches('/').to_string())
361}
362
363/// What to tell the user when every server said no.
364pub fn summarise_failures(failures: &[(String, UploadFailure)]) -> String {
365    match failures {
366        [] => "No media server is configured. Add one in Settings → Network.".to_string(),
367        [(host, e)] => e.describe(host),
368        many => {
369            if let Some(shared) = shared_reason(many) {
370                return shared;
371            }
372            let mut out = String::from("No media server accepted the file:");
373            for (host, e) in many {
374                out.push_str("\n• ");
375                let line = e.describe(host);
376                // A reason that doesn't name its server (the network's own) gets the name.
377                if line.contains(host.as_str()) {
378                    out.push_str(&line);
379                } else {
380                    out.push_str(&format!("{host}: {line}"));
381                }
382            }
383            out
384        }
385    }
386}
387
388/// One reason every server failed with alike (the network refusing them all), as one line.
389fn shared_reason(failures: &[(String, UploadFailure)]) -> Option<String> {
390    let text = |e: &UploadFailure| match e {
391        UploadFailure::Other(m) | UploadFailure::Network(m) => Some(m.clone()),
392        _ => None,
393    };
394    let first = text(&failures.first()?.1)?;
395    if !failures.iter().all(|(_, e)| text(e).as_deref() == Some(first.as_str())) {
396        return None;
397    }
398    Some(if first == crate::transport::Refusal::ExitOff.text() {
399        "I2P-Only is on, so your media servers are off.".to_string()
400    } else {
401        first
402    })
403}
404
405#[cfg(test)]
406mod tests {
407    use super::*;
408    use reqwest::header::HeaderValue;
409
410    fn headers(pairs: &[(&'static str, &str)]) -> HeaderMap {
411        let mut h = HeaderMap::new();
412        for (k, v) in pairs {
413            h.insert(*k, HeaderValue::from_str(v).unwrap());
414        }
415        h
416    }
417
418    #[test]
419    fn a_magnitude_refusal_is_read_from_headers_and_body() {
420        let h = headers(&[("x-error-code", "quota_daily_exceeded"), ("x-retry", "later"), ("x-reason", "prose")]);
421        let body = r#"{"error":"quota_daily_exceeded","message":"Blob would exceed today's upload allowance: 900 of 1000 bytes already uploaded","retry":"later","status":413,"used":900,"limit":1000}"#;
422        let r = Refusal::from_response(413, &h, body);
423        assert_eq!(r.code(), Some("quota_daily_exceeded"));
424        assert_eq!(r.retry, Some(Retry::Later));
425        assert_eq!(r.limit(), Some(1000));
426        assert_eq!(r.details.get("used").and_then(|v| v.as_u64()), Some(900));
427        assert!(r.message.starts_with("Blob would exceed"));
428        assert!(!r.details.contains_key("error"), "envelope fields are not details");
429    }
430
431    #[test]
432    fn a_head_preflight_carries_the_code_with_no_body() {
433        let h = headers(&[("x-error-code", "client_not_permitted"), ("x-retry", "elsewhere"), ("x-reason", "Uploads need a Vector profile")]);
434        let r = Refusal::from_response(403, &h, "");
435        assert_eq!(r.code(), Some("client_not_permitted"));
436        assert_eq!(r.retry, Some(Retry::Elsewhere));
437        assert_eq!(r.message, "Uploads need a Vector profile");
438    }
439
440    #[test]
441    fn a_plain_server_has_no_code_and_keeps_its_body() {
442        let r = Refusal::from_response(400, &HeaderMap::new(), "Content-Type header does not match the file content");
443        assert_eq!(r.code(), None);
444        assert_eq!(r.retry, None);
445        assert!(r.is_mime(), "the keyword heuristic still applies without a code");
446    }
447
448    #[test]
449    fn a_quota_413_is_not_a_size_limit_but_a_plain_413_is() {
450        // Both are 413.
451        let h = headers(&[("x-error-code", "quota_daily_exceeded")]);
452        assert!(!Refusal::from_response(413, &h, "").is_size_limit());
453        let h = headers(&[("x-error-code", "blob_too_large")]);
454        assert!(Refusal::from_response(413, &h, "").is_size_limit());
455        assert!(Refusal::from_response(413, &HeaderMap::new(), "Payload Too Large").is_size_limit());
456    }
457
458    #[test]
459    fn a_coded_401_is_not_a_mime_rejection_but_an_uncoded_one_still_is() {
460        let h = headers(&[("x-error-code", "auth_expired")]);
461        assert!(!Refusal::from_response(401, &h, "").is_mime());
462        // Pre-existing behaviour for servers without the vocabulary, unchanged.
463        assert!(Refusal::from_response(401, &HeaderMap::new(), "Unauthorized").is_mime());
464    }
465
466    #[test]
467    fn a_garbage_code_header_is_ignored() {
468        let h = headers(&[("x-error-code", "Not A Code!")]);
469        assert_eq!(Refusal::from_response(500, &h, "").code(), None);
470    }
471
472    #[test]
473    fn retry_after_comes_from_the_header_or_the_body() {
474        let h = headers(&[("x-error-code", "rate_limited"), ("retry-after", "7")]);
475        assert_eq!(Refusal::from_response(429, &h, "").retry_after(), Some(Duration::from_secs(7)));
476        let r = Refusal::from_response(429, &headers(&[("x-error-code", "rate_limited")]), r#"{"retry_after":3}"#);
477        assert_eq!(r.retry_after(), Some(Duration::from_secs(3)));
478    }
479
480    #[test]
481    fn only_a_short_rate_limit_or_an_internal_error_is_retried_on_the_same_server() {
482        let coded = |code: &str, extra: &str| {
483            Refusal::from_response(400, &headers(&[("x-error-code", code)]), extra)
484        };
485        assert!(coded("rate_limited", r#"{"retry_after":5}"#).worth_retrying_here());
486        assert!(!coded("rate_limited", r#"{"retry_after":600}"#).worth_retrying_here());
487        assert!(coded("internal", "").worth_retrying_here());
488        assert!(!coded("quota_daily_exceeded", "").worth_retrying_here(), "tomorrow is not a retry");
489        assert!(!coded("client_not_permitted", "").worth_retrying_here());
490        assert!(!coded("auth_expired", "").worth_retrying_here());
491        assert!(!coded("blob_too_large", "").worth_retrying_here());
492    }
493
494    #[test]
495    fn an_uncoded_server_is_retried_unless_the_status_is_final() {
496        let plain = |status: u16, body: &str| Refusal::from_response(status, &HeaderMap::new(), body);
497        assert!(plain(500, "Internal Server Error").worth_retrying_here());
498        assert!(plain(408, "").worth_retrying_here());
499        assert!(!plain(413, "").worth_retrying_here());
500        assert!(!plain(415, "").worth_retrying_here());
501        assert!(!plain(503, "").worth_retrying_here(), "gateway statuses route around, as before");
502        assert!(!plain(524, "").worth_retrying_here());
503    }
504
505    #[test]
506    fn descriptions_name_the_host_and_the_numbers() {
507        let h = headers(&[("x-error-code", "quota_daily_exceeded")]);
508        let r = Refusal::from_response(413, &h, r#"{"used":1073741824,"limit":1073741824}"#);
509        assert_eq!(
510            r.describe("magnitude.jskitty.com"),
511            "Today's 1.0 GB upload allowance on magnitude.jskitty.com is used up (1.0 GB uploaded so far). It resets at midnight UTC.",
512        );
513        let h = headers(&[("x-error-code", "blob_too_large")]);
514        let r = Refusal::from_response(413, &h, r#"{"limit":26214400}"#);
515        assert_eq!(r.describe("m.example"), "m.example allows files up to 25.0 MB for your account.");
516        let r = Refusal::from_response(413, &HeaderMap::new(), "");
517        assert_eq!(r.describe("m.example"), "m.example won't accept a file this large.");
518    }
519
520    #[test]
521    fn display_keeps_the_status_shape_the_string_parsers_rely_on() {
522        let h = headers(&[("x-error-code", "blob_too_large")]);
523        let e = UploadFailure::Refused(Refusal::from_response(413, &h, r#"{"message":"too big"}"#));
524        assert_eq!(e.to_string(), "Upload failed with status 413 [blob_too_large]: too big");
525        assert_eq!(UploadFailure::Cancelled.to_string(), "Upload cancelled");
526    }
527
528    #[test]
529    fn mid_stream_drops_are_recognised_only_on_transport_failures() {
530        assert!(UploadFailure::Transport("Upload request failed: connection reset".into()).is_mid_stream_drop());
531        assert!(!UploadFailure::Transport("Upload stalled: x accepted nothing".into()).is_mid_stream_drop());
532        assert!(!UploadFailure::Other("connection reset".into()).is_mid_stream_drop());
533    }
534
535    #[test]
536    fn a_summary_lists_every_server_when_there_are_several() {
537        let a = UploadFailure::Transport("Upload request failed: x".into());
538        let b = UploadFailure::Refused(Refusal::from_response(415, &HeaderMap::new(), ""));
539        assert_eq!(summarise_failures(&[]), "No media server is configured. Add one in Settings → Network.");
540        assert_eq!(summarise_failures(&[("a.example".into(), a.clone())]), "a.example could not be reached.");
541        assert_eq!(
542            summarise_failures(&[("a.example".into(), a), ("b.example".into(), b)]),
543            "No media server accepted the file:\n• a.example could not be reached.\n• b.example doesn't accept this kind of file.",
544        );
545    }
546
547    #[test]
548    fn a_reason_every_server_shares_is_one_line() {
549        let off = || UploadFailure::Other(crate::transport::Refusal::ExitOff.text());
550        let many = [("a.example".to_string(), off()), ("b.example".to_string(), off()), ("c.example".to_string(), off())];
551        assert_eq!(summarise_failures(&many), "I2P-Only is on, so your media servers are off.");
552        let changed = || UploadFailure::Network("The network changed.".into());
553        assert_eq!(summarise_failures(&[("a.example".into(), changed()), ("b.example".into(), changed())]), "The network changed.");
554        let mixed = [("a.example".to_string(), off()), ("b.example".to_string(), UploadFailure::Transport("x".into()))];
555        assert_eq!(
556            summarise_failures(&mixed),
557            "No media server accepted the file:\n• a.example: I2P-Only is on, so this server is off.\n• b.example could not be reached.",
558            "a reason that names no server gets its host",
559        );
560    }
561
562    #[test]
563    fn host_of_strips_the_url_down_to_its_name() {
564        assert_eq!(host_of("https://magnitude.jskitty.com/"), "magnitude.jskitty.com");
565        assert_eq!(host_of("http://localhost:8080"), "localhost");
566        assert_eq!(host_of("not a url"), "not a url");
567    }
568
569    #[test]
570    fn a_clock_the_server_blames_is_named_and_not_retried_on_the_same_clock() {
571        let h = headers(&[("x-error-code", "auth_expired"), ("x-retry", "fix_clock")]);
572        let body = r#"{"error":"auth_expired","message":"m","retry":"fix_clock","status":401,"clock_offset_secs":-241}"#;
573        let r = Refusal::from_response(401, &h, body);
574        assert_eq!(r.retry, Some(Retry::FixClock));
575        assert_eq!(r.clock_offset_secs(), Some(-241));
576        assert!(r.blames_clock());
577        assert!(!r.worth_retrying_here(), "signing again on the same clock gets the same answer");
578        assert!(r.describe("m.example").contains("about 4 minutes slow"), "{}", r.describe("m.example"));
579    }
580
581    #[test]
582    fn an_expired_signature_is_signed_again() {
583        let h = headers(&[("x-error-code", "auth_expired"), ("x-retry", "sign_again")]);
584        let r = Refusal::from_response(401, &h, "");
585        assert_eq!(r.retry, Some(Retry::SignAgain));
586        assert!(!r.blames_clock());
587        assert!(r.worth_retrying_here());
588    }
589}