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.
18pub(crate) const PAGE: u16 = 100;
19/// How long one request may take, connection included.
20pub(crate) const 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(|_| Err(no_answer(self.timeout)))
159        })
160    }
161}
162
163/// What a request that took longer than `timeout` gives.
164pub(crate) fn no_answer(timeout: Duration) -> ApiError {
165    ApiError::Unreachable(format!("no answer within {} seconds", timeout.as_secs()))
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.
181pub(crate) fn 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        );
525    }
526
527    #[test]
528    fn the_page_request_carries_the_limit_and_the_cursor() {
529        let cert = certificate();
530        let (port, heads) = server(&cert, response("200 OK", r#"{"next":null,"vcons":[]}"#));
531        let dir = tempfile::tempdir().expect("temp dir");
532        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
533        api.page(Some("abc")).expect("a page");
534        let heads = heads.lock().expect("the lock");
535        assert!(
536            heads[0].starts_with("get /vcons?limit=100&cursor=abc http/1.1"),
537            "one slash, the limit and the cursor: {}",
538            heads[0]
539        );
540    }
541
542    #[test]
543    fn a_refusal_from_the_server_is_its_status_and_title() {
544        let cert = certificate();
545        let (port, _) = server(
546            &cert,
547            response(
548                "401 Unauthorized",
549                r#"{"title":"unauthorized","status":401}"#,
550            ),
551        );
552        let dir = tempfile::tempdir().expect("temp dir");
553        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
554        assert_eq!(
555            api.key(),
556            Err(ApiError::Status(401, Some("unauthorized".to_owned()))),
557            "the refusal is carried, not hidden"
558        );
559    }
560
561    #[test]
562    fn a_certificate_the_ca_does_not_cover_gets_no_request_and_no_token() {
563        let served = certificate();
564        let trusted = certificate();
565        let (port, heads) = server(&served, response("200 OK", "{}"));
566        let dir = tempfile::tempdir().expect("temp dir");
567        let api = HttpApi::new(&client(dir.path(), port, &trusted, 0o600)).expect("a client");
568        let outcome = api.key();
569        assert!(
570            matches!(outcome, Err(ApiError::Untrusted(_))),
571            "the certificate is verified: {outcome:?}"
572        );
573        assert_eq!(
574            *heads.lock().expect("the lock"),
575            Vec::<String>::new(),
576            "nothing, the token least of all, is sent to a server that is not trusted"
577        );
578    }
579
580    // A certificate the client refuses: what the message says.
581
582    /// A certificate for `name` that is its own issuer, changed by `change`
583    /// before it is signed.
584    fn certificate_with(
585        name: &str,
586        change: impl FnOnce(&mut rcgen::CertificateParams),
587    ) -> Certificate {
588        let signing_key = rcgen::KeyPair::generate().expect("a key");
589        let mut params = rcgen::CertificateParams::new(vec![name.to_owned()]).expect("params");
590        change(&mut params);
591        let cert = params.self_signed(&signing_key).expect("a certificate");
592        rcgen::CertifiedKey { cert, signing_key }
593    }
594
595    /// A self-signed certificate marked as a certificate authority, as
596    /// `openssl req -x509` makes one by default.
597    fn ca_certificate() -> Certificate {
598        certificate_with("localhost", |params| {
599            params.is_ca = rcgen::IsCa::Ca(rcgen::BasicConstraints::Unconstrained);
600        })
601    }
602
603    /// What the UI is told when a server presents `served` and the client
604    /// file trusts `trusted`, and the heads of the requests the server got.
605    fn refusal(served: &Certificate, trusted: &Certificate) -> (String, Vec<String>) {
606        let (port, heads) = server(served, response("200 OK", "{}"));
607        let dir = tempfile::tempdir().expect("temp dir");
608        let api = HttpApi::new(&client(dir.path(), port, trusted, 0o600)).expect("a client");
609        let error = api.key().expect_err("the certificate is refused");
610        let heads = heads.lock().expect("the lock").clone();
611        (error.to_string(), heads)
612    }
613
614    #[test]
615    fn a_ca_certificate_as_the_servers_own_is_said_in_words() {
616        let cert = ca_certificate();
617        let (said, _) = refusal(&cert, &cert);
618        assert!(
619            said.starts_with("the server's certificate was refused: ") && said.contains("CA:TRUE"),
620            "what is wrong: {said}"
621        );
622        assert!(
623            !said.contains("OtherError") && !said.contains("CaUsedAsEndEntity"),
624            "not the library's own text: {said}"
625        );
626    }
627
628    #[test]
629    fn a_ca_certificate_as_the_servers_own_says_what_to_do() {
630        let cert = ca_certificate();
631        let (said, _) = refusal(&cert, &cert);
632        assert!(
633            said.contains("basicConstraints=CA:FALSE"),
634            "the option that makes a certificate a server's: {said}"
635        );
636    }
637
638    #[test]
639    fn a_ca_certificate_as_the_servers_own_is_still_refused_before_any_request() {
640        let cert = ca_certificate();
641        let (_, heads) = refusal(&cert, &cert);
642        assert_eq!(
643            heads,
644            Vec::<String>::new(),
645            "no request, and so no token, goes to that server"
646        );
647    }
648
649    #[test]
650    fn a_certificate_from_an_issuer_the_client_does_not_know_says_to_set_ca() {
651        let served = certificate_with("localhost", |params| {
652            params
653                .distinguished_name
654                .push(rcgen::DnType::CommonName, "another issuer");
655        });
656        let (said, _) = refusal(&served, &certificate());
657        assert!(
658            said.starts_with("the server's certificate was refused: ")
659                && said.contains("set ca in the client file"),
660            "what is wrong and what to do: {said}"
661        );
662    }
663
664    #[test]
665    fn a_replaced_certificate_of_the_same_name_says_to_set_ca() {
666        // Two self-signed certificates with one subject: the trusted one
667        // has the issuer's name and did not sign the served one.
668        let (said, _) = refusal(&certificate(), &certificate());
669        assert!(
670            said.starts_with("the server's certificate was refused: ")
671                && said.contains("set ca in the client file"),
672            "what is wrong and what to do: {said}"
673        );
674        assert!(
675            !said.contains("BadSignature"),
676            "not the library's own text: {said}"
677        );
678    }
679
680    #[test]
681    fn a_certificate_for_another_name_says_so() {
682        let cert = certificate_with("other.example.com", |_| {});
683        let (said, _) = refusal(&cert, &cert);
684        assert!(
685            said.starts_with("the server's certificate was refused: ")
686                && said.contains("not for the name in url"),
687            "what is wrong: {said}"
688        );
689    }
690
691    #[test]
692    fn an_expired_certificate_says_so() {
693        let cert = certificate_with("localhost", |params| {
694            params.not_before = rcgen::date_time_ymd(2020, 1, 1);
695            params.not_after = rcgen::date_time_ymd(2020, 2, 1);
696        });
697        let (said, _) = refusal(&cert, &cert);
698        assert!(
699            said.starts_with("the server's certificate was refused: ")
700                && said.contains("it has expired"),
701            "what is wrong: {said}"
702        );
703    }
704
705    #[test]
706    fn a_certificate_not_valid_yet_says_so() {
707        let cert = certificate_with("localhost", |params| {
708            params.not_before = rcgen::date_time_ymd(2999, 1, 1);
709            params.not_after = rcgen::date_time_ymd(2999, 2, 1);
710        });
711        let (said, _) = refusal(&cert, &cert);
712        assert!(
713            said.starts_with("the server's certificate was refused: ")
714                && said.contains("it is not valid yet"),
715            "what is wrong: {said}"
716        );
717    }
718
719    #[test]
720    fn a_refused_certificate_message_never_holds_the_token() {
721        let cert = ca_certificate();
722        let (said, _) = refusal(&cert, &cert);
723        assert!(!said.contains("secret"), "the token is not in the message");
724    }
725
726    #[test]
727    fn a_closed_port_is_not_called_a_certificate_refusal() {
728        let cert = certificate();
729        let port = {
730            let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("binds");
731            listener.local_addr().expect("an address").port()
732        };
733        let dir = tempfile::tempdir().expect("temp dir");
734        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
735        let said = api.key().expect_err("nothing listens").to_string();
736        assert!(
737            said.starts_with("the server did not answer: ") && !said.contains("certificate"),
738            "no certificate was seen: {said}"
739        );
740    }
741
742    #[test]
743    fn a_refused_certificate_shows_the_connection_as_not_connected() {
744        use crate::tui::state::{Connection, State};
745        let cert = ca_certificate();
746        let (port, _) = server(&cert, response("200 OK", "{}"));
747        let dir = tempfile::tempdir().expect("temp dir");
748        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
749        let (mut state, _) = State::new("https://localhost", (80, 24));
750        // The key answers by hand; then the list is asked of the server.
751        state.step(
752            Event::KeyInfo(Ok(KeyInfo {
753                id: "0011223344556677".to_owned(),
754                tenant: Some("t_example".to_owned()),
755                scopes: vec!["read".to_owned()],
756            })),
757            time::OffsetDateTime::UNIX_EPOCH,
758        );
759        state.step(
760            Event::Page(api.page(None)),
761            time::OffsetDateTime::UNIX_EPOCH,
762        );
763        assert!(
764            matches!(&state.connection, Connection::Failed(why) if why.contains("certificate was refused")),
765            "a server whose certificate is refused is not connected: {:?}",
766            state.connection
767        );
768    }
769
770    #[test]
771    fn a_port_nothing_listens_on_is_unreachable() {
772        let cert = certificate();
773        let port = {
774            let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("binds");
775            listener.local_addr().expect("an address").port()
776        };
777        let dir = tempfile::tempdir().expect("temp dir");
778        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
779        let outcome = api.page(None);
780        assert!(
781            matches!(outcome, Err(ApiError::Unreachable(_))),
782            "no server, no answer: {outcome:?}"
783        );
784    }
785
786    #[test]
787    fn an_answer_longer_than_the_limit_is_given_up() {
788        let cert = certificate();
789        let (port, _) = server(&cert, response("200 OK", &" ".repeat(2 * super::MAX_BODY)));
790        let dir = tempfile::tempdir().expect("temp dir");
791        let api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
792        let outcome = api.page(None);
793        assert!(
794            matches!(&outcome, Err(ApiError::Malformed(why)) if why.contains("longer than")),
795            "the body is not buffered whole: {outcome:?}"
796        );
797    }
798
799    #[test]
800    fn a_server_that_never_answers_is_given_up_after_the_timeout() {
801        let cert = certificate();
802        // Connections are taken by the kernel and never answered.
803        let listener = std::net::TcpListener::bind("127.0.0.1:0").expect("binds");
804        let port = listener.local_addr().expect("an address").port();
805        let dir = tempfile::tempdir().expect("temp dir");
806        let mut api = HttpApi::new(&client(dir.path(), port, &cert, 0o600)).expect("a client");
807        api.timeout = Duration::from_millis(300);
808        let outcome = api.key();
809        assert!(
810            matches!(&outcome, Err(ApiError::Unreachable(why)) if why.contains("no answer within")),
811            "the request ends: {outcome:?}"
812        );
813        drop(listener);
814    }
815
816    #[test]
817    fn a_key_file_other_users_may_read_is_refused_before_any_request() {
818        let cert = certificate();
819        let dir = tempfile::tempdir().expect("temp dir");
820        let refused = HttpApi::new(&client(dir.path(), 1, &cert, 0o644))
821            .expect_err("a world-readable key file");
822        assert!(refused.contains("key_file"), "the file is named: {refused}");
823        assert!(!refused.contains(TOKEN), "the token is not in the message");
824    }
825
826    #[test]
827    fn a_ca_file_with_no_certificate_is_refused() {
828        let cert = certificate();
829        let dir = tempfile::tempdir().expect("temp dir");
830        let config = client(dir.path(), 1, &cert, 0o600);
831        std::fs::write(
832            config.ca.as_ref().expect("a CA file"),
833            "not a certificate\n",
834        )
835        .expect("overwrite the CA");
836        let refused = HttpApi::new(&config).expect_err("no certificate to trust");
837        assert!(
838            refused.starts_with("ca: "),
839            "the setting is named: {refused}"
840        );
841    }
842
843    #[test]
844    fn the_debug_form_never_holds_the_token() {
845        let cert = certificate();
846        let dir = tempfile::tempdir().expect("temp dir");
847        let api = HttpApi::new(&client(dir.path(), 1, &cert, 0o600)).expect("a client");
848        let shown = format!("{api:?}");
849        assert!(
850            shown.contains("https://localhost:1"),
851            "the address is shown: {shown}"
852        );
853        assert!(!shown.contains("secret"), "the token is not: {shown}");
854    }
855}