Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

fix(search): support optional OpenAlex API key auth (polite pool deprecated) (#6289)

LearningCircuitfa1745d5c55b
diff --git a/changelog.d/6289.bugfix.md b/changelog.d/6289.bugfix.md
new file mode 100644
index 0000000000..4ba1393e24
--- /dev/null
+++ b/changelog.d/6289.bugfix.md
@@ -0,0 +1,24 @@
+OpenAlex deprecated the email "polite pool" in February 2026 (the `mailto`
+parameter is ignored), causing 429 rate-limit errors even with an email
+configured. LDR now supports an optional OpenAlex API key (Settings → Search
+→ OpenAlex, or `LDR_SEARCH_ENGINE_WEB_OPENALEX_API_KEY`) sent as an
+`Authorization: Bearer` header everywhere LDR calls `api.openalex.org` — the
+search engine, the DOI enrichment every scientific engine runs, and
+research-library downloads; a free key raises the daily request budget 10x.
+Keyless operation keeps working; the email setting is now used only for
+User-Agent identification.
+
+An unfilled placeholder (`your-api-key-here`, `<your_api_key>`,
+`${OPENALEX_API_KEY}`, `False`, a blank value) or a value that cannot be
+sent as an HTTP header (whitespace, control characters, or characters
+outside latin-1 — what a PDF paste or an editor's autocorrect produces)
+counts as "no key" rather than being sent as a credential OpenAlex would
+reject or one that would break header encoding before the request leaves
+the process. If a real key is rejected, all three call sites drop it and
+retry the same request without it, so a stale or revoked key costs one
+extra request rather than your results, and each object remembers the
+rejection for its own lifetime: a search engine that has its key refused
+— by its own search or by the DOI enrichment pass — sends it on neither
+again, and the library downloader does the same from its own first
+refused request. The authentication failure is reported only when the
+keyless retry also fails.
diff --git a/docs/CONFIGURATION.md b/docs/CONFIGURATION.md
index 177fd5eeec..ac00e0e855 100644
--- a/docs/CONFIGURATION.md
+++ b/docs/CONFIGURATION.md
@@ -353,6 +353,7 @@ They are not available in the Web UI because they are needed to start the applic
| `search.engine.web.nasa_ads.weaknesses` | `LDR_SEARCH_ENGINE_WEB_NASA_ADS_WEAKNESSES` | ``["biomedical content", "computer science papers", "social sciences", "humanities", "requires API key for good performance"]`` | List of research areas where NASA ADS has limited coverage | SEARCH |
| `search.engine.web.openalex` | `LDR_SEARCH_ENGINE_WEB_OPENALEX` | ``{"requires_api_key": false, "requires_llm": true, "description": "Search 250+ million academic papers with natural language queries", "reliability": 0.95}`` | OpenAlex academic search engine configuration | SEARCH |
| `search.engine.web.openalex.agent_enabled` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_AGENT_ENABLED` | `true` | Include OpenAlex as a specialized tool for the langgraph research agent. The engine selected as `search.tool` always keeps its generic web_search tool — this flag only controls additional specialized tools. Independent of egress; the per-collection 'available to the research agent' toggle still wins for collections. | SEARCH |
+| `search.engine.web.openalex.api_key` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_API_KEY` | `` | OpenAlex API key (optional but recommended). Raises the daily request budget 10x. Get a free key at https://openalex.org/settings/api. The old email 'polite pool' was deprecated by OpenAlex in February 2026 and no longer has any effect. | SEARCH |
| `search.engine.web.openalex.default_params.filter_open_access` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_DEFAULT_PARAMS_FILTER_OPEN_ACCESS` | `false` | Only return open access papers that are freely available | SEARCH |
| `search.engine.web.openalex.default_params.from_publication_date` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_DEFAULT_PARAMS_FROM_PUBLICATION_DATE` | `` | Only return papers published after this date (YYYY-MM-DD format, leave empty for all dates) | SEARCH |
| `search.engine.web.openalex.default_params.max_results` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_DEFAULT_PARAMS_MAX_RESULTS` | `25` | Maximum number of results to retrieve from OpenAlex | SEARCH |
@@ -360,11 +361,11 @@ They are not available in the Web UI because they are needed to start the applic
| `search.engine.web.openalex.default_params.sort_by` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_DEFAULT_PARAMS_SORT_BY` | `relevance` | How to sort the search results | SEARCH |
| `search.engine.web.openalex.description` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_DESCRIPTION` | `Search 250+ million academic papers with natural language queries. Comprehensive scholarly database covering all disciplines.` | Human-readable description of the search engine. | SEARCH |
| `search.engine.web.openalex.display_name` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_DISPLAY_NAME` | `OpenAlex` | Display name to use in the U.I. for this search engine. | SEARCH |
-| `search.engine.web.openalex.email` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_EMAIL` | `` | Email address for polite pool access (optional but recommended). Provides faster response times. | SEARCH |
+| `search.engine.web.openalex.email` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_EMAIL` | `` | OpenAlex deprecated the email 'polite pool' in February 2026. This email is now included only in the User-Agent for identification; configure an API key instead to raise the daily request budget. | SEARCH |
| `search.engine.web.openalex.journal_reputation.enabled` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_JOURNAL_REPUTATION_ENABLED` | `true` | Enable journal quality filtering for this search engine. | SEARCH |
| `search.engine.web.openalex.reliability` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_RELIABILITY` | `0.95` | Reliability score for OpenAlex search results (0.0-1.0, higher is better) | SEARCH |
| `search.engine.web.openalex.requires_api_key` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_REQUIRES_API_KEY` | `false` | Whether OpenAlex requires an API key (always false for OpenAlex) | SEARCH |
-| `search.engine.web.openalex.strengths` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_STRENGTHS` | ``["academic papers", "scholarly research", "natural language queries", "all disciplines", "citation analysis", "open access content", "comprehensive coverage", "no API key required", "high rate limits"]`` | List of research areas where OpenAlex excels | SEARCH |
+| `search.engine.web.openalex.strengths` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_STRENGTHS` | ``["academic papers", "scholarly research", "natural language queries", "all disciplines", "citation analysis", "open access content", "comprehensive coverage", "works without an API key", "free API key raises the daily request budget"]`` | List of research areas where OpenAlex excels | SEARCH |
| `search.engine.web.openalex.use_in_auto_search` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_USE_IN_AUTO_SEARCH` | `true` | Include OpenAlex in auto search mode | SEARCH |
| `search.engine.web.openalex.weaknesses` | `LDR_SEARCH_ENGINE_WEB_OPENALEX_WEAKNESSES` | ``["non-academic content", "news articles", "general web content", "real-time information"]`` | List of content types where OpenAlex has limited coverage | SEARCH |
| `search.engine.web.openlibrary` | `LDR_SEARCH_ENGINE_WEB_OPENLIBRARY` | ``{"requires_api_key": false, "requires_llm": true, "description": "Search 2M+ books with metadata, covers, and full text from Internet Archive.", "reliability": 0.9}`` | Open Library search engine configuration | SEARCH |
diff --git a/src/local_deep_research/defaults/settings_openalex.json b/src/local_deep_research/defaults/settings_openalex.json
index d517f9ae0b..bfe44d5a19 100644
--- a/src/local_deep_research/defaults/settings_openalex.json
+++ b/src/local_deep_research/defaults/settings_openalex.json
@@ -76,11 +76,11 @@
},
"search.engine.web.openalex.email": {
"category": "openalex",
- "description": "Email address for polite pool access (optional but recommended). Provides faster response times.",
+ "description": "OpenAlex deprecated the email 'polite pool' in February 2026. This email is now included only in the User-Agent for identification; configure an API key instead to raise the daily request budget.",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Email (for Polite Pool)",
+ "name": "Email (User-Agent identification)",
"options": null,
"step": null,
"type": "SEARCH",
@@ -88,6 +88,20 @@
"value": "",
"visible": true
},
+ "search.engine.web.openalex.api_key": {
+ "category": "openalex",
+ "description": "OpenAlex API key (optional but recommended). Raises the daily request budget 10x. Get a free key at https://openalex.org/settings/api. The old email 'polite pool' was deprecated by OpenAlex in February 2026 and no longer has any effect.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "API Key",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "password",
+ "value": "",
+ "visible": true
+ },
"search.engine.web.openalex.default_params.max_results": {
"category": "openalex",
"description": "Maximum number of results to retrieve from OpenAlex",
@@ -204,8 +218,8 @@
"citation analysis",
"open access content",
"comprehensive coverage",
- "no API key required",
- "high rate limits"
+ "works without an API key",
+ "free API key raises the daily request budget"
],
"visible": true
},
diff --git a/src/local_deep_research/research_library/downloaders/openalex.py b/src/local_deep_research/research_library/downloaders/openalex.py
index e63ac19611..190fb3a867 100644
--- a/src/local_deep_research/research_library/downloaders/openalex.py
+++ b/src/local_deep_research/research_library/downloaders/openalex.py
@@ -12,6 +12,11 @@ from urllib.parse import urlparse
import requests
from loguru import logger
+from ...security.log_sanitizer import scrub_error
+from ...utilities.openalex_enrichment import (
+ normalize_openalex_api_key,
+ send_with_key_fallback,
+)
from .base import BaseDownloader, ContentType, DownloadResult
@@ -19,19 +24,57 @@ class OpenAlexDownloader(BaseDownloader):
"""Downloader for OpenAlex papers with open access PDF support."""
def __init__(
- self, timeout: int = 30, polite_pool_email: Optional[str] = None
+ self,
+ timeout: int = 30,
+ polite_pool_email: Optional[str] = None,
+ api_key: Optional[str] = None,
):
"""
Initialize OpenAlex downloader.
Args:
timeout: Request timeout in seconds
- polite_pool_email: Optional email for polite pool (faster API access)
+ polite_pool_email: Optional email included in the User-Agent for
+ identification; retained under its existing name for compatibility
+ api_key: Optional OpenAlex API key for a higher daily request budget.
+ Placeholders and sentinel values normalize to None so the
+ downloader falls back to the keyless free tier instead of
+ sending a Bearer token OpenAlex will reject. A real key
+ OpenAlex *does* reject is dropped on first use and every
+ later lookup goes out keyless, so a bad key never turns
+ an available PDF into "no PDF available".
"""
super().__init__(timeout)
self.polite_pool_email = polite_pool_email
+ self.api_key: Optional[str] = normalize_openalex_api_key(api_key)
+ # Set only once OpenAlex refuses the key; kept so ``_scrub``
+ # still has the literal to redact after ``api_key`` is cleared.
+ self._rejected_api_key: Optional[str] = None
self.base_api_url = "https://api.openalex.org"
+ def _scrub(self, error: Exception) -> str:
+ """Return a log-safe rendering of *error*.
+
+ logger.warning + this helper replaces logger.exception throughout
+ ``_get_pdf_url``: that frame's locals hold ``headers`` (the
+ "Authorization: Bearer <key>" value), which loguru's diagnose
+ would render into the traceback. Same documented trade-off as
+ ``search_engine_nasa_ads``. This class is not a
+ ``BaseSearchEngine``, so it does its own literal-key redaction
+ instead of relying on ``_scrub_error``/``_secret_attrs``.
+
+ ``getattr`` with a default, like ``BaseSearchEngine._scrub_error``:
+ this runs inside ``except`` handlers, and a partially-constructed
+ instance (``__new__``, or a ``super().__init__`` that raised)
+ must degrade to a shape-only scrub rather than raise
+ ``AttributeError`` from inside the handler.
+ """
+ return scrub_error(
+ error,
+ getattr(self, "api_key", None),
+ getattr(self, "_rejected_api_key", None),
+ )
+
def can_handle(self, url: str) -> bool:
"""Check if URL is from OpenAlex."""
try:
@@ -127,14 +170,46 @@ class OpenAlexDownloader(BaseDownloader):
api_url = f"{self.base_api_url}/works/{work_id}"
params = {"select": "id,open_access,best_oa_location"}
- # Add polite pool email if available (gets faster API access)
+ # Identify the client by email when configured.
headers = {}
if self.polite_pool_email:
headers["User-Agent"] = f"mailto:{self.polite_pool_email}"
- # Make API request
- response = self.session.get(
- api_url, params=params, headers=headers, timeout=self.timeout
+ def _send(with_api_key: bool) -> requests.Response:
+ request_headers = dict(headers)
+ if with_api_key and self.api_key:
+ # Bearer header rather than the equally-supported
+ # ?api_key= query parameter, so the key stays out of
+ # URLs. https://help.openalex.org/api/authentication/
+ request_headers["Authorization"] = f"Bearer {self.api_key}"
+ return self.session.get(
+ api_url,
+ params=params,
+ headers=request_headers,
+ timeout=self.timeout,
+ )
+
+ def _drop_rejected_key() -> None:
+ # The single mutation point: this runs *before* the
+ # keyless retry, so even if that retry raises, the
+ # refused key is already gone and cannot be sent again.
+ # ``or self._rejected_api_key``: a second call must not
+ # store None over the literal and drop it out of
+ # ``_scrub``'s redaction set.
+ self._rejected_api_key = self.api_key or self._rejected_api_key
+ self.api_key = None
+
+ # Make API request. The shared helper retries keylessly once
+ # if OpenAlex refuses the key and drops the key for this
+ # downloader's lifetime, so a stale key costs one extra
+ # request rather than every open-access PDF. If the keyless
+ # retry fails too, the status branches below apply the
+ # pre-existing behaviour (warn, return None).
+ response, _ = send_with_key_fallback(
+ _send,
+ api_key=self.api_key,
+ context="OpenAlex download",
+ on_key_rejected=_drop_rejected_key,
)
if response.status_code == 200:
@@ -183,9 +258,11 @@ class OpenAlexDownloader(BaseDownloader):
logger.info(
f"Landing page is not a PDF (Content-Type: {content_type}), skipping"
)
- except Exception:
- logger.exception(
- f"Failed to validate landing page URL for work {work_id}"
+ except Exception as exc:
+ safe_msg = self._scrub(exc)
+ logger.warning(
+ f"Failed to validate landing page URL for "
+ f"work {work_id}: {safe_msg}"
)
logger.info(
@@ -199,12 +276,14 @@ class OpenAlexDownloader(BaseDownloader):
logger.warning(f"OpenAlex API error: {response.status_code}")
return None
- except requests.exceptions.RequestException:
- logger.exception("Failed to query OpenAlex API")
+ except requests.exceptions.RequestException as exc:
+ safe_msg = self._scrub(exc)
+ logger.warning(f"Failed to query OpenAlex API: {safe_msg}")
return None
- except ValueError:
+ except ValueError as exc:
# JSON decode errors are expected runtime errors
- logger.exception("Failed to parse OpenAlex API response")
+ safe_msg = self._scrub(exc)
+ logger.warning(f"Failed to parse OpenAlex API response: {safe_msg}")
return None
# Note: KeyError and TypeError are not caught - they indicate programming
# bugs that should propagate for debugging
diff --git a/src/local_deep_research/research_library/services/download_service.py b/src/local_deep_research/research_library/services/download_service.py
index 60fa4aa3a0..9ca0be43ba 100644
--- a/src/local_deep_research/research_library/services/download_service.py
+++ b/src/local_deep_research/research_library/services/download_service.py
@@ -212,6 +212,15 @@ class DownloadService:
"search.engine.web.semantic_scholar.api_key", ""
)
+ # Same for OpenAlex: the downloader hits api.openalex.org for every
+ # work lookup, so it needs the key too. It is passed through raw —
+ # ``OpenAlexDownloader.__init__`` runs ``normalize_openalex_api_key``
+ # itself, so placeholders/sentinels/non-strings become None
+ # (keyless free tier) there, in one place.
+ openalex_api_key = self.settings.get_setting(
+ "search.engine.web.openalex.api_key", ""
+ )
+
# ArxivDownloader precedes DirectPDFDownloader: for a paper URL it
# builds the canonical PDF URL rather than fetching whatever the
# input pointed at. It can only do that for URLs that name a paper,
@@ -227,9 +236,9 @@ class DownloadService:
if semantic_scholar_api_key
else None,
),
- OpenAlexDownloader(
- timeout=30
- ), # OpenAlex with API lookup (no key needed)
+ # OpenAlex work lookup; the key is optional (it raises the
+ # daily budget 10x) and None means the keyless free tier.
+ OpenAlexDownloader(timeout=30, api_key=openalex_api_key),
PubMedDownloader(timeout=30, rate_limit_delay=1.0),
BioRxivDownloader(timeout=30),
GenericDownloader(timeout=30), # Generic should be last (fallback)
diff --git a/src/local_deep_research/utilities/openalex_enrichment.py b/src/local_deep_research/utilities/openalex_enrichment.py
index 14c62746ee..7cbbf0a08c 100644
--- a/src/local_deep_research/utilities/openalex_enrichment.py
+++ b/src/local_deep_research/utilities/openalex_enrichment.py
@@ -11,11 +11,13 @@ tiered scoring system is unchanged. This just gives Tier 2 (OpenAlex
snapshot lookup) a reliable key to work with.
"""
-from typing import Any, Dict, List, Optional
+import unicodedata
+from typing import Any, Callable, Dict, List, Optional, Tuple
from loguru import logger
from ..constants import OPENALEX_ENRICHMENT_API_TIMEOUT, USER_AGENT
+from ..security.log_sanitizer import scrub_error
from ..security.safe_requests import safe_get
from .citation_normalizer import _extract_doi
@@ -23,6 +25,285 @@ from .citation_normalizer import _extract_doi
_OPENALEX_API = "https://api.openalex.org"
_MAX_DOIS_PER_REQUEST = 50
+# HTTP statuses treated as "this credential was refused".
+#
+# Sourced, not assumed. OpenAlex's published error table
+# (https://help.openalex.org/api/errors/) documents 200, 301, 400,
+# 403 ("Forbidden - you don't have access to this resource"), 404, 429
+# and 500. It documents **no 401**, and
+# https://help.openalex.org/api/authentication/ does not state which
+# status a rejected key earns. So this is deliberately a small
+# *defensive* set: 403 is documented, and 401 is the standard status for
+# a refused bearer token. Nothing else is guessed at.
+#
+# In particular there is no separate "daily budget exceeded" status to
+# map: the errors page defines 429 as "Rate limit or daily credit budget
+# exceeded; slow down or wait for the reset", and the authentication
+# page confirms "Two things return 429 Too Many Requests: exceeding your
+# daily budget, or making more than 100 requests per second". 429 is
+# already handled by the engine's rate-limit branch, which points at the
+# free key that raises the daily budget 10x.
+#
+# A refused key must never look like "no results": it is an operator
+# misconfiguration. See :func:`send_with_key_fallback`.
+OPENALEX_AUTH_FAILURE_STATUSES = frozenset({401, 403})
+
+
+def normalize_openalex_api_key(api_key: Any) -> Optional[str]:
+ """Normalize a configured OpenAlex API key to a real key, or ``None``.
+
+ ``None`` means "make the request keyless" — OpenAlex works without a
+ key, so an unusable configured value must degrade to the free tier
+ rather than being sent as a ``Bearer`` token that earns a 401/403 and
+ turns a working engine into one that returns nothing.
+
+ Collapses to ``None``:
+
+ * any non-``str`` value (``True``/``1`` from a mis-typed setting used
+ to raise ``AttributeError`` on ``.strip()``),
+ * whitespace-only values (``None``, never ``""``),
+ * the ``"False"`` settings sentinel, case-insensitively,
+ * every placeholder ``BaseSearchEngine._is_valid_api_key`` rejects —
+ ``your-api-key-here``, ``<your_api_key>``, ``${OPENALEX_API_KEY}``, …
+ * any value that is not usable as an HTTP header value. Two
+ independent rules, both required:
+
+ - *internal whitespace or control characters*. Such a value cannot
+ be a real key, and a newline in it makes ``requests`` raise
+ ``InvalidHeader`` whose message embeds the value's ``repr``,
+ which neither scrub pass can match (the literal holds a real
+ newline, the message holds a backslash and an "n"). Rejecting it
+ keeps it out of the logs.
+ - *not latin-1 encodable*. This is the hard constraint: CPython's
+ ``http.client`` encodes every header value as latin-1
+ (``values[i] = one_value.encode('latin-1')``), and neither
+ ``requests``' own header validation nor anything below it gates
+ the encoding. A key carrying U+2010, U+2013 or U+2019 — what a
+ PDF paste or an editor's autocorrect produces — therefore raises
+ ``UnicodeEncodeError`` *before any request leaves the process*.
+ That is not an HTTP status, so :func:`send_with_key_fallback`
+ cannot turn it into a keyless retry by inspecting
+ ``response.status_code``; the value has to be refused here.
+ Characters that *are* latin-1 (``é``, ``ü``) are left alone —
+ they encode fine and could be part of a real key.
+
+ This lives here, rather than next to the placeholder list in
+ ``web_search_engines/search_engine_base.py``, because all three
+ OpenAlex callers need it — the search engine, the base-class DOI
+ enrichment pass, and the research-library downloader — and only this
+ module is low-level enough for the downloader to import. The
+ placeholder list itself is *not* duplicated: it is imported inside
+ the function, which keeps the *module-level* import graph free of the
+ engine package (``research_library.downloaders.openalex`` imports
+ this module at module level).
+ """
+ if not isinstance(api_key, str):
+ return None
+
+ candidate = api_key.strip()
+ # "False" is the repo-wide "unset" sentinel for string settings that
+ # round-tripped through a boolean UI control; it is not a placeholder
+ # name, so the shared list does not (and should not) carry it.
+ if candidate.lower() == "false":
+ return None
+
+ from ..web_search_engines.search_engine_base import (
+ _is_api_key_placeholder,
+ )
+
+ if _is_api_key_placeholder(candidate):
+ return None
+
+ # Checked after the placeholder list so a whitespace-bearing
+ # placeholder is still dropped silently rather than warned about.
+ # The warning deliberately does not include the value.
+ unusable_as_header = any(
+ character.isspace() or unicodedata.category(character).startswith("C")
+ for character in candidate
+ )
+ if not unusable_as_header:
+ # The encoding check the whitespace/control predicates do not
+ # cover. ``http.client`` encodes header values as latin-1 and
+ # nothing between here and there catches the resulting
+ # ``UnicodeEncodeError``, so a key that is not latin-1 encodable
+ # would take out every OpenAlex call — search, enrichment and
+ # download — with no status code for the keyless fallback to
+ # branch on. See the docstring.
+ try:
+ candidate.encode("latin-1")
+ except UnicodeEncodeError:
+ unusable_as_header = True
+
+ if unusable_as_header:
+ logger.warning(
+ "Ignoring the configured OpenAlex API key: it is not usable as "
+ "an HTTP header value (it contains whitespace, control "
+ "characters, or characters outside latin-1). Re-copy the key "
+ "from https://openalex.org/settings/api"
+ )
+ return None
+ return candidate
+
+
+ERROR_BODY_SCRUB_LIMIT = 8192
+
+
+def bounded_error_body(text: str, limit: int = ERROR_BODY_SCRUB_LIMIT) -> str:
+ """Cut an upstream error body down to a bounded, scrub-safe prefix.
+
+ ``safe_requests`` allows a 1 GiB response body, and running all of it
+ through the ~18 compiled patterns of the credential scrubbers only to
+ keep a couple of hundred characters is pointless work. This bounds
+ the *regex passes* — ``response.text`` has already decoded the whole
+ body by the time it is called, so it bounds no allocation.
+
+ Truncating before scrubbing is only safe if the cut cannot create a
+ partial credential, because the scrubbers are shape-anchored and a
+ scrub can *shrink* the text (``Bearer <token>`` collapses to 17
+ characters), pulling content from far beyond the caller's final cap
+ into the characters that get logged.
+
+ The invariant that makes it safe: :func:`normalize_openalex_api_key`
+ refuses any key containing whitespace, so a key is always contained
+ in a single whitespace-free run. Cutting back to the last whitespace
+ character at or before *limit* therefore drops the trailing partial
+ run in its entirety — no fragment of a token that straddles the
+ boundary can survive. A body with no whitespace at all in its first
+ *limit* characters yields ``""``: the whole prefix is one unbroken
+ run and none of it can be shown to be credential-free.
+
+ Args:
+ text: The decoded response body.
+ limit: Maximum number of characters considered before the cut
+ back to a whitespace boundary.
+
+ Returns:
+ *text* unchanged when it is no longer than *limit*, otherwise a
+ prefix ending at a whitespace character, possibly ``""``.
+ """
+ if len(text) <= limit:
+ return text
+ window = text[:limit]
+ for index in range(len(window) - 1, -1, -1):
+ if window[index].isspace():
+ return window[: index + 1]
+ return ""
+
+
+def send_with_key_fallback(
+ send_request: Callable[[bool], Any],
+ *,
+ api_key: Optional[str],
+ context: str,
+ on_key_rejected: Optional[Callable[[], None]] = None,
+ before_retry: Optional[Callable[[], None]] = None,
+) -> Tuple[Any, Optional[str]]:
+ """Send an OpenAlex request; drop a refused key and retry keyless once.
+
+ OpenAlex serves the same endpoints with no key at all, at a lower
+ daily budget (https://help.openalex.org/api/authentication/), so a
+ stale, rotated, typo'd or revoked key must never cost the caller its
+ results. Every LDR call site that can send the OpenAlex credential
+ goes through this one function so the guarantee cannot be
+ implemented in one place and forgotten in another.
+
+ On an auth failure (:data:`OPENALEX_AUTH_FAILURE_STATUSES`) *while a
+ key was actually sent*, or when the keyed send raises
+ ``UnicodeEncodeError`` (see below):
+
+ * exactly one warning is logged. It is scrub-safe by construction:
+ the only interpolated values are *context* (a caller literal) and
+ the integer status code — the key itself is never formatted into
+ it;
+ * the key is dropped. This function returns ``None`` as the key in
+ effect and calls *on_key_rejected* so the caller can clear any
+ cached ``Authorization`` header, which means no later request pays
+ another wasted round-trip with a credential already known to be
+ refused;
+ * *before_retry* runs (rate-limit accounting for the extra request);
+ * the same request is retried once, keyless.
+
+ When no key was sent, or the response is not an auth failure, the
+ response is returned untouched and nothing is logged — keyless
+ behaviour is exactly what it was before the key existed.
+
+ If the keyless retry fails too, its response is returned as-is and
+ the caller applies its own pre-existing failure handling.
+
+ ``UnicodeEncodeError`` from the keyed send is treated exactly like a
+ rejection. It is the one exception that can only come from encoding a
+ request *header value*: ``http.client`` encodes header values as
+ latin-1 *before* opening the connection, so no request went out and a
+ keyless resend is safe and correct. (URLs and query parameters are
+ percent-encoded by ``requests`` and raise ``InvalidURL``, not
+ ``UnicodeEncodeError``.) Which header is not knowable here.
+ :func:`normalize_openalex_api_key` already refuses non-latin-1 keys,
+ so on every in-tree path the ``Authorization`` value is already
+ known-encodable and the likelier source is another configured header
+ value — the contact email interpolated into the ``User-Agent``, which
+ ``requests`` emits before ``Authorization``. Dropping the key is
+ still the right response: it is the only credential-bearing header,
+ and a keyless resend costs nothing when the key was not at fault.
+ The catch is deliberately this one exception type: any other failure
+ is a real network or protocol error, and retrying it keyless would
+ both hide the fault and throw away a key the server never refused.
+
+ Args:
+ send_request: ``send_request(with_api_key)`` issues the request
+ and returns the response. It MUST omit the ``Authorization``
+ header when *with_api_key* is False.
+ api_key: The key that will be sent, or ``None`` for keyless.
+ context: Short literal naming the call site, for the log line.
+ on_key_rejected: Called once, before the retry, to clear the
+ caller's cached credential state.
+ before_retry: Called once, immediately before the retry.
+
+ Returns:
+ ``(response, api_key)`` where *api_key* is ``None`` once dropped.
+ """
+
+ def _drop_and_resend_keyless() -> Tuple[Any, Optional[str]]:
+ # on_key_rejected runs BEFORE the resend, so even if the keyless
+ # request raises, the refused key is already gone and no later
+ # call can send it again.
+ if on_key_rejected is not None:
+ on_key_rejected()
+ if before_retry is not None:
+ before_retry()
+ return send_request(False), None
+
+ try:
+ response = send_request(bool(api_key))
+ except UnicodeEncodeError:
+ if not api_key:
+ # Nothing to drop and nothing to retry differently: the
+ # failure did not come from the credential.
+ raise
+ # The exception carries one character of the offending header
+ # value and its offset, so it is never interpolated into the log
+ # line.
+ logger.warning(
+ f"{context}: a configured OpenAlex request header value (the "
+ "API key or the contact email used in the User-Agent) cannot "
+ "be encoded as an HTTP header value; dropping the key and "
+ "continuing keyless. Re-check both settings at "
+ "https://openalex.org/settings/api"
+ )
+ return _drop_and_resend_keyless()
+
+ if not api_key:
+ return response, api_key
+ if response.status_code not in OPENALEX_AUTH_FAILURE_STATUSES:
+ return response, api_key
+
+ logger.warning(
+ f"{context}: OpenAlex rejected the configured API key "
+ f"(HTTP {response.status_code}); dropping it and continuing "
+ "keyless. Check or rotate the key at "
+ "https://openalex.org/settings/api"
+ )
+ return _drop_and_resend_keyless()
+
def _normalize_doi(doi: str) -> str:
"""Normalize a DOI to ``https://doi.org/<...>`` form for OpenAlex.
@@ -51,6 +332,9 @@ def _normalize_doi(doi: str) -> str:
def enrich_results_with_source_ids(
results: List[Dict[str, Any]],
email: Optional[str] = None,
+ api_key: Optional[str] = None,
+ *,
+ on_key_rejected: Optional[Callable[[str], None]] = None,
) -> List[Dict[str, Any]]:
"""
Batch-enrich results with OpenAlex source_id by DOI lookup.
@@ -63,7 +347,22 @@ def enrich_results_with_source_ids(
Args:
results: List of result dicts from search engines.
- email: Optional email for OpenAlex polite pool.
+ email: Optional email included in the User-Agent for identification.
+ api_key: Optional OpenAlex API key for a higher daily request budget.
+ Normalized through :func:`normalize_openalex_api_key`, so a
+ placeholder or sentinel value degrades to a keyless request
+ instead of a guaranteed 401. A real key OpenAlex refuses is
+ dropped for the rest of this call and every remaining batch
+ goes out keyless (:func:`send_with_key_fallback`), so a bad
+ key costs at most one extra request, never the enrichment.
+ on_key_rejected: Called with the refused key, once, the first
+ time OpenAlex refuses it. This call's own drop is a local,
+ so a caller that keeps the engine alive across runs passes
+ this to latch the rejection on itself — otherwise the next
+ run resolves the same key from the same settings snapshot
+ and pays the wasted round-trip again.
+ ``BaseSearchEngine._note_openalex_key_rejected`` is the
+ production implementation.
Returns:
The same results list, with ``openalex_source_id`` and
@@ -72,6 +371,8 @@ def enrich_results_with_source_ids(
if not results:
return results
+ api_key = normalize_openalex_api_key(api_key)
+
# Collect DOIs for results that need enrichment
doi_to_indices: Dict[str, List[int]] = {}
for i, result in enumerate(results):
@@ -91,6 +392,23 @@ def enrich_results_with_source_ids(
# Batch DOIs into chunks of MAX_DOIS_PER_REQUEST
all_dois = list(doi_to_indices.keys())
enriched_count = 0
+ # Kept for redaction after the key is dropped: ``scrub_error`` can
+ # only redact a literal it is handed, and ``api_key`` becomes None
+ # the moment OpenAlex refuses it.
+ rejected_key: Optional[str] = None
+
+ def _drop_rejected_key() -> None:
+ # The single mutation point: this runs *before* the keyless
+ # retry, so even if that retry raises, the refused key is already
+ # gone and no later chunk can send it again.
+ nonlocal api_key, rejected_key
+ # ``or rejected_key``: a second call must not store None over the
+ # literal and drop it out of the redaction set.
+ rejected_key = api_key or rejected_key
+ api_key = None
+ if on_key_rejected is not None and rejected_key:
+ # Last, so a raising callback cannot leave the key un-dropped.
+ on_key_rejected(rejected_key)
for chunk_start in range(0, len(all_dois), _MAX_DOIS_PER_REQUEST):
chunk = all_dois[chunk_start : chunk_start + _MAX_DOIS_PER_REQUEST]
@@ -101,24 +419,49 @@ def enrich_results_with_source_ids(
"per_page": str(len(chunk)),
"select": "doi,primary_location",
}
- if email:
- params["mailto"] = email
-
# safe_get auto-injects the project User-Agent. We only override
- # it here when an email is configured so OpenAlex's polite pool
- # can identify us. The mailto query param above also achieves
- # the polite-pool effect on its own.
+ # it here when an email is configured to identify this client.
headers: Dict[str, str] = {"Accept": "application/json"}
if email:
headers["User-Agent"] = f"{USER_AGENT} ({email})"
- try:
- response = safe_get(
+ # Defaults bind the loop variables (ruff B023): within a chunk the
+ # params, headers and key are fixed.
+ def _send(
+ with_api_key: bool,
+ _params: Dict[str, str] = params,
+ _headers: Dict[str, str] = headers,
+ _api_key: Optional[str] = api_key,
+ ) -> Any:
+ request_headers = dict(_headers)
+ if with_api_key and _api_key:
+ # Bearer header rather than the equally-supported
+ # ?api_key= query parameter, so the key never lands in a
+ # URL. https://help.openalex.org/api/authentication/
+ request_headers["Authorization"] = f"Bearer {_api_key}"
+ return safe_get(
f"{_OPENALEX_API}/works",
- params=params,
- headers=headers,
+ params=_params,
+ headers=request_headers,
timeout=OPENALEX_ENRICHMENT_API_TIMEOUT,
)
+
+ try:
+ # A refused key is dropped here for the rest of this
+ # enrichment pass, so the remaining chunks do not each pay a
+ # wasted round-trip with a credential already refused.
+ response, _ = send_with_key_fallback(
+ _send,
+ api_key=api_key,
+ context="DOI enrichment",
+ on_key_rejected=_drop_rejected_key,
+ )
+
+ # No 401/403 branch of its own: the helper has already logged
+ # the one "key refused" warning if a key was involved, and a
+ # keyless 401/403 is not a key problem at all. Either way the
+ # batch is skipped with exactly the warning this module used
+ # before the key existed.
if response.status_code != 200:
logger.warning(
f"DOI enrichment: OpenAlex returned {response.status_code}"
@@ -156,8 +499,18 @@ def enrich_results_with_source_ids(
results[idx]["source_type"] = source_type
enriched_count += 1
- except Exception:
- logger.exception("DOI enrichment: OpenAlex batch lookup failed")
+ except Exception as exc:
+ # logger.warning rather than logger.exception: this frame's
+ # locals hold ``headers`` (the "Authorization: Bearer <key>"
+ # value) and ``api_key``, which loguru's diagnose would render
+ # into the traceback. Same documented trade-off as
+ # ``search_engine_nasa_ads``. This module is not a
+ # BaseSearchEngine, so it scrubs the key itself rather than
+ # relying on ``_scrub_error``/``_secret_attrs``.
+ safe_msg = scrub_error(exc, api_key, rejected_key)
+ logger.warning(
+ f"DOI enrichment: OpenAlex batch lookup failed: {safe_msg}"
+ )
# Graceful: results pass through unenriched
continue
diff --git a/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
index 43b73b8cd5..4a97e06d92 100644
--- a/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
+++ b/src/local_deep_research/web_search_engines/engines/search_engine_openalex.py
@@ -7,13 +7,45 @@ from langchain_core.language_models import BaseLLM
from ...constants import SNIPPET_LENGTH_LONG, USER_AGENT
from ...security.safe_requests import safe_get
from ...security.secure_logging import logger
+from ...utilities.openalex_enrichment import (
+ OPENALEX_AUTH_FAILURE_STATUSES,
+ bounded_error_body,
+ normalize_openalex_api_key,
+ send_with_key_fallback,
+)
from ..rate_limiting import RateLimitError
from ..search_engine_base import BaseSearchEngine, Exposure, Sensitivity
+class OpenAlexAuthError(Exception):
+ """OpenAlex refused the request as unauthenticated or forbidden.
+
+ Raised instead of returning ``[]`` so ``BaseSearchEngine.run`` records
+ the search as *failed* with a message, rather than as a successful
+ search that happened to find nothing. A silently empty result set is
+ indistinguishable from "no papers matched" and hides a misconfigured
+ key indefinitely.
+
+ Raised only when a key was actually sent *and* the automatic keyless
+ retry also failed. When the retry succeeds the user gets their
+ results and only a warning is logged; when no key was configured at
+ all, a 401/403 keeps the pre-existing "log an API error, return []"
+ behaviour, because there is no key to blame.
+ """
+
+
class OpenAlexSearchEngine(BaseSearchEngine):
"""OpenAlex search engine implementation with natural language query support."""
+ # Restates the base default. ``openalex_api_key`` is bound to the very
+ # same string object as ``api_key``, so it needs no entry of its own;
+ # ``_rejected_api_key`` does, because once OpenAlex refuses the key
+ # ``self.api_key`` becomes None and ``_scrub_error`` would no longer
+ # have the literal to redact. Kept explicit here (rather than
+ # inherited silently) so a future narrowing of this tuple has to
+ # confront the rejected-key slot.
+ _secret_attrs = ("api_key", "_rejected_api_key")
+
# Mark as public search engine
is_public = True
egress_sensitivity = Sensitivity.NON_SENSITIVE
@@ -27,6 +59,7 @@ class OpenAlexSearchEngine(BaseSearchEngine):
self,
max_results: int = 25,
email: Optional[str] = None,
+ api_key: Optional[str] = None,
sort_by: str = "relevance",
filter_open_access: bool = False,
min_citations: int = 0,
@@ -41,7 +74,9 @@ class OpenAlexSearchEngine(BaseSearchEngine):
Args:
max_results: Maximum number of search results
- email: Email for polite pool (gets faster response) - optional
+ email: Optional email included in the User-Agent for identification;
+ the polite pool was deprecated in February 2026
+ api_key: Optional OpenAlex API key for a higher daily request budget
sort_by: Sort order ('relevance', 'cited_by_count', 'publication_date')
filter_open_access: Only return open access papers
min_citations: Minimum citation count filter
@@ -83,34 +118,178 @@ class OpenAlexSearchEngine(BaseSearchEngine):
from ...config.search_config import get_setting_from_snapshot
try:
+ # An explicit default is required: with no ``default``
+ # argument at all, a snapshot that lacks the key and no
+ # thread-local settings context makes
+ # ``get_setting_from_snapshot`` raise
+ # ``NoSettingsContextError``. The empty string (rather
+ # than None) is the safer spelling because it is falsy
+ # under every version of that function's
+ # "was a default supplied?" test. (exc_info is not
+ # passed: loguru ignores it, so it never produced a
+ # traceback anyway.)
email = get_setting_from_snapshot(
"search.engine.web.openalex.email",
+ default="",
settings_snapshot=settings_snapshot,
)
except Exception:
logger.debug(
- "Failed to read openalex.email from settings snapshot",
- exc_info=True,
+ "Failed to read openalex.email from settings snapshot"
)
# Handle "False" string for email
self.email = email if email and email != "False" else None
+ if not api_key and settings_snapshot:
+ from ...config.search_config import get_setting_from_snapshot
+
+ try:
+ # default="" for the same reason as the email lookup
+ # above; ``normalize_openalex_api_key`` turns "" into
+ # None, i.e. "search keyless".
+ api_key = get_setting_from_snapshot(
+ "search.engine.web.openalex.api_key",
+ default="",
+ settings_snapshot=settings_snapshot,
+ )
+ except Exception:
+ logger.debug(
+ "Failed to read openalex.api_key from settings snapshot"
+ )
+
+ # Placeholders, sentinels and non-strings all become None, i.e.
+ # "search keyless". Sending them as a Bearer token would earn a
+ # 401/403 and silently turn a working engine into an empty one.
+ self.api_key: Optional[str] = normalize_openalex_api_key(api_key)
+ self.openalex_api_key: Optional[str] = self.api_key
+ # Set only once OpenAlex refuses the key; see ``_secret_attrs``.
+ self._rejected_api_key: Optional[str] = None
+
# API configuration
self.api_base = "https://api.openalex.org"
+ ua_email = self.email
self.headers = {
- "User-Agent": f"{USER_AGENT} ({email})" if email else USER_AGENT,
+ "User-Agent": f"{USER_AGENT} ({ua_email})"
+ if ua_email
+ else USER_AGENT,
"Accept": "application/json",
}
-
- if email:
- # Email allows access to polite pool with faster response times
- logger.info(f"Using OpenAlex polite pool with email: {email}")
+ if self.api_key:
+ # Bearer header rather than the equally-supported ?api_key=
+ # query parameter, so the key never lands in a URL (logs,
+ # proxies, error messages). Both schemes "work identically" —
+ # https://help.openalex.org/api/authentication/ ("Sending your
+ # key").
+ self.headers["Authorization"] = f"Bearer {self.api_key}"
+
+ if self.api_key:
+ logger.info(
+ "Using OpenAlex with API key (10x keyless daily budget)"
+ )
else:
logger.info(
- "Using OpenAlex without email (consider adding email for faster responses)"
+ "Using OpenAlex without an API key (free tier; a free key from "
+ "https://openalex.org/settings/api raises the daily budget 10x — "
+ "the old email 'polite pool' was deprecated in Feb 2026)"
)
+ def _request_works(
+ self, params: Dict[str, Any], *, with_api_key: bool
+ ) -> Any:
+ """Call the OpenAlex works endpoint, optionally without the key.
+
+ Args:
+ params: Query parameters for ``/works``.
+ with_api_key: When False, the ``Authorization`` header is
+ dropped so the request uses the keyless free tier.
+ """
+ headers = dict(self.headers)
+ if not with_api_key:
+ headers.pop("Authorization", None)
+ return safe_get(
+ f"{self.api_base}/works",
+ params=params,
+ headers=headers,
+ timeout=30,
+ )
+
+ def _note_openalex_key_rejected(
+ self, api_key: Optional[str] = None
+ ) -> None:
+ """Latch the rejection *and* drop this engine's own credential.
+
+ The base implementation only latches, which is all a non-OpenAlex
+ scientific engine needs: its ``self.api_key`` belongs to another
+ vendor and never reaches ``api.openalex.org``. This engine is the
+ one that also holds an OpenAlex key of its own, in
+ ``self.api_key`` / ``self.openalex_api_key`` and in the cached
+ ``Authorization`` header, so the latch alone would leave the
+ refused credential live for its *searches*.
+
+ That matters when the DOI enrichment pass is the path that learns
+ the key is bad — a search that returned 200 followed by an
+ enrichment 401, e.g. a key revoked mid-run. Enrichment's
+ ``on_key_rejected`` callback is this method; without the drop
+ below the next search on the same instance would send
+ ``Authorization: Bearer <refused key>`` again.
+
+ The single ``_rejected_api_key`` slot never has to hold two
+ different literals: ``_resolve_openalex_enrichment_key`` reads
+ ``self.openalex_api_key`` first, so whenever this engine has a
+ key the enrichment pass sends that same string.
+
+ Idempotent, and safe in either order relative to
+ :meth:`_drop_rejected_api_key`: the base method keeps the stored
+ literal with ``or self._rejected_api_key``, and clearing an
+ already-cleared attribute or popping an absent header is a no-op.
+ The literal is passed up before the attributes are cleared, so it
+ is never lost from ``_scrub_error``'s redaction set.
+ """
+ super()._note_openalex_key_rejected(
+ api_key or getattr(self, "api_key", None)
+ )
+ self.api_key = None
+ self.openalex_api_key = None
+ headers = getattr(self, "headers", None)
+ if isinstance(headers, dict):
+ headers.pop("Authorization", None)
+
+ def _drop_rejected_api_key(self) -> None:
+ """Forget a key OpenAlex refused, for this engine's lifetime.
+
+ Three things have to happen together for "no path sends a refused
+ key twice" to hold, and all three are done by this engine's
+ :meth:`_note_openalex_key_rejected` override:
+
+ * the ``Authorization`` header is cleared, not just the
+ attribute, so every later query on this instance goes out
+ keyless;
+ * ``BaseSearchEngine._note_openalex_key_rejected`` latches the
+ rejection, so the DOI enrichment pass later in the *same*
+ ``run()`` resolves ``None`` instead of re-reading the identical
+ key out of the settings snapshot both it and ``__init__`` read;
+ * the literal is retained in ``_rejected_api_key`` so it stays in
+ ``_scrub_error``'s redaction set.
+
+ Kept as the search path's named entry point (it is what
+ ``send_with_key_fallback`` is handed as ``on_key_rejected``) so
+ the two directions — search-learned and enrichment-learned — meet
+ in one implementation instead of drifting apart.
+ """
+ self._note_openalex_key_rejected(self.api_key)
+
+ def _reapply_rate_limit(self) -> None:
+ """Account for the extra keyless retry request.
+
+ ``apply_rate_limit`` is what paces this engine against
+ ``api.openalex.org``; the retry is a second real request, so it
+ gets its own call rather than riding on the first one's budget.
+ """
+ self._last_wait_time = self.rate_tracker.apply_rate_limit(
+ self.engine_type
+ )
+
def _get_previews(self, query: str) -> List[Dict[str, Any]]:
"""
Get preview information for OpenAlex search results.
@@ -157,10 +336,6 @@ class OpenAlexSearchEngine(BaseSearchEngine):
}
params["sort"] = sort_map.get(self.sort_by, "relevance_score:desc")
- # Add email to params for polite pool
- if self.email and self.email != "False":
- params["mailto"] = self.email
-
try:
# Apply rate limiting before making the request (simple like PubMed)
self._last_wait_time = self.rate_tracker.apply_rate_limit(
@@ -170,14 +345,28 @@ class OpenAlexSearchEngine(BaseSearchEngine):
f"Applied rate limit wait: {self._last_wait_time:.2f}s"
)
- # Make the API request
+ # Make the API request. The shared helper is what guarantees
+ # a refused key costs at most one extra request and never the
+ # results: it retries keylessly once and drops the key for
+ # this engine's lifetime. The same helper backs the DOI
+ # enrichment pass and the research-library downloader.
logger.info(f"Making OpenAlex API request with params: {params}")
- response = safe_get(
- f"{self.api_base}/works",
- params=params,
- headers=self.headers,
- timeout=30,
+ # Read once. ``self.api_key`` is shared mutable state (another
+ # thread on this instance can drop it), and the retry decision
+ # below and the OpenAlexAuthError gate further down must agree
+ # about whether *this* request carried a credential.
+ api_key = self.api_key
+ key_was_sent = api_key is not None
+ response, _ = send_with_key_fallback(
+ lambda with_api_key: self._request_works(
+ params, with_api_key=with_api_key
+ ),
+ api_key=api_key,
+ context="OpenAlex search",
+ on_key_rejected=self._drop_rejected_api_key,
+ before_retry=self._reapply_rate_limit,
)
+
logger.info(f"OpenAlex API response status: {response.status_code}")
# Log rate limit info if available
@@ -233,21 +422,78 @@ class OpenAlexSearchEngine(BaseSearchEngine):
return previews
if response.status_code == 429:
- # Rate limited (very rare with OpenAlex)
- logger.warning("OpenAlex rate limit reached")
+ # 429 is also the *daily budget* status, not just a burst
+ # limit: https://help.openalex.org/api/errors/ defines it
+ # as "Rate limit or daily credit budget exceeded", and
+ # https://help.openalex.org/api/authentication/ says "Two
+ # things return 429 Too Many Requests: exceeding your
+ # daily budget, or making more than 100 requests per
+ # second". Hence the message points at the free key,
+ # which raises that budget 10x.
+ logger.warning(
+ "OpenAlex rate limit reached; a free API key from "
+ "https://openalex.org/settings/api raises the daily budget 10x"
+ )
raise RateLimitError("OpenAlex rate limit exceeded") # noqa: TRY301 — re-raised by except RateLimitError for base class retry
+ # response.text can echo the request (headers included), so it
+ # gets the full dual-scrub — credential shapes AND this
+ # engine's literal key — before it reaches a log sink.
+ # Scrub FIRST, truncate after: cutting at 200 characters
+ # first can split the key so that neither the literal pass
+ # nor the anchored Bearer/Authorization regexes match the
+ # surviving prefix. Same ordering rule as
+ # ``security/log_sanitizer.sanitize_error_for_client``.
+ # ``bounded_error_body`` bounds the *regex passes* (not the
+ # body materialisation: ``response.text`` has already decoded
+ # all of it) by cutting the body back to the last whitespace
+ # character at or before 8192. Cutting mid-token would be
+ # unsafe even at that offset, because scrubbing shrinks the
+ # text — a token-shaped run collapses to 17 characters — and
+ # would pull the fragment the cut created into the surviving
+ # 200. Because ``normalize_openalex_api_key`` refuses any key
+ # containing whitespace, a key always lies inside one
+ # whitespace-free run, so cutting at a whitespace boundary
+ # drops any run straddling it in its entirety and no partial
+ # credential can survive.
+ safe_detail = self._scrub_error(bounded_error_body(response.text))[
+ :200
+ ]
+
+ if (
+ response.status_code in OPENALEX_AUTH_FAILURE_STATUSES
+ and key_was_sent
+ ):
+ # Reached only when a key was sent AND the keyless retry
+ # above also failed. A keyless install that gets a 401/403
+ # from a proxy has no key to blame, so it keeps the
+ # pre-existing "API error → []" behaviour below rather
+ # than being told to check a key it never configured.
+ logger.error(
+ "OpenAlex rejected the API key: "
+ f"{response.status_code} - {safe_detail}"
+ )
+ raise OpenAlexAuthError( # noqa: TRY301 — re-raised by except OpenAlexAuthError so run() records the failure
+ f"OpenAlex authentication failed (HTTP {response.status_code})"
+ )
+
logger.error(
- f"OpenAlex API error: {response.status_code} - {response.text[:200]}"
+ f"OpenAlex API error: {response.status_code} - {safe_detail}"
)
return []
- except RateLimitError:
- # Re-raise rate limit errors for base class retry handling
+ except (RateLimitError, OpenAlexAuthError):
+ # Re-raise for the base class: rate limits drive its retry
+ # handling, auth failures must be recorded as a failed search
+ # rather than disappearing into an empty result list.
raise
except Exception as e:
+ # logger.warning rather than logger.exception: the traceback
+ # frames hold self.headers (the "Authorization: Bearer <key>"
+ # value) and would render it under loguru diagnose. Same
+ # documented trade-off as search_engine_nasa_ads.
safe_msg = self._scrub_error(e)
- logger.exception(
+ logger.warning(
f"Error searching OpenAlex ({type(e).__name__}): {safe_msg}"
)
return []
diff --git a/src/local_deep_research/web_search_engines/search_engine_base.py b/src/local_deep_research/web_search_engines/search_engine_base.py
index 5c1874f37b..f1d0e9d3d2 100644
--- a/src/local_deep_research/web_search_engines/search_engine_base.py
+++ b/src/local_deep_research/web_search_engines/search_engine_base.py
@@ -226,7 +226,43 @@ class BaseSearchEngine(ABC):
# secrets under different names (e.g. Elasticsearch: _api_key/_password).
# Centralizing the list keeps every _scrub_error() call site uniform and
# prevents the per-site drift that previously dropped a secret.
- _secret_attrs: tuple[str, ...] = ("api_key",)
+ # ``_rejected_api_key`` is in the default because the OpenAlex DOI
+ # enrichment pass can store a refused key there on *any* scientific
+ # engine (arxiv, semantic_scholar, …), not just OpenAlexSearchEngine.
+ # ``_scrub_error`` reads it through ``getattr(..., None)``, so engines
+ # that never see a rejection are unaffected.
+ _secret_attrs: tuple[str, ...] = ("api_key", "_rejected_api_key")
+
+ # Class-level defaults so every engine has them without touching
+ # __init__ (and so a ``__new__``-built instance degrades rather than
+ # raising). ``_openalex_key_rejected`` latches "OpenAlex refused this
+ # credential" for the instance's lifetime: dropping the key from the
+ # engine's own attributes is not enough, because
+ # ``_resolve_openalex_enrichment_key`` would otherwise re-read the
+ # very same key out of the settings snapshot it came from and send it
+ # again on the enrichment request of the same ``run()``.
+ _openalex_key_rejected: bool = False
+ # The refused literal, kept only so it stays in the redaction set
+ # (see ``_secret_attrs``) after the live attribute is cleared.
+ _rejected_api_key: Optional[str] = None
+
+ def _note_openalex_key_rejected(
+ self, api_key: Optional[str] = None
+ ) -> None:
+ """Latch that OpenAlex refused *api_key*, for this engine's life.
+
+ Called by every OpenAlex path that can learn a key is bad: the
+ search engine's own ``_drop_rejected_api_key`` and the DOI
+ enrichment pass's ``on_key_rejected`` callback. Once set,
+ ``_resolve_openalex_enrichment_key`` returns ``None``, so no
+ path on this object sends the refused credential a second time.
+
+ ``or self._rejected_api_key`` keeps the stored literal: a second
+ call (two threads driving one engine) must not overwrite it with
+ ``None`` and silently remove it from the redaction set.
+ """
+ self._openalex_key_rejected = True
+ self._rejected_api_key = api_key or self._rejected_api_key
@staticmethod
def _ensure_list(value, *, default=None):
@@ -724,7 +760,14 @@ class BaseSearchEngine(ABC):
email = getattr(self, "email", None)
previews = enrich_results_with_source_ids(
- previews, email=email
+ previews,
+ email=email,
+ api_key=self._resolve_openalex_enrichment_key(),
+ # Enrichment's own drop is call-local; this
+ # latches it on the engine so later runs
+ # resolve None instead of the same refused
+ # key, and keeps the literal redactable.
+ on_key_rejected=self._note_openalex_key_rejected,
)
except Exception:
logger.debug(
@@ -897,6 +940,63 @@ class BaseSearchEngine(ABC):
# Shared Helper Methods for Subclasses
# =========================================================================
+ def _resolve_openalex_enrichment_key(self) -> Optional[str]:
+ """Resolve the OpenAlex API key used by the DOI enrichment pass.
+
+ The enrichment request always goes to ``api.openalex.org``, no
+ matter which engine produced the previews, so every
+ ``is_scientific`` engine (arxiv, semantic_scholar, zenodo,
+ nasa_ads, pubchem, pubmed, …) needs the *OpenAlex* credential
+ here — not its own. Only ``OpenAlexSearchEngine`` sets the
+ ``openalex_api_key`` attribute, so the settings snapshot is the
+ source for everyone else.
+
+ Deliberately never reads ``self.api_key``: sending, say, a NASA
+ ADS key to OpenAlex would hand one vendor's credential to another
+ host. The isolation is pinned by
+ ``test_openalex_enrichment_key_isolated_from_other_engine_keys``.
+ """
+ from ..utilities.openalex_enrichment import (
+ normalize_openalex_api_key,
+ )
+
+ if self._openalex_key_rejected:
+ # OpenAlex already refused this installation's key on this
+ # engine. Clearing ``self.openalex_api_key`` alone would not
+ # help: the snapshot fallback below is where the key came
+ # from in the first place, so without this latch the
+ # enrichment request of the very same ``run()`` re-sends it.
+ return None
+
+ key = normalize_openalex_api_key(
+ getattr(self, "openalex_api_key", None)
+ )
+ if key:
+ return key
+
+ settings_snapshot = getattr(self, "settings_snapshot", None)
+ if not settings_snapshot:
+ return None
+
+ # An explicit default is required: with no ``default`` argument
+ # at all, a non-empty snapshot that lacks this key and no
+ # thread-local settings context makes ``get_setting_from_snapshot``
+ # raise ``NoSettingsContextError``. That would propagate out of
+ # this resolver in the *argument* position of the enrichment call
+ # and be swallowed by the caller's blanket handler, silently
+ # skipping DOI enrichment for every scientific engine. The empty
+ # string (rather than None) is the safer spelling because it is
+ # falsy under every version of that function's "was a default
+ # supplied?" test, and ``normalize_openalex_api_key`` maps it to
+ # None, i.e. "enrich keylessly".
+ return normalize_openalex_api_key(
+ get_setting_from_snapshot(
+ "search.engine.web.openalex.api_key",
+ default="",
+ settings_snapshot=settings_snapshot,
+ )
+ )
+
@staticmethod
def _is_valid_api_key(api_key: Optional[str]) -> bool:
"""
diff --git a/tests/research_library/downloaders/test_openalex_coverage.py b/tests/research_library/downloaders/test_openalex_coverage.py
index 20f193eb2f..0a74f591a5 100644
--- a/tests/research_library/downloaders/test_openalex_coverage.py
+++ b/tests/research_library/downloaders/test_openalex_coverage.py
@@ -23,6 +23,8 @@ def downloader():
d = OpenAlexDownloader.__new__(OpenAlexDownloader)
d.timeout = 30
d.polite_pool_email = None
+ d.api_key = None
+ d._rejected_api_key = None
d.base_api_url = "https://api.openalex.org"
d.session = MagicMock()
d.session.headers = {"User-Agent": "Test"}
@@ -287,7 +289,7 @@ class TestGetPdfUrl:
assert downloader._get_pdf_url("W123") is None
def test_polite_pool_email_in_header(self, downloader):
- """When polite_pool_email is set, User-Agent header is sent."""
+ """When polite_pool_email is set, it identifies the User-Agent."""
downloader.polite_pool_email = "[email protected]"
resp = Mock()
@@ -304,6 +306,206 @@ class TestGetPdfUrl:
)
assert "mailto:[email protected]" in headers.get("User-Agent", "")
+ def test_request_failure_scrubs_the_key_from_the_log(self, downloader):
+ """The frame holds ``headers`` — the key must not reach the sink."""
+ downloader.api_key = "oa-live-abc123"
+ downloader.session.get.side_effect = (
+ requests.exceptions.RequestException(
+ "connect failed with Authorization: Bearer oa-live-abc123"
+ )
+ )
+ logged = []
+
+ with patch(
+ "local_deep_research.research_library.downloaders.openalex.logger.warning",
+ side_effect=lambda msg, *a, **kw: logged.append(msg),
+ ):
+ assert downloader._get_pdf_url("W123") is None
+
+ assert logged
+ assert not any("oa-live-abc123" in message for message in logged)
+
+ def test_api_key_in_authorization_header(self, downloader):
+ downloader.api_key = "openalex-test-key"
+
+ resp = Mock()
+ resp.status_code = 404
+ downloader.session.get.return_value = resp
+
+ downloader._get_pdf_url("W123")
+
+ call_kwargs = downloader.session.get.call_args
+ headers = call_kwargs[1].get(
+ "headers", call_kwargs.kwargs.get("headers", {})
+ )
+ assert headers["Authorization"] == "Bearer openalex-test-key"
+ assert "openalex-test-key" not in call_kwargs[1]["params"].values()
+
+ @pytest.mark.parametrize("auth_status", [401, 403])
+ def test_rejected_key_retries_keyless_and_finds_the_pdf(
+ self, downloader, auth_status
+ ):
+ """A rejected key must not turn an available PDF into "none".
+
+ Pre-key, this lookup was unconditionally keyless and worked.
+ """
+ downloader.api_key = "oa-live-abc123"
+
+ rejected = Mock()
+ rejected.status_code = auth_status
+
+ ok = Mock()
+ ok.status_code = 200
+ ok.json.return_value = {
+ "open_access": {"is_oa": True},
+ "best_oa_location": {"pdf_url": "https://x.com/a.pdf"},
+ }
+ downloader.session.get.side_effect = [rejected, ok]
+
+ assert downloader._get_pdf_url("W123") == "https://x.com/a.pdf"
+
+ assert downloader.session.get.call_count == 2
+ first, second = downloader.session.get.call_args_list
+ assert first.kwargs["headers"]["Authorization"] == (
+ "Bearer oa-live-abc123"
+ )
+ assert "Authorization" not in second.kwargs["headers"]
+ # Dropped for good, but still redactable.
+ assert downloader.api_key is None
+ assert "oa-live-abc123" not in downloader._scrub(
+ RuntimeError("boom oa-live-abc123")
+ )
+
+ def test_rejected_key_is_never_sent_again(self, downloader):
+ """No later work lookup pays a round-trip for a rejected key."""
+ downloader.api_key = "oa-live-abc123"
+
+ rejected = Mock()
+ rejected.status_code = 401
+
+ def _missing():
+ resp = Mock()
+ resp.status_code = 404
+ return resp
+
+ downloader.session.get.side_effect = [
+ rejected,
+ _missing(),
+ _missing(),
+ ]
+
+ downloader._get_pdf_url("W123")
+ downloader._get_pdf_url("W456")
+
+ assert downloader.session.get.call_count == 3
+ keyed = [
+ call
+ for call in downloader.session.get.call_args_list
+ if "Authorization" in call.kwargs["headers"]
+ ]
+ assert len(keyed) == 1
+
+ def test_a_second_drop_keeps_the_literal_in_the_redaction_set(
+ self, downloader
+ ):
+ """Idempotency: the second drop must not store None over the key.
+
+ Unreachable single-threaded — the helper short-circuits on a
+ falsy key — but reachable when one downloader instance is driven
+ from a thread pool and two lookups are refused concurrently. The
+ helper is stubbed here so the callback is invoked twice, which is
+ exactly what that race produces.
+ """
+ downloader.api_key = "oa-live-abc123"
+
+ def _fake_helper(
+ send_request,
+ *,
+ api_key,
+ context,
+ on_key_rejected=None,
+ before_retry=None,
+ ):
+ on_key_rejected()
+ on_key_rejected() # the racing second rejection
+ raise RuntimeError("boom with oa-live-abc123")
+
+ with (
+ patch(
+ "local_deep_research.research_library.downloaders.openalex."
+ "send_with_key_fallback",
+ _fake_helper,
+ ),
+ pytest.raises(RuntimeError),
+ ):
+ downloader._get_pdf_url("W123")
+
+ assert downloader.api_key is None
+ assert downloader._rejected_api_key == "oa-live-abc123"
+ assert "oa-live-abc123" not in downloader._scrub(
+ RuntimeError("boom oa-live-abc123")
+ )
+
+ def test_scrub_survives_a_partially_constructed_downloader(self):
+ """``_scrub`` runs inside ``except`` handlers — it must not raise.
+
+ An instance whose ``__init__`` never completed (or a ``__new__``
+ built one) has neither attribute; direct attribute access would
+ raise ``AttributeError`` from inside the handler and replace the
+ real error with a spurious one.
+ """
+ bare = OpenAlexDownloader.__new__(OpenAlexDownloader)
+ assert not hasattr(bare, "api_key")
+ assert not hasattr(bare, "_rejected_api_key")
+
+ # Degrades to the shape-only scrub rather than raising.
+ scrubbed = bare._scrub(
+ RuntimeError("failed with Authorization: Bearer oa-live-abc123")
+ )
+ assert "oa-live-abc123" not in scrubbed
+
+ def test_keyless_retry_failing_too_returns_none(self, downloader):
+ """Pre-key fallback: warn about the status and give up."""
+ downloader.api_key = "oa-live-abc123"
+
+ rejected = Mock()
+ rejected.status_code = 401
+ downloader.session.get.side_effect = [rejected, rejected]
+ logged = []
+
+ with patch(
+ "local_deep_research.research_library.downloaders.openalex.logger.warning",
+ side_effect=lambda msg, *a, **kw: logged.append(msg),
+ ):
+ assert downloader._get_pdf_url("W123") is None
+
+ assert downloader.session.get.call_count == 2
+ assert any("OpenAlex API error: 401" in message for message in logged)
+ assert not any("oa-live-abc123" in message for message in logged)
+
+ @pytest.mark.parametrize("auth_status", [401, 403])
+ def test_keyless_auth_failure_is_a_single_request(
+ self, downloader, auth_status
+ ):
+ """No key configured → nothing retried, nothing blamed on a key."""
+ rejected = Mock()
+ rejected.status_code = auth_status
+ downloader.session.get.return_value = rejected
+ logged = []
+
+ with patch(
+ "local_deep_research.research_library.downloaders.openalex.logger.warning",
+ side_effect=lambda msg, *a, **kw: logged.append(msg),
+ ):
+ assert downloader._get_pdf_url("W123") is None
+
+ assert downloader.session.get.call_count == 1
+ assert not any("API key" in message for message in logged)
+ assert any(
+ f"OpenAlex API error: {auth_status}" in message
+ for message in logged
+ )
+
def test_no_polite_pool_email_empty_headers(self, downloader):
"""When polite_pool_email is None, no User-Agent override."""
resp = Mock()
@@ -459,15 +661,44 @@ class TestInit:
assert d.timeout == 60
def test_polite_pool_email(self):
- """Polite pool email is stored."""
+ """Identification email is stored under the backward-compatible name."""
d = OpenAlexDownloader(polite_pool_email="[email protected]")
assert d.polite_pool_email == "[email protected]"
def test_polite_pool_default_none(self):
- """Polite pool email defaults to None."""
+ """Identification email defaults to None."""
d = OpenAlexDownloader()
assert d.polite_pool_email is None
+ def test_api_key(self):
+ d = OpenAlexDownloader(api_key="openalex-test-key")
+ assert d.api_key == "openalex-test-key"
+
+ def test_api_key_is_trimmed(self):
+ d = OpenAlexDownloader(api_key=" openalex-test-key ")
+ assert d.api_key == "openalex-test-key"
+
+ @pytest.mark.parametrize(
+ "configured_key",
+ [
+ None,
+ "",
+ " ",
+ "False",
+ " False ",
+ "false",
+ "${OPENALEX_API_KEY}",
+ "<your_api_key>",
+ "your-api-key-here",
+ True,
+ 1,
+ ],
+ )
+ def test_placeholder_key_falls_back_to_keyless(self, configured_key):
+ """A placeholder must not become a Bearer token OpenAlex rejects."""
+ d = OpenAlexDownloader(api_key=configured_key)
+ assert d.api_key is None
+
def test_base_api_url(self):
"""Base API URL is set correctly."""
d = OpenAlexDownloader()
diff --git a/tests/research_library/services/test_download_service_logic.py b/tests/research_library/services/test_download_service_logic.py
index a6385d5f72..c25b07f77d 100644
--- a/tests/research_library/services/test_download_service_logic.py
+++ b/tests/research_library/services/test_download_service_logic.py
@@ -584,3 +584,62 @@ class TestDefaultSnapshotEgressContext:
allowed, _ = service._check_url_against_policy("https://arxiv.org/x")
assert allowed is True # no_context back-compat
service.close()
+
+
+# ---------------------------------------------------------------------------
+# OpenAlex downloader credential wiring
+# ---------------------------------------------------------------------------
+
+
+class TestOpenAlexDownloaderApiKeyWiring:
+ """The library downloader hits api.openalex.org and needs the key too."""
+
+ @staticmethod
+ def _service_with_openalex_key(tmp_path, configured_key):
+ mock_settings = Mock()
+ mock_settings.get_setting.side_effect = lambda key, default=None: {
+ "research_library.storage_path": str(tmp_path),
+ "research_library.pdf_storage_mode": "none",
+ "search.engine.web.semantic_scholar.api_key": "",
+ "search.engine.web.openalex.api_key": configured_key,
+ }.get(key, default)
+
+ with (
+ patch(
+ "local_deep_research.research_library.services.download_service.get_settings_manager",
+ return_value=mock_settings,
+ ),
+ patch(
+ "local_deep_research.research_library.services.download_service.RetryManager",
+ ),
+ patch(
+ "local_deep_research.research_library.services.download_service.get_library_directory",
+ return_value=tmp_path,
+ ),
+ ):
+ from local_deep_research.research_library.services.download_service import (
+ DownloadService,
+ )
+
+ return DownloadService("u", "p")
+
+ @staticmethod
+ def _openalex_downloader(service):
+ from local_deep_research.research_library.downloaders.openalex import (
+ OpenAlexDownloader,
+ )
+
+ matches = [
+ d for d in service.downloaders if isinstance(d, OpenAlexDownloader)
+ ]
+ assert len(matches) == 1
+ return matches[0]
+
+ def test_configured_key_reaches_the_downloader(self, tmp_path):
+ service = self._service_with_openalex_key(tmp_path, "oa-live-abc123")
+ try:
+ assert (
+ self._openalex_downloader(service).api_key == "oa-live-abc123"
+ )
+ finally:
+ service.close()
diff --git a/tests/settings/golden_master_settings.json b/tests/settings/golden_master_settings.json
index 4edafbf123..d3f6301fe7 100644
--- a/tests/settings/golden_master_settings.json
+++ b/tests/settings/golden_master_settings.json
@@ -4744,6 +4744,20 @@
"value": true,
"visible": true
},
+ "search.engine.web.openalex.api_key": {
+ "category": "openalex",
+ "description": "OpenAlex API key (optional but recommended). Raises the daily request budget 10x. Get a free key at https://openalex.org/settings/api. The old email 'polite pool' was deprecated by OpenAlex in February 2026 and no longer has any effect.",
+ "editable": true,
+ "max_value": null,
+ "min_value": null,
+ "name": "API Key",
+ "options": null,
+ "step": null,
+ "type": "SEARCH",
+ "ui_element": "password",
+ "value": "",
+ "visible": true
+ },
"search.engine.web.openalex.default_params.filter_open_access": {
"category": "openalex",
"description": "Only return open access papers that are freely available",
@@ -4857,11 +4871,11 @@
},
"search.engine.web.openalex.email": {
"category": "openalex",
- "description": "Email address for polite pool access (optional but recommended). Provides faster response times.",
+ "description": "OpenAlex deprecated the email 'polite pool' in February 2026. This email is now included only in the User-Agent for identification; configure an API key instead to raise the daily request budget.",
"editable": true,
"max_value": null,
"min_value": null,
- "name": "Email (for Polite Pool)",
+ "name": "Email (User-Agent identification)",
"options": null,
"step": null,
"type": "SEARCH",
@@ -4930,8 +4944,8 @@
"citation analysis",
"open access content",
"comprehensive coverage",
- "no API key required",
- "high rate limits"
+ "works without an API key",
+ "free API key raises the daily request budget"
],
"visible": true
},
diff --git a/tests/utilities/test_openalex_enrichment.py b/tests/utilities/test_openalex_enrichment.py
index 9cd56769ab..4105064960 100644
--- a/tests/utilities/test_openalex_enrichment.py
+++ b/tests/utilities/test_openalex_enrichment.py
@@ -16,8 +16,12 @@ from unittest.mock import MagicMock, patch
import pytest
from local_deep_research.utilities.openalex_enrichment import (
+ ERROR_BODY_SCRUB_LIMIT,
_normalize_doi,
+ bounded_error_body,
enrich_results_with_source_ids,
+ normalize_openalex_api_key,
+ send_with_key_fallback,
)
@@ -292,9 +296,23 @@ class TestEnrichResultsWithSourceIds:
]
assert per_pages == ["50", "25"]
- def test_email_passed_as_mailto_and_user_agent(self):
- """When a polite-pool email is supplied, it lands in both the
- ``mailto`` query param AND the User-Agent header."""
+ def test_api_key_sent_as_authorization_header(self):
+ results = [{"doi": "10.1038/nature12373"}]
+ mock_resp = _make_openalex_response([])
+ with patch(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ return_value=mock_resp,
+ ) as mock_get:
+ enrich_results_with_source_ids(results, api_key="openalex-test-key")
+ call = mock_get.call_args
+ assert call.kwargs["headers"]["Authorization"] == (
+ "Bearer openalex-test-key"
+ )
+ assert "mailto" not in call.kwargs["params"]
+ assert "api_key" not in call.kwargs["params"]
+ assert "openalex-test-key" not in call.kwargs["params"].values()
+
+ def test_email_only_overrides_user_agent(self):
results = [{"doi": "10.1038/nature12373"}]
mock_resp = _make_openalex_response([])
with patch(
@@ -305,8 +323,9 @@ class TestEnrichResultsWithSourceIds:
results, email="[email protected]"
)
call = mock_get.call_args
- assert call.kwargs["params"]["mailto"] == "[email protected]"
+ assert "mailto" not in call.kwargs["params"]
assert "[email protected]" in call.kwargs["headers"]["User-Agent"]
+ assert "Authorization" not in call.kwargs["headers"]
def test_email_omitted_leaves_mailto_absent(self):
"""No email → no mailto param, no User-Agent override."""
@@ -324,3 +343,755 @@ class TestEnrichResultsWithSourceIds:
if __name__ == "__main__":
pytest.main([__file__, "-v"])
+
+
+# ---------------------------------------------------------------------------
+# normalize_openalex_api_key
+# ---------------------------------------------------------------------------
+
+
+class TestNormalizeOpenAlexApiKey:
+ """A value that cannot be a real key must mean "go keyless"."""
+
+ @pytest.mark.parametrize(
+ "configured_key",
+ [
+ None,
+ "",
+ " ",
+ "\t\n",
+ "False",
+ " False ",
+ "false",
+ "FALSE",
+ "none",
+ "null",
+ "placeholder",
+ "api_key",
+ "your_api_key",
+ "your-api-key-here",
+ "YOUR_API_KEY_HERE",
+ "<your_api_key>",
+ "${OPENALEX_API_KEY}",
+ "${openalex_api_key}",
+ True,
+ 1,
+ 3.5,
+ ["k"],
+ {"k": 1},
+ ],
+ )
+ def test_unusable_values_become_none(self, configured_key):
+ assert normalize_openalex_api_key(configured_key) is None
+
+ @pytest.mark.parametrize(
+ ("configured_key", "expected"),
+ [
+ ("oa-live-abc123", "oa-live-abc123"),
+ (" oa-live-abc123 ", "oa-live-abc123"),
+ ("falsework-key", "falsework-key"),
+ ("nonesuch-key", "nonesuch-key"),
+ ],
+ )
+ def test_real_keys_survive(self, configured_key, expected):
+ assert normalize_openalex_api_key(configured_key) == expected
+
+ @pytest.mark.parametrize(
+ "configured_key",
+ [
+ "abc\ndef",
+ "abc\rdef",
+ "abc\tdef",
+ "abc def",
+ "abc\x00def",
+ "abc\x7fdef",
+ "abc\u00a0def",
+ "abc\u200bdef",
+ ],
+ )
+ def test_internal_whitespace_or_control_chars_become_none(
+ self, configured_key
+ ):
+ """Such a value cannot be a header, and its repr defeats scrubbing.
+
+ ``requests`` raises ``InvalidHeader`` embedding the value's
+ ``repr``; the literal-secret pass cannot match it (the literal
+ holds a real newline, the message holds a backslash and an "n")
+ and the anchored Bearer regex stops at the backslash. Rejecting
+ the value up front is what keeps it out of the logs entirely.
+ """
+ assert normalize_openalex_api_key(configured_key) is None
+
+ def test_whitespace_rejection_warns_without_echoing_the_value(self):
+ logged = []
+ with patch(
+ "local_deep_research.utilities.openalex_enrichment.logger.warning",
+ side_effect=lambda msg, *a, **kw: logged.append(msg),
+ ):
+ assert normalize_openalex_api_key("oa-live\nabc123") is None
+
+ assert logged, "an unusable-looking real key must be reported"
+ assert not any("abc123" in message for message in logged)
+ assert not any("oa-live" in message for message in logged)
+
+ def test_placeholder_with_whitespace_is_dropped_silently(self):
+ """The placeholder list runs first, so no misleading warning."""
+ logged = []
+ with patch(
+ "local_deep_research.utilities.openalex_enrichment.logger.warning",
+ side_effect=lambda msg, *a, **kw: logged.append(msg),
+ ):
+ assert normalize_openalex_api_key("<your api key>") is None
+
+ assert logged == []
+
+
+class TestEnrichmentKeyNormalization:
+ """The enrichment request applies the same filter as the engine."""
+
+ @pytest.mark.parametrize(
+ "configured_key",
+ ["${OPENALEX_API_KEY}", "your-api-key-here", "False", " ", True],
+ )
+ def test_placeholder_key_sends_no_authorization_header(
+ self, configured_key
+ ):
+ results = [{"doi": "10.1038/nature12373"}]
+ mock_resp = _make_openalex_response([])
+ with patch(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ return_value=mock_resp,
+ ) as mock_get:
+ enrich_results_with_source_ids(results, api_key=configured_key)
+
+ headers = mock_get.call_args.kwargs["headers"]
+ assert "Authorization" not in headers
+
+ def test_real_key_is_trimmed_before_use(self):
+ results = [{"doi": "10.1038/nature12373"}]
+ mock_resp = _make_openalex_response([])
+ with patch(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ return_value=mock_resp,
+ ) as mock_get:
+ enrich_results_with_source_ids(
+ results, api_key=" oa-live-abc123 "
+ )
+
+ headers = mock_get.call_args.kwargs["headers"]
+ assert headers["Authorization"] == "Bearer oa-live-abc123"
+
+ @pytest.mark.parametrize("auth_status", [401, 403])
+ def test_rejected_key_logs_a_distinct_warning(self, auth_status):
+ results = [{"doi": "10.1038/nature12373"}]
+ rejected = MagicMock()
+ rejected.status_code = auth_status
+ logged = []
+
+ with (
+ patch(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ return_value=rejected,
+ ),
+ patch(
+ "local_deep_research.utilities.openalex_enrichment.logger.warning",
+ side_effect=lambda msg, *a, **kw: logged.append(msg),
+ ),
+ ):
+ enrich_results_with_source_ids(results, api_key="oa-live-abc123")
+
+ assert any(
+ "rejected the configured API key" in message for message in logged
+ )
+ assert not any("oa-live-abc123" in message for message in logged)
+
+
+class TestRejectedKeyKeylessFallback:
+ """A rejected key must never cost the enrichment pass its results.
+
+ Same three-case shape as the search engine and the library
+ downloader, because all three go through
+ ``send_with_key_fallback``.
+ """
+
+ @pytest.mark.parametrize("auth_status", [401, 403])
+ def test_rejected_key_retries_keyless_and_enriches(self, auth_status):
+ """401/403 with a key → one keyless retry that actually works."""
+ results = [{"doi": "10.1038/nature12373"}]
+ rejected = MagicMock()
+ rejected.status_code = auth_status
+ ok = _make_openalex_response(
+ [_work("https://doi.org/10.1038/nature12373", "S137773608")]
+ )
+
+ with patch(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ side_effect=[rejected, ok],
+ ) as mock_get:
+ enrich_results_with_source_ids(results, api_key="oa-live-abc123")
+
+ assert mock_get.call_count == 2
+ first, second = mock_get.call_args_list
+ assert first.kwargs["headers"]["Authorization"] == (
+ "Bearer oa-live-abc123"
+ )
+ # The retry is the same request minus the credential.
+ assert "Authorization" not in second.kwargs["headers"]
+ assert second.kwargs["params"] == first.kwargs["params"]
+ # And the batch was enriched, not dropped.
+ assert results[0]["openalex_source_id"] == "S137773608"
+
+ def test_rejected_key_is_not_sent_again_by_a_later_batch(self):
+ """The key is dropped for the rest of the pass, not per batch.
+
+ Two chunks (>50 DOIs). Without the drop, chunk 2 would send the
+ same rejected credential and pay a second wasted round-trip, and
+ the "rejected" warning would be logged twice.
+ """
+ results = [{"doi": f"10.1234/paper{index}"} for index in range(60)]
+ rejected = MagicMock()
+ rejected.status_code = 401
+ empty = _make_openalex_response([])
+ logged = []
+
+ with (
+ patch(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ side_effect=[rejected, empty, empty],
+ ) as mock_get,
+ patch(
+ "local_deep_research.utilities.openalex_enrichment.logger.warning",
+ side_effect=lambda msg, *a, **kw: logged.append(msg),
+ ),
+ ):
+ enrich_results_with_source_ids(results, api_key="oa-live-abc123")
+
+ # chunk 1 keyed + chunk 1 keyless retry + chunk 2 keyless = 3
+ assert mock_get.call_count == 3
+ sent_with_key = [
+ call
+ for call in mock_get.call_args_list
+ if "Authorization" in call.kwargs["headers"]
+ ]
+ assert len(sent_with_key) == 1
+ assert (
+ sum(
+ "rejected the configured API key" in message
+ for message in logged
+ )
+ == 1
+ )
+
+ def test_keyless_retry_failing_too_skips_the_batch(self):
+ """Pre-key behaviour when even the keyless request is refused."""
+ results = [{"doi": "10.1038/nature12373"}]
+ rejected = MagicMock()
+ rejected.status_code = 401
+ logged = []
+
+ with (
+ patch(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ side_effect=[rejected, rejected],
+ ) as mock_get,
+ patch(
+ "local_deep_research.utilities.openalex_enrichment.logger.warning",
+ side_effect=lambda msg, *a, **kw: logged.append(msg),
+ ),
+ ):
+ out = enrich_results_with_source_ids(
+ results, api_key="oa-live-abc123"
+ )
+
+ assert mock_get.call_count == 2
+ assert out is results
+ assert "openalex_source_id" not in results[0]
+ assert any(
+ "DOI enrichment: OpenAlex returned 401" in message
+ for message in logged
+ )
+ assert not any("oa-live-abc123" in message for message in logged)
+
+ @pytest.mark.parametrize("auth_status", [401, 403])
+ def test_keyless_401_is_unchanged_and_blames_no_key(self, auth_status):
+ """No key configured → one request, and no "your key" advice."""
+ results = [{"doi": "10.1038/nature12373"}]
+ rejected = MagicMock()
+ rejected.status_code = auth_status
+ logged = []
+
+ with (
+ patch(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ return_value=rejected,
+ ) as mock_get,
+ patch(
+ "local_deep_research.utilities.openalex_enrichment.logger.warning",
+ side_effect=lambda msg, *a, **kw: logged.append(msg),
+ ),
+ ):
+ enrich_results_with_source_ids(results)
+
+ assert mock_get.call_count == 1
+ assert not any(
+ "API key" in message or "openalex.org/settings/api" in message
+ for message in logged
+ )
+ assert any(
+ f"DOI enrichment: OpenAlex returned {auth_status}" in message
+ for message in logged
+ )
+
+ def test_lookup_failure_scrubs_the_key_from_the_log(self):
+ results = [{"doi": "10.1038/nature12373"}]
+ logged = []
+
+ with (
+ patch(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ side_effect=RuntimeError(
+ "connect failed with Authorization: Bearer oa-live-abc123"
+ ),
+ ),
+ patch(
+ "local_deep_research.utilities.openalex_enrichment.logger.warning",
+ side_effect=lambda msg, *a, **kw: logged.append(msg),
+ ),
+ ):
+ out = enrich_results_with_source_ids(
+ results, api_key="oa-live-abc123"
+ )
+
+ assert out is results # graceful: results pass through unenriched
+ assert logged
+ assert not any("oa-live-abc123" in message for message in logged)
+
+
+class TestNormalizedKeysAreAlwaysHeaderSafe:
+ """The general property, not the example codepoints.
+
+ ``normalize_openalex_api_key`` exists so that no value it returns can
+ blow up header construction. Whitespace and control characters are one
+ axis; latin-1 encodability is the other, and it is the one that
+ actually decides whether the request leaves the process:
+ ``http.client`` does ``one_value.encode('latin-1')`` on every header
+ value, and ``requests``' own header validation does not gate the
+ encoding. A ``UnicodeEncodeError`` there is raised before any socket
+ work, carries no status code, and so cannot be turned into a keyless
+ retry by anything that branches on ``response.status_code``.
+ """
+
+ @pytest.mark.parametrize(
+ ("configured_key", "why"),
+ [
+ ("oa-key‐abc", "U+2010 HYPHEN — copied out of a PDF"),
+ ("oa-key–abc", "U+2013 EN DASH — editor autocorrect"),
+ ("oa’key", "U+2019 RIGHT SINGLE QUOTATION MARK"),
+ ("oa-key—abc", "U+2014 EM DASH"),
+ ("oa-key€abc", "U+20AC EURO SIGN (not in latin-1)"),
+ ("oa-keyŁabc", "U+0141 LATIN CAPITAL LETTER L WITH STROKE"),
+ ("oa-key中abc", "CJK ideograph"),
+ ("oa-key\U0001f600abc", "astral-plane emoji"),
+ ],
+ )
+ def test_non_latin1_keys_become_none(self, configured_key, why):
+ """None of these is whitespace or category C — only the encoding."""
+ import unicodedata
+
+ assert not any(
+ character.isspace()
+ or unicodedata.category(character).startswith("C")
+ for character in configured_key
+ ), f"{why}: this case must exercise the encoding check, not the old one"
+ assert normalize_openalex_api_key(configured_key) is None
+
+ @pytest.mark.parametrize(
+ "configured_key",
+ [
+ "ké", # é — in latin-1, must survive
+ "oa-key-ü", # ü
+ "éüñ-key",
+ "oa-live-abc123",
+ ],
+ )
+ def test_latin1_keys_survive(self, configured_key):
+ """The encoding check must not swallow a usable key."""
+ assert normalize_openalex_api_key(configured_key) == configured_key
+
+ def test_no_returned_key_can_fail_header_encoding(self):
+ """Sweep the codepoint space, not a handful of examples.
+
+ For every codepoint below U+3000 plus a spread of higher ones,
+ embed it in the middle of an otherwise-fine key and check the
+ invariant that matters: whatever comes back either is ``None`` or
+ can actually be sent. "Can be sent" is modelled on the step the
+ stack performs — ``http.client.putheader`` does
+ ``value.encode("latin-1")`` on each header value, and this
+ re-implements that call on the full ``Bearer <key>`` string
+ rather than driving ``http.client`` itself.
+ """
+ codepoints = list(range(0x3000)) + [
+ 0x303F,
+ 0x3400,
+ 0x4E2D,
+ 0xFEFF,
+ 0xFF21,
+ 0x1F600,
+ 0x10FFFF,
+ ]
+ survivors = 0
+ for codepoint in codepoints:
+ candidate = f"oa-key{chr(codepoint)}abc"
+ normalized = normalize_openalex_api_key(candidate)
+ if normalized is None:
+ continue
+ survivors += 1
+ # Models the encode step http/client.py performs per header
+ # value; it is not http.client itself.
+ f"Bearer {normalized}".encode("latin-1")
+ # Sanity: the sweep is not vacuous — plenty of codepoints are fine.
+ assert survivors > 100
+
+ def test_the_encoding_check_is_what_rejects_them(self):
+ """Guard against "the old predicates already covered this".
+
+ If the whitespace/control predicates alone were enough, this
+ assertion would hold for the non-latin-1 codepoints too, and the
+ encode check would be dead code.
+ """
+ import unicodedata
+
+ leaked = [
+ codepoint
+ for codepoint in range(0x3000)
+ if not (
+ chr(codepoint).isspace()
+ or unicodedata.category(chr(codepoint)).startswith("C")
+ )
+ and codepoint > 0xFF
+ ]
+ assert leaked, "expected non-latin-1, non-space, non-control codepoints"
+ for codepoint in leaked[:200]:
+ assert (
+ normalize_openalex_api_key(f"oa-key{chr(codepoint)}abc") is None
+ )
+
+ def test_encoding_rejection_warns_without_echoing_the_value(self):
+ logged = []
+ with patch(
+ "local_deep_research.utilities.openalex_enrichment.logger.warning",
+ side_effect=lambda msg, *a, **kw: logged.append(msg),
+ ):
+ assert normalize_openalex_api_key("oa-live–abc123") is None
+
+ assert logged, "an unusable-looking real key must be reported"
+ assert not any("abc123" in message for message in logged)
+ assert not any("oa-live" in message for message in logged)
+
+
+class TestHeaderEncodingFallback:
+ """Defence in depth for a caller that skipped the normalizer.
+
+ ``UnicodeEncodeError`` is the one exception that can only come from
+ encoding a header value, i.e. before any request leaves the process.
+ It gets the rejection treatment; nothing else does.
+ """
+
+ @staticmethod
+ def _ok():
+ response = MagicMock()
+ response.status_code = 200
+ return response
+
+ def test_unencodable_key_is_dropped_and_the_send_is_retried_keyless(self):
+ calls = []
+ events = []
+ ok = self._ok()
+ logged = []
+
+ def _send(with_api_key):
+ calls.append(with_api_key)
+ if with_api_key:
+ # Exactly what http.client does to a header value.
+ "Bearer oa-live–abc123".encode("latin-1")
+ return ok
+
+ with patch(
+ "local_deep_research.utilities.openalex_enrichment.logger.warning",
+ side_effect=lambda msg, *a, **kw: logged.append(msg),
+ ):
+ response, key = send_with_key_fallback(
+ _send,
+ api_key="oa-live–abc123",
+ context="Unit test",
+ on_key_rejected=lambda: events.append("rejected"),
+ before_retry=lambda: events.append("retry"),
+ )
+
+ assert response is ok
+ assert key is None
+ assert calls == [True, False]
+ assert events == ["rejected", "retry"]
+ assert len(logged) == 1
+ assert not any("oa-live" in message for message in logged)
+ assert not any("abc123" in message for message in logged)
+
+ @pytest.mark.parametrize(
+ "error",
+ [
+ RuntimeError("connection reset"),
+ # UnicodeEncodeError's base classes: widening the except to
+ # either of these would swallow a real failure and throw the
+ # key away for a fault OpenAlex never reported.
+ ValueError("some other value error"),
+ UnicodeError("some other unicode error"),
+ OSError("network down"),
+ ],
+ )
+ def test_other_exceptions_are_not_retried_keyless(self, error):
+ calls = []
+ events = []
+
+ def _send(with_api_key):
+ calls.append(with_api_key)
+ raise error
+
+ with pytest.raises(type(error)):
+ send_with_key_fallback(
+ _send,
+ api_key="oa-live-abc123",
+ context="Unit test",
+ on_key_rejected=lambda: events.append("rejected"),
+ before_retry=lambda: events.append("retry"),
+ )
+
+ assert calls == [True], "no keyless resend for a non-encoding failure"
+ assert events == [], "the key must not be dropped for a network fault"
+
+ def test_keyless_encoding_failure_propagates(self):
+ """No key means the encoding fault is not the credential's."""
+ calls = []
+
+ def _send(with_api_key):
+ calls.append(with_api_key)
+ "–".encode("latin-1")
+
+ with pytest.raises(UnicodeEncodeError):
+ send_with_key_fallback(_send, api_key=None, context="Unit test")
+
+ assert calls == [False]
+
+ def test_on_key_rejected_runs_before_the_keyless_resend(self):
+ """Ordering, pinned by making the resend observe the drop.
+
+ Moving ``on_key_rejected()`` after ``send_request(False)`` is
+ otherwise invisible: every response-list-driven test sees the same
+ call sequence either way.
+ """
+ holder = {"api_key": "oa-live-abc123"}
+ rejected = MagicMock()
+ rejected.status_code = 401
+ ok = self._ok()
+
+ def _send(with_api_key):
+ if with_api_key:
+ return rejected
+ assert holder["api_key"] is None, (
+ "the key must already be dropped when the keyless resend "
+ "is issued: otherwise a raise here leaves it live"
+ )
+ return ok
+
+ def _drop():
+ holder["api_key"] = None
+
+ response, key = send_with_key_fallback(
+ _send,
+ api_key=holder["api_key"],
+ context="Unit test",
+ on_key_rejected=_drop,
+ )
+
+ assert response is ok
+ assert key is None
+
+
+class TestEnrichmentRejectionCallback:
+ """``on_key_rejected`` lets the caller latch what this call learned."""
+
+ def test_callback_receives_the_refused_key_once(self):
+ results = [{"doi": f"10.1234/paper{index}"} for index in range(60)]
+ rejected = MagicMock()
+ rejected.status_code = 401
+ empty = _make_openalex_response([])
+ seen = []
+
+ with patch(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ side_effect=[rejected, empty, empty],
+ ):
+ enrich_results_with_source_ids(
+ results,
+ api_key="oa-live-abc123",
+ on_key_rejected=seen.append,
+ )
+
+ assert seen == ["oa-live-abc123"]
+
+ def test_callback_is_absent_when_the_key_is_accepted(self):
+ results = [{"doi": "10.1038/nature12373"}]
+ seen = []
+
+ with patch(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ return_value=_make_openalex_response(
+ [_work("https://doi.org/10.1038/nature12373", "S137773608")]
+ ),
+ ):
+ enrich_results_with_source_ids(
+ results,
+ api_key="oa-live-abc123",
+ on_key_rejected=seen.append,
+ )
+
+ assert seen == []
+
+ def test_a_raising_callback_does_not_resurrect_the_key(self):
+ """The drop happens first, so a bad callback cannot undo it."""
+ results = [{"doi": f"10.1234/paper{index}"} for index in range(60)]
+ rejected = MagicMock()
+ rejected.status_code = 401
+ empty = _make_openalex_response([])
+
+ def _boom(_key):
+ raise RuntimeError("callback exploded")
+
+ with patch(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ side_effect=[rejected, empty, empty],
+ ) as mock_get:
+ enrich_results_with_source_ids(
+ results, api_key="oa-live-abc123", on_key_rejected=_boom
+ )
+
+ # chunk 1 keyed (401) then the callback raises, which the module's
+ # blanket handler turns into a skipped chunk; chunk 2 must still go
+ # out keyless rather than re-sending the refused credential.
+ keyed = [
+ call
+ for call in mock_get.call_args_list
+ if "Authorization" in call.kwargs["headers"]
+ ]
+ assert len(keyed) == 1
+
+ def test_a_second_drop_keeps_the_key_redactable(self):
+ """Idempotency: the second drop must not store None over the key.
+
+ Unreachable single-threaded — after the first drop the helper
+ short-circuits on the falsy key — but the module's own scrub
+ depends on the retained literal, so the guard is pinned here by
+ stubbing the helper to invoke the callback twice.
+ """
+ results = [{"doi": "10.1038/nature12373"}]
+ logged = []
+
+ def _fake_helper(
+ send_request,
+ *,
+ api_key,
+ context,
+ on_key_rejected=None,
+ before_retry=None,
+ ):
+ on_key_rejected()
+ on_key_rejected() # the racing second rejection
+ raise RuntimeError("upstream said oa-live-abc123")
+
+ with (
+ patch(
+ "local_deep_research.utilities.openalex_enrichment."
+ "send_with_key_fallback",
+ _fake_helper,
+ ),
+ patch(
+ "local_deep_research.utilities.openalex_enrichment."
+ "logger.warning",
+ side_effect=lambda msg, *a, **kw: logged.append(msg),
+ ),
+ ):
+ enrich_results_with_source_ids(results, api_key="oa-live-abc123")
+
+ assert logged
+ assert not any("oa-live-abc123" in message for message in logged)
+
+
+class TestBoundedErrorBody:
+ """``bounded_error_body`` — bound the scrub without splitting a token.
+
+ The whole point of the helper is that a caller may hand its output to
+ a shape-anchored scrubber and then truncate the result. That is only
+ safe if the bound cannot cut inside a whitespace-free run, because a
+ key never contains whitespace (``normalize_openalex_api_key`` refuses
+ one that does).
+ """
+
+ def test_a_short_body_is_returned_unchanged(self):
+ body = "upstream said no\nwith a trailing token abcdefgh"
+ assert len(body) <= ERROR_BODY_SCRUB_LIMIT
+ assert bounded_error_body(body) is body
+
+ def test_a_body_exactly_at_the_limit_is_returned_unchanged(self):
+ body = "x" * ERROR_BODY_SCRUB_LIMIT
+ assert bounded_error_body(body) == body
+
+ def test_the_cut_lands_on_a_whitespace_character(self):
+ body = "token " * 4000
+ assert len(body) > ERROR_BODY_SCRUB_LIMIT
+ bounded = bounded_error_body(body)
+
+ assert len(bounded) <= ERROR_BODY_SCRUB_LIMIT
+ assert bounded.endswith(" ")
+ assert body.startswith(bounded)
+ # Nothing between the cut and the limit is a whitespace character,
+ # i.e. the cut really is the *last* boundary available.
+ assert not any(
+ character.isspace()
+ for character in body[len(bounded) : ERROR_BODY_SCRUB_LIMIT]
+ )
+
+ def test_a_run_straddling_the_limit_is_dropped_in_full(self):
+ run = "K" * 60
+ head = "a b " * 2100
+ body = head[: ERROR_BODY_SCRUB_LIMIT - 30] + run + " tail"
+ assert len(body) > ERROR_BODY_SCRUB_LIMIT
+
+ bounded = bounded_error_body(body)
+ # Not one character of the straddling run survives.
+ assert "K" not in bounded
+ assert bounded[-1].isspace()
+ assert body.startswith(bounded)
+
+ def test_no_whitespace_anywhere_yields_the_empty_string(self):
+ body = "n" * (ERROR_BODY_SCRUB_LIMIT + 500)
+ assert bounded_error_body(body) == ""
+
+ def test_whitespace_only_after_the_limit_yields_the_empty_string(self):
+ body = "n" * (ERROR_BODY_SCRUB_LIMIT + 10) + " tail"
+ assert bounded_error_body(body) == ""
+
+ def test_non_ascii_whitespace_counts_as_a_boundary(self):
+ """``str.isspace()``, not a latin-1 or ASCII whitelist.
+
+ An upstream body is arbitrary decoded text; a non-breaking or
+ ideographic space is as good a token boundary as ``" "``.
+ """
+ body = "head " + "T" * (ERROR_BODY_SCRUB_LIMIT + 100)
+ bounded = bounded_error_body(body)
+
+ assert bounded == "head "
+ assert "T" not in bounded
+
+ def test_the_limit_is_a_parameter(self):
+ body = "abcd efgh ijkl"
+ assert bounded_error_body(body, limit=6) == "abcd "
+ assert bounded_error_body(body, limit=4) == ""
diff --git a/tests/web_search_engines/engines/test_search_engine_openalex.py b/tests/web_search_engines/engines/test_search_engine_openalex.py
index 42b5166781..883743d002 100644
--- a/tests/web_search_engines/engines/test_search_engine_openalex.py
+++ b/tests/web_search_engines/engines/test_search_engine_openalex.py
@@ -3,7 +3,7 @@ Tests for the OpenAlexSearchEngine class.
Tests cover:
- Initialization and configuration
-- Email handling for polite pool
+- Email identification and optional API-key authentication
- Sort and filter options
- Preview generation
- Abstract reconstruction
@@ -11,10 +11,23 @@ Tests cover:
- Rate limiting
"""
-from unittest.mock import Mock, patch
+from unittest.mock import MagicMock, Mock, patch
import pytest
+def _messages(mock_logger, level):
+ """Return the message strings logged at *level* on a mocked logger.
+
+ The engine modules log through ``security.secure_logging.logger``, a
+ ``__slots__`` proxy: ``patch("....logger.error")`` cannot bind an
+ attribute on it, so the whole logger object is replaced instead.
+ """
+ return [
+ str(call.args[0]) if call.args else ""
+ for call in getattr(mock_logger, level).call_args_list
+ ]
+
+
# Mock JournalReputationFilter for all OpenAlex tests
@pytest.fixture(autouse=True)
def mock_journal_filter():
@@ -43,6 +56,9 @@ class TestOpenAlexSearchEngineInit:
assert engine.min_citations == 0
assert engine.from_publication_date is None
assert engine.email is None
+ assert engine.api_key is None
+ assert engine.openalex_api_key is None
+ assert "Authorization" not in engine.headers
assert engine.api_base == "https://api.openalex.org"
def test_init_with_custom_max_results(self):
@@ -56,7 +72,7 @@ class TestOpenAlexSearchEngineInit:
assert engine.max_results == 50
def test_init_with_email(self):
- """Initialize with email for polite pool."""
+ """Initialize with email for User-Agent identification."""
from local_deep_research.web_search_engines.engines.search_engine_openalex import (
OpenAlexSearchEngine,
)
@@ -66,6 +82,17 @@ class TestOpenAlexSearchEngineInit:
assert engine.email == "[email protected]"
assert "[email protected]" in engine.headers["User-Agent"]
+ def test_init_with_api_key(self):
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ engine = OpenAlexSearchEngine(api_key=" openalex-test-key ")
+
+ assert engine.api_key == "openalex-test-key"
+ assert engine.openalex_api_key == "openalex-test-key"
+ assert engine.headers["Authorization"] == "Bearer openalex-test-key"
+
def test_init_with_false_email_string(self):
"""Initialize with 'False' string email."""
from local_deep_research.web_search_engines.engines.search_engine_openalex import (
@@ -76,6 +103,132 @@ class TestOpenAlexSearchEngineInit:
assert engine.email is None
+ def test_init_with_false_api_key_string(self):
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ engine = OpenAlexSearchEngine(api_key="False")
+
+ assert engine.api_key is None
+ assert engine.openalex_api_key is None
+ assert "Authorization" not in engine.headers
+
+ # Every row below used to be sent verbatim as
+ # ``Authorization: Bearer <value>``, which OpenAlex answers with
+ # 401/403 — turning a working keyless engine into one that returns
+ # nothing. They must all resolve to keyless mode instead.
+ @pytest.mark.parametrize(
+ "configured_key",
+ [
+ "${OPENALEX_API_KEY}",
+ "${openalex_api_key}",
+ "your-api-key-here",
+ "YOUR_API_KEY_HERE",
+ "<your_api_key>",
+ "your_api_key",
+ "none",
+ "placeholder",
+ " False ",
+ "false",
+ "False",
+ "FALSE",
+ ],
+ )
+ def test_init_placeholder_key_falls_back_to_keyless(self, configured_key):
+ """Placeholder/sentinel keys are never sent as a Bearer token."""
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ engine = OpenAlexSearchEngine(api_key=configured_key)
+
+ assert engine.api_key is None
+ assert engine.openalex_api_key is None
+ assert "Authorization" not in engine.headers
+
+ @pytest.mark.parametrize("configured_key", [" ", "\t\n", ""])
+ def test_init_whitespace_only_key_is_none_not_empty_string(
+ self, configured_key
+ ):
+ """A blank key normalizes to None, not "" (an empty credential)."""
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ engine = OpenAlexSearchEngine(api_key=configured_key)
+
+ assert engine.api_key is None
+ assert engine.openalex_api_key is None
+ assert "Authorization" not in engine.headers
+
+ @pytest.mark.parametrize(
+ "configured_key", [True, 1, 123, 3.5, ["k"], {"k": 1}]
+ )
+ def test_init_non_string_key_is_none_not_attribute_error(
+ self, configured_key
+ ):
+ """A truthy non-str setting used to raise AttributeError on .strip()."""
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ engine = OpenAlexSearchEngine(api_key=configured_key)
+
+ assert engine.api_key is None
+ assert engine.openalex_api_key is None
+ assert "Authorization" not in engine.headers
+
+ def test_init_real_key_still_authenticates(self):
+ """The placeholder filter must not reject a genuine key."""
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ engine = OpenAlexSearchEngine(api_key=" oa-live-abc123 ")
+
+ assert engine.api_key == "oa-live-abc123"
+ assert engine.headers["Authorization"] == "Bearer oa-live-abc123"
+
+ def test_secret_attrs_extends_the_base_default(self):
+ """The base default plus the slot holding a dropped key."""
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ engine = OpenAlexSearchEngine(api_key="oa-live-abc123")
+
+ assert set(BaseSearchEngine._secret_attrs) <= set(
+ OpenAlexSearchEngine._secret_attrs
+ )
+ assert "_rejected_api_key" in OpenAlexSearchEngine._secret_attrs
+ assert "oa-live-abc123" not in engine._scrub_error(
+ RuntimeError("boom oa-live-abc123")
+ )
+
+ def test_dropped_key_stays_in_the_redaction_set(self):
+ """Dropping the key must not stop it being scrubbed from logs.
+
+ ``_scrub_error`` can only redact a literal it is handed. Clearing
+ ``self.api_key`` on rejection would otherwise silently remove the
+ key from the redaction set for the rest of the engine's life.
+ """
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ engine = OpenAlexSearchEngine(api_key="oa-live-abc123")
+ engine._drop_rejected_api_key()
+
+ assert engine.api_key is None
+ assert "Authorization" not in engine.headers
+ assert "oa-live-abc123" not in engine._scrub_error(
+ RuntimeError("boom oa-live-abc123")
+ )
+
def test_init_with_sort_by(self):
"""Initialize with custom sort_by."""
from local_deep_research.web_search_engines.engines.search_engine_openalex import (
@@ -218,7 +371,7 @@ class TestGetPreviews:
assert "from_publication_date:2023-01-01" in params["filter"]
def test_get_previews_with_email(self):
- """Get previews includes email in params."""
+ """Get previews uses email only for User-Agent identification."""
from local_deep_research.web_search_engines.engines.search_engine_openalex import (
OpenAlexSearchEngine,
)
@@ -237,7 +390,323 @@ class TestGetPreviews:
call_kwargs = mock_get.call_args[1]
params = call_kwargs["params"]
- assert params.get("mailto") == "[email protected]"
+ headers = call_kwargs["headers"]
+ assert "mailto" not in params
+ assert "[email protected]" in headers["User-Agent"]
+ assert "Authorization" not in headers
+
+ def test_get_previews_with_api_key_uses_authorization_header(self):
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ mock_response = Mock()
+ mock_response.status_code = 200
+ mock_response.headers = {}
+ mock_response.json.return_value = {"meta": {"count": 0}, "results": []}
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",
+ return_value=mock_response,
+ ) as mock_get:
+ engine = OpenAlexSearchEngine(
+ email="[email protected]", api_key="openalex-test-key"
+ )
+ engine._get_previews("test query")
+
+ call_kwargs = mock_get.call_args[1]
+ params = call_kwargs["params"]
+ headers = call_kwargs["headers"]
+ assert headers["Authorization"] == "Bearer openalex-test-key"
+ assert "mailto" not in params
+ assert "api_key" not in params
+ assert "openalex-test-key" not in params.values()
+
+ @pytest.mark.parametrize("auth_status", [401, 403])
+ def test_get_previews_retries_once_without_rejected_key(self, auth_status):
+ """A rejected key must not cost the user their results."""
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ rejected = Mock()
+ rejected.status_code = auth_status
+ rejected.headers = {}
+ rejected.text = "invalid api key"
+
+ ok = Mock()
+ ok.status_code = 200
+ ok.headers = {}
+ ok.json.return_value = {
+ "meta": {"count": 1},
+ "results": [
+ {"id": "https://openalex.org/W1", "display_name": "Paper"}
+ ],
+ }
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",
+ side_effect=[rejected, ok],
+ ) as mock_get:
+ engine = OpenAlexSearchEngine(api_key="oa-live-abc123")
+ previews = engine._get_previews("test query")
+
+ assert len(previews) == 1
+ assert mock_get.call_count == 2
+ first_headers = mock_get.call_args_list[0].kwargs["headers"]
+ retry_headers = mock_get.call_args_list[1].kwargs["headers"]
+ assert first_headers["Authorization"] == "Bearer oa-live-abc123"
+ assert "Authorization" not in retry_headers
+ # And the rejected key is gone for good: the header is cleared,
+ # not just skipped for this one retry.
+ assert "Authorization" not in engine.headers
+ assert engine.api_key is None
+ assert engine.openalex_api_key is None
+
+ def test_rejected_key_is_never_sent_twice(self):
+ """No later query pays another round-trip for a rejected key.
+
+ The general property BL2 is about: once OpenAlex has refused the
+ credential, *no* path on this object sends it again.
+ """
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ rejected = Mock()
+ rejected.status_code = 401
+ rejected.headers = {}
+ rejected.text = "invalid api key"
+
+ def _ok():
+ response = Mock()
+ response.status_code = 200
+ response.headers = {}
+ response.json.return_value = {
+ "meta": {"count": 1},
+ "results": [
+ {"id": "https://openalex.org/W1", "display_name": "Paper"}
+ ],
+ }
+ return response
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",
+ side_effect=[rejected, _ok(), _ok(), _ok()],
+ ) as mock_get:
+ engine = OpenAlexSearchEngine(api_key="oa-live-abc123")
+ engine._get_previews("first query")
+ engine._get_previews("second query")
+ engine._get_previews("third query")
+
+ # 1 keyed + 1 keyless retry + 1 each for the next two queries.
+ assert mock_get.call_count == 4
+ keyed = [
+ call
+ for call in mock_get.call_args_list
+ if "Authorization" in call.kwargs["headers"]
+ ]
+ assert len(keyed) == 1
+ assert not any(
+ "oa-live-abc123" in str(call.kwargs["headers"])
+ for call in mock_get.call_args_list[1:]
+ )
+
+ def test_keyless_retry_is_rate_limited_too(self):
+ """The retry is a real second request, so it gets its own slot."""
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ rejected = Mock()
+ rejected.status_code = 401
+ rejected.headers = {}
+ rejected.text = "invalid api key"
+
+ ok = Mock()
+ ok.status_code = 200
+ ok.headers = {}
+ ok.json.return_value = {"meta": {"count": 0}, "results": []}
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",
+ side_effect=[rejected, ok],
+ ) as mock_get:
+ engine = OpenAlexSearchEngine(api_key="oa-live-abc123")
+ with patch.object(
+ engine.rate_tracker, "apply_rate_limit", return_value=0.0
+ ) as apply_rate_limit:
+ engine._get_previews("test query")
+
+ assert mock_get.call_count == 2
+ assert apply_rate_limit.call_count == 2
+
+ def test_get_previews_auth_failure_after_retry_raises(self):
+ """A persistent auth failure surfaces instead of a silent []."""
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexAuthError,
+ OpenAlexSearchEngine,
+ )
+
+ rejected = Mock()
+ rejected.status_code = 401
+ rejected.headers = {}
+ rejected.text = "invalid api key"
+
+ still_rejected = Mock()
+ still_rejected.status_code = 403
+ still_rejected.headers = {}
+ still_rejected.text = "forbidden"
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",
+ side_effect=[rejected, still_rejected],
+ ) as mock_get:
+ engine = OpenAlexSearchEngine(api_key="oa-live-abc123")
+
+ with pytest.raises(OpenAlexAuthError):
+ engine._get_previews("test query")
+
+ assert mock_get.call_count == 2
+
+ @pytest.mark.parametrize("auth_status", [401, 403])
+ def test_keyless_auth_failure_behaves_exactly_as_before(self, auth_status):
+ """No key configured → nothing to retry, and no key to blame.
+
+ A keyless install behind a corporate proxy or Cloudflare can see
+ a 401/403 that has nothing to do with a credential. It keeps the
+ pre-existing behaviour: one request, an "API error" log, ``[]``
+ — not an ``OpenAlexAuthError`` telling the operator to check a
+ key they never configured.
+ """
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ rejected = Mock()
+ rejected.status_code = auth_status
+ rejected.headers = {}
+ rejected.text = "unauthorized"
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",
+ return_value=rejected,
+ ) as mock_get:
+ engine = OpenAlexSearchEngine()
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.logger",
+ new=MagicMock(),
+ ) as engine_logger:
+ assert engine._get_previews("test query") == []
+
+ logged = _messages(engine_logger, "error")
+ warned = _messages(engine_logger, "warning")
+ assert mock_get.call_count == 1
+ assert not any("API key" in message for message in logged + warned)
+ assert not any(
+ "openalex.org/settings/api" in message for message in warned
+ )
+ assert any(
+ f"OpenAlex API error: {auth_status}" in message
+ for message in logged
+ )
+
+ def test_run_reports_auth_failure_instead_of_empty_success(self):
+ """run() takes the failure path, not the "no results" path.
+
+ Before the fix ``_get_previews`` returned ``[]`` on 401, which
+ ``run`` logs as an ordinary empty search — indistinguishable from
+ "no papers matched".
+ """
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ rejected = Mock()
+ rejected.status_code = 401
+ rejected.headers = {}
+ rejected.text = "unauthorized"
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",
+ return_value=rejected,
+ ):
+ # A key must be configured: the failure is only reported as
+ # an authentication failure when a key was actually sent and
+ # the automatic keyless retry failed too.
+ engine = OpenAlexSearchEngine(
+ programmatic_mode=True, api_key="oa-live-abc123"
+ )
+ with (
+ patch.object(
+ engine.rate_tracker, "apply_rate_limit", return_value=0.0
+ ),
+ patch(
+ "local_deep_research.web_search_engines.search_engine_base.logger",
+ new=MagicMock(),
+ ) as base_logger,
+ ):
+ assert engine.run("test query") == []
+
+ warnings = _messages(base_logger, "warning")
+ assert any(
+ "OpenAlexSearchEngine failed" in message
+ and "authentication failed" in message
+ for message in warnings
+ ), warnings
+
+ def test_get_previews_error_body_is_sanitized(self):
+ """An echoed key never reaches the log sink, at any offset.
+
+ The body is longer than the 200-character log cap and the key is
+ placed so that it straddles that boundary, with no ``Bearer``/
+ ``Authorization:`` prefix in front of it. Truncating before
+ scrubbing (``self._scrub_error(response.text[:200])``) leaves a
+ key *prefix* that neither scrub pass can match: the literal pass
+ looks for the whole key, and the shape regexes are anchored on a
+ credential prefix that is not there. Scrubbing first and cutting
+ afterwards is the only order that holds.
+ """
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ api_key = "oa9fK3mQz7XrVnT4sJhW6yCg1EuA"
+ # Land the key across index 200 with no credential prefix.
+ prefix = "upstream echoed the request: " + "-" * (
+ 200 - len("upstream echoed the request: ") - (len(api_key) // 2)
+ )
+ body = prefix + api_key + "." * 120
+ assert len(body) > 200
+ # The key genuinely straddles the cut.
+ assert len(prefix) < 200 < len(prefix) + len(api_key)
+ assert "Bearer" not in body
+
+ broken = Mock()
+ broken.status_code = 500
+ broken.headers = {}
+ broken.text = body
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",
+ return_value=broken,
+ ):
+ engine = OpenAlexSearchEngine(api_key=api_key)
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.logger",
+ new=MagicMock(),
+ ) as engine_logger:
+ assert engine._get_previews("test query") == []
+
+ logged = _messages(engine_logger, "error")
+ assert logged, "the 500 branch must log an error"
+ joined = " ".join(logged)
+ assert api_key not in joined
+ # No *fragment* of the key survives either: check every substring
+ # of length 8 or more that starts at the key's start, which is
+ # exactly what a truncating-first implementation leaks.
+ for cut in range(8, len(api_key) + 1):
+ assert api_key[:cut] not in joined, api_key[:cut]
def test_get_previews_rate_limit_error(self):
"""Get previews raises RateLimitError on 429."""
@@ -545,3 +1014,626 @@ class TestClassAttributes:
)
assert OpenAlexSearchEngine.is_scientific is True
+
+
+class TestRejectedKeyReachesEnrichment:
+ """The refused key must not come back out of the settings snapshot.
+
+ ``__init__`` reads ``search.engine.web.openalex.api_key`` from the
+ settings snapshot, and so does
+ ``BaseSearchEngine._resolve_openalex_enrichment_key``. Clearing the
+ engine's own attributes therefore is not enough: without a latch, the
+ DOI enrichment pass of the *same* ``run()`` resolves the identical key
+ straight back out of the snapshot and sends it again.
+ """
+
+ SNAPSHOT = {"search.engine.web.openalex.api_key": "oa-live-abc123"}
+
+ @staticmethod
+ def _work_response(count=1):
+ response = Mock()
+ response.status_code = 200
+ response.headers = {}
+ response.json.return_value = {
+ "meta": {"count": count},
+ "results": [
+ {
+ "id": "https://openalex.org/W1",
+ "display_name": "Paper",
+ "doi": "https://doi.org/10.1234/example",
+ }
+ ],
+ }
+ return response
+
+ def test_resolver_returns_none_after_the_engine_dropped_the_key(self):
+ """(a) The snapshot still carries the key; the resolver must not."""
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ engine = OpenAlexSearchEngine(
+ programmatic_mode=True, settings_snapshot=dict(self.SNAPSHOT)
+ )
+ assert engine.api_key == "oa-live-abc123"
+ # Sanity: without the drop the resolver hands the key over.
+ assert engine._resolve_openalex_enrichment_key() == "oa-live-abc123"
+
+ engine._drop_rejected_api_key()
+
+ assert (
+ engine.settings_snapshot["search.engine.web.openalex.api_key"]
+ == "oa-live-abc123"
+ ), "the snapshot is untouched — that is the point"
+ assert engine._resolve_openalex_enrichment_key() is None
+ # And the literal is still redactable after the drop.
+ assert "oa-live-abc123" not in engine._scrub_error(
+ RuntimeError("boom oa-live-abc123")
+ )
+
+ def test_run_never_sends_the_refused_key_to_enrichment(self):
+ """(b) One run(): search 401 → keyless 200 → keyless enrichment.
+
+ Asserted on the sequence of ``Authorization`` values actually put
+ on the wire across both call sites, which is the property the
+ docstrings claim.
+ """
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ authorizations = []
+
+ rejected = Mock()
+ rejected.status_code = 401
+ rejected.headers = {}
+ rejected.text = "invalid api key"
+
+ def _record(**kwargs):
+ authorizations.append(kwargs["headers"].get("Authorization"))
+
+ def _engine_get(*args, **kwargs):
+ _record(**kwargs)
+ if kwargs["headers"].get("Authorization"):
+ return rejected
+ return self._work_response()
+
+ enrichment_ok = MagicMock()
+ enrichment_ok.status_code = 200
+ enrichment_ok.json.return_value = {"results": []}
+
+ def _enrichment_get(*args, **kwargs):
+ _record(**kwargs)
+ return enrichment_ok
+
+ engine = OpenAlexSearchEngine(
+ programmatic_mode=True,
+ search_snippets_only=True,
+ settings_snapshot=dict(self.SNAPSHOT),
+ )
+ engine._preview_filters = []
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",
+ side_effect=_engine_get,
+ ) as engine_get,
+ patch(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ side_effect=_enrichment_get,
+ ) as enrichment_get,
+ patch.object(
+ engine.rate_tracker, "apply_rate_limit", return_value=0.0
+ ),
+ ):
+ results = engine.run("test query")
+
+ assert results, "the keyless retry must still return the results"
+ assert engine_get.call_count == 2
+ assert enrichment_get.call_count == 1, (
+ "enrichment must go out once, keyless — not keyed, refused and "
+ "retried"
+ )
+ assert authorizations == ["Bearer oa-live-abc123", None, None]
+
+ def test_second_run_enriches_keylessly_from_the_first_request(self):
+ """(c) The latch outlives the run that set it."""
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ authorizations = []
+
+ rejected = Mock()
+ rejected.status_code = 401
+ rejected.headers = {}
+ rejected.text = "invalid api key"
+
+ def _engine_get(*args, **kwargs):
+ authorizations.append(
+ ("search", kwargs["headers"].get("Authorization"))
+ )
+ if kwargs["headers"].get("Authorization"):
+ return rejected
+ return self._work_response()
+
+ enrichment_ok = MagicMock()
+ enrichment_ok.status_code = 200
+ enrichment_ok.json.return_value = {"results": []}
+
+ def _enrichment_get(*args, **kwargs):
+ authorizations.append(
+ ("enrich", kwargs["headers"].get("Authorization"))
+ )
+ return enrichment_ok
+
+ engine = OpenAlexSearchEngine(
+ programmatic_mode=True,
+ search_snippets_only=True,
+ settings_snapshot=dict(self.SNAPSHOT),
+ )
+ engine._preview_filters = []
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",
+ side_effect=_engine_get,
+ ),
+ patch(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ side_effect=_enrichment_get,
+ ),
+ patch.object(
+ engine.rate_tracker, "apply_rate_limit", return_value=0.0
+ ),
+ ):
+ engine.run("first query")
+ engine.run("second query")
+
+ assert authorizations == [
+ ("search", "Bearer oa-live-abc123"),
+ ("search", None),
+ ("enrich", None),
+ ("search", None),
+ ("enrich", None),
+ ]
+
+ def test_enrichment_rejection_latches_on_the_engine(self):
+ """The reverse direction: enrichment refuses, search stays keyless.
+
+ The engine's own search key is unset here (keyless install with an
+ enrichment key in the snapshot), so the only rejection comes from
+ the enrichment pass. Its drop is call-local, so without the
+ callback the next run resolves the same key again.
+ """
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ engine = OpenAlexSearchEngine(
+ programmatic_mode=True, settings_snapshot=dict(self.SNAPSHOT)
+ )
+ # Simulate a keyless *search* path with a snapshot key still live
+ # for enrichment: the resolver reads the snapshot, not self.api_key.
+ engine.api_key = None
+ engine.openalex_api_key = None
+ assert engine._resolve_openalex_enrichment_key() == "oa-live-abc123"
+
+ engine._note_openalex_key_rejected("oa-live-abc123")
+
+ assert engine._resolve_openalex_enrichment_key() is None
+ assert "oa-live-abc123" not in engine._scrub_error(
+ RuntimeError("boom oa-live-abc123")
+ )
+
+ def test_a_second_drop_keeps_the_literal_in_the_redaction_set(self):
+ """Idempotency: the second call must not store None over the key."""
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ engine = OpenAlexSearchEngine(api_key="oa-live-abc123")
+ engine._drop_rejected_api_key()
+ engine._drop_rejected_api_key() # self.api_key is now None
+
+ assert engine._rejected_api_key == "oa-live-abc123"
+ assert "oa-live-abc123" not in engine._scrub_error(
+ RuntimeError("boom oa-live-abc123")
+ )
+
+ def test_the_key_is_dropped_before_the_keyless_retry_goes_out(self):
+ """Ordering, observed from inside the retry itself.
+
+ If ``on_key_rejected`` moved after ``send_request(False)``, every
+ response-list-driven test would still pass; this one would not.
+ """
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ rejected = Mock()
+ rejected.status_code = 401
+ rejected.headers = {}
+ rejected.text = "invalid api key"
+
+ observed = {}
+
+ def _get(*args, **kwargs):
+ if kwargs["headers"].get("Authorization"):
+ return rejected
+ observed["api_key"] = engine.api_key
+ observed["header"] = "Authorization" in engine.headers
+ observed["latched"] = engine._openalex_key_rejected
+ return self._work_response()
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",
+ side_effect=_get,
+ ):
+ engine = OpenAlexSearchEngine(api_key="oa-live-abc123")
+ engine._get_previews("test query")
+
+ assert observed == {
+ "api_key": None,
+ "header": False,
+ "latched": True,
+ }, observed
+
+ def test_key_was_sent_is_read_once_not_twice(self):
+ """One read of shared state, used for both decisions.
+
+ ``self.api_key`` is mutable and another thread on the same engine
+ can drop it. Reading it separately for the retry decision and for
+ the ``OpenAlexAuthError`` gate lets the two disagree: the request
+ goes out keyless (so there is no key to blame and no keyless
+ retry to make) while the gate still reports an authentication
+ failure. Simulated here by a key that is gone after the first
+ read.
+ """
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexAuthError,
+ OpenAlexSearchEngine,
+ )
+
+ rejected = Mock()
+ rejected.status_code = 401
+ rejected.headers = {}
+ rejected.text = "invalid api key"
+
+ engine = OpenAlexSearchEngine(api_key="oa-live-abc123")
+ reads = []
+
+ class RacingEngine(type(engine)):
+ """The key is dropped by "another thread" after one read."""
+
+ @property
+ def api_key(self):
+ reads.append(len(reads))
+ return "oa-live-abc123" if len(reads) == 1 else None
+
+ @api_key.setter
+ def api_key(self, value):
+ pass
+
+ del engine.__dict__["api_key"]
+ engine.__class__ = RacingEngine
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",
+ return_value=rejected,
+ ) as mock_get,
+ patch.object(
+ engine.rate_tracker, "apply_rate_limit", return_value=0.0
+ ),
+ pytest.raises(OpenAlexAuthError),
+ ):
+ engine._get_previews("test query")
+
+ # Two requests: the keyed one and its keyless retry. A second read
+ # would hand the helper ``None``, skipping the retry entirely while
+ # still raising OpenAlexAuthError for a request that carried no key.
+ assert mock_get.call_count == 2
+
+
+class TestEnrichmentLearnedRejectionDropsTheEnginesOwnKey:
+ """The latch alone is not enough when *enrichment* is the refused path.
+
+ ``BaseSearchEngine._note_openalex_key_rejected`` only latches, which
+ is all a non-OpenAlex scientific engine needs. This engine also holds
+ the OpenAlex credential in ``api_key``/``openalex_api_key`` and in the
+ cached ``Authorization`` header, so when the DOI enrichment pass is
+ the path that learns the key is bad — a search that returned 200
+ followed by an enrichment 401, i.e. a key revoked mid-run — the next
+ *search* on the same instance would otherwise re-send it.
+ """
+
+ SNAPSHOT = {"search.engine.web.openalex.api_key": "oa-live-abc123"}
+
+ @staticmethod
+ def _work_response():
+ response = Mock()
+ response.status_code = 200
+ response.headers = {}
+ response.json.return_value = {
+ "meta": {"count": 1},
+ "results": [
+ {
+ "id": "https://openalex.org/W1",
+ "display_name": "Paper",
+ "doi": "https://doi.org/10.1234/example",
+ }
+ ],
+ }
+ return response
+
+ def test_enrichment_rejection_stops_the_next_search_sending_the_key(self):
+ """search 200 → enrichment 401 → run #2's search carries no key."""
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ authorizations = []
+
+ def _engine_get(*args, **kwargs):
+ authorizations.append(
+ ("search", kwargs["headers"].get("Authorization"))
+ )
+ # The search endpoint is happy throughout: only enrichment
+ # ever sees the rejection.
+ return self._work_response()
+
+ enrichment_rejected = MagicMock()
+ enrichment_rejected.status_code = 401
+ enrichment_rejected.json.return_value = {}
+ enrichment_ok = MagicMock()
+ enrichment_ok.status_code = 200
+ enrichment_ok.json.return_value = {"results": []}
+
+ def _enrichment_get(*args, **kwargs):
+ authorization = kwargs["headers"].get("Authorization")
+ authorizations.append(("enrich", authorization))
+ return enrichment_rejected if authorization else enrichment_ok
+
+ engine = OpenAlexSearchEngine(
+ programmatic_mode=True,
+ search_snippets_only=True,
+ settings_snapshot=dict(self.SNAPSHOT),
+ )
+ engine._preview_filters = []
+ assert engine.headers["Authorization"] == "Bearer oa-live-abc123"
+
+ with (
+ patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",
+ side_effect=_engine_get,
+ ),
+ patch(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ side_effect=_enrichment_get,
+ ),
+ patch.object(
+ engine.rate_tracker, "apply_rate_limit", return_value=0.0
+ ),
+ ):
+ engine.run("first query")
+ engine.run("second query")
+
+ assert authorizations == [
+ ("search", "Bearer oa-live-abc123"),
+ ("enrich", "Bearer oa-live-abc123"),
+ ("enrich", None),
+ # Without the engine's own drop this one is
+ # "Bearer oa-live-abc123" again.
+ ("search", None),
+ ("enrich", None),
+ ]
+ # The credential is gone from every slot the engine sends from…
+ assert engine.api_key is None
+ assert engine.openalex_api_key is None
+ assert "Authorization" not in engine.headers
+ # …and still redactable.
+ assert engine._rejected_api_key == "oa-live-abc123"
+ assert "oa-live-abc123" not in engine._scrub_error(
+ RuntimeError("boom oa-live-abc123")
+ )
+
+ def test_the_engine_drop_is_idempotent_and_keeps_the_literal(self):
+ """Two rejections (search then enrichment, or a thread race)."""
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ engine = OpenAlexSearchEngine(api_key="oa-live-abc123")
+ engine._note_openalex_key_rejected("oa-live-abc123")
+ # Second call: ``self.api_key`` is already None and the header is
+ # already gone, so nothing may raise and nothing may be lost.
+ engine._note_openalex_key_rejected(None)
+
+ assert engine.api_key is None
+ assert engine.openalex_api_key is None
+ assert "Authorization" not in engine.headers
+ assert engine._openalex_key_rejected is True
+ assert engine._rejected_api_key == "oa-live-abc123"
+
+ def test_a_bare_call_still_drops_the_engines_live_key(self):
+ """``on_key_rejected`` may be invoked with no argument at all.
+
+ ``BaseSearchEngine.run`` hands this method to enrichment, which
+ calls it with the refused key; other callers may call it bare.
+ Either way the engine's own credential has to go.
+ """
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ engine = OpenAlexSearchEngine(api_key="oa-live-abc123")
+ engine._note_openalex_key_rejected()
+
+ assert engine.api_key is None
+ assert "Authorization" not in engine.headers
+ # The live key was picked up as the literal to keep redacting.
+ assert engine._rejected_api_key == "oa-live-abc123"
+
+
+class TestBoundedErrorBody:
+ """The pre-scrub bound must not create a partial credential.
+
+ ``_get_previews`` bounds the regex work before scrubbing an upstream
+ error body. Cutting at a fixed offset is unsafe *at any offset*,
+ because scrubbing shrinks the text — a token-shaped run collapses to
+ ``Bearer [REDACTED]`` (17 characters) — which pulls content from far
+ beyond the 200-character log cap into the characters that get logged,
+ including a key fragment the cut itself created.
+ """
+
+ API_KEY = "oa9fK3mQz7XrVnT4sJhW6yCg1EuA"
+
+ @staticmethod
+ def _logged_errors(body, api_key):
+ """Drive the 500 branch with *body*; return the logged error lines."""
+ from local_deep_research.web_search_engines.engines.search_engine_openalex import (
+ OpenAlexSearchEngine,
+ )
+
+ broken = Mock()
+ broken.status_code = 500
+ broken.headers = {}
+ broken.text = body
+
+ with patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.safe_get",
+ return_value=broken,
+ ):
+ engine = OpenAlexSearchEngine(api_key=api_key)
+ with (
+ patch.object(
+ engine.rate_tracker, "apply_rate_limit", return_value=0.0
+ ),
+ patch(
+ "local_deep_research.web_search_engines.engines.search_engine_openalex.logger",
+ new=MagicMock(),
+ ) as engine_logger,
+ ):
+ assert engine._get_previews("test query") == []
+ return _messages(engine_logger, "error")
+
+ @staticmethod
+ def _key_fragments(key, text, length=4):
+ """Every contiguous *length*-run of *key* that appears in *text*."""
+ return sorted(
+ {
+ key[index : index + length]
+ for index in range(len(key) - length + 1)
+ if key[index : index + length] in text
+ }
+ )
+
+ @pytest.mark.parametrize("key_offset", [8172, 8178, 8184])
+ def test_a_key_straddling_the_pre_scrub_cut_never_reaches_the_log(
+ self, key_offset
+ ):
+ """The shape a fixed ``response.text[:8192]`` leaks.
+
+ A collapsing ``Bearer`` run at the front of the body shrinks to 17
+ characters under the scrub, so the material around the 8192-byte
+ boundary lands inside the 200-character log cap. With the key
+ straddling that boundary, a fixed cut hands the log a key
+ *prefix*: too short for the literal pass to match and with no
+ credential prefix for the shape regexes to anchor on.
+ """
+ prefix_gap = 171
+ collapsing = key_offset - len("Bearer ") - prefix_gap
+ body = (
+ "Bearer "
+ + "A" * collapsing
+ + "!" * prefix_gap
+ + self.API_KEY
+ + "." * 400
+ )
+ # The key genuinely straddles 8192 — that is the whole point.
+ assert len(body) > 8192
+ start = body.index(self.API_KEY)
+ assert start < 8192 < start + len(self.API_KEY)
+
+ joined = " ".join(self._logged_errors(body, self.API_KEY))
+ assert joined, "the 500 branch must log an error"
+ assert self.API_KEY not in joined
+ assert self._key_fragments(self.API_KEY, joined) == []
+
+ def test_a_body_with_no_whitespace_at_all_yields_an_empty_detail(self):
+ """Nothing in the window can be shown to be credential-free.
+
+ The whole 8192-character prefix is one unbroken run, so it is
+ dropped entirely rather than cut mid-token. The status code still
+ reaches the log — the operator does not lose the diagnosis.
+ """
+ body = "x" * 9000
+ assert not any(character.isspace() for character in body)
+
+ logged = self._logged_errors(body, self.API_KEY)
+ assert logged, "the 500 branch must log an error"
+ assert any(
+ message.rstrip() == "OpenAlex API error: 500 -"
+ for message in logged
+ ), logged
+
+ def test_a_key_fully_inside_the_window_is_still_redacted(self):
+ """The cut must not become "drop everything" either."""
+ marker = "upstream echoed the request:"
+ body = f"{marker} {self.API_KEY} " + "." * 9000
+ assert len(body) > 8192
+ assert body.index(self.API_KEY) + len(self.API_KEY) < 8192
+
+ joined = " ".join(self._logged_errors(body, self.API_KEY))
+ assert marker in joined, "the surviving prefix must still be logged"
+ assert self.API_KEY not in joined
+ assert self._key_fragments(self.API_KEY, joined) == []
+
+ def test_no_key_position_survives_the_bounded_scrub_pipeline(self):
+ """200 random placements of the key around the boundary.
+
+ Each body is mixed whitespace and token characters behind a
+ collapsing ``Bearer`` run, so the surviving 200 characters are
+ drawn from the region around the cut rather than from the start of
+ the body. Under a fixed ``response.text[:8192]`` a large minority
+ of these placements leak.
+ """
+ import random
+
+ from local_deep_research.security.log_sanitizer import scrub_error
+ from local_deep_research.utilities.openalex_enrichment import (
+ bounded_error_body,
+ )
+
+ alphabet = (
+ "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "0123456789-._~+/:{}\"',=?&"
+ )
+ whitespace = " \t\n\r\f\v"
+
+ def _mixed(length, rng):
+ return "".join(
+ rng.choice(whitespace)
+ if rng.random() < 0.08
+ else rng.choice(alphabet)
+ for _ in range(length)
+ )
+
+ for trial in range(200):
+ rng = random.Random(6289 + trial)
+ key_offset = rng.randrange(8100, 8230)
+ gap = rng.randrange(80, 190)
+ collapsing = key_offset - gap - len("Bearer ")
+ body = (
+ "Bearer "
+ + "A" * collapsing
+ + _mixed(gap, rng)
+ + self.API_KEY
+ + _mixed(12000, rng)
+ )
+ assert len(body) > 8192
+ detail = scrub_error(bounded_error_body(body), self.API_KEY)[:200]
+ assert self._key_fragments(self.API_KEY, detail) == [], (
+ f"trial {trial}, key at {key_offset}: {detail!r}"
+ )
diff --git a/tests/web_search_engines/engines/test_search_engine_openalex_coverage.py b/tests/web_search_engines/engines/test_search_engine_openalex_coverage.py
index 38e33c95bc..3dab279f3d 100644
--- a/tests/web_search_engines/engines/test_search_engine_openalex_coverage.py
+++ b/tests/web_search_engines/engines/test_search_engine_openalex_coverage.py
@@ -4,7 +4,7 @@ the existing test_search_engine_openalex.py.
Covers:
- __init__: journal_filter is not None → appended to content_filters;
- email retrieved from settings_snapshot; empty email treated as None
+ email and API key retrieved from settings_snapshot; empty email treated as None
- _get_previews: rate-limit header logging branch; work that returns None from
_format_work_preview is skipped without count; exception from safe_get returns []
- _format_work_preview: doi already starts with "https://doi.org/"; doi starts with
@@ -86,22 +86,53 @@ class TestInitExtra:
snapshot = {"dummy": True}
with patch(
"local_deep_research.config.search_config.get_setting_from_snapshot",
- return_value="[email protected]",
+ side_effect=["[email protected]", None],
):
engine = OpenAlexSearchEngine(settings_snapshot=snapshot)
assert engine.email == "[email protected]"
+ def test_api_key_from_settings_snapshot(self):
+ snapshot = {"dummy": True}
+ with patch(
+ "local_deep_research.config.search_config.get_setting_from_snapshot",
+ return_value=" snapshot-openalex-key ",
+ ):
+ engine = OpenAlexSearchEngine(
+ email="[email protected]", settings_snapshot=snapshot
+ )
+ assert engine.api_key == "snapshot-openalex-key"
+ assert engine.openalex_api_key == "snapshot-openalex-key"
+ assert engine.headers["Authorization"] == "Bearer snapshot-openalex-key"
+
def test_empty_email_treated_as_none(self):
engine = _engine(email="")
assert engine.email is None
def test_email_settings_exception_ignored(self):
+ """A failing settings read must not break construction.
+
+ The snapshot has to be non-empty: both lookups are guarded by
+ ``if not <value> and settings_snapshot``, so an empty dict never
+ reaches ``get_setting_from_snapshot`` and the patched raise would
+ never fire. ``mock.called`` pins that.
+ """
with patch(
"local_deep_research.config.search_config.get_setting_from_snapshot",
side_effect=RuntimeError("db gone"),
- ):
- engine = OpenAlexSearchEngine(settings_snapshot={})
+ ) as mock_get_setting:
+ engine = OpenAlexSearchEngine(
+ settings_snapshot={"search.engine.web.openalex.other": "x"}
+ )
+ assert mock_get_setting.called, (
+ "the snapshot branch must actually be exercised"
+ )
+ assert [call.args[0] for call in mock_get_setting.call_args_list] == [
+ "search.engine.web.openalex.email",
+ "search.engine.web.openalex.api_key",
+ ]
assert engine.email is None
+ assert engine.api_key is None
+ assert "Authorization" not in engine.headers
# ---------------------------------------------------------------------------
diff --git a/tests/web_search_engines/test_engine_success_path.py b/tests/web_search_engines/test_engine_success_path.py
index f52d625547..2964a3d20e 100644
--- a/tests/web_search_engines/test_engine_success_path.py
+++ b/tests/web_search_engines/test_engine_success_path.py
@@ -2089,7 +2089,7 @@ class TestSerplyScholarMode:
"""
seen = []
- def fake_enrich(results, email=None):
+ def fake_enrich(results, email=None, api_key=None, **kwargs):
seen.append([dict(r) for r in results])
return results
diff --git a/tests/web_search_engines/test_search_engine_base.py b/tests/web_search_engines/test_search_engine_base.py
index 2bc7f61cc7..1660726b80 100644
--- a/tests/web_search_engines/test_search_engine_base.py
+++ b/tests/web_search_engines/test_search_engine_base.py
@@ -727,7 +727,7 @@ class TestDoiEnrichmentOrdering:
)
return results
- def fake_enrich(results, email=None):
+ def fake_enrich(results, email=None, api_key=None, **kwargs):
for r in results:
r["openalex_source_id"] = "S42"
return results
@@ -750,6 +750,136 @@ class TestDoiEnrichmentOrdering:
"journal reputation filter can use the source_id"
)
+ @pytest.mark.parametrize(
+ ("credential_attr", "credential", "expected_openalex_key"),
+ [
+ ("openalex_api_key", "openalex-test-key", "openalex-test-key"),
+ ("api_key", "other-engine-test-key", None),
+ ],
+ )
+ def test_openalex_enrichment_key_isolated_from_other_engine_keys(
+ self,
+ monkeypatch,
+ credential_attr,
+ credential,
+ expected_openalex_key,
+ ):
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class FakeScientificEngine(BaseSearchEngine):
+ is_scientific = True
+
+ def _get_previews(self, query):
+ return [{"title": "Paper", "doi": "10.1234/example"}]
+
+ def _get_full_content(self, items):
+ return items
+
+ captured_keys = []
+
+ def fake_enrich(results, email=None, api_key=None, **kwargs):
+ captured_keys.append(api_key)
+ return results
+
+ monkeypatch.setattr(
+ "local_deep_research.utilities.openalex_enrichment."
+ "enrich_results_with_source_ids",
+ fake_enrich,
+ )
+ engine = FakeScientificEngine(programmatic_mode=True)
+ setattr(engine, credential_attr, credential)
+
+ engine.run("anything")
+
+ assert captured_keys == [expected_openalex_key]
+
+ def test_openalex_enrichment_key_comes_from_snapshot_for_other_engines(
+ self, monkeypatch
+ ):
+ """Every scientific engine authenticates OpenAlex enrichment.
+
+ Enrichment hits api.openalex.org no matter which engine produced
+ the previews, but only OpenAlexSearchEngine sets
+ ``openalex_api_key`` — so arxiv/semantic_scholar/zenodo/nasa_ads/
+ pubchem/pubmed must pick the key up from the settings snapshot.
+ Their own ``api_key`` must never be sent to OpenAlex.
+ """
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class FakeArxivEngine(BaseSearchEngine):
+ is_scientific = True
+
+ def _get_previews(self, query):
+ return [{"title": "Paper", "doi": "10.1234/example"}]
+
+ def _get_full_content(self, items):
+ return items
+
+ captured_keys = []
+
+ def fake_enrich(results, email=None, api_key=None, **kwargs):
+ captured_keys.append(api_key)
+ return results
+
+ monkeypatch.setattr(
+ "local_deep_research.utilities.openalex_enrichment."
+ "enrich_results_with_source_ids",
+ fake_enrich,
+ )
+ engine = FakeArxivEngine(programmatic_mode=True)
+ # Assigned post-construction (as the sibling tests do) so the
+ # snapshot only exercises the enrichment lookup.
+ engine.settings_snapshot = {
+ "search.engine.web.openalex.api_key": "openalex-snapshot-key",
+ }
+ # The engine's own (non-OpenAlex) credential must stay put.
+ engine.api_key = "arxiv-engine-key"
+
+ engine.run("anything")
+
+ assert captured_keys == ["openalex-snapshot-key"]
+
+ def test_openalex_enrichment_ignores_placeholder_snapshot_key(
+ self, monkeypatch
+ ):
+ """A placeholder in the snapshot means keyless, not a bad Bearer."""
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class FakeArxivEngine(BaseSearchEngine):
+ is_scientific = True
+
+ def _get_previews(self, query):
+ return [{"title": "Paper", "doi": "10.1234/example"}]
+
+ def _get_full_content(self, items):
+ return items
+
+ captured_keys = []
+
+ def fake_enrich(results, email=None, api_key=None, **kwargs):
+ captured_keys.append(api_key)
+ return results
+
+ monkeypatch.setattr(
+ "local_deep_research.utilities.openalex_enrichment."
+ "enrich_results_with_source_ids",
+ fake_enrich,
+ )
+ engine = FakeArxivEngine(programmatic_mode=True)
+ engine.settings_snapshot = {
+ "search.engine.web.openalex.api_key": "${OPENALEX_API_KEY}",
+ }
+
+ engine.run("anything")
+
+ assert captured_keys == [None]
+
def test_non_scientific_engine_skips_enrichment(self, monkeypatch):
"""Non-scientific engines don't pay the enrichment cost."""
from local_deep_research.web_search_engines.search_engine_base import (
@@ -767,7 +897,7 @@ class TestDoiEnrichmentOrdering:
called = {"count": 0}
- def fake_enrich(results, email=None):
+ def fake_enrich(results, email=None, api_key=None, **kwargs):
called["count"] += 1
return results
@@ -784,6 +914,218 @@ class TestDoiEnrichmentOrdering:
"non-scientific engines should not trigger DOI enrichment"
)
+ def test_snapshot_without_the_openalex_key_still_enriches(
+ self, monkeypatch
+ ):
+ """A snapshot that simply lacks the key means "enrich keylessly".
+
+ ``get_setting_from_snapshot`` raises ``NoSettingsContextError``
+ for a key that is absent from a non-empty snapshot when no
+ thread-local settings context is bound *and no default was
+ supplied*. This resolver is evaluated in the argument position of
+ the enrichment call, inside a blanket ``except Exception`` that
+ only logs a debug line — so a raise here would silently skip DOI
+ enrichment entirely for every scientific engine. Reachable with a
+ caller-supplied partial ``base_settings`` dict, or a snapshot
+ persisted before the key existed and replayed later by the queue
+ processor / notes routers.
+ """
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class FakeArxivEngine(BaseSearchEngine):
+ is_scientific = True
+
+ def _get_previews(self, query):
+ return [{"title": "Paper", "doi": "10.1234/example"}]
+
+ def _get_full_content(self, items):
+ return items
+
+ captured_keys = []
+
+ def fake_enrich(results, email=None, api_key=None, **kwargs):
+ captured_keys.append(api_key)
+ return results
+
+ monkeypatch.setattr(
+ "local_deep_research.utilities.openalex_enrichment."
+ "enrich_results_with_source_ids",
+ fake_enrich,
+ )
+
+ engine = FakeArxivEngine(programmatic_mode=True)
+ # Non-empty, but without search.engine.web.openalex.api_key.
+ engine.settings_snapshot = {
+ "search.engine.web.openalex.email": "[email protected]",
+ "search.max_results": 10,
+ }
+ # No thread-local settings context, and not programmatic for the
+ # resolver's purposes — the resolver reads the snapshot directly.
+ engine.programmatic_mode = False
+
+ engine.run("anything")
+
+ assert engine._resolve_openalex_enrichment_key() is None
+ assert captured_keys == [None], (
+ "enrichment must still run keylessly, not be skipped"
+ )
+
+ def test_dict_shaped_snapshot_value_is_unwrapped(self, monkeypatch):
+ """``get_default_settings_snapshot()`` yields full setting dicts.
+
+ ``InMemorySettingsManager().get_all_settings()`` returns
+ ``{"value": ..., "ui_element": "password", ...}`` rows, whereas
+ ``SettingsManager.get_settings_snapshot`` flattens to bare
+ values. Both shapes reach this resolver in production.
+ """
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class FakeArxivEngine(BaseSearchEngine):
+ is_scientific = True
+
+ def _get_previews(self, query):
+ return [{"title": "Paper", "doi": "10.1234/example"}]
+
+ def _get_full_content(self, items):
+ return items
+
+ captured_keys = []
+
+ def fake_enrich(results, email=None, api_key=None, **kwargs):
+ captured_keys.append(api_key)
+ return results
+
+ monkeypatch.setattr(
+ "local_deep_research.utilities.openalex_enrichment."
+ "enrich_results_with_source_ids",
+ fake_enrich,
+ )
+ monkeypatch.delenv(
+ "LDR_SEARCH_ENGINE_WEB_OPENALEX_API_KEY", raising=False
+ )
+
+ engine = FakeArxivEngine(programmatic_mode=True)
+ engine.settings_snapshot = {
+ "search.engine.web.openalex.api_key": {
+ "value": "oa-live-abc123",
+ "ui_element": "password",
+ }
+ }
+
+ engine.run("anything")
+
+ assert engine._resolve_openalex_enrichment_key() == "oa-live-abc123"
+ assert captured_keys == ["oa-live-abc123"]
+
+ def test_enrichment_rejection_latches_for_every_later_run(
+ self, monkeypatch
+ ):
+ """A refused enrichment key must not be resolved again next run.
+
+ The enrichment module's own drop is a call-local, so it only
+ protects the remaining chunks of that one pass. The key came out
+ of the settings snapshot, which the resolver reads afresh on
+ every run — so without a latch on the engine, run 2 sends the
+ refused credential again, forever, for one wasted 401 and a
+ duplicate warning per run.
+ """
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ class FakeArxivEngine(BaseSearchEngine):
+ is_scientific = True
+
+ def _get_previews(self, query):
+ return [{"title": "Paper", "doi": "10.1234/example"}]
+
+ def _get_full_content(self, items):
+ return items
+
+ monkeypatch.delenv(
+ "LDR_SEARCH_ENGINE_WEB_OPENALEX_API_KEY", raising=False
+ )
+
+ authorizations = []
+ rejected = Mock()
+ rejected.status_code = 401
+ ok = Mock()
+ ok.status_code = 200
+ ok.json.return_value = {"results": []}
+
+ def _enrichment_get(*args, **kwargs):
+ authorization = kwargs["headers"].get("Authorization")
+ authorizations.append(authorization)
+ return rejected if authorization else ok
+
+ monkeypatch.setattr(
+ "local_deep_research.utilities.openalex_enrichment.safe_get",
+ _enrichment_get,
+ )
+
+ engine = FakeArxivEngine(programmatic_mode=True)
+ engine.settings_snapshot = {
+ "search.engine.web.openalex.api_key": "oa-live-abc123",
+ }
+ # The engine's own credential must stay put throughout.
+ engine.api_key = "arxiv-engine-key"
+
+ engine.run("first query")
+ engine.run("second query")
+ engine.run("third query")
+
+ assert authorizations == [
+ "Bearer oa-live-abc123", # run 1, refused
+ None, # run 1, keyless retry
+ None, # run 2, keyless from the first request
+ None, # run 3
+ ]
+ assert engine.api_key == "arxiv-engine-key"
+ # The refused literal is still redactable on this engine, even
+ # though it was never one of its own attributes.
+ assert "oa-live-abc123" not in engine._scrub_error(
+ RuntimeError("boom oa-live-abc123")
+ )
+
+ def test_rejected_openalex_key_is_in_the_base_redaction_set(self):
+ """``_rejected_api_key`` must be in the base ``_secret_attrs``.
+
+ Enrichment can store an OpenAlex key there on any scientific
+ engine, not just OpenAlexSearchEngine, so the base default has to
+ carry it — otherwise ``_scrub_error`` silently stops redacting it.
+ """
+ from local_deep_research.web_search_engines.search_engine_base import (
+ BaseSearchEngine,
+ )
+
+ assert "_rejected_api_key" in BaseSearchEngine._secret_attrs
+
+ class FakeArxivEngine(BaseSearchEngine):
+ is_scientific = True
+
+ def _get_previews(self, query):
+ return []
+
+ def _get_full_content(self, items):
+ return items
+
+ engine = FakeArxivEngine(programmatic_mode=True)
+ assert engine._openalex_key_rejected is False
+ assert engine._resolve_openalex_enrichment_key() is None
+
+ engine._note_openalex_key_rejected("oa-live-abc123")
+ assert engine._openalex_key_rejected is True
+ # A second call must not overwrite the literal with None.
+ engine._note_openalex_key_rejected(None)
+ assert engine._rejected_api_key == "oa-live-abc123"
+ assert "oa-live-abc123" not in engine._scrub_error(
+ RuntimeError("boom oa-live-abc123")
+ )
+
class TestInitFullSearchForwardsSettingsSnapshot:
"""Issue #3826: ``_init_full_search`` must forward