diff --git a/crates/libbui-core/Cargo.toml b/crates/libbui-core/Cargo.toml index b5c728a..8c770ca 100644 --- a/crates/libbui-core/Cargo.toml +++ b/crates/libbui-core/Cargo.toml @@ -48,6 +48,12 @@ quick-xml = "0.42.0" unicode-normalization = "0.1.26" fastrand = "2.5.0" +[features] +# Lets plain HTTP to loopback through the HTTPS check, for wiremock in +# other crates' tests. Enable it only from [dev-dependencies]: release +# builds must never turn it on. +test-loopback-http = [] + [target.'cfg(windows)'.dependencies] directories = { workspace = true } diff --git a/crates/libbui-core/src/covers.rs b/crates/libbui-core/src/covers.rs index 45efcfc..f29e22d 100644 --- a/crates/libbui-core/src/covers.rs +++ b/crates/libbui-core/src/covers.rs @@ -40,6 +40,9 @@ pub enum CoverError { /// The request failed. #[error("cannot fetch cover: {0}")] Transport(String), + /// The cover URL, or a redirect it led to, was not HTTPS. + #[error(transparent)] + Insecure(#[from] crate::download::secure::Insecure), /// The cache directory could not be read or written. #[error("cover cache {path}: {message}")] Io { @@ -144,12 +147,14 @@ impl CoverCache { async fn fetch(&self, url: &Url) -> Result, CoverError> { use futures_util::StreamExt; + crate::download::secure::require_https(url)?; let response = self .client .get(url.clone()) .send() .await .map_err(|e| CoverError::Transport(e.to_string()))?; + crate::download::secure::require_https(response.url())?; if !response.status().is_success() { return Err(CoverError::Status(response.status().as_u16())); } @@ -285,6 +290,20 @@ mod tests { assert!(cache.path_for(&url).exists()); } + #[tokio::test] + async fn a_plain_http_cover_is_refused_without_a_request() { + let dir = tempfile::tempdir().unwrap(); + let cache = CoverCache::new(dir.path(), DEFAULT_MAX_BYTES, reqwest::Client::new()); + let url = Url::parse("http://covers.example/c.jpg").unwrap(); + assert_eq!( + cache.get_or_fetch(&url).await, + Err(CoverError::Insecure(crate::download::secure::Insecure { + host: Some("covers.example".to_owned()), + })) + ); + assert!(!cache.path_for(&url).exists()); + } + #[tokio::test] async fn concurrent_requests_share_one_fetch() { let dir = tempfile::tempdir().unwrap(); diff --git a/crates/libbui-core/src/download/adobe/mod.rs b/crates/libbui-core/src/download/adobe/mod.rs index 071fd9d..7aa140c 100644 --- a/crates/libbui-core/src/download/adobe/mod.rs +++ b/crates/libbui-core/src/download/adobe/mod.rs @@ -152,6 +152,10 @@ fn url(raw: &str) -> Result { url.set_scheme("https") .map_err(|_| fail("invalid-url", "HTTPS"))?; } + // Adobe publishes some of its own endpoints as http:// and those are + // upgraded above; anyone else's licence or operator URL must already + // be HTTPS. + super::secure::require_https(&url).map_err(|insecure| ProcessError::insecure(&insecure))?; Ok(url) } fn uuid(raw: &str) -> Result<[u8; 16]> { diff --git a/crates/libbui-core/src/download/adobe/tests.rs b/crates/libbui-core/src/download/adobe/tests.rs index f7b3ff7..aa46ed4 100644 --- a/crates/libbui-core/src/download/adobe/tests.rs +++ b/crates/libbui-core/src/download/adobe/tests.rs @@ -84,6 +84,47 @@ fn unsafe_xml_urls_and_invalid_state_are_explicit_errors() { ); } +#[test] +fn plain_http_operator_and_content_urls_are_refused() { + fn insecure_host(result: Result) -> String { + match result { + Err(ProcessError::Backend { code, detail }) if code == "insecure-url" => detail, + other => panic!("expected an insecure-url refusal, got {other:?}"), + } + } + // A licence's content `src` and a token's `operatorURL` both pass here. + assert_eq!( + insecure_host(url("http://operator.example/fulfillment/Fulfill")), + "operator.example" + ); + assert_eq!( + insecure_host(url("http://cdn.example/book.epub")), + "cdn.example" + ); + // Only Adobe's own hosts are upgraded rather than refused. + assert_eq!( + insecure_host(url("http://adeactivate.adobe.com.evil.example/adept")), + "adeactivate.adobe.com.evil.example" + ); + + let temp = tempfile::tempdir().unwrap(); + let mut token = Node::new("fulfillmentToken"); + token.push(Node::field( + "operatorURL", + "http://operator.example/fulfillment", + )); + let token_file = temp.path().join("loan.acsm"); + std::fs::write(&token_file, token.encode()).unwrap(); + let refused = read_token(&token_file).unwrap_err(); + assert!(!refused.retryable()); + assert_eq!( + refused.reason(), + crate::download::FailReason::InsecureUrl { + host: Some("operator.example".to_owned()), + } + ); +} + #[test] fn aes_rejects_wrong_padding_and_truncation() { for data in [vec![], vec![0; 17], vec![0; 48]] { diff --git a/crates/libbui-core/src/download/ebook.rs b/crates/libbui-core/src/download/ebook.rs index 670971b..9795810 100644 --- a/crates/libbui-core/src/download/ebook.rs +++ b/crates/libbui-core/src/download/ebook.rs @@ -40,6 +40,9 @@ pub enum ProcessError { }, } +/// The backend code for a URL that is not HTTPS. +const INSECURE_URL: &str = "insecure-url"; + impl ProcessError { /// The job failure this becomes. pub fn reason(&self) -> super::FailReason { @@ -54,6 +57,9 @@ impl ProcessError { }, Self::Timeout => FailReason::ProcessingTimeout, Self::InvalidReply => FailReason::ProcessingInvalidReply, + Self::Backend { code, detail } if code == INSECURE_URL => FailReason::InsecureUrl { + host: Some(detail.clone()).filter(|host| !host.is_empty()), + }, Self::Backend { code, detail } => FailReason::Processing { code: code.clone(), detail: detail.clone(), @@ -61,6 +67,14 @@ impl ProcessError { } } + /// A processor refused a URL that is not HTTPS; `detail` is its host. + pub(crate) fn insecure(insecure: &super::secure::Insecure) -> Self { + Self::Backend { + code: INSECURE_URL.to_owned(), + detail: insecure.host.clone().unwrap_or_default(), + } + } + /// Whether an explicit retry may succeed later. pub fn retryable(&self) -> bool { match self { diff --git a/crates/libbui-core/src/download/engine_tests.rs b/crates/libbui-core/src/download/engine_tests.rs index 28dcfe9..ff6627c 100644 --- a/crates/libbui-core/src/download/engine_tests.rs +++ b/crates/libbui-core/src/download/engine_tests.rs @@ -1203,6 +1203,109 @@ async fn link_that_keeps_expiring_fails_after_two_fresh_ones() { engine.shutdown().await.unwrap(); } +/// A failure that is final and names the plain-HTTP host it refused. +fn assert_insecure(job: &Job, host: &str) { + match &job.state { + JobState::Failed { + reason: FailReason::InsecureUrl { host: Some(h) }, + retryable: false, + .. + } if h == host => {} + other => panic!("expected an insecure-URL failure for {host}, got {other:?}"), + } +} + +#[tokio::test] +async fn a_plain_http_content_link_is_refused_before_any_request() { + let h = Harness::new(); + let resolver = FakeResolver::url(Url::parse("http://cdn.example/book.pdf").unwrap()); + let (engine, mut events) = h.start(h.settings(), resolver.clone()); + + engine.enqueue(spec("plain", FileKind::Pdf)).await.unwrap(); + let job = settled(&mut events, "plain").await; + assert_insecure(&job, "cdn.example"); + // Final, so the link is not resolved again in the hope of another. + assert_eq!(resolver.calls(), 1); + engine.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn an_https_link_redirected_to_plain_http_is_refused() { + let h = Harness::new(); + let server = MockServer::start().await; + Mock::given(method("GET")) + .and(path("/hop")) + .respond_with( + ResponseTemplate::new(302).insert_header("location", "http://cdn.example/book.pdf"), + ) + .mount(&server) + .await; + let client = reqwest::Client::builder() + .no_proxy() + .redirect(secure::redirect_policy()) + .build() + .unwrap(); + let (engine, mut events) = Engine::start( + &h.paths, + h.settings(), + FakeResolver::url(url(&server, "/hop")), + client, + ) + .unwrap(); + + engine.enqueue(spec("hop", FileKind::Pdf)).await.unwrap(); + let job = settled(&mut events, "hop").await; + assert_insecure(&job, "cdn.example"); + // One request: the refused hop is not retried. + assert_eq!(server.received_requests().await.unwrap().len(), 1); + engine.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn a_plain_http_licensed_content_link_is_refused() { + let h = Harness::new(); + let processor = Arc::new(FakeEbook::new( + Url::parse("http://cdn.example/book.epub").unwrap(), + epub_bytes("clear"), + )); + let mut settings = h.settings(); + settings.ebook_processor = Some(processor.clone()); + let (engine, mut events) = h.start(settings, token_resolver()); + + engine.enqueue(adobe_spec("plain-adobe")).await.unwrap(); + let job = settled(&mut events, "plain-adobe").await; + assert_insecure(&job, "cdn.example"); + assert!(processor.decrypted_kinds.lock().unwrap().is_empty()); + engine.shutdown().await.unwrap(); +} + +#[tokio::test] +async fn a_plain_http_cover_is_skipped_without_a_request() { + let h = Harness::new(); + let server = MockServer::start().await; + serve(&server, "/book.pdf", PDF).await; + let (engine, mut events) = h.start(h.settings(), FakeResolver::url(url(&server, "/book.pdf"))); + + let mut spec = spec("plain-cover", FileKind::Pdf); + spec.cover_url = Some(Url::parse("http://covers.example/cover.jpg").unwrap()); + engine.enqueue(spec).await.unwrap(); + let job = settled(&mut events, "plain-cover").await; + assert!( + matches!(job.state, JobState::Done { .. }), + "{:?}", + job.state + ); + assert!( + job.warnings + .iter() + .any(|w| matches!(w, JobWarning::CoverUnavailable { .. })), + "{:?}", + job.warnings + ); + assert_eq!(server.received_requests().await.unwrap().len(), 1); + engine.shutdown().await.unwrap(); +} + #[tokio::test] async fn server_errors_are_retried() { let h = Harness::new(); diff --git a/crates/libbui-core/src/download/fetch.rs b/crates/libbui-core/src/download/fetch.rs index 0417fd5..18b1078 100644 --- a/crates/libbui-core/src/download/fetch.rs +++ b/crates/libbui-core/src/download/fetch.rs @@ -99,6 +99,9 @@ pub(crate) enum FetchError { /// Writing the part file failed. #[error("cannot write the download: {0}")] Io(#[from] std::io::Error), + /// The link, or a redirect it led to, was not HTTPS. + #[error(transparent)] + Insecure(#[from] super::secure::Insecure), } impl FetchError { @@ -119,6 +122,9 @@ impl FetchError { path: Some(part.to_path_buf()), detail: error.to_string(), }, + Self::Insecure(insecure) => FailReason::InsecureUrl { + host: insecure.host.clone(), + }, } } @@ -126,6 +132,7 @@ impl FetchError { match self { Self::Expired(_) | Self::Transport(_) | Self::Io(_) | Self::Cancelled => true, Self::Status { retryable, .. } => *retryable, + Self::Insecure(_) => false, } } } @@ -142,6 +149,19 @@ pub(crate) struct FetchRequest<'a> { pub policy: &'a RetryPolicy, } +/// The [`Insecure`](super::secure::Insecure) refusal behind a redirect +/// error, if that is what stopped the request. +fn insecure_redirect(error: &reqwest::Error) -> Option<&super::secure::Insecure> { + let mut source = std::error::Error::source(error); + while let Some(inner) = source { + if let Some(insecure) = inner.downcast_ref::() { + return Some(insecure); + } + source = inner.source(); + } + None +} + /// What the next loop iteration should do after a failed attempt. enum Next { Retry(Option), @@ -162,6 +182,7 @@ pub(crate) async fn fetch( cancel, policy, } = req; + super::secure::require_https(url)?; let mut attempt: u32 = 0; loop { if cancel.is_cancelled() { @@ -197,6 +218,11 @@ pub(crate) async fn fetch( let response = match response { Ok(r) => r, Err(e) => { + // The client's redirect policy refused a plain-HTTP hop: + // retrying would only be refused again. + if let Some(insecure) = insecure_redirect(&e) { + return Err(FetchError::Insecure(insecure.clone())); + } attempt += 1; match give_up_or_wait( attempt, @@ -213,6 +239,9 @@ pub(crate) async fn fetch( } }; + // A client without the HTTPS redirect policy may still have + // followed a hop to plain HTTP; refuse what it fetched. + super::secure::require_https(response.url())?; let status = response.status(); let (start, total) = match status { StatusCode::OK => { diff --git a/crates/libbui-core/src/download/mod.rs b/crates/libbui-core/src/download/mod.rs index 8061738..ff456ba 100644 --- a/crates/libbui-core/src/download/mod.rs +++ b/crates/libbui-core/src/download/mod.rs @@ -38,6 +38,7 @@ mod pdf; mod progress; mod reader; mod resolve; +pub mod secure; mod store; pub mod verify; diff --git a/crates/libbui-core/src/download/reader/tests.rs b/crates/libbui-core/src/download/reader/tests.rs index 44b6bea..868fbec 100644 --- a/crates/libbui-core/src/download/reader/tests.rs +++ b/crates/libbui-core/src/download/reader/tests.rs @@ -135,6 +135,28 @@ fn origin_and_kind_checks_reject_invalid_reader_authorization() { } } +#[test] +fn a_plain_http_reader_origin_is_refused_as_insecure() { + let access = ReaderAccess { + kind: ReaderKind::Ebook, + web: "http://dewey-00000000000000000000000000000000.read.libbyapp.com/" + .parse() + .unwrap(), + message: SecretString::from("credential".to_owned()), + toc_label: "Contents".into(), + }; + let Err(error) = Session::new(&access, CancellationToken::new()) else { + panic!("a plain-HTTP reader origin was accepted"); + }; + assert!(!error.retryable()); + assert_eq!( + error.reason(), + crate::download::FailReason::InsecureUrl { + host: Some("dewey-00000000000000000000000000000000.read.libbyapp.com".to_owned()), + } + ); +} + #[tokio::test] async fn native_pipeline_packages_decoded_spine_notes_fonts_images_and_navigation() { let server = MockServer::start().await; diff --git a/crates/libbui-core/src/download/reader/transport.rs b/crates/libbui-core/src/download/reader/transport.rs index 16e8ddc..a92be34 100644 --- a/crates/libbui-core/src/download/reader/transport.rs +++ b/crates/libbui-core/src/download/reader/transport.rs @@ -36,6 +36,10 @@ fn valid_cdn(url: &Url) -> bool { impl Session { pub(super) fn new(access: &ReaderAccess, cancel: CancellationToken) -> Result { + // Plain HTTP is refused with its own reason before the origin + // check below would call it merely unrecognised. + crate::download::secure::require_https(&access.web) + .map_err(|insecure| crate::download::ebook::ProcessError::insecure(&insecure))?; let host = access.web.host_str().unwrap_or_default(); let authorized = access.web.scheme() == "https" && match access.kind { diff --git a/crates/libbui-core/src/download/secure.rs b/crates/libbui-core/src/download/secure.rs new file mode 100644 index 0000000..5dc3e12 --- /dev/null +++ b/crates/libbui-core/src/download/secure.rs @@ -0,0 +1,121 @@ +//! Every URL the download engine or the Adobe processor fetches must be +//! HTTPS. Content links, licence servers and reader origins come from +//! remote APIs; a plain `http://` one would send a signed link, a licence +//! request or the book itself in the clear, so it is refused rather than +//! upgraded or followed. +//! +//! Tests serve fixtures from a loopback `wiremock` server, which only +//! speaks plain HTTP. Loopback is allowed in this crate's own tests +//! (`cfg(test)`) and when the `test-loopback-http` feature is on. That +//! feature is enabled only by `libbui`'s dev-dependencies, so no release +//! build can turn it on at run time: there is no environment variable or +//! setting for it. + +use url::{Host, Url}; + +/// Whether plain HTTP to a loopback address is allowed in this build. +const LOOPBACK_HTTP: bool = cfg!(any(test, feature = "test-loopback-http")); + +/// A URL that is not HTTPS (and not an allowed test loopback). +#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] +#[error("refusing a URL that is not HTTPS (host {})", host.as_deref().unwrap_or("unknown"))] +pub struct Insecure { + /// The host it pointed at, for the message. + pub host: Option, +} + +/// Accepts `url` only when it is HTTPS, or plain HTTP to loopback in a +/// test build. +/// +/// # Errors +/// [`Insecure`] for anything else (`http://` to a real host, `ftp://`, +/// `file://`, …). +pub fn require_https(url: &Url) -> Result<(), Insecure> { + if allowed(url, LOOPBACK_HTTP) { + Ok(()) + } else { + Err(Insecure { + host: url.host_str().map(str::to_owned), + }) + } +} + +fn allowed(url: &Url, loopback_http: bool) -> bool { + match url.scheme() { + "https" => url.host().is_some(), + "http" => loopback_http && is_loopback(url), + _ => false, + } +} + +fn is_loopback(url: &Url) -> bool { + match url.host() { + Some(Host::Ipv4(ip)) => ip.is_loopback(), + Some(Host::Ipv6(ip)) => ip.is_loopback(), + Some(Host::Domain(name)) => name.eq_ignore_ascii_case("localhost"), + None => false, + } +} + +/// A redirect policy for the content client: follows at most ten +/// redirects, and only to URLs [`require_https`] accepts, so an HTTPS +/// link cannot be bounced to plain HTTP. +#[must_use] +pub fn redirect_policy() -> reqwest::redirect::Policy { + reqwest::redirect::Policy::custom(|attempt| { + if attempt.previous().len() >= 10 { + attempt.error("too many redirects") + } else if let Err(insecure) = require_https(attempt.url()) { + attempt.error(insecure) + } else { + attempt.follow() + } + }) +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use super::*; + + fn check(raw: &str) -> Result<(), Insecure> { + require_https(&Url::parse(raw).unwrap()) + } + + #[test] + fn https_is_accepted() { + assert_eq!(check("https://cdn.example/book.epub"), Ok(())); + } + + #[test] + fn plain_http_and_other_schemes_are_refused() { + for raw in [ + "http://cdn.example/book.epub", + "http://operator.example/fulfillment/Fulfill", + "ftp://cdn.example/book.epub", + "file:///etc/passwd", + "http://127.0.0.1.example/", + ] { + let err = check(raw).unwrap_err(); + assert_eq!( + err.host, + Url::parse(raw).unwrap().host_str().map(str::to_owned), + "{raw}" + ); + } + } + + #[test] + fn loopback_http_is_only_for_tests() { + // This is a test build, so loopback is allowed here. Without the + // test switch (as in release builds) the same URLs are refused. + for raw in [ + "http://127.0.0.1:8080/x", + "http://[::1]:8080/x", + "http://localhost/x", + ] { + assert_eq!(check(raw), Ok(()), "{raw}"); + assert!(!allowed(&Url::parse(raw).unwrap(), false), "{raw}"); + } + } +} diff --git a/crates/libbui/Cargo.toml b/crates/libbui/Cargo.toml index 22242b4..1334799 100644 --- a/crates/libbui/Cargo.toml +++ b/crates/libbui/Cargo.toml @@ -64,6 +64,8 @@ terminal-colorsaurus = "1.0.3" open = "5.4" [dev-dependencies] +# Tests serve fixtures from a loopback wiremock server over plain HTTP. +libbui-core = { workspace = true, features = ["test-loopback-http"] } zip = { version = "9.6.0", default-features = false } insta = { workspace = true } wiremock = { workspace = true } diff --git a/crates/libbui/src/cli/download/tests.rs b/crates/libbui/src/cli/download/tests.rs index e8a16c4..9fb6027 100644 --- a/crates/libbui/src/cli/download/tests.rs +++ b/crates/libbui/src/cli/download/tests.rs @@ -363,6 +363,28 @@ async fn a_file_that_fails_verification_fails_the_command() { assert!(reports[0]["reason"].as_str().is_some_and(|r| !r.is_empty())); } +#[tokio::test] +async fn a_plain_http_download_link_is_refused_with_a_sentence() { + let api = with_acsm(); + api.state().fulfillments.insert( + "ebook-epub-open".to_owned(), + Fulfillment::Download { + url: "http://cdn.example/book.epub".parse().unwrap(), + kind: libby::models::DownloadKind::EpubOpen, + }, + ); + let sandbox = Sandbox::new(); + let (result, reports) = download(&api, &sandbox, &args(&["1000001"])).await; + assert_eq!(result.unwrap_err().code(), exit::FAILURE); + assert_eq!(outcome(&reports, "1000001"), "failed"); + assert_eq!( + reports[0]["reason"].as_str(), + Some( + "The library sent a link to cdn.example that is not secure (not HTTPS), so libbui did not use it." + ) + ); +} + #[tokio::test] async fn all_downloads_what_it_can_and_reports_the_rest() { let api = with_acsm(); diff --git a/crates/libbui/src/startup.rs b/crates/libbui/src/startup.rs index 5d6ebba..00910d4 100644 --- a/crates/libbui/src/startup.rs +++ b/crates/libbui/src/startup.rs @@ -282,13 +282,15 @@ fn service_override(name: &str, raw: Option<&str>) -> libby::Result reqwest::Result { reqwest::Client::builder() .user_agent(concat!("libbui/", env!("CARGO_PKG_VERSION"))) + .redirect(libbui_core::download::secure::redirect_policy()) .build() } @@ -311,3 +313,30 @@ async fn keep_identity(client: Client, store: Arc) { } } } + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + + use wiremock::matchers::path; + use wiremock::{Mock, MockServer, ResponseTemplate}; + + #[tokio::test] + async fn the_content_client_will_not_follow_a_redirect_to_plain_http() { + let server = MockServer::start().await; + Mock::given(path("/hop")) + .respond_with( + ResponseTemplate::new(302).insert_header("location", "http://cdn.example/book"), + ) + .mount(&server) + .await; + let error = super::content_client() + .unwrap() + .get(format!("{}/hop", server.uri())) + .send() + .await + .unwrap_err(); + assert!(error.is_redirect(), "{error:?}"); + assert_eq!(server.received_requests().await.unwrap().len(), 1); + } +}