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