Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 42 additions & 10 deletions src/linkml_reference_validator/etl/reference_fetcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -688,6 +688,10 @@ def _fetch_normalized(
)
if cached is None and self.config.trust_cached_entries:
self._refuse_damaged_trusted_entry(normalized_reference_id)
if self._is_trusted_bot_challenge_entry(normalized_reference_id):
return self._remember(
normalized_reference_id, FetchOutcome(content=None)
)
if cached and self.config.trust_cached_entries:
# Trusted: serve what is on disk. No staleness re-fetch and no
# full-text retry, so nothing can shorten the body or replace it
Expand Down Expand Up @@ -779,7 +783,7 @@ def _refuse_damaged_trusted_entry(self, normalized_reference_id: str) -> None:
Without ``trust_cached_entries`` a damaged entry reads as absent and a
fetch replaces it (#133). A trusted cache is reviewed evidence: a fetch
could replace text a curator quoted, so the damage is reported instead
and the file is left as it is.
and the file is left as it is. ``force_refresh`` bypasses this.

Raises:
DamagedCacheEntryError: if the entry's header is damaged
Expand All @@ -796,6 +800,24 @@ def _refuse_damaged_trusted_entry(self, normalized_reference_id: str) -> None:
"the file, or delete it to fetch the reference again."
)

def _is_trusted_bot_challenge_entry(self, normalized_reference_id: str) -> bool:
"""Return True if a trusted ``url:`` cache entry holds a bot-challenge page (#186)."""
if not normalized_reference_id.startswith("url:"):
return False
cache_path = self.find_cache_file(normalized_reference_id)
if not cache_path.exists():
return False
content_text = cache_path.read_text(encoding="utf-8")
if not content_text.startswith("---"):
return False
reference = self._load_markdown_format(content_text, normalized_reference_id)
if reference is None or not _same_reference_id(
self._canonical_cache_id(reference.reference_id),
self._canonical_cache_id(normalized_reference_id),
):
return False
return is_bot_challenge_title(reference.title)

def _stale_fallback(
self, normalized_reference_id: str, force_refresh: bool
) -> FetchOutcome:
Expand Down Expand Up @@ -2113,15 +2135,25 @@ def _load_from_disk(
# Written before URLSource declined challenge pages (#117), and
# stamped current, so staleness would never catch it. It is not the
# document under any flag, stale or trusted: treat it as absent so
# it is never evidence and the next good fetch replaces it. The
# legacy return above skips this, which is safe: challenge pages were
# cached by Markdown-era versions, never in the pre-Markdown format.
logger.warning(
"Ignoring cache entry for %s: it holds a bot-challenge page "
"(%r), not the document. It will be re-fetched.",
reference_id,
reference.title,
)
# it is never evidence. Under trust_cached_entries (#186), the file
# is not re-fetched or overwritten automatically; without trust, the
# next good fetch replaces it.
if self.config.trust_cached_entries:
logger.warning(
"Ignoring cache entry %s for %s: it holds a bot-challenge page "
"(%r), not the document. trust_cached_entries is set, so it is "
"not re-fetched; refresh with --force or delete the file.",
cache_path,
reference_id,
reference.title,
)
else:
logger.warning(
"Ignoring cache entry for %s: it holds a bot-challenge page "
"(%r), not the document. It will be re-fetched.",
reference_id,
reference.title,
)
return None
if (
allow_stale
Expand Down
49 changes: 49 additions & 0 deletions tests/test_bot_challenge.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,6 +203,55 @@ def test_a_cached_challenge_page_is_not_served_while_still_challenged(
assert fetcher.fetch(f"url:{URL}") is None


def test_trusted_cached_challenge_page_is_not_refetched_or_rewritten(
tmp_path, poisoned_entry, caplog
):
"""Under trust_cached_entries, a cached bot-challenge page is neither served nor rewritten (#186)."""
import logging

before = poisoned_entry.read_bytes()
trusted_cfg = ReferenceValidationConfig(
cache_dir=tmp_path, rate_limit_delay=0.0, trust_cached_entries=True
)
trusted_fetcher = ReferenceFetcher(trusted_cfg)

with patch("linkml_reference_validator.etl.sources.url.ContentAcquirer") as mock_acq:
mock_acq.side_effect = AssertionError(
"Network must not be contacted for a trusted cached bot-challenge entry"
)
with caplog.at_level(logging.WARNING):
result = trusted_fetcher.fetch(f"url:{URL}")
val = SupportingTextValidator(trusted_cfg)
v_res = val.validate("onset typically in childhood", f"url:{URL}", expected_title=TITLE)
t_res = val.validate_title(f"url:{URL}", expected_title=TITLE)

assert result is None
assert poisoned_entry.read_bytes() == before
assert str(poisoned_entry) in caplog.text
assert CHALLENGE_TITLE in caplog.text
assert "trust_cached_entries" in caplog.text
for r in (v_res, t_res):
assert not r.is_valid
assert "Title mismatch" not in r.message


def test_trusted_cached_challenge_page_can_be_refreshed_with_force(
tmp_path, poisoned_entry
):
"""An explicit force_refresh=True still replaces a cached challenge page under trust."""
trusted_fetcher = ReferenceFetcher(
ReferenceValidationConfig(
cache_dir=tmp_path, rate_limit_delay=0.0, trust_cached_entries=True
)
)
with _serving(ARTICLE):
result = trusted_fetcher.fetch(f"url:{URL}", force_refresh=True)

assert result is not None
assert result.title == TITLE
assert f"title: {TITLE}" in poisoned_entry.read_text()


# --- the validator -----------------------------------------------------------


Expand Down
18 changes: 18 additions & 0 deletions tests/test_cache_read_robustness.py
Original file line number Diff line number Diff line change
Expand Up @@ -139,6 +139,24 @@ def test_a_trusted_missing_entry_is_still_fetched(tmp_path):
assert _fetch_with_stub(fetcher).content == FRESH_TEXT


def test_damaged_header_problem_agrees_with_frontmatter_loader():
"""_damaged_header_problem and _load_frontmatter_mapping agree on bad and good headers."""
from linkml_reference_validator.etl.reference_fetcher import (
_damaged_header_problem,
_load_frontmatter_mapping,
)

for header in BAD_HEADERS.values():
split = ReferenceFetcher._split_frontmatter(header)
assert _damaged_header_problem(header) is not None
assert split is None or _load_frontmatter_mapping(split[0]) is None

good = f"---\nreference_id: PMID:1\nextractor_version: {EXTRACTOR_CACHE_VERSION}\n---\nBody\n"
split_good = ReferenceFetcher._split_frontmatter(good)
assert _damaged_header_problem(good) is None
assert split_good is not None and _load_frontmatter_mapping(split_good[0]) is not None


@pytest.mark.parametrize("header", BAD_HEADERS.values(), ids=BAD_HEADERS.keys())
def test_a_damaged_header_is_not_served_even_as_stale(fetcher, header):
"""``allow_stale`` cannot serve a header that does not load."""
Expand Down
Loading