Skip to content

Commit 1ab54b8

Browse files
tobocop2Goldziher
authored andcommitted
fix(sitemap): parse, normalize and deduplicate urlset <loc> entries
map() returned each urlset <loc> as the trimmed raw text. Two spellings of one page (an upper-case scheme or host, a default port, an embedded tab or newline) came back as two entries, a relative <loc> came back as a bare path, and a <loc> that is not an address came back as text. Every urlset consumer (the leaf of a sitemap walk and a urlset or gzip fetched directly) now goes through one collector. It resolves each <loc> against the sitemap's own URL with the resolver sitemap-index children use, without their host rewrite, so an entry on another host stays on that host. A <loc> that does not parse is dropped and logged by length; the sitemap URL is logged redacted when it parses and by length when it does not, through the log helper the index-child path now shares. Entries are deduplicated on the parsed address across every document of one map() call: the walk context, created once per call, holds the set behind a mutex that is only locked in synchronous code. A duplicate is dropped before it counts toward map_limit. A relative <loc> now resolves to an address, so exclude_paths applies to it, and map_search matches the normalized address rather than the raw spelling. Closes #323
1 parent 00f050c commit 1ab54b8

5 files changed

Lines changed: 380 additions & 30 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,17 @@ All notable changes to crawlberg are documented here.
6060
it is used as the duplicate key, matching the resolver already used for redirect targets, and
6161
a child address that fails to parse is skipped instead of fetched as raw text. (#226)
6262

63+
- **`map()` returned sitemap `<loc>` entries as raw text and kept duplicates.** Two spellings of
64+
one page, such as `https://example.com/a` and `HTTPS://example.com:443/a`, came back as two
65+
entries, a relative `<loc>` came back as a bare path, and a `<loc>` that is not an address came
66+
back as text. Each `<loc>` is now resolved against the sitemap's own URL with the same parser as
67+
sitemap-index children and returned in its normalized form. A `<loc>` that does not parse is
68+
dropped. An address is returned once per `map()` call, even when several sitemaps list it, and a
69+
duplicate does not count toward `map_limit`. A relative `<loc>` is now subject to
70+
`exclude_paths`, like every other entry. `map_search` now matches the normalized address, so a
71+
search for a raw spelling, such as a default port or non-ASCII text in the path or host, no
72+
longer matches. (#323)
73+
6374
- **A browser fetch reported no response headers at all on the crawl path.**
6475
`browser_http_to_crawl` built an empty header map, so every header a browser backend had
6576
collected was discarded before the crawl or the escalation path could read it — `ETag`,

‎crates/crawlberg/src/map.rs‎

Lines changed: 284 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ use crate::html::{extract_links, is_html_content, mask_raw_text_markup};
1111
use crate::http::{build_client, fetch_with_retry, http_fetch};
1212
use crate::normalize::{normalize_url, resolve_redirect, rewrite_url_host, strip_fragment};
1313
use crate::sitemap::{
14-
SitemapDocument, SitemapWalkContext, decompress_gzip, fetch_sitemap_tree, is_sitemap_index, parse_sitemap_xml,
14+
SitemapDocument, SitemapWalkContext, collect_urlset_entries, decompress_gzip, fetch_sitemap_tree, is_sitemap_index,
1515
process_sitemap_response,
1616
};
1717
use crate::types::{CrawlConfig, LinkType, MapResult, SitemapUrl};
@@ -33,11 +33,7 @@ pub async fn map(url: &str, config: &CrawlConfig) -> Result<MapResult, CrawlErro
3333
let parsed_url = Url::parse(url).map_err(|e| CrawlError::other(format!("invalid URL: {e}")))?;
3434
let client = build_client(config)?;
3535
let filter = MapFilter::from_config(config)?;
36-
let context = SitemapWalkContext {
37-
config,
38-
client: &client,
39-
filter: &filter,
40-
};
36+
let context = SitemapWalkContext::new(config, &client, &filter);
4137

4238
if config.respect_robots_txt {
4339
let urls = sitemap_urls_from_robots(url, &parsed_url, config, &client, &context).await;
@@ -159,7 +155,7 @@ async fn urls_from_direct_response(
159155
|| url.to_lowercase().ends_with(".gz")
160156
|| (resp.body_bytes.len() >= 2 && resp.body_bytes[0] == GZIP_MAGIC[0] && resp.body_bytes[1] == GZIP_MAGIC[1]);
161157
if is_gzip && let Ok(decompressed) = decompress_gzip(&resp.body_bytes) {
162-
let urls = parse_sitemap_xml(&decompressed);
158+
let urls = collect_urlset_entries(url, &decompressed, context, config.map_limit);
163159
if !urls.is_empty() {
164160
return urls;
165161
}
@@ -169,7 +165,7 @@ async fn urls_from_direct_response(
169165
if is_sitemap_index(&resp.body) {
170166
return fetch_sitemap_tree(url, context, config.map_limit).await;
171167
}
172-
let urls = parse_sitemap_xml(&resp.body);
168+
let urls = collect_urlset_entries(url, &resp.body, context, config.map_limit);
173169
if !urls.is_empty() {
174170
return urls;
175171
}
@@ -640,4 +636,284 @@ mod tests {
640636
"expected an invalid-URL error, got: {error}"
641637
);
642638
}
639+
640+
/// Serve `locs` as the well-known `/sitemap.xml` and return the addresses `map()` reports.
641+
async fn map_well_known_urlset(locs: &[&str], config: &CrawlConfig) -> (String, Vec<String>) {
642+
let mock = MockServer::start().await;
643+
let base = mock.uri();
644+
let locs: Vec<String> = locs.iter().map(|loc| (*loc).to_owned()).collect();
645+
mount_body(&mock, "/sitemap.xml", "application/xml", urlset(&locs)).await;
646+
let result = map(&base, config).await.expect("map should succeed");
647+
(base, result.urls.into_iter().map(|u| u.url).collect())
648+
}
649+
650+
#[tokio::test]
651+
async fn map_lower_cases_the_scheme_and_host_of_a_urlset_loc() {
652+
let (_, urls) = map_well_known_urlset(&["HTTPS://EXAMPLE.COM/Page"], &local_test_config()).await;
653+
654+
assert_eq!(
655+
urls,
656+
vec!["https://example.com/Page".to_owned()],
657+
"a urlset <loc> must be returned in the parser's normalized form, with the path's case kept"
658+
);
659+
}
660+
661+
#[tokio::test]
662+
async fn map_drops_the_default_port_of_a_urlset_loc() {
663+
let (_, urls) = map_well_known_urlset(&["https://example.com:443/a"], &local_test_config()).await;
664+
665+
assert_eq!(urls, vec!["https://example.com/a".to_owned()]);
666+
}
667+
668+
#[tokio::test]
669+
async fn map_strips_stray_whitespace_inside_a_urlset_loc() {
670+
let (_, urls) = map_well_known_urlset(&["https://example.com/a\n\tb"], &local_test_config()).await;
671+
672+
assert_eq!(
673+
urls,
674+
vec!["https://example.com/ab".to_owned()],
675+
"an embedded newline or tab must be removed by the URL parser, not returned"
676+
);
677+
}
678+
679+
#[tokio::test]
680+
async fn map_resolves_a_relative_urlset_loc_against_the_sitemap_url() {
681+
let (base, urls) = map_well_known_urlset(&["/relative/page"], &local_test_config()).await;
682+
683+
assert_eq!(urls, vec![format!("{base}/relative/page")]);
684+
}
685+
686+
#[tokio::test]
687+
async fn map_applies_exclude_paths_to_a_relative_urlset_loc() {
688+
let config = CrawlConfig {
689+
exclude_paths: vec!["^/admin".to_owned()],
690+
..local_test_config()
691+
};
692+
let (base, urls) = map_well_known_urlset(&["/admin/secret", "/blog/one"], &config).await;
693+
694+
assert_eq!(
695+
urls,
696+
vec![format!("{base}/blog/one")],
697+
"a relative <loc> resolves to an address, so exclude_paths must apply to it"
698+
);
699+
}
700+
701+
#[tokio::test]
702+
async fn map_returns_two_spellings_of_one_urlset_page_once() {
703+
let (_, urls) = map_well_known_urlset(
704+
&[
705+
"https://example.com/a",
706+
"HTTPS://example.com:443/a",
707+
"https://example.com/b",
708+
],
709+
&local_test_config(),
710+
)
711+
.await;
712+
713+
assert_eq!(
714+
urls,
715+
vec!["https://example.com/a".to_owned(), "https://example.com/b".to_owned()]
716+
);
717+
}
718+
719+
#[tokio::test]
720+
async fn map_limit_is_not_consumed_by_a_duplicate_urlset_loc() {
721+
let config = CrawlConfig {
722+
map_limit: Some(2),
723+
..local_test_config()
724+
};
725+
let (_, urls) = map_well_known_urlset(
726+
&[
727+
"https://example.com/a",
728+
"https://EXAMPLE.com/a",
729+
"https://example.com/b",
730+
"https://example.com/c",
731+
],
732+
&config,
733+
)
734+
.await;
735+
736+
assert_eq!(
737+
urls,
738+
vec!["https://example.com/a".to_owned(), "https://example.com/b".to_owned()],
739+
"a duplicate must be dropped before it counts toward map_limit"
740+
);
741+
}
742+
743+
#[tokio::test]
744+
async fn map_returns_a_page_listed_by_two_child_sitemaps_once() {
745+
let mock = MockServer::start().await;
746+
let base = mock.uri();
747+
mount_body(
748+
&mock,
749+
"/sitemap.xml",
750+
"application/xml",
751+
format!(
752+
r#"<?xml version="1.0"?><sitemapindex xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><sitemap><loc>{base}/one.xml</loc></sitemap><sitemap><loc>{base}/two.xml</loc></sitemap></sitemapindex>"#
753+
),
754+
)
755+
.await;
756+
let one = vec!["https://example.com/a".to_owned(), "https://example.com/b".to_owned()];
757+
let two = vec![
758+
"https://example.com:443/a".to_owned(),
759+
"https://example.com/c".to_owned(),
760+
];
761+
mount_body(&mock, "/one.xml", "application/xml", urlset(&one)).await;
762+
mount_body(&mock, "/two.xml", "application/xml", urlset(&two)).await;
763+
764+
let result = map(&base, &local_test_config()).await.expect("map should succeed");
765+
766+
assert_eq!(
767+
result.urls.into_iter().map(|u| u.url).collect::<Vec<_>>(),
768+
vec![
769+
"https://example.com/a".to_owned(),
770+
"https://example.com/b".to_owned(),
771+
"https://example.com/c".to_owned()
772+
],
773+
"a page listed by two child sitemaps of one index must be returned once"
774+
);
775+
}
776+
777+
#[tokio::test]
778+
async fn map_returns_a_page_listed_by_two_robots_sitemap_directives_once() {
779+
let mock = MockServer::start().await;
780+
let base = mock.uri();
781+
mount_body(
782+
&mock,
783+
"/robots.txt",
784+
"text/plain",
785+
format!("User-agent: *\nSitemap: {base}/one.xml\nSitemap: {base}/two.xml\n"),
786+
)
787+
.await;
788+
let one = vec!["https://example.com/a".to_owned()];
789+
let two = vec!["HTTPS://example.com/a".to_owned(), "https://example.com/b".to_owned()];
790+
mount_body(&mock, "/one.xml", "application/xml", urlset(&one)).await;
791+
mount_body(&mock, "/two.xml", "application/xml", urlset(&two)).await;
792+
793+
let config = CrawlConfig {
794+
respect_robots_txt: true,
795+
..local_test_config()
796+
};
797+
let result = map(&base, &config).await.expect("map should succeed");
798+
799+
assert_eq!(
800+
result.urls.into_iter().map(|u| u.url).collect::<Vec<_>>(),
801+
vec!["https://example.com/a".to_owned(), "https://example.com/b".to_owned()],
802+
"a page listed by two robots.txt Sitemap: directives must be returned once"
803+
);
804+
}
805+
806+
#[tokio::test]
807+
async fn map_normalizes_and_dedupes_a_urlset_fetched_directly() {
808+
let mock = MockServer::start().await;
809+
let base = mock.uri();
810+
let locs = vec![
811+
"https://example.com/a".to_owned(),
812+
"HTTPS://example.com:443/a".to_owned(),
813+
"/relative".to_owned(),
814+
];
815+
mount_body(&mock, "/feed.xml", "application/xml", urlset(&locs)).await;
816+
817+
let result = map(&format!("{base}/feed.xml"), &local_test_config())
818+
.await
819+
.expect("map should succeed");
820+
821+
assert_eq!(
822+
result.urls.into_iter().map(|u| u.url).collect::<Vec<_>>(),
823+
vec!["https://example.com/a".to_owned(), format!("{base}/relative")]
824+
);
825+
}
826+
827+
#[tokio::test]
828+
async fn map_normalizes_and_dedupes_a_gzip_urlset_fetched_directly() {
829+
use std::io::Write as _;
830+
831+
let mock = MockServer::start().await;
832+
let base = mock.uri();
833+
let locs = vec![
834+
"https://example.com/a".to_owned(),
835+
"HTTPS://example.com:443/a".to_owned(),
836+
"/relative".to_owned(),
837+
];
838+
let mut encoder = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::default());
839+
encoder.write_all(urlset(&locs).as_bytes()).expect("gzip write");
840+
let gzipped = encoder.finish().expect("gzip finish");
841+
mount_bytes(&mock, "/sitemap.xml.gz", "application/octet-stream", gzipped).await;
842+
843+
let result = map(&format!("{base}/sitemap.xml.gz"), &local_test_config())
844+
.await
845+
.expect("map should succeed");
846+
847+
assert_eq!(
848+
result.urls.into_iter().map(|u| u.url).collect::<Vec<_>>(),
849+
vec!["https://example.com/a".to_owned(), format!("{base}/relative")]
850+
);
851+
}
852+
853+
#[test]
854+
#[serial_test::serial(dropped_target_log)]
855+
fn map_drops_an_unparseable_urlset_loc_and_never_logs_its_credentials() {
856+
let runtime = tokio::runtime::Builder::new_current_thread()
857+
.enable_all()
858+
.build()
859+
.expect("a current-thread runtime must build");
860+
let mock = runtime.block_on(MockServer::start());
861+
let base = mock.uri();
862+
let bad_loc = "https://user:hunter2@ex ample.com/bad";
863+
let locs = vec![bad_loc.to_owned(), "https://example.com/kept".to_owned()];
864+
runtime.block_on(mount_body(&mock, "/sitemap.xml", "application/xml", urlset(&locs)));
865+
866+
let (result, fields) = capture_events(|| runtime.block_on(map(&base, &local_test_config())));
867+
868+
assert_eq!(
869+
result
870+
.expect("map should succeed")
871+
.urls
872+
.into_iter()
873+
.map(|u| u.url)
874+
.collect::<Vec<_>>(),
875+
vec!["https://example.com/kept".to_owned()],
876+
"a <loc> that does not parse must be dropped, not returned as text"
877+
);
878+
assert_logged_without_secret(&fields, "hunter2", "urlset entry");
879+
assert!(
880+
fields
881+
.iter()
882+
.any(|(name, value)| name == "target_len" && *value == bad_loc.len().to_string()),
883+
"the dropped <loc> must be logged by length, got {fields:?}"
884+
);
885+
}
886+
887+
#[test]
888+
#[serial_test::serial(dropped_target_log)]
889+
fn map_redacts_credentials_carried_by_a_credentialed_seed_url_when_logging_an_unparseable_urlset_loc() {
890+
// ~keep `sitemap_urls_from_well_known` builds the well-known sitemap URL from the
891+
// ~keep seed's authority, which carries the seed's userinfo along. That built URL
892+
// ~keep parses, so this exercises `log_unparseable_loc`'s `source_url_parses` branch,
893+
// ~keep the one M10 (log `source_url` unredacted) leaves uncovered.
894+
let runtime = tokio::runtime::Builder::new_current_thread()
895+
.enable_all()
896+
.build()
897+
.expect("a current-thread runtime must build");
898+
let mock = runtime.block_on(MockServer::start());
899+
let base = mock.uri();
900+
let seed_url = base.replacen("http://", "http://user:hunter2@", 1);
901+
let bad_loc = "https://ex ample.com/bad";
902+
let locs = vec![bad_loc.to_owned(), "https://example.com/kept".to_owned()];
903+
runtime.block_on(mount_body(&mock, "/sitemap.xml", "application/xml", urlset(&locs)));
904+
905+
let (result, fields) = capture_events(|| runtime.block_on(map(&seed_url, &local_test_config())));
906+
907+
assert_eq!(
908+
result
909+
.expect("map should succeed")
910+
.urls
911+
.into_iter()
912+
.map(|u| u.url)
913+
.collect::<Vec<_>>(),
914+
vec!["https://example.com/kept".to_owned()],
915+
"a <loc> that does not parse must still be dropped when the seed URL carries credentials"
916+
);
917+
assert_logged_without_secret(&fields, "hunter2", "127.0.0.1");
918+
}
643919
}

0 commit comments

Comments
 (0)