diff --git a/crates/server/src/import/feed.rs b/crates/server/src/import/feed.rs index 4d5193a4..8eccbf4c 100644 --- a/crates/server/src/import/feed.rs +++ b/crates/server/src/import/feed.rs @@ -300,12 +300,45 @@ fn unexpected(what: &str, answer: &UpstreamAnswer) -> SourceError { SourceError::Invalid(format!("the feed's {what}: {}", answer_text(answer))) } +/// What tells the administrator that the document at `url` is larger than +/// the `limit` bytes Forge reads, and which setting holds the limit. +fn too_large(url: &str, limit: u64) -> String { + format!( + "{url} is larger than the {limit} bytes Forge reads of a metadata document; raise \ + `proxy.max_metadata_bytes` to read it" + ) +} + impl SourceError { - /// A transport or status error of the upstream client. + /// A transport or status error of the upstream client. A document + /// larger than Forge reads, a target Forge does not request and a + /// redirect that does not end are the same on every try: they are + /// [`SourceError::Invalid`], never retried, and say what to change. pub fn of(e: UpstreamError) -> Self { match e { UpstreamError::Status { status, url } => SourceError::status(status, &url), - other => SourceError::Unreachable(other.to_string()), + UpstreamError::TooLarge { url, limit } => SourceError::Invalid(too_large(&url, limit)), + UpstreamError::MetadataTarget { url } => SourceError::Invalid(format!( + "{url} is a link-local or cloud-metadata address, which Forge does not request" + )), + UpstreamError::TooManyRedirects { url, max } => SourceError::Invalid(format!( + "{url} redirects more than {max} times; give the URL the source answers at" + )), + other @ (UpstreamError::Transport { .. } | UpstreamError::Io(_)) => { + SourceError::Unreachable(other.to_string()) + } + } + } + + /// [`SourceError::of`] for a listing of every package: one larger than + /// Forge reads also says that naming what to import reads no listing. + pub fn of_listing(e: UpstreamError) -> Self { + match e { + UpstreamError::TooLarge { url, limit } => SourceError::Invalid(format!( + "{}, or name the packages or scopes to import instead", + too_large(&url, limit) + )), + other => SourceError::of(other), } } @@ -330,3 +363,84 @@ impl SourceError { } } } + +#[cfg(test)] +mod tests { + use super::*; + + const URL: &str = "https://npm.example.com/-/all"; + + /// The error is permanent: not retried by the worker, and a 400 of the + /// preflight rather than its 502. + fn permanent(e: UpstreamError) -> String { + let error = SourceError::of(e); + assert!(matches!(error, SourceError::Invalid(_)), "{error:?}"); + assert!(!error.is_transient(), "{error:?}"); + let text = error.to_string(); + assert!(!text.contains("unreachable"), "{text}"); + text + } + + #[test] + fn a_document_larger_than_forge_reads_is_permanent_and_names_the_limit_and_its_setting() { + let too_large = || UpstreamError::TooLarge { + url: URL.into(), + limit: 33_554_432, + }; + let text = permanent(too_large()); + assert!(text.contains(URL), "{text}"); + assert!(text.contains("33554432 bytes"), "{text}"); + assert!(text.contains("`proxy.max_metadata_bytes`"), "{text}"); + assert!(!text.contains("name the packages"), "{text}"); + + // A listing of every package: naming what to import is the other way. + let listing = SourceError::of_listing(too_large()); + assert!(!listing.is_transient(), "{listing:?}"); + let text = listing.to_string(); + assert!(text.contains("33554432 bytes"), "{text}"); + assert!(text.contains("`proxy.max_metadata_bytes`"), "{text}"); + assert!( + text.contains("name the packages or scopes to import instead"), + "{text}" + ); + } + + #[test] + fn a_refused_target_is_permanent_and_names_the_url() { + let url = "http://169.254.169.254/latest/meta-data/"; + let text = permanent(UpstreamError::MetadataTarget { url: url.into() }); + assert!(text.contains(url), "{text}"); + assert!(text.contains("link-local or cloud-metadata"), "{text}"); + } + + #[test] + fn too_many_redirects_are_permanent_and_name_the_url() { + let text = permanent(UpstreamError::TooManyRedirects { + url: URL.into(), + max: 5, + }); + assert!(text.contains(URL), "{text}"); + assert!(text.contains("more than 5 times"), "{text}"); + } + + #[test] + fn a_listing_keeps_the_other_errors_as_they_are() { + let error = SourceError::of_listing(UpstreamError::TooManyRedirects { + url: URL.into(), + max: 5, + }); + assert!(matches!(error, SourceError::Invalid(_)), "{error:?}"); + let error = SourceError::of_listing(UpstreamError::Status { + url: URL.into(), + status: StatusCode::BAD_GATEWAY, + }); + assert!(error.is_transient(), "{error:?}"); + } + + #[test] + fn a_failed_transfer_is_still_retried() { + let error = SourceError::of(UpstreamError::Io(std::io::Error::other("disk"))); + assert!(matches!(error, SourceError::Unreachable(_)), "{error:?}"); + assert!(error.is_transient()); + } +} diff --git a/crates/server/src/import/npm.rs b/crates/server/src/import/npm.rs index 82928378..4231e751 100644 --- a/crates/server/src/import/npm.rs +++ b/crates/server/src/import/npm.rs @@ -113,14 +113,22 @@ impl NpmRegistry { url: &str, accept: &str, ) -> Result, SourceError> { + self.fetch(url, accept).await.map_err(SourceError::of) + } + + /// [`Self::document`], with the upstream client's own error. + async fn fetch( + &self, + url: &str, + accept: &str, + ) -> Result, UpstreamError> { match self .http .get_metadata_body(url, self.auth().as_ref(), Some(accept)) .await { - Ok(body) => Ok(body), Err(UpstreamError::Status { status, .. }) if not_served(status) => Ok(None), - Err(e) => Err(SourceError::of(e)), + answer => answer, } } @@ -150,7 +158,11 @@ impl NpmRegistry { /// not serve it. pub async fn all(&self) -> Result>, SourceError> { let url = format!("{}{}", self.url, npm::ALL_PATH); - let Some(body) = self.document(&url, FULL_ACCEPT).await? else { + let Some(body) = self + .fetch(&url, FULL_ACCEPT) + .await + .map_err(SourceError::of_listing)? + else { return Ok(None); }; read(body, |reader| npm::read_all(reader)).await.map(Some) diff --git a/crates/server/tests/import.rs b/crates/server/tests/import.rs index 8a650439..6e680c0c 100644 --- a/crates/server/tests/import.rs +++ b/crates/server/tests/import.rs @@ -131,6 +131,10 @@ struct SourceState { /// import's own credentials: a resource they may not read, or one the /// source fails on. refused: HashMap, + /// Paths (`/repository/...`) that redirect to themselves, without end. + redirecting: HashSet, + /// Requests with the import's credentials, by path. + hits: HashMap, } /// A version of an npm package at a mock registry. @@ -169,6 +173,8 @@ struct NpmSource { search: NpmSearch, /// Serves `/-/all`. all: bool, + /// Bytes `/-/all` holds besides its packages. + all_padding: usize, } #[derive(Clone)] @@ -350,8 +356,15 @@ async fn answer(state: &Mutex, base: &str, req: Request) -> Respons .into_response(); } let path = req.uri().path().to_string(); - if let Some(status) = state.lock().unwrap().refused.get(&path) { - return status.into_response(); + { + let mut s = state.lock().unwrap(); + *s.hits.entry(path.clone()).or_default() += 1; + if let Some(status) = s.refused.get(&path) { + return status.into_response(); + } + if s.redirecting.contains(&path) { + return (StatusCode::FOUND, [(header::LOCATION, path)]).into_response(); + } } let query: HashMap = url::form_urlencoded::parse(req.uri().query().unwrap_or("").as_bytes()) @@ -614,6 +627,9 @@ fn npm_registry( "-/all" if registry.all => { let mut all = serde_json::Map::new(); all.insert("_updated".into(), json!(1)); + if registry.all_padding > 0 { + all.insert("_padding".into(), json!("x".repeat(registry.all_padding))); + } for (name, versions) in ®istry.packages { let tags = registry.tags.get(name).cloned().unwrap_or_default(); all.insert( @@ -779,6 +795,11 @@ impl Source { format!("{}/repository/{name}", self.url) } + /// Requests the source answered at `path`. + fn hits(&self, path: &str) -> usize { + self.with(|s| s.hits.get(path).copied().unwrap_or(0)) + } + fn npm_downloads(&self, registry: &str, name: &str, version: &str) -> usize { self.with(|s| { s.downloads @@ -3280,3 +3301,167 @@ async fn an_import_into_a_read_only_repository_is_refused_and_one_queued_before_ } } } + +/// Issue #777: a listing larger than `proxy.max_metadata_bytes` is the same +/// on every try. The preflight refuses it with a 400 that names the limit, +/// its setting and the other way (naming what to import), not a 502 "the +/// source is unreachable"; the worker fails at once with the same message. +#[tokio::test] +async fn a_listing_larger_than_forge_reads_fails_at_once_and_says_what_to_do() { + let srv = common::start_with( + common::fresh_pool().await, + ServerOpts { + bootstrap_admin: Some(( + format!("admin{}@example.com", common::unique()), + "adminpw".into(), + )), + extra_toml: Some("[proxy]\nmax_metadata_bytes = 8192\n".into()), + ..Default::default() + }, + ) + .await; + let source = Source::start().await; + let reg = "npm-large"; + source.npm(reg, |r| { + r.search = NpmSearch::Nothing; + r.all = true; + r.all_padding = 16_384; + }); + source.npm_version( + reg, + "alpha", + "1.0.0", + tgz("alpha", "1.0.0", "alpha"), + "2022-02-02T00:00:00.000Z", + ); + let repo = repo_name("npm-large"); + create_repo( + &srv, + json!({"name": repo, "kind": "hosted", "format": "npm"}), + ) + .await; + let all = format!("/repository/{reg}/-/all"); + let says_what_to_do = |text: &str| { + assert!(!text.contains("unreachable"), "{text}"); + assert!( + text.contains(&format!( + "{}{all} is larger than the 8192 bytes", + source.url + )), + "{text}" + ); + assert!(text.contains("`proxy.max_metadata_bytes`"), "{text}"); + assert!( + text.contains("name the packages or scopes to import instead"), + "{text}" + ); + }; + + // The preflight. + let resp = admin( + &srv, + reqwest::Method::POST, + &format!("/admin/repositories/{repo}/imports"), + Some(from(source.npm_url(reg))), + ) + .await; + let (status, text) = (resp.status(), resp.text().await.unwrap()); + assert_eq!(status, 400, "{text}"); + says_what_to_do(&text); + assert_eq!(source.hits(&all), 1); + + // The worker: the listing grew after the import was created. + source.npm(reg, |r| r.all_padding = 0); + let id = start(&srv, &repo, from(source.npm_url(reg))).await; + source.npm(reg, |r| r.all_padding = 16_384); + let before = source.hits(&all); + let done = run(&srv, &repo, id).await; + assert_eq!(done["state"], "failed", "{done}"); + says_what_to_do(done["last_error"].as_str().unwrap_or_default()); + assert_eq!(source.hits(&all) - before, 1, "read once, not retried"); +} + +/// Issue #777: a redirect that does not end, and a link-local target, are +/// the same on every try: a 400 of the preflight that names the URL, and for +/// the worker an item that fails at once, where the import went on retrying +/// "the source is unreachable". +#[tokio::test] +async fn endless_redirects_and_a_refused_target_fail_at_once_and_name_the_url() { + let srv = forge().await; + let source = Source::start().await; + let repo = repo_name("npm-redirects"); + create_repo( + &srv, + json!({"name": repo, "kind": "hosted", "format": "npm"}), + ) + .await; + let attempt = |url: String| { + let srv = &srv; + let repo = &repo; + async move { + let resp = admin( + srv, + reqwest::Method::POST, + &format!("/admin/repositories/{repo}/imports"), + Some(from(url)), + ) + .await; + (resp.status().as_u16(), resp.text().await.unwrap()) + } + }; + + // The preflight: the registry's ping redirects to itself. + let looping = "npm-looping"; + source.npm(looping, |_| {}); + let ping = format!("/repository/{looping}/-/ping"); + source.with(|s| s.redirecting.insert(ping.clone())); + let (status, text) = attempt(source.npm_url(looping)).await; + assert_eq!(status, 400, "{text}"); + assert!(!text.contains("unreachable"), "{text}"); + assert!( + text.contains(&format!("{}{ping} redirects more than 5 times", source.url)), + "{text}" + ); + + // The preflight: a cloud-metadata address is never requested. + let (status, text) = attempt("http://169.254.169.254/repository/npm".into()).await; + assert_eq!(status, 400, "{text}"); + assert!(!text.contains("unreachable"), "{text}"); + assert!( + text.contains( + "http://169.254.169.254/repository/npm/-/ping is a link-local or cloud-metadata \ + address" + ), + "{text}" + ); + + // The worker: a named package whose packument redirects to itself is an + // item that fails, read once; the other names go on. + let reg = "npm-one-loops"; + for name in ["alpha", "beta"] { + source.npm_version( + reg, + name, + "1.0.0", + tgz(name, "1.0.0", name), + "2022-02-02T00:00:00.000Z", + ); + source.npm_tag(reg, name, "latest", "1.0.0"); + } + let beta = format!("/repository/{reg}/beta"); + source.with(|s| s.redirecting.insert(beta.clone())); + let mut body = from(source.npm_url(reg)); + body["names"] = json!(["alpha", "beta"]); + let id = start(&srv, &repo, body).await; + let done = run(&srv, &repo, id).await; + assert_eq!(done["state"], "completed", "{done}"); + assert_eq!(done["progress"]["failed"], 1, "{done}"); + let detail = failure_of(&srv, &repo, id, "beta").await; + assert!( + detail.contains(&format!("{}{beta} redirects more than 5 times", source.url)), + "{detail}" + ); + // The request and its five redirects, once. + assert_eq!(source.hits(&beta), 6, "not retried"); + assert!(npm_tarball(&srv, &repo, "alpha", "1.0.0").await.is_some()); +} diff --git a/docs/changes/2.2.0/777.fixed.md b/docs/changes/2.2.0/777.fixed.md new file mode 100644 index 00000000..5cbc899b --- /dev/null +++ b/docs/changes/2.2.0/777.fixed.md @@ -0,0 +1,7 @@ +An import reported a document larger than `proxy.max_metadata_bytes`, a +link-local or cloud-metadata target and a redirect that does not end as "the +source is unreachable": the preflight answered 502, and the worker downloaded +the document four times before it failed. They fail at once, the preflight +with 400, and say what to change: the limit and its setting (for a listing +such as npm's `/-/all`, also naming the packages or scopes to import +instead), or the URL.