From 93242f140041903333f7c1c05ff1499551f97cac Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Mon, 16 Nov 2026 19:28:08 -0500 Subject: [PATCH 1/4] fix(libby): drop the unused ACSM file name The fulfilment carried a 'safe' file name taken from the server's Content-Disposition, but nothing named files with it and its sanitizer was weak. Remove it from Fulfillment::Acsm, Resolved::Bytes and the services resolver, along with the Content-Disposition parsing. --- crates/libbui-core/src/download/engine.rs | 2 +- .../libbui-core/src/download/engine_tests.rs | 3 - crates/libbui-core/src/download/resolve.rs | 9 +- crates/libbui/src/cli/download/tests.rs | 1 - crates/libbui/src/services.rs | 5 +- crates/libby/src/client/fulfil.rs | 113 +++--------------- crates/libby/src/client/http.rs | 7 +- crates/libby/tests/client.rs | 1 - 8 files changed, 24 insertions(+), 117 deletions(-) diff --git a/crates/libbui-core/src/download/engine.rs b/crates/libbui-core/src/download/engine.rs index 3aee071..b8cf7ce 100644 --- a/crates/libbui-core/src/download/engine.rs +++ b/crates/libbui-core/src/download/engine.rs @@ -1322,7 +1322,7 @@ impl Worker { self.update(Update::State(JobState::Resolving)); } let (url, expected_len) = match self.resolve().await? { - Resolved::Bytes { bytes, .. } => { + Resolved::Bytes { bytes } => { let len = bytes.len() as u64; let path = complete.to_path_buf(); let written = tokio::task::spawn_blocking(move || { diff --git a/crates/libbui-core/src/download/engine_tests.rs b/crates/libbui-core/src/download/engine_tests.rs index 3468722..f03feff 100644 --- a/crates/libbui-core/src/download/engine_tests.rs +++ b/crates/libbui-core/src/download/engine_tests.rs @@ -955,7 +955,6 @@ async fn acsm_bytes_from_the_resolver_are_saved_as_is() { let resolver = FakeResolver::new(|_, _| { Ok(Resolved::Bytes { bytes: ACSM.to_vec(), - filename: Some("ignored.acsm".to_owned()), }) }); let (engine, mut events) = h.start(h.settings(), resolver); @@ -1407,7 +1406,6 @@ async fn clear_finished_and_remove() { } else { Resolved::Bytes { bytes: PDF.to_vec(), - filename: None, } }) }); @@ -1672,7 +1670,6 @@ async fn a_good_save_after_a_failed_one_is_announced() { let resolver = FakeResolver::new(|_, _| { Ok(Resolved::Bytes { bytes: PDF.to_vec(), - filename: None, }) }); let (engine, mut events) = h.start(h.settings(), resolver); diff --git a/crates/libbui-core/src/download/resolve.rs b/crates/libbui-core/src/download/resolve.rs index 1d12e1b..59b386d 100644 --- a/crates/libbui-core/src/download/resolve.rs +++ b/crates/libbui-core/src/download/resolve.rs @@ -34,11 +34,9 @@ pub enum Resolved { /// The resolver already has the whole file (an `.acsm` fulfilment /// token is returned by the API call itself). Bytes { - /// The file contents. + /// The file contents. The library name always comes from the + /// configured template, never from the server. bytes: Vec, - /// The server's suggested file name. Only logged: the library name - /// always comes from the configured template. - filename: Option, }, } @@ -55,7 +53,7 @@ impl std::fmt::Debug for Resolved { .field("bytes", &bytes.len()) .finish(), Self::Reader { access } => f.debug_struct("Reader").field("access", access).finish(), - Self::Bytes { bytes, .. } => f + Self::Bytes { bytes } => f .debug_struct("Bytes") .field("bytes", &bytes.len()) .finish(), @@ -172,7 +170,6 @@ mod tests { }, Resolved::Bytes { bytes: b"secret".to_vec(), - filename: Some("private".into()), }, Resolved::Reader { access: ReaderAccess { diff --git a/crates/libbui/src/cli/download/tests.rs b/crates/libbui/src/cli/download/tests.rs index 0ea51e4..e8a16c4 100644 --- a/crates/libbui/src/cli/download/tests.rs +++ b/crates/libbui/src/cli/download/tests.rs @@ -141,7 +141,6 @@ fn with_acsm() -> Arc { "ebook-epub-adobe".to_owned(), Fulfillment::Acsm { bytes: ACSM.to_vec(), - filename: "psalm.acsm".to_owned(), }, ); api diff --git a/crates/libbui/src/services.rs b/crates/libbui/src/services.rs index df30d9e..c7bbcaf 100644 --- a/crates/libbui/src/services.rs +++ b/crates/libbui/src/services.rs @@ -246,10 +246,7 @@ impl Resolver for LoanResolver { Ok(Fulfillment::Acsm { bytes, .. }) if spec.is_adobe_book() => { Ok(Resolved::AdobeLicense { bytes }) } - Ok(Fulfillment::Acsm { bytes, filename }) => Ok(Resolved::Bytes { - bytes, - filename: Some(filename), - }), + Ok(Fulfillment::Acsm { bytes }) => Ok(Resolved::Bytes { bytes }), // A web reader or player, not a file. Nothing here will fetch // what sits behind it. Ok(Fulfillment::External { .. }) => { diff --git a/crates/libby/src/client/fulfil.rs b/crates/libby/src/client/fulfil.rs index b98c3d7..99baa0c 100644 --- a/crates/libby/src/client/fulfil.rs +++ b/crates/libby/src/client/fulfil.rs @@ -23,12 +23,9 @@ use super::http::{Idempotency, JSON_LIMIT, Reply, SentryCall, browser_headers, e use crate::error::{Error, Result, Service}; use crate::ids::FormatId; use crate::models::{DownloadKind, FormatAccess, Loan}; -use crate::sanitize::sanitize_line; /// Most redirects followed before giving up. const MAX_HOPS: usize = 10; -/// Longest file name derived for an `.acsm` file (in characters). -const MAX_FILENAME: usize = 120; /// The result of [`Client::fulfill`]. #[derive(Clone, PartialEq, Eq)] @@ -41,12 +38,12 @@ pub enum Fulfillment { /// EPUB or PDF. kind: DownloadKind, }, - /// An Adobe fulfilment token, to be saved exactly as received. + /// An Adobe fulfilment token, to be saved exactly as received. It has + /// no file name: the server's `Content-Disposition` is untrusted input, + /// and the library names every file from its own template. Acsm { /// The `.acsm` file's bytes. bytes: Vec, - /// A safe file name (no directories), ending in `.acsm`. - filename: String, }, /// Delivery happens elsewhere (Kindle): open this in a browser. External { @@ -63,9 +60,7 @@ impl std::fmt::Debug for Fulfillment { .field("host", &url.host_str()) .field("kind", kind) .finish(), - Self::Acsm { bytes, .. } => { - f.debug_struct("Acsm").field("bytes", &bytes.len()).finish() - } + Self::Acsm { bytes } => f.debug_struct("Acsm").field("bytes", &bytes.len()).finish(), Self::External { url } => f .debug_struct("External") .field("host", &url.host_str()) @@ -146,9 +141,7 @@ impl Client { let url = self.follow_to_download(&start, reply).await?; Ok(Fulfillment::Download { url, kind }) } - FormatAccess::Download(DownloadKind::EpubAcsm | DownloadKind::PdfAcsm) => { - acsm(&reply, &loan.title) - } + FormatAccess::Download(DownloadKind::EpubAcsm | DownloadKind::PdfAcsm) => acsm(&reply), FormatAccess::Kindle => { let url = link_target(&start, &reply)?; Ok(Fulfillment::External { url }) @@ -260,8 +253,8 @@ fn link_target(base: &Url, reply: &Reply) -> Result { } } -/// Checks that `reply` is an `.acsm` token and names it. -fn acsm(reply: &Reply, title: &str) -> Result { +/// Checks that `reply` is an `.acsm` token. +fn acsm(reply: &Reply) -> Result { if reply.status != StatusCode::OK { return Err(malformed( Service::Sentry, @@ -277,56 +270,11 @@ fn acsm(reply: &Reply, title: &str) -> Result { if !looks_like_xml { return Err(malformed(Service::Sentry, "the .acsm answer is not XML")); } - let stem = reply - .content_disposition() - .and_then(disposition_filename) - .map(|name| { - name.strip_suffix(".acsm") - .map_or(name.clone(), str::to_owned) - }) - .unwrap_or_else(|| title.to_owned()); Ok(Fulfillment::Acsm { bytes: reply.body.clone(), - filename: format!("{}.acsm", safe_stem(&stem)), - }) -} - -/// The plain `filename=` parameter of a `Content-Disposition` header. -/// (`filename*=` is not used by the fulfilment server; when it is the only -/// one present, the title is used instead.) -fn disposition_filename(header: &str) -> Option { - header.split(';').find_map(|part| { - let (key, value) = part.trim().split_once('=')?; - if !key.trim().eq_ignore_ascii_case("filename") { - return None; - } - let value = value.trim(); - let value = value - .strip_prefix('"') - .and_then(|v| v.strip_suffix('"')) - .unwrap_or(value); - (!value.is_empty()).then(|| value.to_owned()) }) } -/// A file-name stem with no directories, control characters or leading dots. -fn safe_stem(raw: &str) -> String { - let cleaned: String = sanitize_line(raw) - .chars() - .map(|c| match c { - '/' | '\\' | ':' | '*' | '?' | '"' | '<' | '>' | '|' => '_', - c => c, - }) - .take(MAX_FILENAME) - .collect(); - let cleaned = cleaned.trim().trim_start_matches('.').trim(); - if cleaned.is_empty() { - "loan".to_owned() - } else { - cleaned.to_owned() - } -} - fn malformed(service: Service, message: &str) -> Error { Error::Malformed { service, @@ -366,7 +314,6 @@ mod tests { }, Fulfillment::Acsm { bytes: b"secret".to_vec(), - filename: "private".into(), }, Fulfillment::External { url: Url::parse("https://example.test/private?sig=secret").unwrap(), @@ -414,46 +361,22 @@ mod tests { } #[test] - fn acsm_naming() { + fn acsm_tokens_are_returned_byte_for_byte_without_a_server_name() { let ok = reply( 200, - &[("content-disposition", r#"attachment; filename="Dune.acsm""#)], + &[( + "content-disposition", + r#"attachment; filename="../../CON\u{202e}.acsm""#, + )], b"\xEF\xBB\xBF ", ); - let Fulfillment::Acsm { filename, bytes } = acsm(&ok, "ignored").unwrap() else { - panic!("not an acsm"); - }; - assert_eq!(filename, "Dune.acsm"); - assert!(bytes.ends_with(b"")); - - let untitled = reply(200, &[], b""); - let Fulfillment::Acsm { filename, .. } = acsm(&untitled, "../A/B: \u{1b}[31mC?").unwrap() - else { - panic!("not an acsm"); - }; - assert_eq!(filename, "_A_B_ C_.acsm"); - - assert!(acsm(&reply(200, &[], b"{\"json\":1}"), "t").is_err()); - assert!(acsm(&reply(302, &[], b""), "t").is_err()); - } - - #[test] - fn disposition_parsing() { - assert_eq!( - disposition_filename("attachment; filename=plain.acsm").as_deref(), - Some("plain.acsm") - ); assert_eq!( - disposition_filename("attachment; filename*=UTF-8''x.acsm"), - None + acsm(&ok).unwrap(), + Fulfillment::Acsm { + bytes: b"\xEF\xBB\xBF ".to_vec() + } ); - assert_eq!(disposition_filename("attachment"), None); - } - - #[test] - fn stems_are_safe() { - assert_eq!(safe_stem("..."), "loan"); - assert_eq!(safe_stem(" .hidden "), "hidden"); - assert_eq!(safe_stem(&"x".repeat(500)).len(), MAX_FILENAME); + assert!(acsm(&reply(200, &[], b"{\"json\":1}")).is_err()); + assert!(acsm(&reply(302, &[], b"")).is_err()); } } diff --git a/crates/libby/src/client/http.rs b/crates/libby/src/client/http.rs index 705c678..3c3e34e 100644 --- a/crates/libby/src/client/http.rs +++ b/crates/libby/src/client/http.rs @@ -5,8 +5,7 @@ use std::future::Future; use std::time::Duration; use reqwest::header::{ - ACCEPT, CACHE_CONTROL, CONTENT_DISPOSITION, HeaderMap, LOCATION, ORIGIN, PRAGMA, REFERER, - RETRY_AFTER, + ACCEPT, CACHE_CONTROL, HeaderMap, LOCATION, ORIGIN, PRAGMA, REFERER, RETRY_AFTER, }; use reqwest::{Method, RequestBuilder, StatusCode}; use secrecy::{ExposeSecret, SecretString}; @@ -62,10 +61,6 @@ impl Reply { pub(super) fn location(&self) -> Option<&str> { self.header(LOCATION) } - - pub(super) fn content_disposition(&self) -> Option<&str> { - self.header(CONTENT_DISPOSITION) - } } /// The headers the Libby web app sends. diff --git a/crates/libby/tests/client.rs b/crates/libby/tests/client.rs index 51ce6a9..862e630 100644 --- a/crates/libby/tests/client.rs +++ b/crates/libby/tests/client.rs @@ -1500,7 +1500,6 @@ async fn acsm_is_returned_as_is() { outcome, Fulfillment::Acsm { bytes: token.to_vec(), - filename: "An Open Book.acsm".into(), } ); } -- knotmirror 0.0.1 From 1b183528536318da431e193b01f758baa03f0798 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Mon, 16 Nov 2026 20:39:18 -0500 Subject: [PATCH 2/4] fix(downloads): give failures a typed, localised reason The engine stored download failures as English sentences, which the TUI and CLI showed as they were. Failures now carry a FailReason enum with the technical detail (paths, OS errors, status codes) as data, and libbui turns it into Fluent messages, with plural selectors for counts. Engine and state-file errors, including NewerVersion, go through Fluent too. Queues saved by older builds still load: a plain-text "message" becomes FailReason::Legacy and is shown as it was saved. A reason type from a newer build loads as Unknown instead of quarantining the queue. --- crates/libbui-core/src/download/ebook.rs | 20 ++ crates/libbui-core/src/download/engine.rs | 170 ++++++------ .../libbui-core/src/download/engine_tests.rs | 12 +- crates/libbui-core/src/download/fetch.rs | 20 ++ crates/libbui-core/src/download/finalize.rs | 13 + crates/libbui-core/src/download/job.rs | 205 ++++++++++++++- crates/libbui-core/src/download/mod.rs | 4 +- crates/libbui-core/src/download/store.rs | 4 +- crates/libbui-core/src/download/verify.rs | 27 +- crates/libbui/locales/en-US/downloads.ftl | 66 +++++ crates/libbui/src/app/errors.rs | 247 ++++++++++++++++++ crates/libbui/src/app/mod.rs | 4 +- crates/libbui/src/app/walk_tests.rs | 6 +- crates/libbui/src/cli/download.rs | 11 +- crates/libbui/src/screens/detail/view.rs | 7 +- crates/libbui/src/screens/downloads/mod.rs | 9 +- ...loads__tests__snapshot_failed_details.snap | 4 +- ...ds__tests__snapshot_mixed_queue_60x16.snap | 2 +- ...ds__tests__snapshot_mixed_queue_80x24.snap | 2 +- ...ds__tests__snapshot_mixed_queue_ascii.snap | 2 +- ...ads__tests__snapshot_mixed_queue_wide.snap | 2 +- crates/libbui/src/screens/downloads/tests.rs | 25 +- crates/libbui/src/screens/shelf/view.rs | 4 +- crates/libbui/src/startup.rs | 18 +- 24 files changed, 767 insertions(+), 117 deletions(-) diff --git a/crates/libbui-core/src/download/ebook.rs b/crates/libbui-core/src/download/ebook.rs index e3fb5bc..670971b 100644 --- a/crates/libbui-core/src/download/ebook.rs +++ b/crates/libbui-core/src/download/ebook.rs @@ -41,6 +41,26 @@ pub enum ProcessError { } impl ProcessError { + /// The job failure this becomes. + pub fn reason(&self) -> super::FailReason { + use super::FailReason; + match self { + Self::Cancelled => FailReason::Internal { + detail: "cancelled".to_owned(), + }, + Self::Io(error) => FailReason::Io { + path: None, + detail: error.to_string(), + }, + Self::Timeout => FailReason::ProcessingTimeout, + Self::InvalidReply => FailReason::ProcessingInvalidReply, + Self::Backend { code, detail } => FailReason::Processing { + code: code.clone(), + detail: detail.clone(), + }, + } + } + /// Whether an explicit retry may succeed later. pub fn retryable(&self) -> bool { match self { diff --git a/crates/libbui-core/src/download/engine.rs b/crates/libbui-core/src/download/engine.rs index b8cf7ce..b79b887 100644 --- a/crates/libbui-core/src/download/engine.rs +++ b/crates/libbui-core/src/download/engine.rs @@ -30,7 +30,7 @@ use tokio_util::sync::CancellationToken; use super::fetch::{self, FetchError, FetchRequest, FetchUpdate}; use super::finalize::{self, Placed}; -use super::job::{FileKind, Job, JobId, JobSpec, JobState, JobWarning, Stage}; +use super::job::{FailReason, FileKind, Job, JobId, JobSpec, JobState, JobWarning, Stage}; use super::progress::{Meter, Progress}; use super::resolve::{Resolved, Resolver}; use super::verify::{self, VerifyError}; @@ -402,7 +402,7 @@ enum Outcome { }, Failed { stage: Stage, - message: String, + reason: FailReason, retryable: bool, }, FatalForCard { @@ -414,14 +414,29 @@ enum Outcome { Panicked(String), } -fn failed(stage: Stage, message: impl Into, retryable: bool) -> Outcome { +fn failed(stage: Stage, reason: FailReason, retryable: bool) -> Outcome { Outcome::Failed { stage, - message: message.into(), + reason, retryable, } } +/// A staging-area file operation on `path` failed. +fn io_reason(path: &Path, error: &std::io::Error) -> FailReason { + FailReason::Io { + path: Some(path.to_path_buf()), + detail: error.to_string(), + } +} + +/// A blocking task was cancelled or panicked. +fn join_reason(error: &tokio::task::JoinError) -> FailReason { + FailReason::Internal { + detail: error.to_string(), + } +} + struct Actor { shared: Arc, concurrency: usize, @@ -590,7 +605,7 @@ impl Actor { job.id(), JobState::Failed { stage: Stage::Resolve, - message, + reason: FailReason::Resolver { message }, retryable: false, }, ); @@ -892,15 +907,15 @@ impl Actor { } Outcome::Failed { stage, - message, + reason, retryable, } => { - tracing::warn!(job = %id, ?stage, %message, "download failed"); + tracing::warn!(job = %id, ?stage, ?reason, "download failed"); self.set_state( &id, JobState::Failed { stage, - message, + reason, retryable, }, ); @@ -925,7 +940,7 @@ impl Actor { &id, JobState::Failed { stage, - message: format!("internal error: {message}"), + reason: FailReason::Internal { detail: message }, retryable: true, }, ); @@ -946,7 +961,7 @@ impl Actor { .insert(card_id.clone(), message.clone()); let failed = JobState::Failed { stage: Stage::Resolve, - message, + reason: FailReason::Resolver { message }, retryable: false, }; let victims: Vec = self @@ -1171,11 +1186,7 @@ impl Worker { let dir = self.shared.job_dir(&self.id); let complete = dir.join(complete_file(self.spec.kind)); if let Err(e) = tokio::fs::create_dir_all(&dir).await { - return failed( - Stage::Fetch, - format!("cannot create {}: {e}", dir.display()), - true, - ); + return failed(Stage::Fetch, io_reason(&dir, &e), true); } #[cfg(unix)] { @@ -1183,11 +1194,7 @@ impl Worker { if let Err(error) = tokio::fs::set_permissions(&dir, std::fs::Permissions::from_mode(0o700)).await { - return failed( - Stage::Fetch, - format!("cannot protect {}: {error}", dir.display()), - true, - ); + return failed(Stage::Fetch, io_reason(&dir, &error), true); } } // A complete file survives from an earlier run (paused while @@ -1197,11 +1204,7 @@ impl Worker { Ok(false) => { if self.spec.is_adobe_book() || self.spec.is_reader_book() { let Some(processor) = &self.shared.ebook_processor else { - return failed( - Stage::Process, - "ebook processing is not configured".to_owned(), - true, - ); + return failed(Stage::Process, FailReason::ProcessingUnavailable, true); }; self.update(Update::State(JobState::Processing)); let checked = if self.spec.is_reader_book() { @@ -1212,7 +1215,7 @@ impl Worker { if let Err(error) = checked { return match error { super::ebook::ProcessError::Cancelled => Outcome::Stopped, - error => failed(Stage::Process, error.to_string(), error.retryable()), + error => failed(Stage::Process, error.reason(), error.retryable()), }; } } @@ -1220,7 +1223,9 @@ impl Worker { let work = if self.spec.is_adobe_book() && match tokio::fs::try_exists(&token).await { Ok(exists) => exists, - Err(error) => return failed(Stage::Process, error.to_string(), true), + Err(error) => { + return failed(Stage::Process, io_reason(&token, &error), true); + } } { self.process_adobe(&dir, &complete).await } else { @@ -1235,11 +1240,7 @@ impl Worker { } } Err(e) => { - return failed( - Stage::Fetch, - format!("cannot read {}: {e}", complete.display()), - true, - ); + return failed(Stage::Fetch, io_reason(&complete, &e), true); } }; if self.cancel.is_cancelled() { @@ -1258,9 +1259,9 @@ impl Worker { Ok(Ok(v)) => v, Ok(Err(e)) => { let retryable = matches!(e, VerifyError::Io(_)); - return failed(Stage::Verify, e.to_string(), retryable); + return failed(Stage::Verify, e.reason(&complete), retryable); } - Err(e) => return failed(Stage::Verify, e.to_string(), true), + Err(e) => return failed(Stage::Verify, join_reason(&e), true), }; if self.cancel.is_cancelled() { return Outcome::Stopped; @@ -1292,8 +1293,8 @@ impl Worker { .await { Ok(Ok(placed)) => placed, - Ok(Err(e)) => return failed(Stage::Finalize, e.to_string(), true), - Err(e) => return failed(Stage::Finalize, e.to_string(), true), + Ok(Err(e)) => return failed(Stage::Finalize, e.reason(), true), + Err(e) => return failed(Stage::Finalize, join_reason(&e), true), }; if let Placed::AlreadyPresent(path) = &placed { tracing::info!(job = %self.id, path = %path.display(), "identical file already in the library"); @@ -1340,39 +1341,42 @@ impl Worker { ))); Ok(Some(len)) } - Ok(Err(e)) => Err(failed(Stage::Fetch, e.to_string(), true)), - Err(e) => Err(failed(Stage::Fetch, e.to_string(), true)), + Ok(Err(e)) => Err(failed(Stage::Fetch, io_reason(complete, &e), true)), + Err(e) => Err(failed(Stage::Fetch, join_reason(&e), true)), }; } Resolved::AdobeLicense { bytes } => { if !self.spec.is_adobe_book() { return Err(failed( Stage::Process, - "Adobe license for an incompatible job".to_owned(), + FailReason::MismatchedFulfillment, false, )); } let dir = self.shared.job_dir(&self.id); let token = dir.join("license.acsm"); + let target = token.clone(); let written = tokio::task::spawn_blocking(move || { verify::check_acsm_bytes(&bytes)?; - crate::fsutil::write_atomic(&token, &bytes, Some(0o600))?; + crate::fsutil::write_atomic(&target, &bytes, Some(0o600))?; Ok::<_, VerifyError>(()) }) .await; match written { Ok(Ok(())) => return self.process_adobe(&dir, complete).await, Ok(Err(error)) => { - return Err(failed(Stage::Process, error.to_string(), true)); + return Err(failed(Stage::Process, error.reason(&token), true)); + } + Err(error) => { + return Err(failed(Stage::Process, join_reason(&error), true)); } - Err(error) => return Err(failed(Stage::Process, error.to_string(), true)), } } Resolved::Reader { access } => { if !self.spec.is_reader_book() { return Err(failed( Stage::Process, - "reader access for an incompatible job".to_owned(), + FailReason::MismatchedFulfillment, false, )); } @@ -1424,11 +1428,7 @@ impl Worker { last_total.or(Some(len)), ))); if let Err(e) = tokio::fs::rename(part, complete).await { - return Err(failed( - Stage::Fetch, - format!("cannot finish {}: {e}", part.display()), - true, - )); + return Err(failed(Stage::Fetch, io_reason(part, &e), true)); } return Ok(expected_len); } @@ -1439,17 +1439,17 @@ impl Worker { Err(FetchError::Expired(status)) => { return Err(failed( Stage::Fetch, - format!( - "the download link kept expiring (HTTP {status}), \ - even after {MAX_RERESOLVES} fresh links" - ), + FailReason::LinkExpired { + status, + attempts: MAX_RERESOLVES, + }, true, )); } Err(FetchError::Cancelled) => return Err(Outcome::Stopped), Err(e) => { let retryable = e.retryable(); - return Err(failed(Stage::Fetch, e.to_string(), retryable)); + return Err(failed(Stage::Fetch, e.reason(part), retryable)); } } } @@ -1463,7 +1463,7 @@ impl Worker { let Some(processor) = &self.shared.ebook_processor else { return Err(failed( Stage::Process, - "ebook processing is not configured".to_owned(), + FailReason::ProcessingUnavailable, true, )); }; @@ -1480,16 +1480,16 @@ impl Worker { if invalid && !tokio::fs::try_exists(&license) .await - .map_err(|error| failed(Stage::Process, error.to_string(), true))? + .map_err(|e| failed(Stage::Process, io_reason(&license, &e), true))? { tokio::fs::remove_file(&token) .await - .map_err(|error| failed(Stage::Process, error.to_string(), true))?; + .map_err(|e| failed(Stage::Process, io_reason(&token, &e), true))?; retryable = true; } - return Err(failed(Stage::Process, error.to_string(), retryable)); + return Err(failed(Stage::Process, error.reason(&token), retryable)); } - Err(error) => return Err(failed(Stage::Process, error.to_string(), true)), + Err(error) => return Err(failed(Stage::Process, join_reason(&error), true)), } if let Err(error) = processor.validate_token(&token, &self.cancel).await { let invalid = matches!(&error, ProcessError::Backend { code, .. } @@ -1498,18 +1498,18 @@ impl Worker { if invalid && !tokio::fs::try_exists(&license) .await - .map_err(|error| failed(Stage::Process, error.to_string(), true))? + .map_err(|e| failed(Stage::Process, io_reason(&license, &e), true))? { // It has not been fulfilled: do not let a malformed source // checkpoint prevent an explicit retry from resolving again. tokio::fs::remove_file(&token) .await - .map_err(|error| failed(Stage::Process, error.to_string(), true))?; + .map_err(|e| failed(Stage::Process, io_reason(&token, &e), true))?; retryable = true; } return Err(match error { ProcessError::Cancelled => Outcome::Stopped, - error => failed(Stage::Process, error.to_string(), retryable), + error => failed(Stage::Process, error.reason(), retryable), }); } let encrypted = dir.join(format!("encrypted.{}", self.spec.kind.extension())); @@ -1517,7 +1517,7 @@ impl Worker { let output = dir.join("decrypted.part"); let process_error = |error: ProcessError| match error { ProcessError::Cancelled => Outcome::Stopped, - error => failed(Stage::Process, error.to_string(), error.retryable()), + error => failed(Stage::Process, error.reason(), error.retryable()), }; let mut refresh = false; let mut attempts = 0; @@ -1530,14 +1530,14 @@ impl Worker { .map_err(process_error)?; let exists = tokio::fs::try_exists(&encrypted) .await - .map_err(|error| failed(Stage::Fetch, error.to_string(), true))?; + .map_err(|error| failed(Stage::Fetch, io_reason(&encrypted, &error), true))?; if exists { break; } let received = match tokio::fs::metadata(&part).await { Ok(metadata) => metadata.len(), Err(error) if error.kind() == std::io::ErrorKind::NotFound => 0, - Err(error) => return Err(failed(Stage::Fetch, error.to_string(), true)), + Err(error) => return Err(failed(Stage::Fetch, io_reason(&part, &error), true)), }; self.update(Update::State(JobState::Fetching { received, @@ -1577,7 +1577,7 @@ impl Worker { ))); tokio::fs::rename(&part, &encrypted) .await - .map_err(|error| failed(Stage::Fetch, error.to_string(), true))?; + .map_err(|error| failed(Stage::Fetch, io_reason(&part, &error), true))?; break; } Err(FetchError::Expired(_)) if attempts < MAX_RERESOLVES => { @@ -1585,8 +1585,18 @@ impl Worker { refresh = true; } Err(FetchError::Cancelled) => return Err(Outcome::Stopped), + Err(FetchError::Expired(status)) => { + return Err(failed( + Stage::Fetch, + FailReason::LinkExpired { + status, + attempts: MAX_RERESOLVES, + }, + true, + )); + } Err(error) => { - return Err(failed(Stage::Fetch, error.to_string(), error.retryable())); + return Err(failed(Stage::Fetch, error.reason(&part), error.retryable())); } } } @@ -1606,7 +1616,7 @@ impl Worker { let Some(processor) = &self.shared.ebook_processor else { return Err(failed( Stage::Process, - "ebook processing is not configured".to_owned(), + FailReason::ProcessingUnavailable, true, )); }; @@ -1616,7 +1626,13 @@ impl Worker { match tokio::fs::remove_file(&progress_file).await { Ok(()) => {} Err(error) if error.kind() == std::io::ErrorKind::NotFound => {} - Err(error) => return Err(failed(Stage::Process, error.to_string(), true)), + Err(error) => { + return Err(failed( + Stage::Process, + io_reason(&progress_file, &error), + true, + )); + } } self.update(Update::State(JobState::Processing)); let work = processor.reader(self.spec.kind, access, &output, &self.cancel); @@ -1655,7 +1671,7 @@ impl Worker { let expired = matches!(&error, super::ebook::ProcessError::Backend { code, detail } if code == "http" && matches!(detail.as_str(), "400" | "401" | "403" | "410")); let retryable = expired || error.retryable(); - failed(Stage::Process, error.to_string(), retryable) + failed(Stage::Process, error.reason(), retryable) } }); } @@ -1678,18 +1694,18 @@ impl Worker { .write(true) .open(&output) .await - .map_err(|error| failed(Stage::Process, error.to_string(), true))? + .map_err(|error| failed(Stage::Process, io_reason(output, &error), true))? .sync_all() .await - .map_err(|error| failed(Stage::Process, error.to_string(), true))?; + .map_err(|error| failed(Stage::Process, io_reason(output, &error), true))?; tokio::fs::rename(&output, complete) .await - .map_err(|error| failed(Stage::Process, error.to_string(), true))?; + .map_err(|error| failed(Stage::Process, io_reason(output, &error), true))?; let checkpoint_dir = dir.to_path_buf(); tokio::task::spawn_blocking(move || crate::fsutil::sync_dir(&checkpoint_dir)) .await - .map_err(|error| failed(Stage::Process, error.to_string(), true))? - .map_err(|error| failed(Stage::Process, error.to_string(), true))?; + .map_err(|error| failed(Stage::Process, join_reason(&error), true))? + .map_err(|error| failed(Stage::Process, io_reason(dir, &error), true))?; Ok(None) } @@ -1718,7 +1734,11 @@ impl Worker { .insert(self.spec.card_id.clone(), e.message.clone()); Err(Outcome::FatalForCard { message: e.message }) } - Err(e) => Err(failed(Stage::Resolve, e.message, e.retryable)), + Err(e) => Err(failed( + Stage::Resolve, + FailReason::Resolver { message: e.message }, + e.retryable, + )), } } } diff --git a/crates/libbui-core/src/download/engine_tests.rs b/crates/libbui-core/src/download/engine_tests.rs index f03feff..28dcfe9 100644 --- a/crates/libbui-core/src/download/engine_tests.rs +++ b/crates/libbui-core/src/download/engine_tests.rs @@ -812,9 +812,11 @@ async fn content_transport_errors_do_not_expose_signed_urls() { .await .unwrap(); let failed = settled(&mut events, "redaction").await; - let JobState::Failed { message, .. } = failed.state else { + let JobState::Failed { reason, .. } = failed.state else { panic!("expected transport failure") }; + assert!(matches!(reason, FailReason::Network { .. }), "{reason:?}"); + let message = format!("{reason:?}"); assert!(!message.contains("private-token"), "{message}"); assert!(!message.contains("private-signature"), "{message}"); engine.shutdown().await.unwrap(); @@ -1614,7 +1616,9 @@ async fn start_sweeps_only_orphaned_staging() { let mut failed = Job::new(spec("failed", FileKind::Pdf)); failed.state = JobState::Failed { stage: Stage::Fetch, - message: "boom".to_owned(), + reason: FailReason::Network { + detail: "boom".to_owned(), + }, retryable: true, }; let blocked = FakeResolver::new(|_, _| Err(ResolveError::permanent("not today"))); @@ -1773,7 +1777,9 @@ async fn fatal_card_error_fails_that_cards_jobs_only() { finished[card_1], JobState::Failed { stage: Stage::Resolve, - message: "This card has expired.".to_owned(), + reason: FailReason::Resolver { + message: "This card has expired.".to_owned(), + }, retryable: false, }, "{card_1}" diff --git a/crates/libbui-core/src/download/fetch.rs b/crates/libbui-core/src/download/fetch.rs index d9a2e67..0417fd5 100644 --- a/crates/libbui-core/src/download/fetch.rs +++ b/crates/libbui-core/src/download/fetch.rs @@ -102,6 +102,26 @@ pub(crate) enum FetchError { } impl FetchError { + /// The job failure this becomes; `part` is the file being written. + pub(crate) fn reason(&self, part: &Path) -> super::FailReason { + use super::FailReason; + match self { + Self::Expired(status) | Self::Status { status, .. } => { + FailReason::HttpStatus { status: *status } + } + Self::Cancelled => FailReason::Internal { + detail: "cancelled".to_owned(), + }, + Self::Transport(detail) => FailReason::Network { + detail: detail.clone(), + }, + Self::Io(error) => FailReason::Io { + path: Some(part.to_path_buf()), + detail: error.to_string(), + }, + } + } + pub(crate) fn retryable(&self) -> bool { match self { Self::Expired(_) | Self::Transport(_) | Self::Io(_) | Self::Cancelled => true, diff --git a/crates/libbui-core/src/download/finalize.rs b/crates/libbui-core/src/download/finalize.rs index 97a38b2..1aece1a 100644 --- a/crates/libbui-core/src/download/finalize.rs +++ b/crates/libbui-core/src/download/finalize.rs @@ -44,6 +44,19 @@ pub(crate) enum FinalizeError { }, } +impl FinalizeError { + /// The job failure this becomes. + pub(crate) fn reason(&self) -> super::FailReason { + match self { + Self::Io { path, source } => super::FailReason::Io { + path: Some(path.clone()), + detail: source.to_string(), + }, + Self::NoFreeName { path } => super::FailReason::NoFreeName { path: path.clone() }, + } + } +} + /// Where a finished file landed. #[derive(Debug, Clone, PartialEq, Eq)] pub(crate) enum Placed { diff --git a/crates/libbui-core/src/download/job.rs b/crates/libbui-core/src/download/job.rs index ff9924c..08ddfa5 100644 --- a/crates/libbui-core/src/download/job.rs +++ b/crates/libbui-core/src/download/job.rs @@ -231,8 +231,11 @@ pub enum JobState { Failed { /// The step that failed. stage: Stage, - /// What went wrong. - message: String, + /// What went wrong, as data for the front end to put into words. + /// Queues saved before reasons were typed stored an English + /// `message`; it loads as [`FailReason::Legacy`]. + #[serde(alias = "message", deserialize_with = "FailReason::deserialize_compat")] + reason: FailReason, /// Whether trying again might help. retryable: bool, }, @@ -278,6 +281,147 @@ impl JobState { } } +/// Why a job failed. +/// +/// Deliberately not `Display`: front ends map each variant to a localized +/// sentence. The fields are arguments for that sentence (numbers, paths, +/// OS or parser diagnostics), never finished English prose. The `type` tag +/// is stable on disk. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "snake_case")] +pub enum FailReason { + /// A file operation in the staging area failed. + Io { + /// The file or directory involved, when known. + #[serde(default, skip_serializing_if = "Option::is_none")] + path: Option, + /// The operating system's description. + detail: String, + }, + /// The book needs ebook processing (Adobe licence or reader download) + /// and this engine has none. + ProcessingUnavailable, + /// The resolver answered with a licence or reader access for a job of + /// another kind. + MismatchedFulfillment, + /// The resolver (the library account) refused. Its owner wrote the + /// message for readers already. + Resolver { + /// The resolver's message. + message: String, + }, + /// A server answered with an HTTP error status. + HttpStatus { + /// The status code. + status: u16, + }, + /// The download link kept expiring even after fresh ones. + LinkExpired { + /// The last status code. + status: u16, + /// How many fresh links were tried. + attempts: u32, + }, + /// The connection kept failing. + Network { + /// The transport's description. + detail: String, + }, + /// The library handed out a link that is not `https`. + InsecureUrl { + /// The link's host, when it has one. + #[serde(default, skip_serializing_if = "Option::is_none")] + host: Option, + }, + /// The file's size differs from what the server announced. + WrongSize { + /// Announced size in bytes. + expected: u64, + /// Actual size in bytes. + actual: u64, + }, + /// The file is not the format it claims to be. + InvalidFile { + /// The claimed format (`EPUB`, `PDF`, `MP3`, `ACSM`). + kind: String, + /// The parser's diagnostic. + detail: String, + }, + /// Every free name for the book in its library folder is taken. + NoFreeName { + /// The name the template produced. + path: PathBuf, + }, + /// Ebook processing timed out (or another engine holds the + /// authorization). + ProcessingTimeout, + /// The ebook processor produced an invalid reply. + ProcessingInvalidReply, + /// The ebook processor failed with a machine-readable code (see + /// [`super::ebook::ProcessError::Backend`]). + Processing { + /// The processor's code, such as `enrollment-uncertain`. + code: String, + /// A credential-free diagnostic. + detail: String, + }, + /// A bug: a worker panicked or a background task vanished. + Internal { + /// What happened. + detail: String, + }, + /// A reason saved by an older libbui as plain English text. + Legacy { + /// The saved text. + message: String, + }, + /// A reason from a newer libbui this build does not know. + #[serde(other)] + Unknown, +} + +impl FailReason { + /// Reads either a typed reason or the plain string older queues saved. + fn deserialize_compat<'de, D>(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + #[derive(Deserialize)] + #[serde(untagged)] + enum Stored { + Text(String), + Typed(FailReason), + } + Ok(match Stored::deserialize(deserializer)? { + Stored::Text(message) => Self::Legacy { message }, + Stored::Typed(reason) => reason, + }) + } + + /// A short machine-readable name, for logs. + pub fn code(&self) -> &str { + match self { + Self::Io { .. } => "io", + Self::ProcessingUnavailable => "processing_unavailable", + Self::MismatchedFulfillment => "mismatched_fulfillment", + Self::Resolver { .. } => "resolver", + Self::HttpStatus { .. } => "http_status", + Self::LinkExpired { .. } => "link_expired", + Self::Network { .. } => "network", + Self::InsecureUrl { .. } => "insecure_url", + Self::WrongSize { .. } => "wrong_size", + Self::InvalidFile { .. } => "invalid_file", + Self::NoFreeName { .. } => "no_free_name", + Self::ProcessingTimeout => "processing_timeout", + Self::ProcessingInvalidReply => "processing_invalid_reply", + Self::Processing { code, .. } => code, + Self::Internal { .. } => "internal", + Self::Legacy { .. } => "legacy", + Self::Unknown => "unknown", + } + } +} + /// Something that went wrong without failing the job, such as a cover /// that could not be fetched. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -396,7 +540,10 @@ pub(crate) mod tests { let mut job = Job::new(spec("j1", FileKind::Epub)); job.state = JobState::Failed { stage: Stage::Verify, - message: "nope".into(), + reason: FailReason::WrongSize { + expected: 10, + actual: 9, + }, retryable: false, }; job.warnings.push(JobWarning::CoverUnavailable { @@ -408,6 +555,58 @@ pub(crate) mod tests { assert_eq!(back, job); } + #[test] + fn failure_reasons_are_tagged_data() { + let state = JobState::Failed { + stage: Stage::Fetch, + reason: FailReason::LinkExpired { + status: 403, + attempts: 2, + }, + retryable: true, + }; + let value = serde_json::to_value(&state).unwrap(); + assert_eq!( + value, + serde_json::json!({ + "state": "failed", + "stage": "fetch", + "reason": {"type": "link_expired", "status": 403, "attempts": 2}, + "retryable": true, + }) + ); + assert_eq!(serde_json::from_value::(value).unwrap(), state); + } + + #[test] + fn a_plain_text_failure_from_an_older_queue_still_loads() { + let old = r#"{"state":"failed","stage":"verify","message":"not a valid EPUB: no mimetype","retryable":false}"#; + let state: JobState = serde_json::from_str(old).unwrap(); + assert_eq!( + state, + JobState::Failed { + stage: Stage::Verify, + reason: FailReason::Legacy { + message: "not a valid EPUB: no mimetype".to_owned() + }, + retryable: false, + } + ); + } + + #[test] + fn a_failure_type_from_a_newer_libbui_loads_as_unknown() { + let newer = r#"{"state":"failed","stage":"fetch","reason":{"type":"quantum_flux","flux":7},"retryable":true}"#; + let state: JobState = serde_json::from_str(newer).unwrap(); + assert!(matches!( + state, + JobState::Failed { + reason: FailReason::Unknown, + .. + } + )); + } + #[test] fn state_predicates() { assert!( diff --git a/crates/libbui-core/src/download/mod.rs b/crates/libbui-core/src/download/mod.rs index 8f77215..8061738 100644 --- a/crates/libbui-core/src/download/mod.rs +++ b/crates/libbui-core/src/download/mod.rs @@ -46,7 +46,9 @@ use std::time::Duration; pub use engine::{Engine, EngineError, EngineHandle}; pub use fetch::RetryPolicy; -pub use job::{FileKind, InvalidJobId, Job, JobId, JobSpec, JobState, JobWarning, Stage}; +pub use job::{ + FailReason, FileKind, InvalidJobId, Job, JobId, JobSpec, JobState, JobWarning, Stage, +}; pub use progress::Progress; pub use resolve::{ReaderAccess, ReaderKind, ResolveError, Resolved, Resolver}; diff --git a/crates/libbui-core/src/download/store.rs b/crates/libbui-core/src/download/store.rs index e16608e..91ca6b3 100644 --- a/crates/libbui-core/src/download/store.rs +++ b/crates/libbui-core/src/download/store.rs @@ -74,7 +74,7 @@ mod tests { #![allow(clippy::unwrap_used)] use super::*; use crate::download::job::tests::spec; - use crate::download::{FileKind, Stage}; + use crate::download::{FailReason, FileKind, Stage}; #[test] fn round_trip_pauses_in_flight_jobs() { @@ -92,7 +92,7 @@ mod tests { JobState::Paused, JobState::Failed { stage: Stage::Fetch, - message: "x".into(), + reason: FailReason::HttpStatus { status: 503 }, retryable: true, }, JobState::Cancelled, diff --git a/crates/libbui-core/src/download/verify.rs b/crates/libbui-core/src/download/verify.rs index d7fdaa8..f7b0b89 100644 --- a/crates/libbui-core/src/download/verify.rs +++ b/crates/libbui-core/src/download/verify.rs @@ -101,6 +101,27 @@ pub(crate) fn sha256_bytes(bytes: &[u8]) -> String { crate::fsutil::hex(&Sha256::digest(bytes)) } +impl VerifyError { + /// The job failure this becomes; `path` is the file that was checked. + pub(crate) fn reason(&self, path: &Path) -> super::FailReason { + use super::FailReason; + match self { + Self::Io(error) => FailReason::Io { + path: Some(path.to_path_buf()), + detail: error.to_string(), + }, + Self::Length { expected, actual } => FailReason::WrongSize { + expected: *expected, + actual: *actual, + }, + Self::Format { kind, reason } => FailReason::InvalidFile { + kind: (*kind).to_owned(), + detail: reason.clone(), + }, + } + } +} + fn format_err(kind: &'static str, reason: impl Into) -> VerifyError { VerifyError::Format { kind, @@ -647,7 +668,7 @@ const MAX_ACSM_BYTES: u64 = 1024 * 1024; fn check_acsm(path: &Path) -> Result<(), VerifyError> { let len = std::fs::metadata(path)?.len(); if len > MAX_ACSM_BYTES { - return Err(format_err("ACSM file", format!("{len} bytes is too large"))); + return Err(format_err("ACSM", format!("{len} bytes is too large"))); } check_acsm_bytes(&std::fs::read(path)?) } @@ -655,7 +676,7 @@ fn check_acsm(path: &Path) -> Result<(), VerifyError> { /// Validate a token before it becomes a resumable checkpoint. pub(crate) fn check_acsm_bytes(bytes: &[u8]) -> Result<(), VerifyError> { use quick_xml::events::Event; - const KIND: &str = "ACSM file"; + const KIND: &str = "ACSM"; if bytes.len() as u64 > MAX_ACSM_BYTES { return Err(format_err(KIND, "token is too large")); } @@ -699,7 +720,7 @@ fn note_element(root: &mut Option, depth: usize, name: &str) -> Result<( if root.is_none() { *root = Some(name.to_owned()); } else if depth == 0 { - return Err(format_err("ACSM file", "more than one root element")); + return Err(format_err("ACSM", "more than one root element")); } Ok(()) } diff --git a/crates/libbui/locales/en-US/downloads.ftl b/crates/libbui/locales/en-US/downloads.ftl index d6cbbc7..92a6549 100644 --- a/crates/libbui/locales/en-US/downloads.ftl +++ b/crates/libbui/locales/en-US/downloads.ftl @@ -55,6 +55,72 @@ downloads-stage-finalize = saving downloads-retry-may-help = This may be temporary. Press { $key } to try again. downloads-retry-wont-help = Trying again is unlikely to help. +## Why a download failed +## The engine records reasons as data; these are their sentences. $detail is +## a technical diagnostic (an OS or parser message) shown as is. +download-failure-io = A file could not be read or written ({ $detail }). +download-failure-io-path = Could not use { $path } ({ $detail }). +download-failure-processing-unavailable = This book needs a DRM-free conversion, and this libbui was started without one. +download-failure-mismatched = The library sent a different kind of file than this download expects. Remove the download and add it again. +download-failure-http-status = The server refused with HTTP { $status }. +download-failure-link-expired = The download link kept expiring (HTTP { $status }), even after { $attempts -> + [one] one fresh link + *[other] { $attempts } fresh links +}. +download-failure-network = Could not reach the server ({ $detail }). +download-failure-insecure-url = The library sent a link that is not secure (not HTTPS), so libbui did not use it. +download-failure-insecure-url-host = The library sent a link to { $host } that is not secure (not HTTPS), so libbui did not use it. +download-failure-wrong-size = The server promised { $expected -> + [one] { $expected } byte + *[other] { $expected } bytes +} but sent { $actual -> + [one] { $actual } byte + *[other] { $actual } bytes +}. +download-failure-invalid-file = The download is not a valid { $kind } file ({ $detail }). +download-failure-no-free-name = Every file name near { $path } is already taken. +download-failure-processing-timeout = Preparing the DRM-free file took too long. Another libbui may be using the Adobe authorization; close it and try again. +download-failure-processing-invalid-reply = Preparing the DRM-free file stopped unexpectedly. +download-failure-processing = Preparing the DRM-free file failed ({ $code }: { $detail }). +download-failure-adobe-server = The Adobe licence server refused ({ $detail }). +download-failure-unsupported-encryption = This book uses a kind of DRM that libbui cannot remove. +download-failure-invalid-clock = Your computer’s clock looks wrong, so the licence cannot be checked. Correct the date and time and try again. +download-failure-adobe-enrollment-uncertain = libbui could not tell whether registering this computer with Adobe finished. Run “libbui adobe reset” to register again, then retry the download. +download-failure-internal = Something went wrong inside libbui ({ $detail }). Please report this. +download-failure-unknown = This download failed in a newer version of libbui. + +## The download queue itself +download-engine-stopped = The download queue has stopped. +download-engine-unknown-job = There is no download { $id }. +download-engine-duplicate = Download { $id } is already in the queue. +download-engine-invalid-transition = Cannot { $action -> + [pause] pause + [resume] resume + [cancel] cancel + [retry] retry + [remove] remove + *[other] change +} download { $id } while it is { $state -> + [queued] queued + [resolving] asking the library + [fetching] downloading + [processing] being prepared + [verifying] being checked + [finalizing] being saved + [done] finished + [paused] paused + [failed] failed + [cancelled] cancelled + *[other] busy +}. +download-engine-queue-in-use = Another libbui is already using the download queue in { $path }. + +## State files (the download queue, the library index) +state-file-io = Could not use { $path } ({ $detail }). +state-file-corrupt = { $path } could not be read ({ $detail }). It was moved to { $moved_to } and a fresh one will be started. +state-file-newer-version = { $path } was saved by a newer libbui (format version { $version }). Upgrade libbui to use it; the file was left untouched. +state-file-encode = Could not save { $path } ({ $detail }). + ## Details pane downloads-saved-at = Saved at downloads-was-at = Was saved at diff --git a/crates/libbui/src/app/errors.rs b/crates/libbui/src/app/errors.rs index 9c0f2af..21bd4f2 100644 --- a/crates/libbui/src/app/errors.rs +++ b/crates/libbui/src/app/errors.rs @@ -5,6 +5,8 @@ //! sentence exists, and always saying what to do next when there is //! something to do. +use libbui_core::StateFileError; +use libbui_core::download::{EngineError, FailReason}; use libby::Error; use crate::t; @@ -44,3 +46,248 @@ pub fn describe(error: &Error) -> String { other => libby::sanitize::sanitize_line(&other.to_string()), } } + +/// A localized sentence for why a download failed. +/// +/// The engine records failures as data ([`FailReason`]); this is the only +/// place they become words. Technical detail (paths, OS and parser +/// diagnostics) is passed through as an argument, cleaned of control +/// characters, never stitched into English here. +#[must_use] +pub fn describe_failure(reason: &FailReason) -> String { + use libby::sanitize::sanitize_line as clean; + match reason { + FailReason::Io { + path: Some(path), + detail, + } => t!( + "download-failure-io-path", + path = clean(&path.display().to_string()), + detail = clean(detail) + ), + FailReason::Io { path: None, detail } => { + t!("download-failure-io", detail = clean(detail)) + } + FailReason::ProcessingUnavailable => t!("download-failure-processing-unavailable"), + FailReason::MismatchedFulfillment => t!("download-failure-mismatched"), + FailReason::Resolver { message } => clean(message), + FailReason::HttpStatus { status } => { + t!("download-failure-http-status", status = *status) + } + FailReason::LinkExpired { status, attempts } => t!( + "download-failure-link-expired", + status = *status, + attempts = *attempts + ), + FailReason::Network { detail } => { + t!("download-failure-network", detail = clean(detail)) + } + FailReason::InsecureUrl { host: Some(host) } => { + t!("download-failure-insecure-url-host", host = clean(host)) + } + FailReason::InsecureUrl { host: None } => t!("download-failure-insecure-url"), + FailReason::WrongSize { expected, actual } => t!( + "download-failure-wrong-size", + expected = *expected, + actual = *actual + ), + FailReason::InvalidFile { kind, detail } => t!( + "download-failure-invalid-file", + kind = clean(kind), + detail = clean(detail) + ), + FailReason::NoFreeName { path } => t!( + "download-failure-no-free-name", + path = clean(&path.display().to_string()) + ), + FailReason::ProcessingTimeout => t!("download-failure-processing-timeout"), + FailReason::ProcessingInvalidReply => t!("download-failure-processing-invalid-reply"), + FailReason::Processing { code, detail } => describe_processing(code, detail), + FailReason::Internal { detail } => { + t!("download-failure-internal", detail = clean(detail)) + } + FailReason::Legacy { message } => clean(message), + FailReason::Unknown => t!("download-failure-unknown"), + } +} + +/// Ebook processing failures with a code a reader can act on get their +/// own sentence; the rest share one that names the code for bug reports. +fn describe_processing(code: &str, detail: &str) -> String { + use libby::sanitize::sanitize_line as clean; + match code { + "enrollment-uncertain" => t!("download-failure-adobe-enrollment-uncertain"), + "insecure-url" => t!("download-failure-insecure-url"), + "network" => t!("download-failure-network", detail = clean(detail)), + "http" => match detail.parse::() { + Ok(status) => t!("download-failure-http-status", status = status), + Err(_) => t!( + "download-failure-processing", + code = clean(code), + detail = clean(detail) + ), + }, + "server" => t!("download-failure-adobe-server", detail = clean(detail)), + "unsupported-encryption" => t!("download-failure-unsupported-encryption"), + "invalid-clock" => t!("download-failure-invalid-clock"), + _ => t!( + "download-failure-processing", + code = clean(code), + detail = clean(detail) + ), + } +} + +/// A localized sentence for a download engine error. +#[must_use] +pub fn describe_engine(error: &EngineError) -> String { + match error { + EngineError::Stopped => t!("download-engine-stopped"), + EngineError::UnknownJob(id) => t!("download-engine-unknown-job", id = id.as_str()), + EngineError::Duplicate(id) => t!("download-engine-duplicate", id = id.as_str()), + EngineError::InvalidTransition { id, state, action } => t!( + "download-engine-invalid-transition", + id = id.as_str(), + state = *state, + action = *action + ), + EngineError::State(error) => describe_state_file(error), + EngineError::QueueInUse { path } => t!( + "download-engine-queue-in-use", + path = path.display().to_string() + ), + } +} + +/// A localized sentence for a state file (download queue, library index) +/// that could not be used. +#[must_use] +pub fn describe_state_file(error: &StateFileError) -> String { + use libby::sanitize::sanitize_line as clean; + match error { + StateFileError::Io { path, source } => t!( + "state-file-io", + path = path.display().to_string(), + detail = clean(&source.to_string()) + ), + StateFileError::Corrupt { + path, + moved_to, + message, + } => t!( + "state-file-corrupt", + path = path.display().to_string(), + moved_to = moved_to.display().to_string(), + detail = clean(message) + ), + StateFileError::NewerVersion { path, version } => t!( + "state-file-newer-version", + path = path.display().to_string(), + version = *version + ), + StateFileError::Encode { path, source } => t!( + "state-file-encode", + path = path.display().to_string(), + detail = clean(&source.to_string()) + ), + } +} + +#[cfg(test)] +mod tests { + #![allow(clippy::unwrap_used)] + use std::path::PathBuf; + + use libbui_core::StateFileError; + use libbui_core::download::{EngineError, FailReason, JobId}; + + use super::{describe_engine, describe_failure, describe_state_file}; + + #[test] + fn counts_choose_their_plural() { + let once = describe_failure(&FailReason::LinkExpired { + status: 403, + attempts: 1, + }); + assert_eq!( + once, + "The download link kept expiring (HTTP 403), even after one fresh link." + ); + let twice = describe_failure(&FailReason::LinkExpired { + status: 410, + attempts: 2, + }); + assert_eq!( + twice, + "The download link kept expiring (HTTP 410), even after 2 fresh links." + ); + let size = describe_failure(&FailReason::WrongSize { + expected: 1, + actual: 0, + }); + assert_eq!(size, "The server promised 1 byte but sent 0 bytes."); + } + + #[test] + fn technical_detail_is_an_argument_cleaned_of_controls() { + let text = describe_failure(&FailReason::Io { + path: Some(PathBuf::from("/books/a\u{1b}[31m.part")), + detail: "No space left on device (os error 28)\nsecond line".to_owned(), + }); + assert!(!text.contains('\u{1b}'), "{text:?}"); + assert!(!text.contains('\n'), "{text:?}"); + assert!(text.contains("No space left on device"), "{text}"); + } + + #[test] + fn a_reason_saved_as_text_by_an_older_libbui_is_shown_as_saved() { + let text = describe_failure(&FailReason::Legacy { + message: "not a valid EPUB: no mimetype".to_owned(), + }); + assert_eq!(text, "not a valid EPUB: no mimetype"); + } + + #[test] + fn processing_codes_with_a_remedy_get_their_own_sentence() { + let uncertain = describe_failure(&FailReason::Processing { + code: "enrollment-uncertain".to_owned(), + detail: String::new(), + }); + assert!(uncertain.contains("libbui adobe reset"), "{uncertain}"); + let http = describe_failure(&FailReason::Processing { + code: "http".to_owned(), + detail: "503".to_owned(), + }); + assert_eq!(http, "The server refused with HTTP 503."); + let other = describe_failure(&FailReason::Processing { + code: "invalid-pdf".to_owned(), + detail: "missing trailer".to_owned(), + }); + assert!(other.contains("invalid-pdf"), "{other}"); + assert!(other.contains("missing trailer"), "{other}"); + } + + #[test] + fn engine_and_state_file_errors_are_sentences() { + let newer = describe_state_file(&StateFileError::NewerVersion { + path: PathBuf::from("/state/downloads.json"), + version: 2, + }); + assert_eq!( + newer, + "/state/downloads.json was saved by a newer libbui (format version 2). \ + Upgrade libbui to use it; the file was left untouched." + ); + let busy = describe_engine(&EngineError::InvalidTransition { + id: JobId::new("abc").unwrap(), + state: "finalizing", + action: "cancel", + }); + assert_eq!(busy, "Cannot cancel download abc while it is being saved."); + let wrapped = describe_engine(&EngineError::State(StateFileError::NewerVersion { + path: PathBuf::from("q.json"), + version: 9, + })); + assert!(wrapped.contains("format version 9"), "{wrapped}"); + } +} diff --git a/crates/libbui/src/app/mod.rs b/crates/libbui/src/app/mod.rs index 66524af..dd972ff 100644 --- a/crates/libbui/src/app/mod.rs +++ b/crates/libbui/src/app/mod.rs @@ -1425,10 +1425,10 @@ impl App { JobState::Done { .. } => self .toasts .push(Toast::success(t!("download-done", title = title))), - JobState::Failed { message, .. } => self.toasts.push(Toast::error(t!( + JobState::Failed { reason, .. } => self.toasts.push(Toast::error(t!( "download-failed", title = title, - reason = message.as_str() + reason = errors::describe_failure(reason) ))), _ => {} } diff --git a/crates/libbui/src/app/walk_tests.rs b/crates/libbui/src/app/walk_tests.rs index bc6953b..8a5cda1 100644 --- a/crates/libbui/src/app/walk_tests.rs +++ b/crates/libbui/src/app/walk_tests.rs @@ -6,7 +6,7 @@ use std::collections::BTreeSet; use std::time::Duration; -use libbui_core::download::{Event, JobState, Progress, Stage}; +use libbui_core::download::{Event, FailReason, JobState, Progress, Stage}; use super::Shared; use crate::testing::{FakeState, Harness, done, search_page, sync_state}; @@ -138,7 +138,9 @@ pub(super) async fn walk( 3, JobState::Failed { stage: Stage::Fetch, - message: "the connection closed early".to_owned(), + reason: FailReason::Network { + detail: "the connection closed early".to_owned(), + }, retryable: true, }, ) diff --git a/crates/libbui/src/cli/download.rs b/crates/libbui/src/cli/download.rs index 95ad3a8..f1414be 100644 --- a/crates/libbui/src/cli/download.rs +++ b/crates/libbui/src/cli/download.rs @@ -29,6 +29,7 @@ use super::exit::Failure; use super::output::{Io, Tone}; use super::{DownloadArgs, Env}; use crate::api::Api; +use crate::app::errors::{describe_engine, describe_failure, describe_state_file}; use crate::services::LoanResolver; use crate::t; use crate::ui::text::{bytes, truncate, width}; @@ -219,7 +220,7 @@ pub(crate) async fn run( let card = super::account::card_filter(&state, args.card.as_deref())?.map(|card| card.id.clone()); let index = LibraryIndex::load(setup.paths.library_index_file()) - .map_err(|error| Failure::Failed(error.to_string()))?; + .map_err(|error| Failure::Failed(describe_state_file(&error)))?; let (fetch, mut reports) = plan(&state.loans, args, card.as_ref(), &index)?; for report in &reports { @@ -265,11 +266,11 @@ pub(crate) async fn run( let resolver = Arc::new(LoanResolver::with_state(api, &state)); let (engine, events) = Engine::start(&setup.paths, setup.settings, resolver, setup.client) - .map_err(|error| Failure::Failed(error.to_string()))?; + .map_err(|error| Failure::Failed(describe_engine(&error)))?; let outcome = drive(cx, &engine, events, &fetch, interrupt, io).await; let shutdown = engine.shutdown().await; let mut finished = outcome?; - shutdown.map_err(|error| Failure::Failed(error.to_string()))?; + shutdown.map_err(|error| Failure::Failed(describe_engine(&error)))?; let interrupted = finished.iter().any(|r| r.outcome == Outcome::Paused); let failed = finished @@ -423,14 +424,14 @@ async fn drive( } fn engine_failure(error: libbui_core::download::EngineError) -> Failure { - Failure::Failed(t!("cli-engine-failed", reason = error.to_string())) + Failure::Failed(t!("cli-engine-failed", reason = describe_engine(&error))) } /// The report for a job that has finished, or `None` while it runs. fn settle(job: &Job, loan: &Loan) -> Option { let (outcome, path, reason) = match &job.state { JobState::Done { path, .. } => (Outcome::Done, Some(path.display().to_string()), None), - JobState::Failed { message, .. } => (Outcome::Failed, None, Some(message.clone())), + JobState::Failed { reason, .. } => (Outcome::Failed, None, Some(describe_failure(reason))), JobState::Cancelled => (Outcome::Failed, None, Some(t!("cli-download-cancelled"))), _ => return None, }; diff --git a/crates/libbui/src/screens/detail/view.rs b/crates/libbui/src/screens/detail/view.rs index 922d8d9..d4144df 100644 --- a/crates/libbui/src/screens/detail/view.rs +++ b/crates/libbui/src/screens/detail/view.rs @@ -847,10 +847,13 @@ fn download_field(id: &libby::TitleId, shared: &Shared) -> Option { t!("detail-file-paused"), theme.warning, ), - JobState::Failed { message, .. } => Field::marked( + JobState::Failed { reason, .. } => Field::marked( label, symbols.error, - t!("detail-file-failed", reason = sanitize_line(message)), + t!( + "detail-file-failed", + reason = crate::app::errors::describe_failure(reason) + ), theme.danger, ), JobState::Cancelled => return None, diff --git a/crates/libbui/src/screens/downloads/mod.rs b/crates/libbui/src/screens/downloads/mod.rs index f9d743d..6491b00 100644 --- a/crates/libbui/src/screens/downloads/mod.rs +++ b/crates/libbui/src/screens/downloads/mod.rs @@ -26,6 +26,7 @@ use ratatui::style::Style; use ratatui::text::{Line, Span}; use ratatui::widgets::{Block, Paragraph, Scrollbar, ScrollbarOrientation, ScrollbarState}; +use crate::app::errors::describe_failure; use crate::app::{Ctx, QueueOff, Request, Shared}; use crate::keymap::{Command, Context}; use crate::screens::{Handled, Screen}; @@ -399,13 +400,13 @@ fn state_words( ), JobState::Done { bytes, .. } => finished(*bytes, job.updated_at), JobState::Paused => (symbols.paused, theme.warning, t!("downloads-state-paused")), - JobState::Failed { stage, message, .. } => ( + JobState::Failed { stage, reason, .. } => ( symbols.error, theme.danger, t!( "downloads-state-failed", stage = t!(stage_key(*stage)), - message = message.as_str() + message = describe_failure(reason) ), ), JobState::Cancelled => (symbols.dot, theme.muted, t!("downloads-state-cancelled")), @@ -909,7 +910,7 @@ impl Downloads { None => match entry.state() { Some(JobState::Failed { stage, - message, + reason, retryable, }) => { lines.push(Line::from(vec![ @@ -921,7 +922,7 @@ impl Downloads { style, ), ])); - para(&mut lines, message, theme.text); + para(&mut lines, &describe_failure(reason), theme.text); let advice = if *retryable { t!( "downloads-retry-may-help", diff --git a/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_failed_details.snap b/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_failed_details.snap index b68e41c..1cf616d 100644 --- a/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_failed_details.snap +++ b/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_failed_details.snap @@ -13,7 +13,7 @@ expression: screen │ 三体 EPUB ⠋ Asking the library… │ │ │ │ ✗ Failed 1 │ -│▌ The New Yorker: Nov 9, 2026 EPUB ✗ Failed while downloading: the server closed the c… │ +│▌ The New Yorker: Nov 9, 2026 EPUB ✗ Failed while downloading: Could not reach the ser… │ │ │ │ ↓ Finished 1 │ │ Designing Data-Intensive Applicati… EPUB ! File missing · 9.4 MB │ @@ -24,7 +24,7 @@ expression: screen │ Open EPUB ebook │ │ │ │ ✗ Failed while downloading │ -│ the server closed the connection before the file was complete │ +│ Could not reach the server (connection closed before message completed). │ │ │ │ This may be temporary. Press r to try again. │ │ │ diff --git a/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_60x16.snap b/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_60x16.snap index a337cfa..530d9e4 100644 --- a/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_60x16.snap +++ b/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_60x16.snap @@ -13,7 +13,7 @@ expression: h.screen() │ 三体 ⠋ Asking the library… ┃ │ ┃ │ ✗ Failed 1 ┃ -│ The New Yorker: Nov 9,… ✗ Failed while downloading: t… ┃ +│ The New Yorker: Nov 9,… ✗ Failed while downloading: C… ┃ │ ┃ │ ↓ Finished 1 ┃ ╰──────────────────────────────────────────────────────────╯ diff --git a/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_80x24.snap b/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_80x24.snap index 556e20d..2efd273 100644 --- a/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_80x24.snap +++ b/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_80x24.snap @@ -13,7 +13,7 @@ expression: h.screen() │ 三体 EPUB ⠋ Asking the library… │ │ │ │ ✗ Failed 1 │ -│ The New Yorker: Nov 9, 20… EPUB ✗ Failed while downloading: the server c… │ +│ The New Yorker: Nov 9, 20… EPUB ✗ Failed while downloading: Could not re… │ │ │ │ ↓ Finished 1 │ │ Designing Data-Intensive… EPUB ! File missing · 9.4 MB │ diff --git a/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_ascii.snap b/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_ascii.snap index 828f62f..fed3f65 100644 --- a/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_ascii.snap +++ b/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_ascii.snap @@ -13,7 +13,7 @@ expression: h.screen() | 三体 EPUB | Asking the library... | | | | x Failed 1 | -| The New Yorker: Nov 9, 2026 EPUB x Failed while downloading: the server closed the... | +| The New Yorker: Nov 9, 2026 EPUB x Failed while downloading: Could not reach the s... | | | | v Finished 1 | | Designing Data-Intensive Applica... EPUB ! File missing - 9.4 MB | diff --git a/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_wide.snap b/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_wide.snap index 6fb4979..6bb1265 100644 --- a/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_wide.snap +++ b/crates/libbui/src/screens/downloads/snapshots/libbui__screens__downloads__tests__snapshot_mixed_queue_wide.snap @@ -13,7 +13,7 @@ expression: h.screen() │ 三体 EPUB ⠋ Asking the library… ││ 1.4 MB of 3.8 MB │ │ ││ 500 KB/s · less than a minute left │ │ ✗ Failed 1 ││ │ -│ The New Yorker: Nov 9, 2026 EPUB ✗ Failed while downloading: the server clo… ││ │ +│ The New Yorker: Nov 9, 2026 EPUB ✗ Failed while downloading: Could not reac… ││ │ │ ││ │ │ ↓ Finished 1 ││ │ │ Designing Data-Intensive Ap… EPUB ! File missing · 9.4 MB ││ │ diff --git a/crates/libbui/src/screens/downloads/tests.rs b/crates/libbui/src/screens/downloads/tests.rs index 9ab105d..c27cd07 100644 --- a/crates/libbui/src/screens/downloads/tests.rs +++ b/crates/libbui/src/screens/downloads/tests.rs @@ -6,7 +6,7 @@ use std::path::PathBuf; use std::time::Duration; use jiff::Timestamp; -use libbui_core::download::{Event, FileKind, Job, JobId, JobState, Progress, Stage}; +use libbui_core::download::{Event, FailReason, FileKind, Job, JobId, JobState, Progress, Stage}; use libbui_core::library::LibraryEntry; use super::{Key, Presence, Section, arrange, gauge_cells, percent, speed}; @@ -42,7 +42,9 @@ fn progress(job: &Job, received: u64, total: Option, rate: f64, eta: Option fn failed(retryable: bool) -> JobState { JobState::Failed { stage: Stage::Fetch, - message: "the server closed the connection before the file was complete".to_owned(), + reason: FailReason::Network { + detail: "connection closed before message completed".to_owned(), + }, retryable, } } @@ -312,6 +314,25 @@ async fn snapshot_failed_details() { insta::assert_snapshot!(screen); } +#[tokio::test] +async fn a_failure_saved_as_text_by_an_older_libbui_still_shows() { + // Queues written before failures were typed stored an English sentence. + let old: JobState = serde_json::from_str( + r#"{"state":"failed","stage":"verify","message":"not a valid EPUB: no mimetype","retryable":false}"#, + ) + .unwrap(); + let mut h = on_downloads(100, 30, |_| {}).await; + h.job(0, old).await; + let screen = h.screen(); + assert!( + screen.contains("Failed while checking the file: not a valid EPUB"), + "{screen}" + ); + h.keys(&["j"]).await; + let screen = h.screen(); + assert!(screen.contains("not a valid EPUB: no mimetype"), "{screen}"); +} + #[tokio::test] async fn snapshot_empty_says_what_and_where() { let mut h = on_downloads(80, 24, |shared| { diff --git a/crates/libbui/src/screens/shelf/view.rs b/crates/libbui/src/screens/shelf/view.rs index 69972e1..e8e546c 100644 --- a/crates/libbui/src/screens/shelf/view.rs +++ b/crates/libbui/src/screens/shelf/view.rs @@ -831,10 +831,10 @@ fn download_value(loan: &Loan, width: usize, shared: &Shared) -> Value { )] } Some(JobState::Paused) => vec![line(symbols.paused, t!("shelf-dl-paused"), theme.warning)], - Some(JobState::Failed { message, .. }) => { + Some(JobState::Failed { reason, .. }) => { let mut rows = vec![line(symbols.error, t!("shelf-dl-failed"), theme.danger)]; rows.extend( - text::wrap(message, width) + text::wrap(&crate::app::errors::describe_failure(reason), width) .into_iter() .take(3) .map(|row| vec![Span::styled(row, theme.muted)]), diff --git a/crates/libbui/src/startup.rs b/crates/libbui/src/startup.rs index b2cef5b..5d6ebba 100644 --- a/crates/libbui/src/startup.rs +++ b/crates/libbui/src/startup.rs @@ -82,7 +82,10 @@ pub async fn launch(args: Args) -> Result<()> { let (_, events) = tokio::sync::mpsc::unbounded_channel(); (None, events) } - Err(error) => return Err(error).wrap_err("could not start the download queue"), + Err(error) => { + let sentence = crate::app::errors::describe_engine(&error); + return Err(error).wrap_err(sentence); + } }; let downloads = Downloads { jobs: match &engine { @@ -93,10 +96,15 @@ pub async fn launch(args: Args) -> Result<()> { None => Vec::new(), }, off: engine.is_none().then_some(QueueOff::Elsewhere), - index: LibraryIndex::load(paths.library_index_file()) - .wrap_err("could not read the library index")? - .entries() - .to_vec(), + index: match LibraryIndex::load(paths.library_index_file()) { + Ok(index) => index, + Err(error) => { + let sentence = crate::app::errors::describe_state_file(&error); + return Err(error).wrap_err(sentence); + } + } + .entries() + .to_vec(), library_dir: Some(config.download_dir(&paths)), ..Downloads::default() }; -- knotmirror 0.0.1 From 2d51f62e37db299aff803ddeecc98ed35588badf Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Mon, 16 Nov 2026 20:47:03 -0500 Subject: [PATCH 3/4] fix(downloads): refuse plain-HTTP content, licence and reader URLs Content links, cover URLs, Adobe operator and licence URLs and reader origins from the API were accepted over plain HTTP, and the content client followed redirects from HTTPS to HTTP. Every URL the engine or the Adobe processor fetches must now be HTTPS (Adobe's own endpoints are still upgraded). The content client refuses redirects to anything else. A refusal fails the job for good with a localised reason naming the host. Plain HTTP to loopback stays possible for wiremock, only in this crate's tests and through the test-loopback-http feature, which libbui enables from its dev-dependencies alone. --- crates/libbui-core/Cargo.toml | 6 + crates/libbui-core/src/covers.rs | 19 +++ crates/libbui-core/src/download/adobe/mod.rs | 4 + .../libbui-core/src/download/adobe/tests.rs | 41 ++++++ crates/libbui-core/src/download/ebook.rs | 14 ++ .../libbui-core/src/download/engine_tests.rs | 103 +++++++++++++++ crates/libbui-core/src/download/fetch.rs | 29 +++++ crates/libbui-core/src/download/mod.rs | 1 + .../libbui-core/src/download/reader/tests.rs | 22 ++++ .../src/download/reader/transport.rs | 4 + crates/libbui-core/src/download/secure.rs | 121 ++++++++++++++++++ crates/libbui/Cargo.toml | 2 + crates/libbui/src/cli/download/tests.rs | 22 ++++ crates/libbui/src/startup.rs | 31 ++++- 14 files changed, 418 insertions(+), 1 deletion(-) create mode 100644 crates/libbui-core/src/download/secure.rs 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); + } +} -- knotmirror 0.0.1 From ecbaf803a93d1f06b87efbf0d7ba3edf08f6cf72 Mon Sep 17 00:00:00 2001 From: Vincent Taverna Date: Mon, 16 Nov 2026 20:55:37 -0500 Subject: [PATCH 4/4] fix(adobe): recover from an interrupted device registration If the anonymous Adobe sign-in was interrupted before its reply arrived, libbui marked the authorization as uncertain and refused every Adobe download from then on, with nothing to clear the mark. Signing in again is safe: an anonymous sign-in only creates an identity with fresh keys and activates no device, so it cannot use up an activation. The mark now records when the sign-in started. libbui waits out a 15-minute cool-down and then signs in again by itself; marks from older versions carry no time and are retried at once. A refusal from Adobe (an error reply or a 4xx) settles the sign-in instead of leaving it uncertain. The failure is retryable and its message says when libbui will try again. `libbui adobe reset` forgets an interrupted sign-in so the next download registers at once. It never touches a finished authorization. doctor now shows its ebook and reader reasons as localised sentences. --- README.md | 6 + crates/libbui-core/src/download/adobe/mod.rs | 104 +++++++-- .../libbui-core/src/download/adobe/tests.rs | 205 +++++++++++++++++- crates/libbui-core/src/download/ebook.rs | 23 +- crates/libbui/locales/en-US/cli.ftl | 3 + crates/libbui/locales/en-US/downloads.ftl | 5 +- crates/libbui/src/app/errors.rs | 6 +- crates/libbui/src/cli/account.rs | 1 + crates/libbui/src/cli/doctor.rs | 11 +- crates/libbui/src/cli/local.rs | 33 ++- crates/libbui/src/cli/mod.rs | 19 ++ crates/libbui/tests/cli.rs | 61 ++++++ 12 files changed, 455 insertions(+), 22 deletions(-) diff --git a/README.md b/README.md index 65bff3f..5d078a7 100644 --- a/README.md +++ b/README.md @@ -279,6 +279,7 @@ error, so piping stays clean. | `libbui config init [--force] \| show \| path` | Write a commented configuration file, show the one in effect, or print its path. | | `libbui completions SHELL` | Completion script for bash, zsh, fish, elvish or powershell. | | `libbui doctor [--online]` | Check the terminal, configuration and pairing. Makes no request unless `--online` (then exactly one sync). | +| `libbui adobe reset [--json]` | Forget an interrupted Adobe registration so the next download registers again at once. A finished registration is never touched. | `CARD` is a card id or a library key, as listed by `libbui cards`. Every command that takes a title id accepts the ids printed by `loans`, `holds` @@ -418,6 +419,11 @@ still works. - **A title says "Download not supported"**: libbui has no download path for the offered format. Press `o` to open the title in Libby and see its other reading or device-transfer options. +- **"libbui could not tell whether registering this device with Adobe + finished"**: the first Adobe download was interrupted while it registered + this device. libbui registers again by itself 15 minutes later; run + `libbui adobe reset` to do it at once. Registering again uses no Adobe + device activation. - **Odd characters or broken borders**: use a font with box drawing characters, or start with `--ascii`. - **Colours look wrong**: try `--theme dark`, `--theme light` or diff --git a/crates/libbui-core/src/download/adobe/mod.rs b/crates/libbui-core/src/download/adobe/mod.rs index 7aa140c..95c85e4 100644 --- a/crates/libbui-core/src/download/adobe/mod.rs +++ b/crates/libbui-core/src/download/adobe/mod.rs @@ -85,6 +85,10 @@ struct State { operators: Vec, #[serde(default, skip_serializing_if = "std::ops::Not::not")] enrollment_pending: bool, + /// When the pending sign-in was sent, in Unix seconds. Absent in files + /// written before the cool-down existed. + #[serde(default, skip_serializing_if = "Option::is_none")] + enrollment_started: Option, } impl Drop for State { fn drop(&mut self) { @@ -117,6 +121,54 @@ struct License { notification_index: usize, } +/// How long an anonymous sign-in whose outcome is unknown is left alone +/// before libbui signs in again by itself. +/// +/// Signing in again is safe: an anonymous sign-in only creates an Adobe +/// identity with fresh keys and activates no device, so it cannot use up +/// an activation slot. A lost reply leaves an unused identity on Adobe's +/// side, nothing more. The wait only keeps a run of interrupted attempts +/// from hammering Adobe. +pub(crate) const ENROLLMENT_COOL_DOWN: Duration = Duration::from_secs(15 * 60); + +fn unix_now() -> i64 { + jiff::Timestamp::now().as_second() +} + +/// Refuses to sign in while an earlier sign-in's outcome is unknown and +/// recent. A file from before the cool-down existed has no start time and +/// is treated as long past, as is a start time in the future (the clock +/// went back). +fn enrollment_gate(state: &State, now: i64) -> Result<()> { + let wait = i64::try_from(ENROLLMENT_COOL_DOWN.as_secs()).unwrap_or(i64::MAX); + match state.enrollment_started { + Some(started) if state.enrollment_pending && (0..wait).contains(&(now - started)) => { + Err(fail( + "enrollment-uncertain", + "the previous anonymous sign-in was interrupted; waiting before signing in again", + )) + } + _ => Ok(()), + } +} + +/// Whether Adobe answered a sign-in with a refusal, so it created nothing +/// and the sign-in can be forgotten rather than left uncertain. A lost +/// connection, a cancellation, a garbled reply or a 5xx (a gateway may +/// time out after Adobe acted) stay uncertain. +fn refused_outright(error: &ProcessError) -> bool { + match error { + ProcessError::Backend { code, detail } => { + code == "server" + || (code == "http" + && detail + .parse::() + .is_ok_and(|status| (400..500).contains(&status))) + } + _ => false, + } +} + fn load(path: &Path) -> Result { let mut bytes = Zeroizing::new(Vec::new()); std::fs::File::open(path)? @@ -310,18 +362,14 @@ impl Service { activation_url: None, operators: Vec::new(), enrollment_pending: false, + enrollment_started: None, }; store(&path, &state)?; state }; validate_state(&state)?; if state.pkcs12.is_none() { - if state.enrollment_pending { - return Err(fail( - "enrollment-uncertain", - "the previous anonymous sign-in response was interrupted; authorization must be recovered before enrolling again", - )); - } + enrollment_gate(&state, unix_now())?; let info = self .request( &format!( @@ -353,14 +401,26 @@ impl Service { .map_err(|_| fail("backend", "key generation task"))??; cancelled(cancel)?; state.enrollment_pending = true; + state.enrollment_started = Some(unix_now()); store(&path, &state)?; - let credentials = self + let credentials = match self .request( &format!("{}/SignInDirect", auth.as_str().trim_end_matches('/')), Some(&enrollment), cancel, ) - .await?; + .await + { + Ok(credentials) => credentials, + Err(error) => { + if refused_outright(&error) { + state.enrollment_pending = false; + state.enrollment_started = None; + store(&path, &state)?; + } + return Err(error); + } + }; if !credentials.is(ADEPT, "credentials") { return Err(fail("invalid-response", "credentials")); } @@ -375,6 +435,7 @@ impl Service { crypto::private(&private)?; state.private_license_key = Some(b64(private.as_slice())); state.enrollment_pending = false; + state.enrollment_started = None; crypto::verify_enrollment(&enrollment, &state)?; validate_state(&state)?; store(&path, &state)?; @@ -754,15 +815,30 @@ pub(crate) fn check(account: &Path) -> Result<()> { if path.try_exists()? { let state: State = load(&path)?; validate_state(&state)?; - if state.enrollment_pending { - return Err(fail( - "enrollment-uncertain", - "interrupted anonymous sign-in", - )); - } + enrollment_gate(&state, unix_now())?; } Ok(()) } + +/// Forgets an anonymous sign-in whose outcome is unknown, so the next +/// download signs in again at once instead of waiting out +/// [`ENROLLMENT_COOL_DOWN`]. Returns whether there was one. An +/// authorization that finished signing in is never touched. +pub(crate) fn reset_enrollment(account: &Path) -> Result { + let path = account.join("authorization.json"); + if !path.try_exists()? { + return Ok(false); + } + let mut state: State = load(&path)?; + validate_state(&state)?; + if !state.enrollment_pending || state.pkcs12.is_some() { + return Ok(false); + } + state.enrollment_pending = false; + state.enrollment_started = None; + store(&path, &state)?; + Ok(true) +} pub(crate) fn validate_token(token: &Path) -> Result<()> { read_token(token).map(|_| ()) } diff --git a/crates/libbui-core/src/download/adobe/tests.rs b/crates/libbui-core/src/download/adobe/tests.rs index aa46ed4..148fa29 100644 --- a/crates/libbui-core/src/download/adobe/tests.rs +++ b/crates/libbui-core/src/download/adobe/tests.rs @@ -254,7 +254,7 @@ async fn error_replies_never_expose_private_response_content() { } #[tokio::test] -async fn ambiguous_enrollment_never_creates_another_identity() { +async fn a_recent_uncertain_enrollment_never_creates_another_identity() { let temp = tempfile::tempdir().unwrap(); let path = temp.path().join("authorization.json"); let state = State { @@ -270,6 +270,7 @@ async fn ambiguous_enrollment_never_creates_another_identity() { activation_url: None, operators: Vec::new(), enrollment_pending: true, + enrollment_started: Some(unix_now()), }; store(&path, &state).unwrap(); assert!( @@ -572,6 +573,208 @@ async fn interrupted_enrollment_is_durable_and_preflight_stops_before_any_repeat assert_eq!(server.received_requests().await.unwrap().len(), 3); } +/// A server for an anonymous sign-in whose first `SignInDirect` reply is +/// garbled (so its outcome is unknown) and whose later ones refuse. +async fn sign_in_server() -> MockServer { + let server = MockServer::start().await; + let certificate = fixture_state().license_certificate.clone().unwrap(); + Mock::given(method("GET")).and(path("/ActivationServiceInfo")) + .respond_with(ResponseTemplate::new(200).set_body_string(format!("{}",server.uri()))) + .mount(&server).await; + Mock::given(method("GET")).and(path("/AuthenticationServiceInfo")) + .respond_with(ResponseTemplate::new(200).set_body_string(format!("{certificate}"))) + .mount(&server).await; + Mock::given(method("POST")) + .and(path("/SignInDirect")) + .respond_with(ResponseTemplate::new(200).set_body_string("")), + ) + .mount(&server) + .await; + server +} + +async fn sign_ins(server: &MockServer) -> usize { + server + .received_requests() + .await + .unwrap() + .iter() + .filter(|request| request.url.path() == "/SignInDirect") + .count() +} + +fn uncertain(result: &Result) -> bool { + matches!(result, Err(ProcessError::Backend { code, .. }) if code == "enrollment-uncertain") +} + +#[tokio::test] +async fn an_uncertain_sign_in_is_tried_again_after_the_cool_down() { + let server = sign_in_server().await; + let mut service = Service::new().unwrap(); + service.activation = url(&server.uri()).unwrap(); + let temp = tempfile::tempdir().unwrap(); + let file = temp.path().join("authorization.json"); + let cancel = CancellationToken::new(); + + // A garbled reply: Adobe may or may not have created the identity. + assert!(matches!( + service.authorize(temp.path(), &cancel).await, + Err(ProcessError::Backend { code, .. }) if code == "invalid-xml" + )); + let pending: State = load(&file).unwrap(); + assert!(pending.enrollment_pending); + let started = pending.enrollment_started.unwrap(); + assert!((unix_now() - started).abs() < 60); + // Within the cool-down, nothing is sent and a retry is worth offering. + let refused = service.authorize(temp.path(), &cancel).await; + assert!(uncertain(&refused)); + let Err(refused) = refused else { + panic!("signed in again within the cool-down") + }; + assert!(refused.retryable()); + assert!(uncertain(&check(temp.path()))); + assert_eq!(sign_ins(&server).await, 1); + + // Once the cool-down has passed, libbui signs in again by itself. + let mut aged: State = load(&file).unwrap(); + aged.enrollment_started = + Some(started - i64::try_from(ENROLLMENT_COOL_DOWN.as_secs()).unwrap() - 1); + store(&file, &aged).unwrap(); + check(temp.path()).unwrap(); + assert!(matches!( + service.authorize(temp.path(), &cancel).await, + Err(ProcessError::Backend { code, detail }) if code == "server" && detail == "E_AUTH_FAILED" + )); + assert_eq!(sign_ins(&server).await, 2); + // Adobe refused outright, so nothing is left uncertain: the next + // attempt goes straight ahead. + let refused: State = load(&file).unwrap(); + assert!(!refused.enrollment_pending); + assert_eq!(refused.enrollment_started, None); + assert_eq!(refused.salt, aged.salt); + assert_eq!(refused.fingerprint, aged.fingerprint); + check(temp.path()).unwrap(); + assert!(service.authorize(temp.path(), &cancel).await.is_err()); + assert_eq!(sign_ins(&server).await, 3); +} + +#[tokio::test] +async fn an_uncertain_sign_in_from_an_older_libbui_is_tried_again() { + let server = sign_in_server().await; + let mut service = Service::new().unwrap(); + service.activation = url(&server.uri()).unwrap(); + let temp = tempfile::tempdir().unwrap(); + let file = temp.path().join("authorization.json"); + // Older versions recorded no start time and never cleared the flag. + std::fs::write( + &file, + format!( + r#"{{"version":1,"salt":"{}","fingerprint":"{}","operators":[],"enrollment_pending":true}}"#, + b64([0; 16]), + b64([1; 20]) + ), + ) + .unwrap(); + check(temp.path()).unwrap(); + let _ = service + .authorize(temp.path(), &CancellationToken::new()) + .await; + assert_eq!(sign_ins(&server).await, 1); +} + +#[test] +fn the_sign_in_gate_waits_only_for_a_recent_uncertain_sign_in() { + let wait = i64::try_from(ENROLLMENT_COOL_DOWN.as_secs()).unwrap(); + let now = 1_800_000_000; + let at = |pending: bool, started: Option| { + let mut state = fixture_state(); + state.enrollment_pending = pending; + state.enrollment_started = started; + enrollment_gate(&state, now) + }; + assert!(at(false, None).is_ok()); + assert!(at(false, Some(now)).is_ok()); + assert!(uncertain(&at(true, Some(now)))); + assert!(uncertain(&at(true, Some(now - wait + 1)))); + assert!(at(true, Some(now - wait)).is_ok()); + // No start time: written before the cool-down existed. + assert!(at(true, None).is_ok()); + // A start in the future means the clock went back; do not wait forever. + assert!(at(true, Some(now + 3600)).is_ok()); +} + +#[test] +fn only_a_refusal_from_adobe_settles_a_sign_in() { + let backend = |code: &str, detail: &str| ProcessError::Backend { + code: code.to_owned(), + detail: detail.to_owned(), + }; + assert!(refused_outright(&backend("server", "E_AUTH_FAILED"))); + assert!(refused_outright(&backend("http", "400"))); + assert!(refused_outright(&backend("http", "429"))); + for (code, detail) in [ + ("http", "502"), + ("http", "503"), + ("http", "junk"), + ("network", "transport"), + ("network", "response body"), + ("invalid-xml", ""), + ("invalid-response", "credentials"), + ] { + assert!(!refused_outright(&backend(code, detail)), "{code} {detail}"); + } + assert!(!refused_outright(&ProcessError::Cancelled)); + assert!(!refused_outright(&ProcessError::Timeout)); +} + +#[test] +fn reset_forgets_only_an_unfinished_sign_in() { + let temp = tempfile::tempdir().unwrap(); + let file = temp.path().join("authorization.json"); + // Nothing on disk: nothing to reset, and nothing is created. + assert!(!reset_enrollment(temp.path()).unwrap()); + assert!(!file.exists()); + + // A finished authorization is left exactly as it is. + store(&file, &fixture_state()).unwrap(); + let authorized = std::fs::read(&file).unwrap(); + assert!(!reset_enrollment(temp.path()).unwrap()); + assert_eq!(std::fs::read(&file).unwrap(), authorized); + + // An uncertain sign-in is forgotten, keeping the device's salt and + // fingerprint, and the next attempt may go ahead at once. + let mut state = fixture_state(); + state.user = None; + state.pkcs12 = None; + state.license_certificate = None; + state.authentication_certificate = None; + state.private_license_key = None; + state.device = None; + state.activation_url = None; + state.operators.clear(); + state.enrollment_pending = true; + state.enrollment_started = Some(unix_now()); + store(&file, &state).unwrap(); + assert!(uncertain(&check(temp.path()))); + assert!(reset_enrollment(temp.path()).unwrap()); + let reset: State = load(&file).unwrap(); + assert!(!reset.enrollment_pending); + assert_eq!(reset.enrollment_started, None); + assert_eq!(reset.salt, state.salt); + assert_eq!(reset.fingerprint, state.fingerprint); + check(temp.path()).unwrap(); + assert!(!reset_enrollment(temp.path()).unwrap()); +} + #[derive(Deserialize)] struct BookKeyVector { rights: String, diff --git a/crates/libbui-core/src/download/ebook.rs b/crates/libbui-core/src/download/ebook.rs index 9795810..2e65f37 100644 --- a/crates/libbui-core/src/download/ebook.rs +++ b/crates/libbui-core/src/download/ebook.rs @@ -40,6 +40,10 @@ pub enum ProcessError { }, } +/// Minutes libbui waits before signing in to Adobe again after a sign-in +/// whose outcome is unknown (backend code `enrollment-uncertain`). +pub const ENROLLMENT_RETRY_MINUTES: u64 = super::adobe::ENROLLMENT_COOL_DOWN.as_secs() / 60; + /// The backend code for a URL that is not HTTPS. const INSECURE_URL: &str = "insecure-url"; @@ -80,9 +84,11 @@ impl ProcessError { match self { Self::Io(_) | Self::Timeout => true, Self::Backend { code, detail } => { + // An uncertain Adobe sign-in clears itself after + // `ENROLLMENT_RETRY_MINUTES`, so a later retry can work. matches!( code.as_str(), - "network" | "invalid-audio-cache" | "incomplete-audio" + "network" | "invalid-audio-cache" | "incomplete-audio" | "enrollment-uncertain" ) || (code == "http" && matches!( detail.as_str(), @@ -173,6 +179,21 @@ impl EbookRuntime { blocking(cancel, move |_| super::adobe::check(&account)).await } + /// Forgets an Adobe sign-in that was interrupted before its outcome + /// was known, so the next download signs in again at once rather than + /// after [`ENROLLMENT_RETRY_MINUTES`]. Returns whether there was one + /// to forget. A finished authorization (and its device activation) is + /// never touched, so this cannot use up an activation slot. + /// + /// # Errors + /// The authorization file could not be read or written, is invalid, + /// or a download held it past the processing timeout. + pub async fn reset_enrollment(&self, cancel: &CancellationToken) -> Result { + let _lock = self.lock(cancel).await?; + let account = self.account_dir.clone(); + blocking(cancel, move |_| super::adobe::reset_enrollment(&account)).await + } + async fn lock( &self, cancel: &CancellationToken, diff --git a/crates/libbui/locales/en-US/cli.ftl b/crates/libbui/locales/en-US/cli.ftl index b0ab267..830788b 100644 --- a/crates/libbui/locales/en-US/cli.ftl +++ b/crates/libbui/locales/en-US/cli.ftl @@ -156,6 +156,9 @@ cli-doctor-size-unknown = not a terminal cli-doctor-config-missing = no file at { $path }; using defaults cli-doctor-ebooks-ready = Adobe ebook processing is ready cli-doctor-ebooks-unavailable = Adobe ebook processing unavailable: { $reason } +cli-adobe-reset-done = Forgot the interrupted Adobe registration. The next download registers this device again. +cli-adobe-reset-nothing = Nothing to reset: no Adobe registration was interrupted. A finished registration is left as it is. +cli-adobe-reset-failed = Could not reset the Adobe registration: { $reason } cli-doctor-reader-ready = Reader downloads are ready cli-doctor-reader-unavailable = Reader downloads unavailable: { $reason } cli-doctor-keymap = { $count -> diff --git a/crates/libbui/locales/en-US/downloads.ftl b/crates/libbui/locales/en-US/downloads.ftl index 92a6549..5ff5a32 100644 --- a/crates/libbui/locales/en-US/downloads.ftl +++ b/crates/libbui/locales/en-US/downloads.ftl @@ -85,7 +85,10 @@ download-failure-processing = Preparing the DRM-free file failed ({ $code }: { $ download-failure-adobe-server = The Adobe licence server refused ({ $detail }). download-failure-unsupported-encryption = This book uses a kind of DRM that libbui cannot remove. download-failure-invalid-clock = Your computer’s clock looks wrong, so the licence cannot be checked. Correct the date and time and try again. -download-failure-adobe-enrollment-uncertain = libbui could not tell whether registering this computer with Adobe finished. Run “libbui adobe reset” to register again, then retry the download. +download-failure-adobe-enrollment-uncertain = libbui could not tell whether registering this device with Adobe finished. It will register again by itself in { $minutes -> + [one] { $minutes } minute + *[other] { $minutes } minutes + }; retry the download then, or run “libbui adobe reset” to register again now. download-failure-internal = Something went wrong inside libbui ({ $detail }). Please report this. download-failure-unknown = This download failed in a newer version of libbui. diff --git a/crates/libbui/src/app/errors.rs b/crates/libbui/src/app/errors.rs index 21bd4f2..2de517c 100644 --- a/crates/libbui/src/app/errors.rs +++ b/crates/libbui/src/app/errors.rs @@ -116,7 +116,10 @@ pub fn describe_failure(reason: &FailReason) -> String { fn describe_processing(code: &str, detail: &str) -> String { use libby::sanitize::sanitize_line as clean; match code { - "enrollment-uncertain" => t!("download-failure-adobe-enrollment-uncertain"), + "enrollment-uncertain" => t!( + "download-failure-adobe-enrollment-uncertain", + minutes = libbui_core::download::ebook::ENROLLMENT_RETRY_MINUTES + ), "insecure-url" => t!("download-failure-insecure-url"), "network" => t!("download-failure-network", detail = clean(detail)), "http" => match detail.parse::() { @@ -254,6 +257,7 @@ mod tests { detail: String::new(), }); assert!(uncertain.contains("libbui adobe reset"), "{uncertain}"); + assert!(uncertain.contains("in 15 minutes;"), "{uncertain}"); let http = describe_failure(&FailReason::Processing { code: "http".to_owned(), detail: "503".to_owned(), diff --git a/crates/libbui/src/cli/account.rs b/crates/libbui/src/cli/account.rs index 97f4cbe..d22719c 100644 --- a/crates/libbui/src/cli/account.rs +++ b/crates/libbui/src/cli/account.rs @@ -96,6 +96,7 @@ pub(crate) async fn run(command: Command, env: &Env, io: &mut Io<'_>) -> Result< | Command::Config { .. } | Command::Completions { .. } | Command::Doctor(_) + | Command::Adobe { .. } | Command::Annotations { .. } | Command::Unpair(_) => unreachable!("handled before the account commands"), }; diff --git a/crates/libbui/src/cli/doctor.rs b/crates/libbui/src/cli/doctor.rs index 7b1b00f..e57bdd8 100644 --- a/crates/libbui/src/cli/doctor.rs +++ b/crates/libbui/src/cli/doctor.rs @@ -19,6 +19,7 @@ use super::output::{Io, Tone}; use super::session::Session; use super::table::{Column, Table}; use super::{DoctorArgs, Env}; +use crate::app::errors::describe_failure; use crate::keymap::Keymap; use crate::t; use crate::theme::ColorDepth; @@ -302,7 +303,10 @@ pub(crate) async fn run( Ok(()) => (Status::Ok, t!("cli-doctor-ebooks-ready")), Err(error) => ( Status::Warn, - t!("cli-doctor-ebooks-unavailable", reason = error.to_string()), + t!( + "cli-doctor-ebooks-unavailable", + reason = describe_failure(&error.reason()) + ), ), }; checks.push(check("ebooks", status, detail)); @@ -310,7 +314,10 @@ pub(crate) async fn run( Ok(()) => (Status::Ok, t!("cli-doctor-reader-ready")), Err(error) => ( Status::Warn, - t!("cli-doctor-reader-unavailable", reason = error.to_string()), + t!( + "cli-doctor-reader-unavailable", + reason = describe_failure(&error.reason()) + ), ), }; checks.push(check("reader", status, detail)); diff --git a/crates/libbui/src/cli/local.rs b/crates/libbui/src/cli/local.rs index 6c4a7f1..0e946ce 100644 --- a/crates/libbui/src/cli/local.rs +++ b/crates/libbui/src/cli/local.rs @@ -1,4 +1,5 @@ -//! Commands that only touch local files: `paths`, `config`, `completions`. +//! Commands that only touch local files: `paths`, `config`, `completions`, +//! `adobe`. //! None of them makes a network request or starts logging. use std::path::Path; @@ -10,7 +11,8 @@ use serde::Serialize; use super::exit::Failure; use super::output::{Io, Tone}; use super::table::{Column, Table}; -use super::{Args, ConfigCommand, Env, JsonArg}; +use super::{AdobeCommand, Args, ConfigCommand, Env, JsonArg}; +use crate::app::errors::describe_failure; use crate::t; #[derive(Debug, Serialize)] @@ -32,6 +34,33 @@ fn shown(path: &Path) -> String { path.display().to_string() } +#[derive(Debug, Serialize)] +struct ResetReport { + /// Whether an interrupted registration was forgotten. + reset: bool, +} + +/// `libbui adobe`. +pub(crate) async fn adobe(env: &Env, action: AdobeCommand, io: &mut Io<'_>) -> Result<(), Failure> { + let AdobeCommand::Reset(output) = action; + let runtime = + libbui_core::download::ebook::EbookRuntime::new(env.paths.ebook_authorization_dir()); + let cancel = tokio_util::sync::CancellationToken::new(); + let reset = runtime.reset_enrollment(&cancel).await.map_err(|error| { + Failure::Failed(t!( + "cli-adobe-reset-failed", + reason = describe_failure(&error.reason()) + )) + })?; + if output.json { + io.json(&ResetReport { reset }) + } else if reset { + io.line(&t!("cli-adobe-reset-done")) + } else { + io.line(&t!("cli-adobe-reset-nothing")) + } +} + /// `libbui paths`. pub(crate) fn paths(env: &Env, args: &JsonArg, io: &mut Io<'_>) -> Result<(), Failure> { // The download folder comes from the config; a broken config is still diff --git a/crates/libbui/src/cli/mod.rs b/crates/libbui/src/cli/mod.rs index 67b7ad8..d2567a0 100644 --- a/crates/libbui/src/cli/mod.rs +++ b/crates/libbui/src/cli/mod.rs @@ -179,6 +179,12 @@ pub enum Command { }, /// Check the terminal, configuration and pairing. Doctor(DoctorArgs), + /// Adobe ebook authorization kept on this device. + Adobe { + /// What to do. + #[command(subcommand)] + action: AdobeCommand, + }, } /// `--json`. @@ -309,6 +315,18 @@ pub struct DoctorArgs { pub output: JsonArg, } +/// `adobe` actions. +#[derive(Debug, Clone, Subcommand)] +pub enum AdobeCommand { + /// Forget an Adobe registration that was interrupted, so the next + /// download registers this device again at once. + /// + /// libbui also tries again by itself a few minutes later. A finished + /// registration is never touched, so this cannot use up one of your + /// Adobe device activations. + Reset(JsonArg), +} + /// `config` actions. #[derive(Debug, Clone, Subcommand)] pub enum ConfigCommand { @@ -382,6 +400,7 @@ async fn dispatch( Command::Config { action } => local::config(env, action, io), Command::Completions { shell } => local::completions(shell, io), Command::Doctor(doctor) => doctor::run(env, &doctor, &args.log, io).await, + Command::Adobe { action } => local::adobe(env, action, io).await, Command::Annotations { action } => personal::local(env, action, io), local if personal::is_local(&local, env)? => account::run_local(local, env, io).await, network => { diff --git a/crates/libbui/tests/cli.rs b/crates/libbui/tests/cli.rs index 16b9c49..2a2357a 100644 --- a/crates/libbui/tests/cli.rs +++ b/crates/libbui/tests/cli.rs @@ -98,6 +98,7 @@ fn help_lists_the_commands_and_the_exit_codes() { "config", "completions", "doctor", + "adobe", ] { assert!(help.contains(command), "{command} missing from:\n{help}"); } @@ -243,6 +244,66 @@ fn ebook_processing_is_available_without_any_external_executable() { assert!(!home.path().join("data/ebook-authorization").exists()); } +#[test] +fn adobe_reset_forgets_only_an_interrupted_registration() { + let home = Home::new(); + let dir = home.path().join("data/ebook-authorization"); + let file = dir.join("authorization.json"); + + // Nothing registered: nothing to do, and nothing is created. + let output = home.run(&["adobe", "reset"]); + assert_eq!(code(&output), 0, "{}", stderr(&output)); + assert!( + stdout(&output).starts_with("Nothing to reset"), + "{}", + stdout(&output) + ); + assert!(!file.exists()); + + // A registration interrupted just now, still inside the cool-down. + std::fs::create_dir_all(&dir).unwrap(); + let now = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_secs(); + let pending = format!( + r#"{{"version":1,"salt":"AAAAAAAAAAAAAAAAAAAAAA==","fingerprint":"AQEBAQEBAQEBAQEBAQEBAQEBAQE=","operators":[],"enrollment_pending":true,"enrollment_started":{now}}}"# + ); + std::fs::write(&file, pending).unwrap(); + let doctor = home.run(&["doctor", "--json"]); + let checks: Vec = serde_json::from_slice(&doctor.stdout).unwrap(); + let ebooks = checks.iter().find(|check| check["id"] == "ebooks").unwrap(); + assert_eq!(ebooks["status"], "warn", "{ebooks}"); + assert!( + ebooks["detail"] + .as_str() + .unwrap() + .contains("libbui adobe reset"), + "{ebooks}" + ); + + let output = home.run(&["adobe", "reset", "--json"]); + assert_eq!(code(&output), 0, "{}", stderr(&output)); + let report: serde_json::Value = serde_json::from_str(&stdout(&output)).unwrap(); + assert_eq!(report["reset"], true); + let state: serde_json::Value = serde_json::from_slice(&std::fs::read(&file).unwrap()).unwrap(); + assert!(state.get("enrollment_pending").is_none(), "{state}"); + assert_eq!(state["salt"], "AAAAAAAAAAAAAAAAAAAAAA=="); + let doctor = home.run(&["doctor", "--json"]); + let checks: Vec = serde_json::from_slice(&doctor.stdout).unwrap(); + let ebooks = checks.iter().find(|check| check["id"] == "ebooks").unwrap(); + assert_eq!(ebooks["status"], "ok", "{ebooks}"); + + // A second reset finds nothing left to forget. + let output = home.run(&["adobe", "reset"]); + assert_eq!(code(&output), 0, "{}", stderr(&output)); + assert!( + stdout(&output).starts_with("Nothing to reset"), + "{}", + stdout(&output) + ); +} + #[test] fn personal_local_commands_work_without_credentials_or_account_logs() { let home = Home::new(); -- knotmirror 0.0.1