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            },
227        )
228    }
229
230    fn host_of(uri: &str) -> String {
231        uri.parse::<Url>()
232            .expect("valid uri")
233            .host_str()
234            .expect("has host")
235            .to_string()
236    }
237
238    fn base_of(server_uri: &str) -> Url {
239        // The wiremock server roots at `/`; Unpaywall lives at `/v2/<DOI>`.
240        // Including the `/v2` segment in the base lets `request_url`'s
241        // single-push DOI segment land at the correct path.
242        format!("{}/v2", server_uri).parse().expect("valid base")
243    }
244
245    fn ok_response_body() -> serde_json::Value {
246        serde_json::json!({
247            "doi": TEST_DOI,
248            "is_oa": true,
249            "title": "Example",
250            "best_oa_location": {
251                "url": "https://example.org/free.pdf",
252                "license": "cc-by"
253            }
254        })
255    }
256
257    #[test]
258    fn unpaywall_can_serve_returns_true_for_doi() {
259        let s = UnpaywallSource::new(TEST_EMAIL.to_string());
260        let profile = CapabilityProfile::from_env().expect("profile");
261        let r = Ref::Doi(Doi(TEST_DOI.to_string()));
262        assert!(s.can_serve(&profile, &r));
263    }
264
265    #[test]
266    fn unpaywall_can_serve_returns_false_for_arxiv() {
267        let s = UnpaywallSource::new(TEST_EMAIL.to_string());
268        let profile = CapabilityProfile::from_env().expect("profile");
269        let r = Ref::Arxiv(ArxivId("2401.12345".to_string()));
270        assert!(!s.can_serve(&profile, &r));
271    }
272
273    #[tokio::test]
274    async fn unpaywall_fetch_returns_oa_metadata() {
275        let server = MockServer::start().await;
276        Mock::given(method("GET"))
277            .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
278            .and(query_param("email", TEST_EMAIL))
279            .respond_with(ResponseTemplate::new(200).set_body_json(ok_response_body()))
280            .mount(&server)
281            .await;
282
283        let host = host_of(&server.uri());
284        let (_td, ctx) = build_test_context(&host);
285        let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
286        let profile = CapabilityProfile::from_env().expect("profile");
287        let r = Ref::Doi(Doi(TEST_DOI.to_string()));
288
289        let res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
290        assert_eq!(res.source, "unpaywall");
291        assert!(res.final_url.is_some());
292        let meta = res.metadata_json.expect("metadata present");
293        let parsed: UnpaywallWork = serde_json::from_value(meta).expect("metadata round-trips");
294        assert!(parsed.is_oa);
295        assert_eq!(parsed.doi, TEST_DOI);
296    }
297
298    #[tokio::test]
299    async fn unpaywall_extracts_license_from_best_oa_location() {
300        let server = MockServer::start().await;
301        Mock::given(method("GET"))
302            .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
303            .and(query_param("email", TEST_EMAIL))
304            .respond_with(ResponseTemplate::new(200).set_body_json(ok_response_body()))
305            .mount(&server)
306            .await;
307
308        let host = host_of(&server.uri());
309        let (_td, ctx) = build_test_context(&host);
310        let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
311        let profile = CapabilityProfile::from_env().expect("profile");
312        let r = Ref::Doi(Doi(TEST_DOI.to_string()));
313
314        let res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
315        assert_eq!(res.license, "cc-by");
316    }
317
318    #[tokio::test]
319    async fn unpaywall_falls_back_to_unknown_license() {
320        let body = serde_json::json!({
321            "doi": TEST_DOI,
322            "is_oa": true,
323            "best_oa_location": {
324                "url": "https://example.org/free.pdf",
325                "license": serde_json::Value::Null
326            }
327        });
328        let server = MockServer::start().await;
329        Mock::given(method("GET"))
330            .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
331            .and(query_param("email", TEST_EMAIL))
332            .respond_with(ResponseTemplate::new(200).set_body_json(body))
333            .mount(&server)
334            .await;
335
336        let host = host_of(&server.uri());
337        let (_td, ctx) = build_test_context(&host);
338        let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
339        let profile = CapabilityProfile::from_env().expect("profile");
340        let r = Ref::Doi(Doi(TEST_DOI.to_string()));
341
342        let res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
343        assert_eq!(res.license, "unknown");
344    }
345
346    #[tokio::test]
347    async fn unpaywall_with_arxiv_ref_errors_not_eligible() {
348        // No mock: should never reach the network because the ref-kind
349        // gate fires first.
350        let (_td, ctx) = build_test_context("127.0.0.1");
351        let s = UnpaywallSource::new(TEST_EMAIL.to_string());
352        let profile = CapabilityProfile::from_env().expect("profile");
353        let r = Ref::Arxiv(ArxivId("2401.12345".to_string()));
354
355        let err = s
356            .fetch(&r, &profile, &ctx)
357            .await
358            .expect_err("arxiv must be ineligible");
359        match err {
360            FetchError::NotEligible { source_key } => {
361                assert_eq!(source_key, "unpaywall");
362            }
363            other => panic!("expected NotEligible, got {:?}", other),
364        }
365    }
366
367    #[tokio::test]
368    async fn unpaywall_writes_log_row_with_license() {
369        let server = MockServer::start().await;
370        Mock::given(method("GET"))
371            .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
372            .and(query_param("email", TEST_EMAIL))
373            .respond_with(ResponseTemplate::new(200).set_body_json(ok_response_body()))
374            .mount(&server)
375            .await;
376
377        let host = host_of(&server.uri());
378        let (td, ctx) = build_test_context(&host);
379        let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
380        let profile = CapabilityProfile::from_env().expect("profile");
381        let r = Ref::Doi(Doi(TEST_DOI.to_string()));
382
383        let _res = s.fetch(&r, &profile, &ctx).await.expect("fetch ok");
384
385        // Read every JSON-Lines row from the log file and assert the Fetch
386        // row is present with license="cc-by".
387        let log_path = Utf8PathBuf::try_from(td.path().to_path_buf())
388            .expect("temp path utf-8")
389            .join("test.jsonl");
390        let raw = std::fs::read_to_string(&log_path).expect("read log");
391        let rows: Vec<LogRow> = raw
392            .lines()
393            .filter(|l| !l.is_empty())
394            .map(|l| serde_json::from_str::<LogRow>(l).expect("valid LogRow"))
395            .collect();
396
397        let fetch_rows: Vec<&LogRow> = rows.iter().filter(|r| r.event == LogEvent::Fetch).collect();
398        assert_eq!(
399            fetch_rows.len(),
400            1,
401            "expected one Fetch row, got {:?}",
402            rows
403        );
404        let row = fetch_rows[0];
405        assert_eq!(row.result, LogResult::Ok);
406        assert_eq!(row.license.as_deref(), Some("cc-by"));
407        assert_eq!(row.source.as_deref(), Some("unpaywall"));
408        assert_eq!(row.ref_.as_deref(), Some(TEST_DOI));
409    }
410
411    #[test]
412    fn unpaywall_email_is_in_query_string() {
413        // White-box: invoke `request_url` directly to assert the email is
414        // serialized into the query. The wiremock-driven tests above assert
415        // the same property via the `query_param("email", ...)` matcher,
416        // but this test pins the contract without booting an HTTP server.
417        // `query_pairs_mut().append_pair` percent-encodes the `@`, so we
418        // verify against the decoded form via `query_pairs()`.
419        let s = UnpaywallSource::new(TEST_EMAIL.to_string());
420        let doi = Doi(TEST_DOI.to_string());
421        let url = s.request_url(&doi).expect("url builds");
422        let pair = url
423            .query_pairs()
424            .find(|(k, _)| k == "email")
425            .expect("email pair present");
426        assert_eq!(pair.1, TEST_EMAIL, "decoded email must match: {:?}", pair);
427    }
428
429    #[tokio::test]
430    async fn unpaywall_404_maps_to_http_error() {
431        let server = MockServer::start().await;
432        Mock::given(method("GET"))
433            .and(path(format!("/v2/{}", TEST_DOI_ENCODED)))
434            .respond_with(ResponseTemplate::new(404))
435            .mount(&server)
436            .await;
437
438        let host = host_of(&server.uri());
439        let (_td, ctx) = build_test_context(&host);
440        let s = UnpaywallSource::with_base(base_of(&server.uri()), TEST_EMAIL.to_string());
441        let profile = CapabilityProfile::from_env().expect("profile");
442        let r = Ref::Doi(Doi(TEST_DOI.to_string()));
443
444        let err = s
445            .fetch(&r, &profile, &ctx)
446            .await
447            .expect_err("404 must error");
448        match err {
449            FetchError::Http(_) => {}
450            other => panic!("expected FetchError::Http, got {:?}", other),
451        }
452    }
453}