Skip to main content

vcon_server/tui/
client.rs

1//! The server's HTTP API as the terminal UI uses it: `GET /key` and
2//! `GET /vcons`, with one bearer key over TLS. The requests are behind
3//! [`Api`], so the UI is driven in tests without a network; the conversions
4//! a request makes (its path, and its answer to a value) are functions of
5//! their own.
6
7use std::error::Error;
8use std::time::Duration;
9
10use serde::Deserialize;
11use serde::de::DeserializeOwned;
12use zeroize::Zeroizing;
13
14use crate::mcp::stdio::{self, ClientConfig};
15use crate::tui::state::{ApiError, Effect, Event, KeyInfo, Page};
16
17/// The vCons asked for in one page.
18const PAGE: u16 = 100;
19/// How long one request may take, connection included.
20const TIMEOUT: Duration = Duration::from_secs(15);
21/// The most bytes read of one answer; a page of [`PAGE`] rows is far
22/// smaller.
23const MAX_BODY: usize = 1 << 20;
24
25/// The requests the UI makes.
26pub trait Api: Send + Sync {
27    /// `GET /key`: the key in use.
28    ///
29    /// # Errors
30    ///
31    /// [`ApiError`] when no answer arrived, or it was a refusal.
32    fn key(&self) -> Result<KeyInfo, ApiError>;
33
34    /// `GET /vcons`: one page, from `cursor` or from the start.
35    ///
36    /// # Errors
37    ///
38    /// [`ApiError`] when no answer arrived, or it was a refusal.
39    fn page(&self, cursor: Option<&str>) -> Result<Page, ApiError>;
40}
41
42/// Makes the request `effect` names and returns its answer as an event.
43pub fn perform(api: &dyn Api, effect: &Effect) -> Event {
44    match effect {
45        Effect::FetchKey => Event::KeyInfo(api.key()),
46        Effect::FetchPage(cursor) => Event::Page(api.page(cursor.as_deref())),
47    }
48}
49
50/// The server's address without trailing slashes, so a path can follow it.
51#[must_use]
52pub fn base(url: &str) -> String {
53    url.trim_end_matches('/').to_owned()
54}
55
56/// The path and query of one page of the list.
57#[must_use]
58pub fn page_path(cursor: Option<&str>) -> String {
59    let mut path = format!("/vcons?limit={PAGE}");
60    if let Some(cursor) = cursor {
61        path.push_str("&cursor=");
62        path.extend(form_urlencoded::byte_serialize(cursor.as_bytes()));
63    }
64    path
65}
66
67/// The value a `status` and `body` answer holds.
68///
69/// # Errors
70///
71/// [`ApiError::Status`] for any status but 200, with the title of the
72/// problem document if the body is one; [`ApiError::Malformed`] for a 200
73/// whose body is not a `T`.
74pub fn answer<T: DeserializeOwned>(status: u16, body: &[u8]) -> Result<T, ApiError> {
75    #[derive(Deserialize)]
76    struct Problem {
77        title: String,
78    }
79    if status == 200 {
80        return serde_json::from_slice(body).map_err(|e| ApiError::Malformed(e.to_string()));
81    }
82    let title = serde_json::from_slice::<Problem>(body)
83        .ok()
84        .map(|problem| problem.title);
85    Err(ApiError::Status(status, title))
86}
87
88/// A running server, reached over HTTPS with one key.
89pub struct HttpApi {
90    base: String,
91    token: Zeroizing<String>,
92    client: reqwest::Client,
93    runtime: tokio::runtime::Runtime,
94    /// How long one request may take; [`TIMEOUT`] outside tests.
95    timeout: Duration,
96}
97
98/// The address only: the token is never written.
99impl std::fmt::Debug for HttpApi {
100    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
101        f.debug_struct("HttpApi")
102            .field("base", &self.base)
103            .finish_non_exhaustive()
104    }
105}
106
107impl HttpApi {
108    /// The server a client file names. The key file is held to the one
109    /// secret-file rule, and the server's certificate is always verified:
110    /// against the file's `ca`, or the system's roots without it.
111    ///
112    /// # Errors
113    ///
114    /// A sentence naming the key file, the CA file or the runtime that
115    /// could not be used. It never holds the token.
116    pub fn new(config: &ClientConfig) -> Result<Self, String> {
117        let token = stdio::token(&config.key_file).map_err(|e| e.to_string())?;
118        let client = stdio::https_client(config.ca.as_deref()).map_err(|e| e.to_string())?;
119        let runtime = tokio::runtime::Builder::new_current_thread()
120            .enable_all()
121            .build()
122            .map_err(|e| format!("the runtime: {e}"))?;
123        Ok(Self {
124            base: base(&config.url),
125            token: Zeroizing::new(token),
126            client,
127            runtime,
128            timeout: TIMEOUT,
129        })
130    }
131
132    /// One GET of `path`, read as a `T`.
133    fn get<T: DeserializeOwned>(&self, path: &str) -> Result<T, ApiError> {
134        let url = format!("{}{path}", self.base);
135        let exchange = async {
136            let mut response = self
137                .client
138                .get(&url)
139                .bearer_auth(self.token.as_str())
140                .send()
141                .await
142                .map_err(|e| unreachable(&e))?;
143            let status = response.status().as_u16();
144            let mut body = Vec::new();
145            while let Some(chunk) = response.chunk().await.map_err(|e| unreachable(&e))? {
146                if body.len().saturating_add(chunk.len()) > MAX_BODY {
147                    return Err(ApiError::Malformed(format!(
148                        "it is longer than {MAX_BODY} bytes"
149                    )));
150                }
151                body.extend_from_slice(&chunk);
152            }
153            answer(status, &body)
154        };
155        self.runtime.block_on(async {
156            tokio::time::timeout(self.timeout, exchange)
157                .await
158                .unwrap_or_else(|_| {
159                    Err(ApiError::Unreachable(format!(
160                        "no answer within {} seconds",
161                        self.timeout.as_secs()
162                    )))
163                })
164        })
165    }
166}
167
168impl Api for HttpApi {
169    fn key(&self) -> Result<KeyInfo, ApiError> {
170        self.get("/key")
171    }
172
173    fn page(&self, cursor: Option<&str>) -> Result<Page, ApiError> {
174        self.get(&page_path(cursor))
175    }
176}
177
178/// What is wrong with a certificate the client refused, and what to do,
179/// for the refusals an operator can act on; `None` for any other, whose
180/// own text is shown.
181fn certificate_advice(error: &rustls::CertificateError) -> Option<&'static str> {
182    use rustls::CertificateError as Refused;
183    match error {
184        // rustls carries webpki's `CaUsedAsEndEntity` only as an opaque
185        // error, so its name in the debug form is all there is to match.
186        // The test against a server with such a certificate fails if a
187        // rustls release changes it.
188        Refused::Other(other) if format!("{other:?}").contains("CaUsedAsEndEntity") => Some(
189            "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",
190        ),
191        // A trusted certificate of the issuer's name that did not sign it
192        // is a bad signature: the server's certificate was replaced and
193        // the client file's `ca` still holds the old one.
194        Refused::UnknownIssuer | Refused::BadSignature => Some(
195            "no certificate this client trusts signed it; set ca in the client file to the server's current certificate authority",
196        ),
197        Refused::NotValidForName | Refused::NotValidForNameContext { .. } => Some(
198            "it is not for the name in url; use a name the certificate holds, or give the server a certificate for this one",
199        ),
200        Refused::Expired | Refused::ExpiredContext { .. } => {
201            Some("it has expired; renew the server's certificate, or correct this machine's clock")
202        }
203        Refused::NotValidYet | Refused::NotValidYetContext { .. } => Some(
204            "it is not valid yet; correct this machine's clock, or wait for the certificate's start",
205        ),
206        _ => None,
207    }
208}
209
210/// The TLS library's error at `cause`: the cause itself, or what the I/O
211/// errors around it carry. A failed handshake arrives as an I/O error that
212/// holds an I/O error that holds it, and `source` does not look inside one.
213fn tls_error<'a>(cause: &'a (dyn Error + 'static)) -> Option<&'a rustls::Error> {
214    let mut at = cause;
215    loop {
216        if let Some(found) = at.downcast_ref::<rustls::Error>() {
217            return Some(found);
218        }
219        at = at.downcast_ref::<std::io::Error>()?.get_ref()?;
220    }
221}
222
223/// A request that got no answer: a refused certificate in words an
224/// operator can act on, else the causes reqwest keeps below its own
225/// sentence (the refused connection, the handshake that failed).
226fn unreachable(error: &reqwest::Error) -> ApiError {
227    let mut why = error.to_string();
228    let mut cause = error.source();
229    while let Some(inner) = cause {
230        if let Some(rustls::Error::InvalidCertificate(refused)) = tls_error(inner)
231            && let Some(advice) = certificate_advice(refused)
232        {
233            return ApiError::Untrusted(advice.to_owned());
234        }
235        why.push_str(": ");
236        why.push_str(&inner.to_string());
237        cause = inner.source();
238    }
239    ApiError::Unreachable(why)
240}
241
242#[cfg(test)]
243mod tests {
244    use super::{Api, answer, base, page_path, perform};
245    use crate::tui::state::{ApiError, Effect, Event, KeyInfo, Page};
246
247    /// An API that answers from memory and records what it was asked.
248    struct Canned {
249        asked: std::sync::Mutex<Vec<String>>,
250    }
251
252    impl Api for Canned {
253        fn key(&self) -> Result<KeyInfo, ApiError> {
254            self.asked.lock().expect("the lock").push("key".to_owned());
255            Err(ApiError::Status(401, None))
256        }
257
258        fn page(&self, cursor: Option<&str>) -> Result<Page, ApiError> {
259            self.asked
260                .lock()
261                .expect("the lock")
262                .push(format!("page {cursor:?}"));
263            Ok(Page {
264                vcons: Vec::new(),
265                next: None,
266            })
267        }
268    }
269
270    // Success.
271
272    #[test]
273    fn a_key_answer_is_read() {
274        let info: KeyInfo = answer(
275            200,
276            br#"{"id":"0123456789abcdef","tenant":"t_example","scopes":["read","audit"]}"#,
277        )
278        .expect("a key answer");
279        assert_eq!(info.tenant.as_deref(), Some("t_example"), "the tenant");
280        assert_eq!(info.scopes, ["read", "audit"], "the scopes");
281    }
282
283    #[test]
284    fn a_page_answer_is_read_with_its_cursor() {
285        let page: Page = answer(
286            200,
287            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"}]}"#,
288        )
289        .expect("a page");
290        assert_eq!(page.next.as_deref(), Some("GOHD"), "the cursor");
291        assert_eq!(
292            page.vcons[0].uuid, "01a07da8-c2bb-83e5-b9a2-279e0d16bc46",
293            "the row"
294        );
295    }
296
297    #[test]
298    fn the_first_page_is_asked_for_without_a_cursor() {
299        assert_eq!(page_path(None), "/vcons?limit=100", "the first page");
300    }
301
302    #[test]
303    fn each_effect_is_one_request_and_its_answer_one_event() {
304        let api = Canned {
305            asked: std::sync::Mutex::default(),
306        };
307        let page = perform(&api, &Effect::FetchPage(Some("c".to_owned())));
308        assert!(
309            matches!(page, Event::Page(Ok(_))),
310            "a page's answer is a page event"
311        );
312        let key = perform(&api, &Effect::FetchKey);
313        assert_eq!(
314            key,
315            Event::KeyInfo(Err(ApiError::Status(401, None))),
316            "a refusal is carried"
317        );
318        assert_eq!(
319            *api.asked.lock().expect("the lock"),
320            ["page Some(\"c\")", "key"],
321            "one request each, with the cursor"
322        );
323    }
324
325    // Failure.
326
327    #[test]
328    fn a_refusal_carries_its_status_and_the_problems_title() {
329        let refused: Result<Page, _> = answer(
330            403,
331            br#"{"type":"https://vcon-server.com/problems/forbidden/","title":"forbidden","status":403}"#,
332        );
333        assert_eq!(
334            refused,
335            Err(ApiError::Status(403, Some("forbidden".to_owned()))),
336            "the title of the problem document"
337        );
338    }
339
340    #[test]
341    fn a_refusal_without_a_problem_document_carries_only_its_status() {
342        let refused: Result<Page, _> = answer(502, b"<html>bad gateway</html>");
343        assert_eq!(
344            refused,
345            Err(ApiError::Status(502, None)),
346            "a proxy's page is not shown"
347        );
348    }
349
350    #[test]
351    fn a_200_that_is_not_the_documented_json_is_malformed() {
352        let odd: Result<Page, _> = answer(200, b"{\"vcons\": 7}");
353        assert!(
354            matches!(odd, Err(ApiError::Malformed(_))),
355            "not a page: {odd:?}"
356        );
357    }
358
359    // Edge.
360
361    #[test]
362    fn a_cursor_is_percent_encoded() {
363        assert_eq!(
364            page_path(Some("a+b/c=&d")),
365            "/vcons?limit=100&cursor=a%2Bb%2Fc%3D%26d",
366            "a cursor cannot add a parameter"
367        );
368    }
369
370    #[test]
371    fn the_address_loses_its_trailing_slashes() {
372        assert_eq!(
373            base("https://vcon.example.com:8443/"),
374            "https://vcon.example.com:8443",
375            "one"
376        );
377        assert_eq!(
378            base("https://vcon.example.com"),
379            "https://vcon.example.com",
380            "none"
381        );
382    }
383
384    #[test]
385    fn an_operator_keys_null_tenant_is_none() {
386        let info: KeyInfo = answer(
387            200,
388            br#"{"id":"0123456789abcdef","tenant":null,"scopes":["admin"]}"#,
389        )
390        .expect("a key answer");
391        assert_eq!(info.tenant, None, "null is no tenant");
392    }
393
394    #[test]
395    fn a_last_page_has_no_cursor() {
396        let page: Page = answer(200, br#"{"next":null,"vcons":[]}"#).expect("a page");
397        assert_eq!(
398            page,
399            Page {
400                vcons: Vec::new(),
401                next: None
402            },
403            "empty and last"
404        );
405    }
406
407    // The HTTPS client, against a TLS server on loopback.
408
409    use std::io::{Read, Write};
410    use std::path::Path;
411    use std::sync::{Arc, Mutex};
412    use std::time::Duration;
413
414    use super::HttpApi;
415    use crate::mcp::stdio::ClientConfig;
416
417    const TOKEN: &str = "vcs_0011223344556677_secret";
418
419    type Certificate = rcgen::CertifiedKey<rcgen::KeyPair>;
420
421    fn certificate() -> Certificate {
422        rcgen::generate_simple_self_signed(vec!["localhost".to_owned()]).expect("a certificate")
423    }
424
425    /// A TLS server for one test: it answers every request with `reply`, a
426    /// whole HTTP/1.1 response, and keeps each request's head.
427    fn server(cert: &Certificate, reply: Vec<u8>) -> (u16, Arc<Mutex<Vec<String>>>) {
428        let chain = vec![cert.cert.der().clone()];
429        let key = rustls::pki_types::PrivateKeyDer::Pkcs8(cert.signing_key.serialize_der().into());
430        let provider = Arc::new(rustls::crypto::aws_lc_rs::default_provider());
431        let mut config = rustls::ServerConfig::builder_with_provider(provider)
432            .with_safe_default_protocol_versions()
433            .expect("versions")
434            .with_no_client_auth()
435            .with_single_cert(chain, key)
436            .expect("a server config");
437        config.alpn_protocols = vec![b"http/1.1".to_vec()];
438        let config = Arc::new(config);
439        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("binds");
440        let port = listener.local_addr().expect("an address").port();
441        let heads = Arc::new(Mutex::new(Vec::new()));
442        let seen = Arc::clone(&heads);
443        std::thread::spawn(move || {
444            for stream in listener.incoming() {
445                let Ok(tcp) = stream else { return };
446                let conn =
447                    rustls::ServerConnection::new(Arc::clone(&config)).expect("a connection");
448                let mut tls = rustls::StreamOwned::new(conn, tcp);
449                let mut head = Vec::new();
450                let mut byte = [0u8; 1];
451                while !head.ends_with(b"\r\n\r\n") {
452                    match tls.read(&mut byte) {
453                        Ok(1) => head.push(byte[0]),
454                        _ => break,
455                    }
456                }
457                if !head.is_empty() {
458                    seen.lock()
459                        .expect("the lock")
460                        .push(String::from_utf8_lossy(&head).to_ascii_lowercase());
461                }
462                // A client that stops reading early closes; that is its
463                // test's point, not a failure here.
464                drop(tls.write_all(&reply));
465                tls.conn.send_close_notify();
466                drop(tls.flush());
467            }
468        });
469        (port, heads)
470    }
471
472    /// An HTTP/1.1 response with a JSON body.
473    fn response(status: &str, body: &str) -> Vec<u8> {
474        format!(
475            "HTTP/1.1 {status}\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{body}",
476            body.len()
477        )
478        .into_bytes()
479    }
480
481    /// A client file's values for the server on `port`, trusting `ca`, with
482    /// the token in a file of `mode`.
483    fn client(dir: &Path, port: u16, ca: &Certificate, mode: u32) -> ClientConfig {
484        use std::os::unix::fs::PermissionsExt;
485        let ca_file = dir.join("ca.pem");
486        std::fs::write(&ca_file, ca.cert.pem()).expect("write the CA");
487        let key_file = dir.join("tui.token");
488        std::fs::write(&key_file, format!("{TOKEN}\n")).expect("write the key file");
489        std::fs::set_permissions(&key_file, std::fs::Permissions::from_mode(mode)).expect("chmod");
490        ClientConfig {
491            url: format!("https://localhost:{port}/"),
492            key_file,
493            ca: Some(ca_file),
494        }
495    }
496
497    #[test]
498    fn the_key_request_carries_the_token_as_a_bearer_and_its_answer_is_read() {
499        let cert = certificate();
500        let (port, heads) = server(
501            &cert,
502            response(
503                "200 OK",
504                r#"{"id":"0011223344556677","tenant":"t_example","scopes":["read"]}"#,
505            ),
506        );
507        let dir = tempfile::tempdir().expect("temp dir");
508        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
509        let info = api.key().expect("the key's answer");
510        assert_eq!(
511            info.tenant.as_deref(),
512            Some("t_example"),
513            "the answer is read"
514        );
515        let heads = heads.lock().expect("the lock");
516        assert!(
517            heads[0].starts_with("get /key http/1.1"),
518            "the route: {}",
519            heads[0]
520        );
521        assert!(
522            heads[0].contains(&format!("authorization: bearer {TOKEN}")),
523            "the token goes in the Authorization header: {}",
524            heads[0]
525        );
526    }
527
528    #[test]
529    fn the_page_request_carries_the_limit_and_the_cursor() {
530        let cert = certificate();
531        let (port, heads) = server(&cert, response("200 OK", r#"{"next":null,"vcons":[]}"#));
532        let dir = tempfile::tempdir().expect("temp dir");
533        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
534        api.page(Some("abc")).expect("a page");
535        let heads = heads.lock().expect("the lock");
536        assert!(
537            heads[0].starts_with("get /vcons?limit=100&cursor=abc http/1.1"),
538            "one slash, the limit and the cursor: {}",
539            heads[0]
540        );
541    }
542
543    #[test]
544    fn a_refusal_from_the_server_is_its_status_and_title() {
545        let cert = certificate();
546        let (port, _) = server(
547            &cert,
548            response(
549                "401 Unauthorized",
550                r#"{"title":"unauthorized","status":401}"#,
551            ),
552        );
553        let dir = tempfile::tempdir().expect("temp dir");
554        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
555        assert_eq!(
556            api.key(),
557            Err(ApiError::Status(401, Some("unauthorized".to_owned()))),
558            "the refusal is carried, not hidden"
559        );
560    }
561
562    #[test]
563    fn a_certificate_the_ca_does_not_cover_gets_no_request_and_no_token() {
564        let served = certificate();
565        let trusted = certificate();
566        let (port, heads) = server(&served, response("200 OK", "{}"));
567        let dir = tempfile::tempdir().expect("temp dir");
568        let api = HttpApi::new(&client(dir.path(), port, &trusted, 0o600)).expect("a client");
569        let outcome = api.key();
570        assert!(
571            matches!(outcome, Err(ApiError::Untrusted(_))),
572            "the certificate is verified: {outcome:?}"
573        );
574        assert_eq!(
575            *heads.lock().expect("the lock"),
576            Vec::<String>::new(),
577            "nothing, the token least of all, is sent to a server that is not trusted"
578        );
579    }
580
581    // A certificate the client refuses: what the message says.
582
583    /// A certificate for `name` that is its own issuer, changed by `change`
584    /// before it is signed.
585    fn certificate_with(
586        name: &str,
587        change: impl FnOnce(&mut rcgen::CertificateParams),
588    ) -> Certificate {
589        let signing_key = rcgen::KeyPair::generate().expect("a key");
590        let mut params = rcgen::CertificateParams::new(vec![name.to_owned()]).expect("params");
591        change(&mut params);
592        let cert = params.self_signed(&signing_key).expect("a certificate");
593        rcgen::CertifiedKey { cert, signing_key }
594    }
595
596    /// A self-signed certificate marked as a certificate authority, as
597    /// `openssl req -x509` makes one by default.
598    fn ca_certificate() -> Certificate {
599        certificate_with("localhost", |params| {
600            params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
601        })
602    }
603
604    /// What the UI is told when a server presents `served` and the client
605    /// file trusts `trusted`, and the heads of the requests the server got.
606    fn refusal(served: &Certificate, trusted: &Certificate) -> (String, Vec<String>) {
607        let (port, heads) = server(served, response("200 OK", "{}"));
608        let dir = tempfile::tempdir().expect("temp dir");
609        let api = HttpApi::new(&client(dir.path(), port, trusted, 0o600)).expect("a client");
610        let error = api.key().expect_err("the certificate is refused");
611        let heads = heads.lock().expect("the lock").clone();
612        (error.to_string(), heads)
613    }
614
615    #[test]
616    fn a_ca_certificate_as_the_servers_own_is_said_in_words() {
617        let cert = ca_certificate();
618        let (said, _) = refusal(&cert, &cert);
619        assert!(
620            said.starts_with("the server's certificate was refused: ") && said.contains("CA:TRUE"),
621            "what is wrong: {said}"
622        );
623        assert!(
624            !said.contains("OtherError") && !said.contains("CaUsedAsEndEntity"),
625            "not the library's own text: {said}"
626        );
627    }
628
629    #[test]
630    fn a_ca_certificate_as_the_servers_own_says_what_to_do() {
631        let cert = ca_certificate();
632        let (said, _) = refusal(&cert, &cert);
633        assert!(
634            said.contains("basicConstraints=CA:FALSE"),
635            "the option that makes a certificate a server's: {said}"
636        );
637    }
638
639    #[test]
640    fn a_ca_certificate_as_the_servers_own_is_still_refused_before_any_request() {
641        let cert = ca_certificate();
642        let (_, heads) = refusal(&cert, &cert);
643        assert_eq!(
644            heads,
645            Vec::<String>::new(),
646            "no request, and so no token, goes to that server"
647        );
648    }
649
650    #[test]
651    fn a_certificate_from_an_issuer_the_client_does_not_know_says_to_set_ca() {
652        let served = certificate_with("localhost", |params| {
653            params
654                .distinguished_name
655                .push(rcgen::DnType::CommonName, "another issuer");
656        });
657        let (said, _) = refusal(&served, &certificate());
658        assert!(
659            said.starts_with("the server's certificate was refused: ")
660                && said.contains("set ca in the client file"),
661            "what is wrong and what to do: {said}"
662        );
663    }
664
665    #[test]
666    fn a_replaced_certificate_of_the_same_name_says_to_set_ca() {
667        // Two self-signed certificates with one subject: the trusted one
668        // has the issuer's name and did not sign the served one.
669        let (said, _) = refusal(&certificate(), &certificate());
670        assert!(
671            said.starts_with("the server's certificate was refused: ")
672                && said.contains("set ca in the client file"),
673            "what is wrong and what to do: {said}"
674        );
675        assert!(
676            !said.contains("BadSignature"),
677            "not the library's own text: {said}"
678        );
679    }
680
681    #[test]
682    fn a_certificate_for_another_name_says_so() {
683        let cert = certificate_with("other.example.com", |_| {});
684        let (said, _) = refusal(&cert, &cert);
685        assert!(
686            said.starts_with("the server's certificate was refused: ")
687                && said.contains("not for the name in url"),
688            "what is wrong: {said}"
689        );
690    }
691
692    #[test]
693    fn an_expired_certificate_says_so() {
694        let cert = certificate_with("localhost", |params| {
695            params.not_before = rcgen::date_time_ymd(2020, 1, 1);
696            params.not_after = rcgen::date_time_ymd(2020, 2, 1);
697        });
698        let (said, _) = refusal(&cert, &cert);
699        assert!(
700            said.starts_with("the server's certificate was refused: ")
701                && said.contains("it has expired"),
702            "what is wrong: {said}"
703        );
704    }
705
706    #[test]
707    fn a_certificate_not_valid_yet_says_so() {
708        let cert = certificate_with("localhost", |params| {
709            params.not_before = rcgen::date_time_ymd(2999, 1, 1);
710            params.not_after = rcgen::date_time_ymd(2999, 2, 1);
711        });
712        let (said, _) = refusal(&cert, &cert);
713        assert!(
714            said.starts_with("the server's certificate was refused: ")
715                && said.contains("it is not valid yet"),
716            "what is wrong: {said}"
717        );
718    }
719
720    #[test]
721    fn a_refused_certificate_message_never_holds_the_token() {
722        let cert = ca_certificate();
723        let (said, _) = refusal(&cert, &cert);
724        assert!(
725            !said.contains("secret"),
726            "the token is not in the message: {said}"
727        );
728    }
729
730    #[test]
731    fn a_closed_port_is_not_called_a_certificate_refusal() {
732        let cert = certificate();
733        let port = {
734            let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("binds");
735            listener.local_addr().expect("an address").port()
736        };
737        let dir = tempfile::tempdir().expect("temp dir");
738        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
739        let said = api.key().expect_err("nothing listens").to_string();
740        assert!(
741            said.starts_with("the server did not answer: ") && !said.contains("certificate"),
742            "no certificate was seen: {said}"
743        );
744    }
745
746    #[test]
747    fn a_refused_certificate_shows_the_connection_as_not_connected() {
748        use crate::tui::state::{Connection, State};
749        let cert = ca_certificate();
750        let (port, _) = server(&cert, response("200 OK", "{}"));
751        let dir = tempfile::tempdir().expect("temp dir");
752        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
753        let (mut state, _) = State::new("https://localhost", (80, 24));
754        // The key answers by hand; then the list is asked of the server.
755        state.step(
756            Event::KeyInfo(Ok(KeyInfo {
757                id: "0011223344556677".to_owned(),
758                tenant: Some("t_example".to_owned()),
759                scopes: vec!["read".to_owned()],
760            })),
761            time::OffsetDateTime::UNIX_EPOCH,
762        );
763        state.step(
764            Event::Page(api.page(None)),
765            time::OffsetDateTime::UNIX_EPOCH,
766        );
767        assert!(
768            matches!(&state.connection, Connection::Failed(why) if why.contains("certificate was refused")),
769            "a server whose certificate is refused is not connected: {:?}",
770            state.connection
771        );
772    }
773
774    #[test]
775    fn a_port_nothing_listens_on_is_unreachable() {
776        let cert = certificate();
777        let port = {
778            let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("binds");
779            listener.local_addr().expect("an address").port()
780        };
781        let dir = tempfile::tempdir().expect("temp dir");
782        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
783        let outcome = api.page(None);
784        assert!(
785            matches!(outcome, Err(ApiError::Unreachable(_))),
786            "no server, no answer: {outcome:?}"
787        );
788    }
789
790    #[test]
791    fn an_answer_longer_than_the_limit_is_given_up() {
792        let cert = certificate();
793        let (port, _) = server(&cert, response("200 OK", &" ".repeat(2 * super::MAX_BODY)));
794        let dir = tempfile::tempdir().expect("temp dir");
795        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
796        let outcome = api.page(None);
797        assert!(
798            matches!(&outcome, Err(ApiError::Malformed(why)) if why.contains("longer than")),
799            "the body is not buffered whole: {outcome:?}"
800        );
801    }
802
803    #[test]
804    fn a_server_that_never_answers_is_given_up_after_the_timeout() {
805        let cert = certificate();
806        // Connections are taken by the kernel and never answered.
807        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("binds");
808        let port = listener.local_addr().expect("an address").port();
809        let dir = tempfile::tempdir().expect("temp dir");
810        let mut api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
811        api.timeout = Duration::from_millis(300);
812        let outcome = api.key();
813        assert!(
814            matches!(&outcome, Err(ApiError::Unreachable(why)) if why.contains("no answer within")),
815            "the request ends: {outcome:?}"
816        );
817        drop(listener);
818    }
819
820    #[test]
821    fn a_key_file_other_users_may_read_is_refused_before_any_request() {
822        let cert = certificate();
823        let dir = tempfile::tempdir().expect("temp dir");
824        let refused = HttpApi::new(&client(dir.path(), 1, &cert, 0o644))
825            .expect_err("a world-readable key file");
826        assert!(refused.contains("key_file"), "the file is named: {refused}");
827        assert!(
828            !refused.contains(TOKEN),
829            "the token is not in the message: {refused}"
830        );
831    }
832
833    #[test]
834    fn a_ca_file_with_no_certificate_is_refused() {
835        let cert = certificate();
836        let dir = tempfile::tempdir().expect("temp dir");
837        let config = client(dir.path(), 1, &cert, 0o600);
838        std::fs::write(
839            config.ca.as_ref().expect("a CA file"),
840            "not a certificate\n",
841        )
842        .expect("overwrite the CA");
843        let refused = HttpApi::new(&config).expect_err("no certificate to trust");
844        assert!(
845            refused.starts_with("ca: "),
846            "the setting is named: {refused}"
847        );
848    }
849
850    #[test]
851    fn the_debug_form_never_holds_the_token() {
852        let cert = certificate();
853        let dir = tempfile::tempdir().expect("temp dir");
854        let api = HttpApi::new(&client(dir.path(), 1, &cert, 0o600)).expect("a client");
855        let shown = format!("{api:?}");
856        assert!(
857            shown.contains("https://localhost:1"),
858            "the address is shown: {shown}"
859        );
860        assert!(!shown.contains("secret"), "the token is not: {shown}");
861    }
862}