Skip to main content

vcon_server/tui/
client.rs

1//! The server's HTTP API as the terminal UI uses it: `GET /key`,
2//! `GET /vcons`, a vCon's masked view (`?view=masked`) and its reveals
3//! (`?reveal=<part>`), with one bearer key over TLS. The requests are behind
4//! [`Api`], so the UI is driven in tests without a network; the conversions
5//! a request makes (its path, and its answer to a value) are functions of
6//! their own.
7
8use std::error::Error;
9use std::time::Duration;
10
11use serde::Deserialize;
12use serde::de::DeserializeOwned;
13use zeroize::Zeroizing;
14
15use crate::masked::{self, Summary};
16use crate::mcp::stdio::{self, ClientConfig};
17use crate::reveal::{self, Part};
18use crate::tui::state::{ApiError, Effect, Event, KeyInfo, Page};
19
20/// The vCons asked for in one page.
21pub(crate) const PAGE: u16 = 100;
22/// How long one request may take, connection included.
23pub(crate) const TIMEOUT: Duration = Duration::from_secs(15);
24/// The most bytes read of one answer; a page of [`PAGE`] rows is far
25/// smaller.
26const MAX_BODY: usize = 1 << 20;
27
28/// The requests the UI makes.
29pub trait Api: Send + Sync {
30    /// `GET /key`: the key in use.
31    ///
32    /// # Errors
33    ///
34    /// [`ApiError`] when no answer arrived, or it was a refusal.
35    fn key(&self) -> Result<KeyInfo, ApiError>;
36
37    /// `GET /vcons`: one page, from `cursor` or from the start.
38    ///
39    /// # Errors
40    ///
41    /// [`ApiError`] when no answer arrived, or it was a refusal.
42    fn page(&self, cursor: Option<&str>) -> Result<Page, ApiError>;
43
44    /// `GET /vcons/{uuid}?view=masked`: the vCon's masked view, as the
45    /// lines the detail view shows ([`summary_lines`]).
46    ///
47    /// # Errors
48    ///
49    /// [`ApiError`] when no answer arrived, it was a refusal, or it was not
50    /// the masked view.
51    fn masked(&self, uuid: &str) -> Result<Vec<String>, ApiError>;
52
53    /// `GET /vcons/{uuid}?reveal=<part>`: the whole vCon's text, inflated,
54    /// read as a reveal of `part`, which the audit log records.
55    ///
56    /// # Errors
57    ///
58    /// [`ApiError`] when no answer arrived, it was a refusal, or it could
59    /// not be read.
60    fn reveal(&self, uuid: &str, part: Part) -> Result<String, ApiError>;
61
62    /// Ends every request under way, and refuses every later one, at once.
63    /// The UI calls it at its exit, before it joins its requests' threads.
64    fn close(&self) {}
65}
66
67/// Makes the request `effect` names and returns its answer as an event. A
68/// reveal's answer is reduced at once to the part it reveals.
69pub fn perform(api: &dyn Api, effect: &Effect) -> Event {
70    match effect {
71        Effect::FetchKey => Event::KeyInfo(api.key()),
72        Effect::FetchPage(cursor) => Event::Page(api.page(cursor.as_deref())),
73        Effect::FetchMasked(uuid) => Event::Masked(uuid.clone(), api.masked(uuid)),
74        Effect::FetchReveal(uuid, part) => Event::Revealed(
75            uuid.clone(),
76            *part,
77            api.reveal(uuid, *part)
78                .map(|text| reveal_text(&text, *part)),
79        ),
80    }
81}
82
83/// The most bytes read of a reveal's answer, and of the vCon it inflates
84/// to: 16 MiB.
85pub const REVEAL_BODY: usize = 16 << 20;
86
87/// A path segment with every byte but the unreserved ones percent-encoded.
88fn segment(text: &str) -> String {
89    text.bytes()
90        .map(|b| {
91            if b.is_ascii_alphanumeric() || b"-._~".contains(&b) {
92                char::from(b).to_string()
93            } else {
94                format!("%{b:02X}")
95            }
96        })
97        .collect()
98}
99
100/// The path of a vCon's masked view.
101#[must_use]
102pub fn masked_path(uuid: &str) -> String {
103    format!(
104        "/vcons/{}?{}={}",
105        segment(uuid),
106        masked::PARAMETER,
107        masked::MASKED
108    )
109}
110
111/// The path of a reveal of `part` of a vCon.
112#[must_use]
113pub fn reveal_path(uuid: &str, part: Part) -> String {
114    format!(
115        "/vcons/{}?{}={}",
116        segment(uuid),
117        reveal::MARKER,
118        part.name()
119    )
120}
121
122/// The masked view as the lines the detail view shows.
123#[must_use]
124pub fn summary_lines(made: &Summary) -> Vec<String> {
125    let mut lines = vec![
126        "Masked view".to_owned(),
127        format!("Form          {}", made.form),
128        format!(
129            "Created       {}",
130            if made.created.is_empty() {
131                "not given"
132            } else {
133                &made.created
134            }
135        ),
136        format!("Subject       {}", made.subject),
137    ];
138    if let Some(signature) = &made.signature {
139        let or_none = |text: &str| {
140            if text.is_empty() {
141                "none".to_owned()
142            } else {
143                text.to_owned()
144            }
145        };
146        lines.push(format!(
147            "Signature     alg {}, kid {}, x5t {}",
148            or_none(&signature.alg),
149            or_none(&signature.kid),
150            or_none(&signature.x5t)
151        ));
152    }
153    lines.push(format!("Parties       {}", made.parties.len()));
154    lines.extend(made.parties.iter().map(|line| format!("  {line}")));
155    lines.push(format!(
156        "Dialogs       {}, {} s in all",
157        made.dialogs,
158        masked::js_number(made.seconds)
159    ));
160    lines.extend(made.dialog.iter().map(|line| format!("  {line}")));
161    lines.push(format!("Attachments   {}", made.attachments));
162    lines.push(format!("Analyses      {}", made.analyses));
163    lines.push(format!("Links         {}", made.links));
164    lines
165}
166
167/// The answer to the masked view, as its lines.
168///
169/// # Errors
170///
171/// [`ApiError::Status`] for a refusal; [`ApiError::Malformed`] for a 200
172/// that is not the view, such as the whole vCon a server older than the
173/// view sends, which is never shown.
174pub fn masked_answer(status: u16, media: &str, body: &[u8]) -> Result<Vec<String>, ApiError> {
175    if status == 200 && media.starts_with("application/vcon") {
176        return Err(ApiError::Malformed(
177            "the server sent the whole vCon, not its masked view: it is older than this terminal UI, so upgrade it; nothing of the vCon is shown"
178                .to_owned(),
179        ));
180    }
181    answer::<Summary>(status, body).map(|made| summary_lines(&made))
182}
183
184/// The answer to a reveal, as the vCon's text: inflated within
185/// [`REVEAL_BODY`] when it was stored gzipped, read as a browser reads it.
186///
187/// # Errors
188///
189/// [`ApiError::Status`] for a refusal; [`ApiError::Malformed`] for a body
190/// that does not inflate or inflates past the limit.
191pub fn reveal_answer(status: u16, media: &str, body: &[u8]) -> Result<String, ApiError> {
192    use std::io::Read;
193    if status != 200 {
194        return answer::<serde_json::Value>(status, body).map(|_| String::new());
195    }
196    if !media.starts_with("application/vcon+gzip") {
197        return Ok(masked::text_of(body));
198    }
199    let mut inflated = Vec::new();
200    flate2::read::MultiGzDecoder::new(body)
201        .take(
202            u64::try_from(REVEAL_BODY)
203                .unwrap_or(u64::MAX)
204                .saturating_add(1),
205        )
206        .read_to_end(&mut inflated)
207        .map_err(|e| ApiError::Malformed(format!("the gzipped vCon does not inflate: {e}")))?;
208    if inflated.len() > REVEAL_BODY {
209        return Err(ApiError::Malformed(format!(
210            "the vCon is longer than {REVEAL_BODY} bytes, the most the terminal UI reads"
211        )));
212    }
213    Ok(masked::text_of(&inflated))
214}
215
216/// What the console says of a part of a vCon it cannot read in parts.
217const NO_PARTS: &str = "This vCon cannot be read in parts. Reveal the whole vCon instead.";
218
219/// `part` of the vCon `text`, as the detail view shows it: as the console
220/// shows each reveal (src/masked.rs `section`), links one a line, and the
221/// whole vCon as stored, cut at [`masked::DISPLAY_LIMIT`] characters.
222#[must_use]
223pub fn reveal_text(text: &str, part: Part) -> String {
224    match part {
225        Part::All | Part::Audio => {
226            let (kept, left) = masked::shown(text);
227            if left == 0 {
228                kept.to_owned()
229            } else {
230                format!(
231                    "{kept}\n\nOnly the first {} characters are shown; {left} more are not.",
232                    masked::DISPLAY_LIMIT
233                )
234            }
235        }
236        Part::Links => {
237            if masked::section(text, Part::Subject).is_none() {
238                return NO_PARTS.to_owned();
239            }
240            let found = masked::links(text);
241            if found.is_empty() {
242                return "No links in this vCon.".to_owned();
243            }
244            found
245                .iter()
246                .map(|link| format!("{}: {} (never loaded)", link.place, link.url))
247                .collect::<Vec<_>>()
248                .join("\n")
249        }
250        Part::Parties | Part::Subject | Part::Dialog | Part::Analysis => {
251            masked::section(text, part).unwrap_or_else(|| NO_PARTS.to_owned())
252        }
253    }
254}
255
256/// The server's address without trailing slashes, so a path can follow it.
257#[must_use]
258pub fn base(url: &str) -> String {
259    url.trim_end_matches('/').to_owned()
260}
261
262/// The path and query of one page of the list.
263#[must_use]
264pub fn page_path(cursor: Option<&str>) -> String {
265    let mut path = format!("/vcons?limit={PAGE}");
266    if let Some(cursor) = cursor {
267        path.push_str("&cursor=");
268        path.extend(form_urlencoded::byte_serialize(cursor.as_bytes()));
269    }
270    path
271}
272
273/// The value a `status` and `body` answer holds.
274///
275/// # Errors
276///
277/// [`ApiError::Status`] for any status but 200, with the title of the
278/// problem document if the body is one; [`ApiError::Malformed`] for a 200
279/// whose body is not a `T`.
280pub fn answer<T: DeserializeOwned>(status: u16, body: &[u8]) -> Result<T, ApiError> {
281    #[derive(Deserialize)]
282    struct Problem {
283        title: String,
284    }
285    if status == 200 {
286        return serde_json::from_slice(body).map_err(|e| ApiError::Malformed(e.to_string()));
287    }
288    let title = serde_json::from_slice::<Problem>(body)
289        .ok()
290        .map(|problem| problem.title);
291    Err(ApiError::Status(status, title))
292}
293
294/// A running server, reached over HTTPS with one key.
295pub struct HttpApi {
296    base: String,
297    token: Zeroizing<String>,
298    client: reqwest::Client,
299    runtime: tokio::runtime::Runtime,
300    /// How long one request may take; [`TIMEOUT`] outside tests.
301    timeout: Duration,
302    /// True once [`Api::close`] is called: every request under way ends,
303    /// and no later one starts.
304    closed: tokio::sync::watch::Sender<bool>,
305}
306
307/// The address only: the token is never written.
308impl std::fmt::Debug for HttpApi {
309    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
310        f.debug_struct("HttpApi")
311            .field("base", &self.base)
312            .finish_non_exhaustive()
313    }
314}
315
316impl HttpApi {
317    /// The server a client file names. The key file is held to the one
318    /// secret-file rule, and the server's certificate is always verified:
319    /// against the file's `ca`, or the system's roots without it.
320    ///
321    /// # Errors
322    ///
323    /// A sentence naming the key file, the CA file or the runtime that
324    /// could not be used. It never holds the token.
325    pub fn new(config: &ClientConfig) -> Result<Self, String> {
326        let token = stdio::token(&config.key_file).map_err(|e| e.to_string())?;
327        let client = stdio::https_client(config.ca.as_deref()).map_err(|e| e.to_string())?;
328        let runtime = tokio::runtime::Builder::new_current_thread()
329            .enable_all()
330            .build()
331            .map_err(|e| format!("the runtime: {e}"))?;
332        Ok(Self {
333            base: base(&config.url),
334            token,
335            client,
336            runtime,
337            timeout: TIMEOUT,
338            closed: tokio::sync::watch::Sender::new(false),
339        })
340    }
341
342    /// One GET of `path`, read as a `T`.
343    fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T, ApiError> {
344        let (status, _, body) = self.fetch(path, MAX_BODY)?;
345        answer(status, &body)
346    }
347
348    /// One GET of `path`: its status, media type and body, at most `limit`
349    /// bytes of it.
350    fn fetch(&self, path: &str, limit: usize) -> Result<(u16, String, Vec<u8>), ApiError> {
351        let url = format!("{}{path}", self.base);
352        let exchange = async {
353            let mut response = self
354                .client
355                .get(&url)
356                .bearer_auth(self.token.as_str())
357                .send()
358                .await
359                .map_err(|e| unreachable(&e))?;
360            let status = response.status().as_u16();
361            let media = response
362                .headers()
363                .get(reqwest::header::CONTENT_TYPE)
364                .and_then(|value| value.to_str().ok())
365                .unwrap_or_default()
366                .to_ascii_lowercase();
367            let mut body = Vec::new();
368            while let Some(chunk) = response.chunk().await.map_err(|e| unreachable(&e))? {
369                if body.len().saturating_add(chunk.len()) > limit {
370                    return Err(ApiError::Malformed(format!(
371                        "it is longer than {limit} bytes"
372                    )));
373                }
374                body.extend_from_slice(&chunk);
375            }
376            Ok((status, media, body))
377        };
378        let mut closed = self.closed.subscribe();
379        self.runtime.block_on(async {
380            tokio::select! {
381                // First, so a request made after the close never starts.
382                biased;
383                _ = closed.wait_for(|closed| *closed) => Err(was_closed()),
384                answer = tokio::time::timeout(self.timeout, exchange) => {
385                    answer.unwrap_or_else(|_| Err(no_answer(self.timeout)))
386                }
387            }
388        })
389    }
390}
391
392/// What a request of a closed client gives.
393fn was_closed() -> ApiError {
394    ApiError::Unreachable("the client was closed".to_owned())
395}
396
397/// What a request that took longer than `timeout` gives.
398pub(crate) fn no_answer(timeout: Duration) -> ApiError {
399    ApiError::Unreachable(format!("no answer within {} seconds", timeout.as_secs()))
400}
401
402impl Api for HttpApi {
403    fn key(&self) -> Result<KeyInfo, ApiError> {
404        self.get("/key")
405    }
406
407    fn page(&self, cursor: Option<&str>) -> Result<Page, ApiError> {
408        self.get(&page_path(cursor))
409    }
410
411    fn masked(&self, uuid: &str) -> Result<Vec<String>, ApiError> {
412        let (status, media, body) = self.fetch(&masked_path(uuid), MAX_BODY)?;
413        masked_answer(status, &media, &body)
414    }
415
416    fn reveal(&self, uuid: &str, part: Part) -> Result<String, ApiError> {
417        let (status, media, body) = self.fetch(&reveal_path(uuid, part), REVEAL_BODY)?;
418        reveal_answer(status, &media, &body)
419    }
420
421    fn close(&self) {
422        // Kept even with no request under way, for the requests after it.
423        self.closed.send_replace(true);
424    }
425}
426
427/// What is wrong with a certificate the client refused, and what to do,
428/// for the refusals an operator can act on; `None` for any other, whose
429/// own text is shown.
430pub(crate) fn certificate_advice(error: &rustls::CertificateError) -> Option<&'static str> {
431    use rustls::CertificateError as Refused;
432    match error {
433        // rustls carries webpki's `CaUsedAsEndEntity` only as an opaque
434        // error, so its name in the debug form is all there is to match.
435        // The test against a server with such a certificate fails if a
436        // rustls release changes it.
437        Refused::Other(other) if format!("{other:?}").contains("CaUsedAsEndEntity") => Some(
438            "it is marked as a certificate authority (CA:TRUE), and a server's own certificate may not be one; make the server's certificate with basicConstraints=CA:FALSE, as getting started shows",
439        ),
440        // A trusted certificate of the issuer's name that did not sign it
441        // is a bad signature: the server's certificate was replaced and
442        // the client file's `ca` still holds the old one.
443        Refused::UnknownIssuer | Refused::BadSignature => Some(
444            "no certificate this client trusts signed it; set ca in the client file to the server's current certificate authority",
445        ),
446        Refused::NotValidForName | Refused::NotValidForNameContext { .. } => Some(
447            "it is not for the name in url; use a name the certificate holds, or give the server a certificate for this one",
448        ),
449        Refused::Expired | Refused::ExpiredContext { .. } => {
450            Some("it has expired; renew the server's certificate, or correct this machine's clock")
451        }
452        Refused::NotValidYet | Refused::NotValidYetContext { .. } => Some(
453            "it is not valid yet; correct this machine's clock, or wait for the certificate's start",
454        ),
455        _ => None,
456    }
457}
458
459/// The TLS library's error at `cause`: the cause itself, or what the I/O
460/// errors around it carry. A failed handshake arrives as an I/O error that
461/// holds an I/O error that holds it, and `source` does not look inside one.
462fn tls_error<'a>(cause: &'a (dyn Error + 'static)) -> Option<&'a rustls::Error> {
463    let mut at = cause;
464    loop {
465        if let Some(found) = at.downcast_ref::<rustls::Error>() {
466            return Some(found);
467        }
468        at = at.downcast_ref::<std::io::Error>()?.get_ref()?;
469    }
470}
471
472/// A request that got no answer: a refused certificate in words an
473/// operator can act on, else the causes reqwest keeps below its own
474/// sentence (the refused connection, the handshake that failed).
475fn unreachable(error: &reqwest::Error) -> ApiError {
476    let mut why = error.to_string();
477    let mut cause = error.source();
478    while let Some(inner) = cause {
479        if let Some(rustls::Error::InvalidCertificate(refused)) = tls_error(inner)
480            && let Some(advice) = certificate_advice(refused)
481        {
482            return ApiError::Untrusted(advice.to_owned());
483        }
484        why.push_str(": ");
485        why.push_str(&inner.to_string());
486        cause = inner.source();
487    }
488    ApiError::Unreachable(why)
489}
490
491#[cfg(test)]
492mod tests {
493    use super::{Api, answer, base, page_path, perform};
494    use crate::tui::state::{ApiError, Effect, Event, KeyInfo, Page};
495
496    /// An API that answers from memory and records what it was asked.
497    struct Canned {
498        asked: std::sync::Mutex<Vec<String>>,
499    }
500
501    impl Api for Canned {
502        fn key(&self) -> Result<KeyInfo, ApiError> {
503            self.asked.lock().expect("the lock").push("key".to_owned());
504            Err(ApiError::Status(401, None))
505        }
506
507        fn page(&self, cursor: Option<&str>) -> Result<Page, ApiError> {
508            self.asked
509                .lock()
510                .expect("the lock")
511                .push(format!("page {cursor:?}"));
512            Ok(Page {
513                vcons: Vec::new(),
514                next: None,
515            })
516        }
517
518        fn masked(&self, uuid: &str) -> Result<Vec<String>, ApiError> {
519            self.asked
520                .lock()
521                .expect("the lock")
522                .push(format!("masked {uuid}"));
523            Err(ApiError::Status(404, None))
524        }
525
526        fn reveal(&self, uuid: &str, part: Part) -> Result<String, ApiError> {
527            self.asked
528                .lock()
529                .expect("the lock")
530                .push(format!("reveal {uuid} {}", part.name()));
531            Err(ApiError::Status(404, None))
532        }
533    }
534
535    // Success.
536
537    #[test]
538    fn a_key_answer_is_read() {
539        let info: KeyInfo = answer(
540            200,
541            br#"{"id":"0123456789abcdef","tenant":"t_example","scopes":["read","audit"]}"#,
542        )
543        .expect("a key answer");
544        assert_eq!(info.tenant.as_deref(), Some("t_example"), "the tenant");
545        assert_eq!(info.scopes, ["read", "audit"], "the scopes");
546    }
547
548    #[test]
549    fn a_page_answer_is_read_with_its_cursor() {
550        let page: Page = answer(
551            200,
552            br#"{"next":"GOHD","vcons":[{"stored_at":"2026-10-25T12:00:00Z","updated_at":"2026-10-25T12:30:00Z","uuid":"01a07da8-c2bb-83e5-b9a2-279e0d16bc46","version":"4f0c4b0a1d2e3f405162738495a6b7c8"}]}"#,
553        )
554        .expect("a page");
555        assert_eq!(page.next.as_deref(), Some("GOHD"), "the cursor");
556        assert_eq!(
557            page.vcons[0].uuid, "01a07da8-c2bb-83e5-b9a2-279e0d16bc46",
558            "the row"
559        );
560    }
561
562    #[test]
563    fn the_first_page_is_asked_for_without_a_cursor() {
564        assert_eq!(page_path(None), "/vcons?limit=100", "the first page");
565    }
566
567    #[test]
568    fn each_effect_is_one_request_and_its_answer_one_event() {
569        let api = Canned {
570            asked: std::sync::Mutex::default(),
571        };
572        let page = perform(&api, &Effect::FetchPage(Some("c".to_owned())));
573        assert!(
574            matches!(page, Event::Page(Ok(_))),
575            "a page's answer is a page event"
576        );
577        let key = perform(&api, &Effect::FetchKey);
578        assert_eq!(
579            key,
580            Event::KeyInfo(Err(ApiError::Status(401, None))),
581            "a refusal is carried"
582        );
583        assert_eq!(
584            *api.asked.lock().expect("the lock"),
585            ["page Some(\"c\")", "key"],
586            "one request each, with the cursor"
587        );
588    }
589
590    use super::{
591        REVEAL_BODY, masked_answer, masked_path, reveal_answer, reveal_path, reveal_text,
592        summary_lines,
593    };
594    use crate::masked::{Signature, summary};
595    use crate::reveal::Part;
596
597    const VCON_UUID: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc46";
598
599    /// The masked view, and the reveals, as `Canned` answers them.
600    struct Revealing;
601
602    impl Api for Revealing {
603        fn key(&self) -> Result<KeyInfo, ApiError> {
604            Err(ApiError::Status(401, None))
605        }
606
607        fn page(&self, _: Option<&str>) -> Result<Page, ApiError> {
608            Err(ApiError::Status(401, None))
609        }
610
611        fn masked(&self, uuid: &str) -> Result<Vec<String>, ApiError> {
612            Ok(vec![format!("masked {uuid}")])
613        }
614
615        fn reveal(&self, _: &str, _: Part) -> Result<String, ApiError> {
616            Ok(r#"{"subject":"Renewal call"}"#.to_owned())
617        }
618    }
619
620    #[test]
621    fn the_masked_and_reveal_effects_are_events_for_their_uuid_and_part() {
622        assert_eq!(
623            perform(&Revealing, &Effect::FetchMasked(VCON_UUID.to_owned())),
624            Event::Masked(
625                VCON_UUID.to_owned(),
626                Ok(vec![format!("masked {VCON_UUID}")])
627            ),
628            "the masked view"
629        );
630        assert_eq!(
631            perform(
632                &Revealing,
633                &Effect::FetchReveal(VCON_UUID.to_owned(), Part::Subject)
634            ),
635            Event::Revealed(
636                VCON_UUID.to_owned(),
637                Part::Subject,
638                Ok("Renewal call".to_owned())
639            ),
640            "the part, as the view shows it"
641        );
642    }
643
644    #[test]
645    fn the_paths_ask_for_the_view_and_name_the_part() {
646        assert_eq!(
647            masked_path(VCON_UUID),
648            format!("/vcons/{VCON_UUID}?view=masked"),
649            "view"
650        );
651        assert_eq!(
652            reveal_path(VCON_UUID, Part::All),
653            format!("/vcons/{VCON_UUID}?reveal=all"),
654            "reveal"
655        );
656    }
657
658    #[test]
659    fn the_masked_view_is_shown_as_labeled_lines_with_one_line_a_party_and_a_dialog() {
660        let text = r#"{"created_at":"2026-11-10T09:15:00Z","subject":"x","parties":[{"tel":"+12125550142"}],
661            "dialog":[{"type":"text","duration":12.5}],"analysis":[{}]}"#;
662        assert_eq!(
663            summary_lines(&summary(text)),
664            [
665                "Masked view",
666                "Form          unsigned",
667                "Created       2026-11-10 09:15:00 UTC+00:00",
668                "Subject       present, hidden",
669                "Parties       1",
670                "  Party 1: number ending 0142",
671                "Dialogs       1, 12.5 s in all",
672                "  Dialog 1: text, no start, 12.5 s, no parties; no content",
673                "Attachments   0",
674                "Analyses      1",
675                "Links         0",
676            ],
677            "the lines"
678        );
679    }
680
681    #[test]
682    fn a_signed_vcons_header_is_a_line_and_no_created_time_is_said() {
683        let mut made = summary("{}");
684        made.signature = Some(Signature {
685            alg: "ES256".to_owned(),
686            kid: "key-1".to_owned(),
687            x5t: String::new(),
688        });
689        let lines = summary_lines(&made);
690        assert!(
691            lines.contains(&"Signature     alg ES256, kid key-1, x5t none".to_owned()),
692            "{lines:?}"
693        );
694        assert!(
695            lines.contains(&"Created       not given".to_owned()),
696            "{lines:?}"
697        );
698    }
699
700    #[test]
701    fn a_masked_answer_is_read_as_its_lines() {
702        let body = serde_json::to_vec(&summary("{}")).expect("JSON");
703        let lines = masked_answer(200, "application/json", &body).expect("read");
704        assert_eq!(
705            lines.first().map(String::as_str),
706            Some("Masked view"),
707            "{lines:?}"
708        );
709    }
710
711    #[test]
712    fn each_part_is_shown_as_the_console_shows_it() {
713        let text = r#"{"subject":"Renewal call","parties":[{"name":"Ada Example"}],
714            "dialog":[{"url":"https://media.example.com/a.wav"}],"analysis":[]}"#;
715        assert_eq!(reveal_text(text, Part::Subject), "Renewal call", "subject");
716        assert!(
717            reveal_text(text, Part::Parties).contains("\"name\": \"Ada Example\""),
718            "parties"
719        );
720        assert!(
721            reveal_text(text, Part::Dialog).contains("media.example.com"),
722            "dialog"
723        );
724        assert_eq!(reveal_text(text, Part::Analysis), "none", "analysis");
725        assert_eq!(
726            reveal_text(text, Part::Links),
727            "dialog 1: https://media.example.com/a.wav (never loaded)",
728            "links"
729        );
730        assert_eq!(
731            reveal_text(text, Part::All),
732            text,
733            "the whole vCon as stored"
734        );
735    }
736
737    #[test]
738    fn a_reveal_answer_is_the_vcons_text() {
739        assert_eq!(
740            reveal_answer(200, "application/vcon", br#"{"a":1}"#),
741            Ok(r#"{"a":1}"#.to_owned()),
742            "as stored"
743        );
744    }
745
746    // Failure.
747
748    /// A server older than the view passes the query over and sends the
749    /// whole vCon: it is not shown, and the screen says why.
750    #[test]
751    fn the_whole_vcon_in_answer_to_the_masked_view_is_refused_and_not_shown() {
752        for media in ["application/vcon", "application/vcon+gzip"] {
753            let refused = masked_answer(200, media, br#"{"subject":"Renewal call"}"#);
754            let Err(ApiError::Malformed(why)) = refused else {
755                panic!("{media}: refused, not {refused:?}");
756            };
757            assert!(why.contains("older"), "{why}");
758            assert!(!why.contains("Renewal"), "{why}");
759        }
760    }
761
762    #[test]
763    fn a_refused_masked_view_or_reveal_carries_its_status_and_title() {
764        let body = br#"{"title":"forbidden","status":403}"#;
765        assert_eq!(
766            masked_answer(403, "application/problem+json", body),
767            Err(ApiError::Status(403, Some("forbidden".to_owned()))),
768            "masked"
769        );
770        assert_eq!(
771            reveal_answer(
772                410,
773                "application/problem+json",
774                br#"{"title":"gone","status":410}"#
775            ),
776            Err(ApiError::Status(410, Some("gone".to_owned()))),
777            "reveal"
778        );
779    }
780
781    #[test]
782    fn a_gzipped_reveal_that_does_not_inflate_is_refused() {
783        let refused = reveal_answer(200, "application/vcon+gzip", b"not gzip");
784        assert!(
785            matches!(refused, Err(ApiError::Malformed(_))),
786            "{refused:?}"
787        );
788    }
789
790    #[test]
791    fn a_gzipped_reveal_that_inflates_past_the_limit_is_refused() {
792        use std::io::Write as _;
793        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::best());
794        gz.write_all(&vec![b' '; REVEAL_BODY + 1]).expect("gzip");
795        let body = gz.finish().expect("gzip");
796        let refused = reveal_answer(200, "application/vcon+gzip", &body);
797        let Err(ApiError::Malformed(why)) = refused else {
798            panic!("refused, not {refused:?}");
799        };
800        assert!(why.contains(&REVEAL_BODY.to_string()), "{why}");
801    }
802
803    #[test]
804    fn a_masked_answer_that_is_not_the_view_is_malformed() {
805        let refused = masked_answer(200, "application/json", br#"{"form":"unsigned"}"#);
806        assert!(
807            matches!(refused, Err(ApiError::Malformed(_))),
808            "{refused:?}"
809        );
810    }
811
812    #[test]
813    fn a_part_of_a_vcon_that_cannot_be_read_in_parts_says_so() {
814        for part in [Part::Parties, Part::Subject, Part::Links] {
815            assert_eq!(
816                reveal_text(r#"{"ciphertext":"x"}"#, part),
817                "This vCon cannot be read in parts. Reveal the whole vCon instead.",
818                "{part:?}"
819            );
820        }
821    }
822
823    // Edge.
824
825    #[test]
826    fn a_vcon_without_links_says_so() {
827        assert_eq!(
828            reveal_text("{}", Part::Links),
829            "No links in this vCon.",
830            "none"
831        );
832    }
833
834    #[test]
835    fn a_whole_vcon_longer_than_the_limit_is_cut_and_says_how_much_was_left_out() {
836        let text = format!("\"{}\"", "x".repeat(crate::masked::DISPLAY_LIMIT));
837        let shown = reveal_text(&text, Part::All);
838        assert!(
839            shown.ends_with("Only the first 2097152 characters are shown; 2 more are not."),
840            "{}",
841            shown
842                .get(shown.len().saturating_sub(80)..)
843                .unwrap_or_default()
844        );
845    }
846
847    #[test]
848    fn a_uuid_in_a_path_is_percent_encoded() {
849        assert_eq!(
850            masked_path("a b/c"),
851            "/vcons/a%20b%2Fc?view=masked",
852            "encoded"
853        );
854    }
855
856    #[test]
857    fn a_reveal_answer_with_a_byte_order_mark_loses_it() {
858        assert_eq!(
859            reveal_answer(200, "application/vcon", b"\xef\xbb\xbf{}"),
860            Ok("{}".to_owned()),
861            "dropped"
862        );
863    }
864
865    // Failure.
866
867    #[test]
868    fn a_refusal_carries_its_status_and_the_problems_title() {
869        let refused: Result<Page, _> = answer(
870            403,
871            br#"{"type":"https://vcon-server.com/problems/forbidden/","title":"forbidden","status":403}"#,
872        );
873        assert_eq!(
874            refused,
875            Err(ApiError::Status(403, Some("forbidden".to_owned()))),
876            "the title of the problem document"
877        );
878    }
879
880    #[test]
881    fn a_refusal_without_a_problem_document_carries_only_its_status() {
882        let refused: Result<Page, _> = answer(502, b"<html>bad gateway</html>");
883        assert_eq!(
884            refused,
885            Err(ApiError::Status(502, None)),
886            "a proxy's page is not shown"
887        );
888    }
889
890    #[test]
891    fn a_200_that_is_not_the_documented_json_is_malformed() {
892        let odd: Result<Page, _> = answer(200, b"{\"vcons\": 7}");
893        assert!(
894            matches!(odd, Err(ApiError::Malformed(_))),
895            "not a page: {odd:?}"
896        );
897    }
898
899    // Edge.
900
901    #[test]
902    fn a_cursor_is_percent_encoded() {
903        assert_eq!(
904            page_path(Some("a+b/c=&d")),
905            "/vcons?limit=100&cursor=a%2Bb%2Fc%3D%26d",
906            "a cursor cannot add a parameter"
907        );
908    }
909
910    #[test]
911    fn the_address_loses_its_trailing_slashes() {
912        assert_eq!(
913            base("https://vcon.example.com:8443/"),
914            "https://vcon.example.com:8443",
915            "one"
916        );
917        assert_eq!(
918            base("https://vcon.example.com"),
919            "https://vcon.example.com",
920            "none"
921        );
922    }
923
924    #[test]
925    fn an_operator_keys_null_tenant_is_none() {
926        let info: KeyInfo = answer(
927            200,
928            br#"{"id":"0123456789abcdef","tenant":null,"scopes":["admin"]}"#,
929        )
930        .expect("a key answer");
931        assert_eq!(info.tenant, None, "null is no tenant");
932    }
933
934    #[test]
935    fn a_last_page_has_no_cursor() {
936        let page: Page = answer(200, br#"{"next":null,"vcons":[]}"#).expect("a page");
937        assert_eq!(
938            page,
939            Page {
940                vcons: Vec::new(),
941                next: None
942            },
943            "empty and last"
944        );
945    }
946
947    // The HTTPS client, against a TLS server on loopback.
948
949    use std::io::{Read, Write};
950    use std::path::Path;
951    use std::sync::{Arc, Mutex};
952    use std::time::Duration;
953
954    use super::HttpApi;
955    use crate::mcp::stdio::ClientConfig;
956    use crate::stub_server::StubServer;
957
958    const TOKEN: &str = "vcs_0011223344556677_secret";
959
960    type Certificate = rcgen::CertifiedKey<rcgen::KeyPair>;
961
962    fn certificate() -> Certificate {
963        rcgen::generate_simple_self_signed(vec!["localhost".to_owned()]).expect("a certificate")
964    }
965
966    /// A TLS server for one test: it answers every request with `reply`, a
967    /// whole HTTP/1.1 response, and keeps each request's head. The server
968    /// ends its threads when dropped; then its port.
969    fn server(cert: &Certificate, reply: Vec<u8>) -> (StubServer, u16, Arc<Mutex<Vec<String>>>) {
970        let chain = vec![cert.cert.der().clone()];
971        let key = rustls::pki_types::PrivateKeyDer::Pkcs8(cert.signing_key.serialize_der().into());
972        let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
973        let mut config = rustls::ServerConfig::builder_with_provider(provider)
974            .with_safe_default_protocol_versions()
975            .expect("versions")
976            .with_no_client_auth()
977            .with_single_cert(chain, key)
978            .expect("a server config");
979        config.alpn_protocols = vec![b"http/1.1".to_vec()];
980        let config = Arc::new(config);
981        let heads = Arc::new(Mutex::new(Vec::new()));
982        let seen = Arc::clone(&heads);
983        let stub = StubServer::start(move |tcp| {
984            let conn = rustls::ServerConnection::new(Arc::clone(&config)).expect("a connection");
985            let mut tls = rustls::StreamOwned::new(conn, tcp);
986            let mut head = Vec::new();
987            let mut byte = [0u8; 1];
988            while !head.ends_with(b"\r\n\r\n") {
989                match tls.read(&mut byte) {
990                    Ok(1) => head.push(byte[0]),
991                    _ => break,
992                }
993            }
994            if !head.is_empty() {
995                seen.lock()
996                    .expect("the lock")
997                    .push(String::from_utf8_lossy(&head).to_ascii_lowercase());
998            }
999            // A client that stops reading early closes; that is its
1000            // test's point, not a failure here.
1001            drop(tls.write_all(&reply));
1002            tls.conn.send_close_notify();
1003            drop(tls.flush());
1004        });
1005        let port = stub.address().port();
1006        (stub, port, heads)
1007    }
1008
1009    /// An HTTP/1.1 response with a JSON body.
1010    fn response(status: &str, body: &str) -> Vec<u8> {
1011        format!(
1012            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
1013            body.len()
1014        )
1015        .into_bytes()
1016    }
1017
1018    /// A client file's values for the server on `port`, trusting `ca`, with
1019    /// the token in a file of `mode`.
1020    fn client(dir: &Path, port: u16, ca: &Certificate, mode: u32) -> ClientConfig {
1021        use std::os::unix::fs::PermissionsExt;
1022        let ca_file = dir.join("ca.pem");
1023        std::fs::write(&ca_file, ca.cert.pem()).expect("write the CA");
1024        let key_file = dir.join("tui.token");
1025        std::fs::write(&key_file, format!("{TOKEN}\n")).expect("write the key file");
1026        std::fs::set_permissions(&key_file, std::fs::Permissions::from_mode(mode)).expect("chmod");
1027        ClientConfig {
1028            url: format!("https://localhost:{port}/"),
1029            key_file,
1030            ca: Some(ca_file),
1031        }
1032    }
1033
1034    #[test]
1035    fn the_key_request_carries_the_token_as_a_bearer_and_its_answer_is_read() {
1036        let cert = certificate();
1037        let (_stub, port, heads) = server(
1038            &cert,
1039            response(
1040                "200 OK",
1041                r#"{"id":"0011223344556677","tenant":"t_example","scopes":["read"]}"#,
1042            ),
1043        );
1044        let dir = tempfile::tempdir().expect("temp dir");
1045        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
1046        let info = api.key().expect("the key's answer");
1047        assert_eq!(
1048            info.tenant.as_deref(),
1049            Some("t_example"),
1050            "the answer is read"
1051        );
1052        let heads = heads.lock().expect("the lock");
1053        assert!(
1054            heads[0].starts_with("get /key http/1.1"),
1055            "the route: {}",
1056            heads[0]
1057        );
1058        assert!(
1059            heads[0].contains(&format!("authorization: bearer {TOKEN}")),
1060            "the token goes in the Authorization header"
1061        );
1062    }
1063
1064    /// An HTTP/1.1 response with `body` as `content_type`.
1065    fn typed(status: &str, content_type: &str, body: &[u8]) -> Vec<u8> {
1066        let mut made = format!(
1067            "HTTP/1.1 {status}\r\ncontent-type: {content_type}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
1068            body.len()
1069        )
1070        .into_bytes();
1071        made.extend_from_slice(body);
1072        made
1073    }
1074
1075    #[test]
1076    fn the_masked_request_asks_for_the_view_and_its_answer_is_read_as_lines() {
1077        let cert = certificate();
1078        let body = serde_json::to_vec(&crate::masked::summary("{}")).expect("JSON");
1079        let (_stub, port, heads) = server(&cert, typed("200 OK", "application/json", &body));
1080        let dir = tempfile::tempdir().expect("temp dir");
1081        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
1082        let lines = api.masked(VCON_UUID).expect("the masked view");
1083        assert!(
1084            lines.contains(&"Form          unsigned".to_owned()),
1085            "{lines:?}"
1086        );
1087        let heads = heads.lock().expect("the lock");
1088        assert!(
1089            heads[0].starts_with(&format!("get /vcons/{VCON_UUID}?view=masked http/1.1")),
1090            "the route: {}",
1091            heads[0]
1092        );
1093        assert!(
1094            heads[0].contains(&format!("authorization: bearer {TOKEN}")),
1095            "the token goes in the Authorization header"
1096        );
1097    }
1098
1099    #[test]
1100    fn the_reveal_request_names_its_part_and_a_gzipped_answer_is_inflated() {
1101        let cert = certificate();
1102        let mut gz = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
1103        gz.write_all(br#"{"subject":"Renewal call"}"#)
1104            .expect("gzip");
1105        let body = gz.finish().expect("gzip");
1106        let (_stub, port, heads) = server(&cert, typed("200 OK", "application/vcon+gzip", &body));
1107        let dir = tempfile::tempdir().expect("temp dir");
1108        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
1109        let text = api.reveal(VCON_UUID, Part::Subject).expect("the vCon");
1110        assert_eq!(text, r#"{"subject":"Renewal call"}"#, "inflated");
1111        let heads = heads.lock().expect("the lock");
1112        assert!(
1113            heads[0].starts_with(&format!("get /vcons/{VCON_UUID}?reveal=subject http/1.1")),
1114            "the route: {}",
1115            heads[0]
1116        );
1117    }
1118
1119    #[test]
1120    fn the_page_request_carries_the_limit_and_the_cursor() {
1121        let cert = certificate();
1122        let (_stub, port, heads) = server(&cert, response("200 OK", r#"{"next":null,"vcons":[]}"#));
1123        let dir = tempfile::tempdir().expect("temp dir");
1124        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
1125        api.page(Some("abc")).expect("a page");
1126        let heads = heads.lock().expect("the lock");
1127        assert!(
1128            heads[0].starts_with("get /vcons?limit=100&cursor=abc http/1.1"),
1129            "one slash, the limit and the cursor: {}",
1130            heads[0]
1131        );
1132    }
1133
1134    #[test]
1135    fn a_refusal_from_the_server_is_its_status_and_title() {
1136        let cert = certificate();
1137        let (_stub, port, _) = server(
1138            &cert,
1139            response(
1140                "401 Unauthorized",
1141                r#"{"title":"unauthorized","status":401}"#,
1142            ),
1143        );
1144        let dir = tempfile::tempdir().expect("temp dir");
1145        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
1146        assert_eq!(
1147            api.key(),
1148            Err(ApiError::Status(401, Some("unauthorized".to_owned()))),
1149            "the refusal is carried, not hidden"
1150        );
1151    }
1152
1153    #[test]
1154    fn a_certificate_the_ca_does_not_cover_gets_no_request_and_no_token() {
1155        let served = certificate();
1156        let trusted = certificate();
1157        let (_stub, port, heads) = server(&served, response("200 OK", "{}"));
1158        let dir = tempfile::tempdir().expect("temp dir");
1159        let api = HttpApi::new(&client(dir.path(), port, &trusted, 0o600)).expect("a client");
1160        let outcome = api.key();
1161        assert!(
1162            matches!(outcome, Err(ApiError::Untrusted(_))),
1163            "the certificate is verified: {outcome:?}"
1164        );
1165        assert_eq!(
1166            *heads.lock().expect("the lock"),
1167            Vec::<String>::new(),
1168            "nothing, the token least of all, is sent to a server that is not trusted"
1169        );
1170    }
1171
1172    // A certificate the client refuses: what the message says.
1173
1174    /// A certificate for `name` that is its own issuer, changed by `change`
1175    /// before it is signed.
1176    fn certificate_with(
1177        name: &str,
1178        change: impl FnOnce(&mut rcgen::CertificateParams),
1179    ) -> Certificate {
1180        let signing_key = rcgen::KeyPair::generate().expect("a key");
1181        let mut params = rcgen::CertificateParams::new(vec![name.to_owned()]).expect("params");
1182        change(&mut params);
1183        let cert = params.self_signed(&signing_key).expect("a certificate");
1184        rcgen::CertifiedKey { cert, signing_key }
1185    }
1186
1187    /// A self-signed certificate marked as a certificate authority, as
1188    /// `openssl req -x509` makes one by default.
1189    fn ca_certificate() -> Certificate {
1190        certificate_with("localhost", |params| {
1191            params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
1192        })
1193    }
1194
1195    /// What the UI is told when a server presents `served` and the client
1196    /// file trusts `trusted`, and the heads of the requests the server got.
1197    fn refusal(served: &Certificate, trusted: &Certificate) -> (String, Vec<String>) {
1198        let (_stub, port, heads) = server(served, response("200 OK", "{}"));
1199        let dir = tempfile::tempdir().expect("temp dir");
1200        let api = HttpApi::new(&client(dir.path(), port, trusted, 0o600)).expect("a client");
1201        let error = api.key().expect_err("the certificate is refused");
1202        let heads = heads.lock().expect("the lock").clone();
1203        (error.to_string(), heads)
1204    }
1205
1206    #[test]
1207    fn a_ca_certificate_as_the_servers_own_is_said_in_words() {
1208        let cert = ca_certificate();
1209        let (said, _) = refusal(&cert, &cert);
1210        assert!(
1211            said.starts_with("the server's certificate was refused: ") && said.contains("CA:TRUE"),
1212            "what is wrong: {said}"
1213        );
1214        assert!(
1215            !said.contains("OtherError") && !said.contains("CaUsedAsEndEntity"),
1216            "not the library's own text: {said}"
1217        );
1218    }
1219
1220    #[test]
1221    fn a_ca_certificate_as_the_servers_own_says_what_to_do() {
1222        let cert = ca_certificate();
1223        let (said, _) = refusal(&cert, &cert);
1224        assert!(
1225            said.contains("basicConstraints=CA:FALSE"),
1226            "the option that makes a certificate a server's: {said}"
1227        );
1228    }
1229
1230    #[test]
1231    fn a_ca_certificate_as_the_servers_own_is_still_refused_before_any_request() {
1232        let cert = ca_certificate();
1233        let (_, heads) = refusal(&cert, &cert);
1234        assert_eq!(
1235            heads,
1236            Vec::<String>::new(),
1237            "no request, and so no token, goes to that server"
1238        );
1239    }
1240
1241    #[test]
1242    fn a_certificate_from_an_issuer_the_client_does_not_know_says_to_set_ca() {
1243        let served = certificate_with("localhost", |params| {
1244            params
1245                .distinguished_name
1246                .push(rcgen::DnType::CommonName, "another issuer");
1247        });
1248        let (said, _) = refusal(&served, &certificate());
1249        assert!(
1250            said.starts_with("the server's certificate was refused: ")
1251                && said.contains("set ca in the client file"),
1252            "what is wrong and what to do: {said}"
1253        );
1254    }
1255
1256    #[test]
1257    fn a_replaced_certificate_of_the_same_name_says_to_set_ca() {
1258        // Two self-signed certificates with one subject: the trusted one
1259        // has the issuer's name and did not sign the served one.
1260        let (said, _) = refusal(&certificate(), &certificate());
1261        assert!(
1262            said.starts_with("the server's certificate was refused: ")
1263                && said.contains("set ca in the client file"),
1264            "what is wrong and what to do: {said}"
1265        );
1266        assert!(
1267            !said.contains("BadSignature"),
1268            "not the library's own text: {said}"
1269        );
1270    }
1271
1272    #[test]
1273    fn a_certificate_for_another_name_says_so() {
1274        let cert = certificate_with("other.example.com", |_| {});
1275        let (said, _) = refusal(&cert, &cert);
1276        assert!(
1277            said.starts_with("the server's certificate was refused: ")
1278                && said.contains("not for the name in url"),
1279            "what is wrong: {said}"
1280        );
1281    }
1282
1283    #[test]
1284    fn an_expired_certificate_says_so() {
1285        let cert = certificate_with("localhost", |params| {
1286            params.not_before = rcgen::date_time_ymd(2020, 1, 1);
1287            params.not_after = rcgen::date_time_ymd(2020, 2, 1);
1288        });
1289        let (said, _) = refusal(&cert, &cert);
1290        assert!(
1291            said.starts_with("the server's certificate was refused: ")
1292                && said.contains("it has expired"),
1293            "what is wrong: {said}"
1294        );
1295    }
1296
1297    #[test]
1298    fn a_certificate_not_valid_yet_says_so() {
1299        let cert = certificate_with("localhost", |params| {
1300            params.not_before = rcgen::date_time_ymd(2999, 1, 1);
1301            params.not_after = rcgen::date_time_ymd(2999, 2, 1);
1302        });
1303        let (said, _) = refusal(&cert, &cert);
1304        assert!(
1305            said.starts_with("the server's certificate was refused: ")
1306                && said.contains("it is not valid yet"),
1307            "what is wrong: {said}"
1308        );
1309    }
1310
1311    #[test]
1312    fn a_refused_certificate_message_never_holds_the_token() {
1313        let cert = ca_certificate();
1314        let (said, _) = refusal(&cert, &cert);
1315        assert!(!said.contains("secret"), "the token is not in the message");
1316    }
1317
1318    #[test]
1319    fn a_closed_port_is_not_called_a_certificate_refusal() {
1320        let cert = certificate();
1321        let port = {
1322            let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("binds");
1323            listener.local_addr().expect("an address").port()
1324        };
1325        let dir = tempfile::tempdir().expect("temp dir");
1326        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
1327        let said = api.key().expect_err("nothing listens").to_string();
1328        assert!(
1329            said.starts_with("the server did not answer: ") && !said.contains("certificate"),
1330            "no certificate was seen: {said}"
1331        );
1332    }
1333
1334    #[test]
1335    fn a_refused_certificate_shows_the_connection_as_not_connected() {
1336        use crate::tui::state::{Connection, State};
1337        let cert = ca_certificate();
1338        let (_stub, port, _) = server(&cert, response("200 OK", "{}"));
1339        let dir = tempfile::tempdir().expect("temp dir");
1340        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
1341        let (mut state, _) = State::new("https://localhost", (80, 24));
1342        // The key answers by hand; then the list is asked of the server.
1343        state.step(
1344            Event::KeyInfo(Ok(KeyInfo {
1345                id: "0011223344556677".to_owned(),
1346                tenant: Some("t_example".to_owned()),
1347                scopes: vec!["read".to_owned()],
1348            })),
1349            time::OffsetDateTime::UNIX_EPOCH,
1350        );
1351        state.step(
1352            Event::Page(api.page(None)),
1353            time::OffsetDateTime::UNIX_EPOCH,
1354        );
1355        assert!(
1356            matches!(&state.connection, Connection::Failed(why) if why.contains("certificate was refused")),
1357            "a server whose certificate is refused is not connected: {:?}",
1358            state.connection
1359        );
1360    }
1361
1362    #[test]
1363    fn a_port_nothing_listens_on_is_unreachable() {
1364        let cert = certificate();
1365        let port = {
1366            let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("binds");
1367            listener.local_addr().expect("an address").port()
1368        };
1369        let dir = tempfile::tempdir().expect("temp dir");
1370        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
1371        let outcome = api.page(None);
1372        assert!(
1373            matches!(outcome, Err(ApiError::Unreachable(_))),
1374            "no server, no answer: {outcome:?}"
1375        );
1376    }
1377
1378    #[test]
1379    fn an_answer_longer_than_the_limit_is_given_up() {
1380        let cert = certificate();
1381        let (_stub, port, _) = server(&cert, response("200 OK", &" ".repeat(2 * super::MAX_BODY)));
1382        let dir = tempfile::tempdir().expect("temp dir");
1383        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
1384        let outcome = api.page(None);
1385        assert!(
1386            matches!(&outcome, Err(ApiError::Malformed(why)) if why.contains("longer than")),
1387            "the body is not buffered whole: {outcome:?}"
1388        );
1389    }
1390
1391    #[test]
1392    fn a_server_that_never_answers_is_given_up_after_the_timeout() {
1393        let cert = certificate();
1394        // Connections are taken by the kernel and never answered.
1395        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("binds");
1396        let port = listener.local_addr().expect("an address").port();
1397        let dir = tempfile::tempdir().expect("temp dir");
1398        let mut api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
1399        api.timeout = Duration::from_millis(300);
1400        let outcome = api.key();
1401        assert!(
1402            matches!(&outcome, Err(ApiError::Unreachable(why)) if why.contains("no answer within")),
1403            "the request ends: {outcome:?}"
1404        );
1405        drop(listener);
1406    }
1407
1408    /// A client of a server whose kernel takes connections that are never
1409    /// answered, with a timeout far past the test's bounds: a request ends
1410    /// only by [`Api::close`]. Returns the listener too, which the test
1411    /// holds open.
1412    fn api_of_a_server_that_never_answers(
1413        dir: &std::path::Path,
1414    ) -> (HttpApi, std::net::TcpListener) {
1415        let cert = certificate();
1416        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("binds");
1417        let port = listener.local_addr().expect("an address").port();
1418        let mut api = HttpApi::new(&client(dir, port, &cert, 0o600)).expect("a client");
1419        api.timeout = Duration::from_secs(60);
1420        (api, listener)
1421    }
1422
1423    #[test]
1424    fn close_ends_a_request_under_way_at_once() {
1425        let dir = tempfile::tempdir().expect("temp dir");
1426        let (api, listener) = api_of_a_server_that_never_answers(dir.path());
1427        let api = std::sync::Arc::new(api);
1428        let request = {
1429            let api = std::sync::Arc::clone(&api);
1430            std::thread::spawn(move || api.key())
1431        };
1432        std::thread::sleep(Duration::from_millis(300));
1433        let closed_at = std::time::Instant::now();
1434        api.close();
1435        let outcome = request.join().expect("the request's thread ends");
1436        assert!(
1437            closed_at.elapsed() < Duration::from_secs(10),
1438            "the request ended when the client closed, not at its 60 s timeout: {:?}",
1439            closed_at.elapsed()
1440        );
1441        assert!(
1442            matches!(&outcome, Err(ApiError::Unreachable(why)) if why.contains("closed")),
1443            "the request says the client closed: {outcome:?}"
1444        );
1445        drop(listener);
1446    }
1447
1448    #[test]
1449    fn a_request_after_close_ends_without_waiting() {
1450        let dir = tempfile::tempdir().expect("temp dir");
1451        let (api, listener) = api_of_a_server_that_never_answers(dir.path());
1452        api.close();
1453        let began = std::time::Instant::now();
1454        let outcome = api.page(None);
1455        assert!(
1456            began.elapsed() < Duration::from_secs(10),
1457            "no request starts once the client is closed: {:?}",
1458            began.elapsed()
1459        );
1460        assert!(
1461            matches!(&outcome, Err(ApiError::Unreachable(why)) if why.contains("closed")),
1462            "the request says the client closed: {outcome:?}"
1463        );
1464        drop(listener);
1465    }
1466
1467    #[test]
1468    fn close_twice_is_the_same_as_once() {
1469        let dir = tempfile::tempdir().expect("temp dir");
1470        let (api, listener) = api_of_a_server_that_never_answers(dir.path());
1471        api.close();
1472        api.close();
1473        let outcome = api.masked(UUID_FOR_CLOSE);
1474        assert!(
1475            matches!(&outcome, Err(ApiError::Unreachable(why)) if why.contains("closed")),
1476            "still closed: {outcome:?}"
1477        );
1478        drop(listener);
1479    }
1480
1481    #[test]
1482    fn a_client_never_closed_answers_as_before() {
1483        let cert = certificate();
1484        let (_stub, port, _) = server(&cert, response("200 OK", r#"{"vcons":[],"next":null}"#));
1485        let dir = tempfile::tempdir().expect("temp dir");
1486        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
1487        let page = api.page(None).expect("a page");
1488        assert!(page.vcons.is_empty(), "the page was read: {page:?}");
1489    }
1490
1491    /// A vCon id for the requests a closed client refuses.
1492    const UUID_FOR_CLOSE: &str = "01a07da8-c2bb-83e5-b9a2-279e0d16bc00";
1493
1494    #[test]
1495    fn a_key_file_other_users_may_read_is_refused_before_any_request() {
1496        let cert = certificate();
1497        let dir = tempfile::tempdir().expect("temp dir");
1498        let refused = HttpApi::new(&client(dir.path(), 1, &cert, 0o644))
1499            .expect_err("a world-readable key file");
1500        assert!(refused.contains("key_file"), "the file is named: {refused}");
1501        assert!(!refused.contains(TOKEN), "the token is not in the message");
1502    }
1503
1504    #[test]
1505    fn a_ca_file_with_no_certificate_is_refused() {
1506        let cert = certificate();
1507        let dir = tempfile::tempdir().expect("temp dir");
1508        let config = client(dir.path(), 1, &cert, 0o600);
1509        std::fs::write(
1510            config.ca.as_ref().expect("a CA file"),
1511            "not a certificate\n",
1512        )
1513        .expect("overwrite the CA");
1514        let refused = HttpApi::new(&config).expect_err("no certificate to trust");
1515        assert!(
1516            refused.starts_with("ca: "),
1517            "the setting is named: {refused}"
1518        );
1519    }
1520
1521    #[test]
1522    fn the_debug_form_never_holds_the_token() {
1523        let cert = certificate();
1524        let dir = tempfile::tempdir().expect("temp dir");
1525        let api = HttpApi::new(&client(dir.path(), 1, &cert, 0o600)).expect("a client");
1526        let shown = format!("{api:?}");
1527        assert!(
1528            shown.contains("https://localhost:1"),
1529            "the address is shown: {shown}"
1530        );
1531        assert!(!shown.contains("secret"), "the token is not: {shown}");
1532    }
1533}