Skip to main content

doiget_core/sources/
unpaywall.rs

1//! Unpaywall source — OA URL discovery + license metadata for a given DOI.
2//!
3//! Spec: docs/SOURCES.md §4 Unpaywall. Free public API; the polite pool
4//! requires `email=<contact>` in the URL query. The `email` is set per
5//! `[network] unpaywall_email` in `config.toml` (Phase 1: caller-injected
6//! via `UnpaywallSource::new`).
7
8use async_trait::async_trait;
9use serde::Deserialize;
10use url::Url;
11
12use crate::provenance::{Capability, LogEvent, LogResult, RowInput};
13use crate::source::{FetchContext, FetchError, FetchResult, Source};
14use crate::{CapabilityProfile, Ref};
15
16const DEFAULT_BASE: &str = "https://api.unpaywall.org/v2";
17
18/// Unpaywall Source impl.
19#[derive(Clone, Debug)]
20pub struct UnpaywallSource {
21    base: Url,
22    contact_email: String,
23}
24
25impl UnpaywallSource {
26    /// Production constructor. The `contact_email` is REQUIRED for the polite
27    /// pool — Unpaywall returns 403 without it.
28    pub fn new(contact_email: String) -> Self {
29        // `DEFAULT_BASE` is a compile-time const string with a valid HTTPS
30        // URL syntax; `Url::parse` on it cannot fail at runtime. The local
31        // `allow` is the documented exception to the workspace `expect_used`
32        // lint (see `rate_limiter.rs::acquire`).
33        #[allow(clippy::expect_used)]
34        let base = Url::parse(DEFAULT_BASE).expect("hard-coded base URL is valid");
35        Self {
36            base,
37            contact_email,
38        }
39    }
40
41    /// Construct with an arbitrary base URL.
42    ///
43    /// The orchestrator (`doiget-cli::commands::fetch`) uses this to honor
44    /// the `DOIGET_UNPAYWALL_BASE` env var, which lets integration tests
45    /// point the source at a wiremock origin without compile-time gates.
46    /// Production callers use [`UnpaywallSource::new`].
47    pub fn with_base(base: Url, contact_email: String) -> Self {
48        Self {
49            base,
50            contact_email,
51        }
52    }
53
54    fn request_url(&self, doi: &crate::Doi) -> Result<Url, FetchError> {
55        // The path layout is `/v2/<DOI>`. Unpaywall accepts the bare DOI
56        // (no `doi:` scheme); `Doi::as_str()` already strips it.
57        let mut url = self.base.clone();
58        // `path_segments_mut` properly URL-encodes each segment, including the
59        // forward slash inside the DOI suffix.
60        url.path_segments_mut()
61            .map_err(|()| FetchError::SourceSchema {
62                hint: "unpaywall base URL is cannot-be-a-base".into(),
63            })?
64            .push(doi.as_str()); // single-push so the `/` in the DOI is encoded
65        url.query_pairs_mut()
66            .append_pair("email", &self.contact_email);
67        Ok(url)
68    }
69}
70
71#[async_trait]
72impl Source for UnpaywallSource {
73    fn name(&self) -> &str {
74        "unpaywall"
75    }
76
77    fn can_serve(&self, _profile: &CapabilityProfile, ref_: &Ref) -> bool {
78        matches!(ref_, Ref::Doi(_))
79    }
80
81    async fn fetch(
82        &self,
83        ref_: &Ref,
84        _profile: &CapabilityProfile,
85        ctx: &FetchContext,
86    ) -> Result<FetchResult, FetchError> {
87        let doi = match ref_ {
88            Ref::Doi(d) => d,
89            Ref::Arxiv(_) => {
90                return Err(FetchError::NotEligible {
91                    source_key: "unpaywall".into(),
92                });
93            }
94        };
95
96        let _permit = ctx.rate_limiter.acquire(self.name()).await;
97
98        let url = self.request_url(doi)?;
99        let (body, final_url) = ctx.http.fetch_bytes(self.name(), url).await?;
100
101        let work: UnpaywallWork =
102            serde_json::from_slice(&body).map_err(|e| FetchError::SourceSchema {
103                hint: format!("unpaywall returned non-JSON: {e}"),
104            })?;
105
106        // Resolve a license string from `best_oa_location.license`, falling back
107        // to "unknown" if absent. Spec: docs/STORE.md §2 — `license` is always
108        // a string (use "unknown" when not provided).
109        let license = work
110            .best_oa_location
111            .as_ref()
112            .and_then(|loc| loc.license.clone())
113            .unwrap_or_else(|| "unknown".to_string());
114
115        // ADR-0021 §1 canonical-digest under the "unpaywall" resolver
116        // profile. Distinct from a Crossref attempt for the same DOI.
117        let canonical = ref_.promote(self.name(), None).digest_hex();
118        ctx.log.append(RowInput {
119            event: LogEvent::Fetch,
120            result: LogResult::Ok,
121            capability: Capability::Oa,
122            ref_: Some(doi.as_str()),
123            source: Some(self.name()),
124            error_code: None,
125            size_bytes: Some(body.len() as u64),
126            license: Some(&license),
127            store_path: None,
128            canonical_digest: Some(&canonical),
129        })?;
130
131        // Note: this source returns metadata only; the actual PDF fetch
132        // from the discovered OA URL is the orchestrator's job
133        // (`crate::orchestrator::try_fetch_oa_pdf`, called from
134        // `fetch_paper_doi`). That leg runs the OA URL through the
135        // `oa-publisher` per-publisher allowlist BOTH as a pre-fetch host
136        // check (issue #145; `docs/REDIRECT_ALLOWLIST.md` §1 — applied to
137        // the metadata-discovered URL before the fetch is issued) and on
138        // every redirect hop via the per-source redirect closure in
139        // `crate::http`. See ARCHITECTURE.md §6.
140        Ok(FetchResult {
141            source: self.name().to_string(),
142            license,
143            pdf_bytes: None,
144            final_url: Some(final_url),
145            metadata_json: Some(serde_json::to_value(&work).unwrap_or(serde_json::Value::Null)),
146        })
147    }
148}
149
150/// Subset of the Unpaywall work record. We deserialize loosely — extra fields
151/// are ignored (no `deny_unknown_fields`) so future API additions don't break.
152#[derive(Debug, Deserialize, serde::Serialize)]
153struct UnpaywallWork {
154    doi: String,
155    is_oa: bool,
156    #[serde(default)]
157    title: Option<String>,
158    #[serde(default)]
159    best_oa_location: Option<UnpaywallOaLocation>,
160    #[serde(default)]
161    oa_locations: Vec<UnpaywallOaLocation>,
162}
163
164#[derive(Debug, Deserialize, serde::Serialize, Clone)]
165struct UnpaywallOaLocation {
166    #[serde(default)]
167    url: Option<String>,
168    #[serde(default)]
169    url_for_pdf: Option<String>,
170    #[serde(default)]
171    license: Option<String>,
172}
173
174// ---------------------------------------------------------------------------
175// Tests
176// ---------------------------------------------------------------------------
177
178#[cfg(test)]
179#[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
180mod tests {
181    use super::*;
182
183    use std::sync::Arc;
184
185    use camino::Utf8PathBuf;
186    use tempfile::TempDir;
187    use wiremock::matchers::{method, path, query_param};
188    use wiremock::{Mock, MockServer, ResponseTemplate};
189
190    use crate::http::HttpClient;
191    use crate::provenance::{LogRow, ProvenanceLog};
192    use crate::rate_limiter::RateLimiter;
193    use crate::source::FetchContext;
194    use crate::{ArxivId, CapabilityProfile, Doi, RateLimits};
195
196    const TEST_EMAIL: &str = "alice@example.org";
197    const TEST_DOI: &str = "10.1234/example";
198    /// Percent-encoded form of `TEST_DOI` as it appears on the wire after
199    /// `path_segments_mut().push(...)`. Wiremock's `path` matcher operates on
200    /// the request's encoded path portion, so we match against this form.
201    const TEST_DOI_ENCODED: &str = "10.1234%2Fexample";
202
203    /// Build a `FetchContext` whose `HttpClient` allows plain-HTTP initial
204    /// legs against the wiremock origin. The redirect closure is unchanged
205    /// (HTTPS-only + allowlist) — only the *initial* connection is relaxed.
206    fn build_test_context(host: &str) -> (TempDir, FetchContext) {
207        let td = TempDir::new().expect("tempdir");
208        let log_dir =
209            Utf8PathBuf::try_from(td.path().to_path_buf()).expect("temp dir path must be UTF-8");
210        let log_path = log_dir.join("test.jsonl");
211
212        let http = Arc::new(HttpClient::new_for_tests_allow_http("unpaywall", host));
213        let rate_limiter = Arc::new(RateLimiter::new(RateLimits::HARD_CODED));
214        let session_id = "01J0000000000000000000TEST".to_string();
215        let log = Arc::new(
216            ProvenanceLog::open(log_path, session_id.clone()).expect("provenance log opens"),
217        );
218
219        (
220            td,
221            FetchContext {
222                http,
223                rate_limiter,
224                log,
225                session_id,
226                cache_root: None,
227            },
228        )
229    }
230
231    fn host_of(uri: &str) -> String {
232        uri.parse::<Url>()
233            .expect("valid uri")
234            .host_str()
235            .expect("has host")
236            .to_string()
237    }
238
239    fn base_of(server_uri: &str) -> Url {
240        // The wiremock server roots at `/`; Unpaywall lives at `/v2/<DOI>`.
241        // Including the `/v2` segment in the base lets `request_url`'s
242        // single-push DOI segment land at the correct path.
243        format!("{}/v2", server_uri).parse().expect("valid base")
244    }
245
246    fn ok_response_body() -> serde_json::Value {
247        serde_json::json!({
248            "doi": TEST_DOI,
249            "is_oa": true,
250            "title": "Example",
251            "best_oa_location": {
252                "url": "https://example.org/free.pdf",
253                "license": "cc-by"
254            }
255        })
256    }
257
258    #[test]
259    fn unpaywall_can_serve_returns_true_for_doi() {
260        let s = UnpaywallSource::new(TEST_EMAIL.to_string());
261        let profile = CapabilityProfile::from_env().expect("profile");
262        let r = Ref::Doi(Doi(TEST_DOI.to_string()));
263        assert!(s.can_serve(&profile, &r));
264    }
265
266    #[test]
267    fn unpaywall_can_serve_returns_false_for_arxiv() {
268        let s = UnpaywallSource::new(TEST_EMAIL.to_string());
269        let profile = CapabilityProfile::from_env().expect("profile");
270        let r = Ref::Arxiv(ArxivId("2401.12345".to_string()));
271        assert!(!s.can_serve(&profile, &r));
272    }
273
274    #[tokio::test]
275    async fn unpaywall_fetch_returns_oa_metadata() {
276        let server = MockServer::start().await;
277        Mock::given(method("GET"))
278            .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
279            .and(query_param("email", TEST_EMAIL))
280            .respond_with(ResponseTemplate::new(200).set_body_json(ok_response_body()))
281            .mount(&server)
282            .await;
283
284        let host = host_of(&server.uri());
285        let (_td, ctx) = build_test_context(&host);
286        let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
287        let profile = CapabilityProfile::from_env().expect("profile");
288        let r = Ref::Doi(Doi(TEST_DOI.to_string()));
289
290        let res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
291        assert_eq!(res.source, "unpaywall");
292        assert!(res.final_url.is_some());
293        let meta = res.metadata_json.expect("metadata present");
294        let parsed: UnpaywallWork = serde_json::from_value(meta).expect("metadata round-trips");
295        assert!(parsed.is_oa);
296        assert_eq!(parsed.doi, TEST_DOI);
297    }
298
299    #[tokio::test]
300    async fn unpaywall_extracts_license_from_best_oa_location() {
301        let server = MockServer::start().await;
302        Mock::given(method("GET"))
303            .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
304            .and(query_param("email", TEST_EMAIL))
305            .respond_with(ResponseTemplate::new(200).set_body_json(ok_response_body()))
306            .mount(&server)
307            .await;
308
309        let host = host_of(&server.uri());
310        let (_td, ctx) = build_test_context(&host);
311        let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
312        let profile = CapabilityProfile::from_env().expect("profile");
313        let r = Ref::Doi(Doi(TEST_DOI.to_string()));
314
315        let res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
316        assert_eq!(res.license, "cc-by");
317    }
318
319    #[tokio::test]
320    async fn unpaywall_falls_back_to_unknown_license() {
321        let body = serde_json::json!({
322            "doi": TEST_DOI,
323            "is_oa": true,
324            "best_oa_location": {
325                "url": "https://example.org/free.pdf",
326                "license": serde_json::Value::Null
327            }
328        });
329        let server = MockServer::start().await;
330        Mock::given(method("GET"))
331            .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
332            .and(query_param("email", TEST_EMAIL))
333            .respond_with(ResponseTemplate::new(200).set_body_json(body))
334            .mount(&server)
335            .await;
336
337        let host = host_of(&server.uri());
338        let (_td, ctx) = build_test_context(&host);
339        let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
340        let profile = CapabilityProfile::from_env().expect("profile");
341        let r = Ref::Doi(Doi(TEST_DOI.to_string()));
342
343        let res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
344        assert_eq!(res.license, "unknown");
345    }
346
347    #[tokio::test]
348    async fn unpaywall_with_arxiv_ref_errors_not_eligible() {
349        // No mock: should never reach the network because the ref-kind
350        // gate fires first.
351        let (_td, ctx) = build_test_context("127.0.0.1");
352        let s = UnpaywallSource::new(TEST_EMAIL.to_string());
353        let profile = CapabilityProfile::from_env().expect("profile");
354        let r = Ref::Arxiv(ArxivId("2401.12345".to_string()));
355
356        let err = s
357            .fetch(&r, &profile, &ctx)
358            .await
359            .expect_err("arxiv must be ineligible");
360        match err {
361            FetchError::NotEligible { source_key } => {
362                assert_eq!(source_key, "unpaywall");
363            }
364            other => panic!("expected NotEligible, got {:?}", other),
365        }
366    }
367
368    #[tokio::test]
369    async fn unpaywall_writes_log_row_with_license() {
370        let server = MockServer::start().await;
371        Mock::given(method("GET"))
372            .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
373            .and(query_param("email", TEST_EMAIL))
374            .respond_with(ResponseTemplate::new(200).set_body_json(ok_response_body()))
375            .mount(&server)
376            .await;
377
378        let host = host_of(&server.uri());
379        let (td, ctx) = build_test_context(&host);
380        let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
381        let profile = CapabilityProfile::from_env().expect("profile");
382        let r = Ref::Doi(Doi(TEST_DOI.to_string()));
383
384        let _res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
385
386        // Read every JSON-Lines row from the log file and assert the Fetch
387        // row is present with license="cc-by".
388        let log_path = Utf8PathBuf::try_from(td.path().to_path_buf())
389            .expect("temp path utf-8")
390            .join("test.jsonl");
391        let raw = std::fs::read_to_string(&log_path).expect("read log");
392        let rows: Vec<LogRow> = raw
393            .lines()
394            .filter(|l| !l.is_empty())
395            .map(|l| serde_json::from_str::<LogRow>(l).expect("valid LogRow"))
396            .collect();
397
398        let fetch_rows: Vec<&LogRow> = rows.iter().filter(|r| r.event == LogEvent::Fetch).collect();
399        assert_eq!(
400            fetch_rows.len(),
401            1,
402            "expected one Fetch row, got {:?}",
403            rows
404        );
405        let row = fetch_rows[0];
406        assert_eq!(row.result, LogResult::Ok);
407        assert_eq!(row.license.as_deref(), Some("cc-by"));
408        assert_eq!(row.source.as_deref(), Some("unpaywall"));
409        assert_eq!(row.ref_.as_deref(), Some(TEST_DOI));
410    }
411
412    #[test]
413    fn unpaywall_email_is_in_query_string() {
414        // White-box: invoke `request_url` directly to assert the email is
415        // serialized into the query. The wiremock-driven tests above assert
416        // the same property via the `query_param("email", ...)` matcher,
417        // but this test pins the contract without booting an HTTP server.
418        // `query_pairs_mut().append_pair` percent-encodes the `@`, so we
419        // verify against the decoded form via `query_pairs()`.
420        let s = UnpaywallSource::new(TEST_EMAIL.to_string());
421        let doi = Doi(TEST_DOI.to_string());
422        let url = s.request_url(&doi).expect("url builds");
423        let pair = url
424            .query_pairs()
425            .find(|(k, _)| k == "email")
426            .expect("email pair present");
427        assert_eq!(pair.1, TEST_EMAIL, "decoded email must match: {:?}", pair);
428    }
429
430    #[tokio::test]
431    async fn unpaywall_404_maps_to_http_error() {
432        let server = MockServer::start().await;
433        Mock::given(method("GET"))
434            .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
435            .respond_with(ResponseTemplate::new(404))
436            .mount(&server)
437            .await;
438
439        let host = host_of(&server.uri());
440        let (_td, ctx) = build_test_context(&host);
441        let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
442        let profile = CapabilityProfile::from_env().expect("profile");
443        let r = Ref::Doi(Doi(TEST_DOI.to_string()));
444
445        let err = s
446            .fetch(&r, &profile, &ctx)
447            .await
448            .expect_err("404 must error");
449        match err {
450            FetchError::Http(_) => {}
451            other => panic!("expected FetchError::Http, got {:?}", other),
452        }
453    }
454}