defter 0.5.4

Self-hosted Zotero sync and file storage server, with metadata in SQLite and attachments in S3.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
//! Optional sign-in through an OpenID Connect provider such as Keycloak, beside
//! the API keys: the authorization code flow with PKCE, a state tied to the
//! browser by a cookie, and a nonce. The account's ORCID iD, a claim of the ID
//! token or of the userinfo response, is who signs in: a user, someone invited,
//! or an admin (see `control::Control::sign_in`).
//!
//! The ID token comes straight from the provider's token endpoint over TLS, so
//! its signature is not checked, as OpenID Connect Core 3.1.3.7 allows; its
//! issuer, audience, expiry and nonce are.

use std::time::{Duration, SystemTime, UNIX_EPOCH};

use aws_lc_rs::digest;
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde_json::Value;

use crate::profile;

/// How long a sign-in may take at the provider.
pub const LOGIN_TTL: Duration = Duration::from_secs(600);

/// The cookie tying a sign-in in progress to the browser that started it.
pub const STATE_COOKIE: &str = "defter_oidc";

/// Allowance for clocks differing between here and the provider.
const CLOCK_SKEW: u64 = 60;

/// The claim holding an account's ORCID iD, and what to call the provider, when
/// not set. A variable set to nothing counts as not set.
const DEFAULT_ORCID_CLAIM: &str = "orcid";
const DEFAULT_NAME: &str = "Keycloak";

/// How long a request to the provider may take: a sign-in waits for it.
const REQUEST_TIMEOUT: Duration = Duration::from_secs(10);

fn non_empty(value: &str, default: &str) -> String {
    match value.trim() {
        "" => default.to_string(),
        value => value.to_string(),
    }
}

/// How to reach the provider, and who it lets in.
#[derive(Debug, Clone)]
pub struct OidcConfig {
    pub issuer: String,
    pub client_id: String,
    /// `None` for a public client, which PKCE alone protects.
    pub client_secret: Option<String>,
    pub orcid_claim: String,
    /// What the sign-in button calls the provider.
    pub name: String,
}

impl OidcConfig {
    /// Check the settings. `allowed` is comma-separated ORCID iDs or URLs.
    pub fn new(
        issuer: &str,
        client_id: &str,
        client_secret: Option<String>,
        orcid_claim: &str,
        name: &str,
    ) -> Result<Self, String> {
        let issuer = issuer.trim().trim_end_matches('/').to_string();
        if !secure_url(&issuer, &issuer) {
            return Err(format!("--oidc-issuer: {issuer:?} is not an https URL"));
        }
        if client_id.trim().is_empty() {
            return Err("--oidc-client-id is empty".to_string());
        }
        Ok(OidcConfig {
            issuer,
            client_id: client_id.trim().to_string(),
            client_secret: client_secret.filter(|secret| !secret.trim().is_empty()),
            orcid_claim: non_empty(orcid_claim, DEFAULT_ORCID_CLAIM),
            name: non_empty(name, DEFAULT_NAME),
        })
    }
}

/// Whether a plain HTTP URL's host is this machine. Exactly: `localhost.example.org`
/// or `localhost@example.org` are not.
fn local_http(url: &str) -> bool {
    let Some(rest) = url.strip_prefix("http://") else {
        return false;
    };
    let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
    if authority.contains('@') {
        return false;
    }
    let host = match authority
        .strip_suffix(']')
        .or(authority.rsplit_once("]:").map(|(h, _)| h))
    {
        Some(ipv6) => format!("{ipv6}]"),
        None => authority.split(':').next().unwrap_or("").to_string(),
    };
    matches!(host.as_str(), "127.0.0.1" | "[::1]" | "localhost")
}

/// `url` is https, or plain HTTP on this machine, for development and tests,
/// when `issuer` is too. The ID token's signature goes unchecked because of TLS,
/// so nothing else may pass.
fn secure_url(url: &str, issuer: &str) -> bool {
    url.starts_with("https://") || (local_http(url) && local_http(issuer))
}

/// A sign-in in progress, under its state.
#[derive(Debug, Clone)]
pub struct PendingLogin {
    pub nonce: String,
    pub verifier: String,
    /// The Zotero login to return to, if one sent the browser here.
    pub login_session: Option<String>,
}

/// The provider's endpoints.
#[derive(Debug, Clone)]
pub struct Provider {
    pub authorization_endpoint: String,
    token_endpoint: String,
    userinfo_endpoint: Option<String>,
    end_session_endpoint: Option<String>,
}

/// A finished sign-in.
#[derive(Debug, Clone)]
pub struct SignedIn {
    /// The account's ORCID iD, `None` when it has none.
    pub orcid: Option<String>,
    /// Kept for signing out at the provider, which it tells who is leaving.
    pub id_token: String,
}

fn text<'a>(value: &'a Value, field: &str) -> Option<&'a str> {
    value.get(field).and_then(Value::as_str)
}

async fn get_json(request: reqwest::RequestBuilder, what: &str) -> Result<Value, String> {
    let response = request
        .timeout(REQUEST_TIMEOUT)
        .send()
        .await
        .map_err(|e| format!("{what}: {e}"))?;
    let status = response.status();
    let body = response.text().await.map_err(|e| format!("{what}: {e}"))?;
    if !status.is_success() {
        // A provider's error says what is wrong, and holds no secret.
        let parsed: Value = serde_json::from_str(&body).unwrap_or(Value::Null);
        let error = text(&parsed, "error").unwrap_or("no error given");
        return Err(format!("{what}: {status}: {error}"));
    }
    serde_json::from_str(&body).map_err(|e| format!("{what}: not JSON: {e}"))
}

/// Read the provider's configuration, which must name the configured issuer.
pub async fn discover(http: &reqwest::Client, cfg: &OidcConfig) -> Result<Provider, String> {
    let url = format!("{}/.well-known/openid-configuration", cfg.issuer);
    let doc = get_json(http.get(&url), "provider configuration").await?;
    if text(&doc, "issuer").map(|i| i.trim_end_matches('/')) != Some(cfg.issuer.as_str()) {
        return Err(format!("{url} names another issuer"));
    }
    let endpoint = |field: &str| -> Result<String, String> {
        let url = text(&doc, field).ok_or_else(|| format!("no {field}"))?;
        if !secure_url(url, &cfg.issuer) {
            return Err(format!("{field} is not an https URL"));
        }
        Ok(url.to_string())
    };
    Ok(Provider {
        authorization_endpoint: endpoint("authorization_endpoint")?,
        token_endpoint: endpoint("token_endpoint")?,
        userinfo_endpoint: endpoint("userinfo_endpoint").ok(),
        end_session_endpoint: endpoint("end_session_endpoint").ok(),
    })
}

/// PKCE's S256 challenge for `verifier`.
pub fn challenge(verifier: &str) -> String {
    URL_SAFE_NO_PAD.encode(digest::digest(&digest::SHA256, verifier.as_bytes()))
}

/// Where to send the browser to sign in.
pub fn authorization_url(
    provider: &Provider,
    cfg: &OidcConfig,
    redirect_uri: &str,
    state: &str,
    pending: &PendingLogin,
) -> Result<String, String> {
    let query = serde_urlencoded::to_string([
        ("response_type", "code"),
        ("client_id", cfg.client_id.as_str()),
        ("redirect_uri", redirect_uri),
        ("scope", "openid"),
        ("state", state),
        ("nonce", pending.nonce.as_str()),
        ("code_challenge", challenge(&pending.verifier).as_str()),
        ("code_challenge_method", "S256"),
    ])
    .map_err(|e| e.to_string())?;
    let separator = if provider.authorization_endpoint.contains('?') {
        '&'
    } else {
        '?'
    };
    Ok(format!(
        "{}{separator}{query}",
        provider.authorization_endpoint
    ))
}

/// Where to send the browser to end its session at the provider, which then
/// sends it to `back`. `None` if the provider has no such endpoint.
pub fn logout_url(
    provider: &Provider,
    cfg: &OidcConfig,
    id_token: &str,
    back: &str,
) -> Option<String> {
    let endpoint = provider.end_session_endpoint.as_ref()?;
    let query = serde_urlencoded::to_string([
        ("client_id", cfg.client_id.as_str()),
        ("id_token_hint", id_token),
        ("post_logout_redirect_uri", back),
    ])
    .ok()?;
    let separator = if endpoint.contains('?') { '&' } else { '?' };
    Some(format!("{endpoint}{separator}{query}"))
}

/// What the ID token says, if it is for this client and this sign-in.
fn verify_id_token(
    id_token: &str,
    cfg: &OidcConfig,
    nonce: &str,
    now: u64,
) -> Result<Value, String> {
    let payload = id_token
        .split('.')
        .nth(1)
        .ok_or("the ID token is not a JWT")?;
    let payload = URL_SAFE_NO_PAD
        .decode(payload)
        .map_err(|e| format!("the ID token is not base64url: {e}"))?;
    let claims: Value =
        serde_json::from_slice(&payload).map_err(|e| format!("the ID token is not JSON: {e}"))?;

    if text(&claims, "iss").map(|i| i.trim_end_matches('/')) != Some(cfg.issuer.as_str()) {
        return Err("the ID token is from another issuer".to_string());
    }
    let client = cfg.client_id.as_str();
    let for_this_client = match claims.get("aud") {
        Some(Value::String(aud)) => aud == client,
        Some(Value::Array(auds)) => auds.iter().any(|a| a.as_str() == Some(client)),
        _ => false,
    };
    if !for_this_client {
        return Err("the ID token is for another client".to_string());
    }
    if text(&claims, "azp").is_some_and(|azp| azp != client) {
        return Err("the ID token was issued to another client".to_string());
    }
    let expiry = claims.get("exp").and_then(Value::as_u64).unwrap_or(0);
    if expiry.saturating_add(CLOCK_SKEW) <= now {
        return Err("the ID token has expired".to_string());
    }
    if text(&claims, "nonce") != Some(nonce) {
        return Err("the ID token is from another sign-in".to_string());
    }
    if text(&claims, "sub").is_none_or(str::is_empty) {
        return Err("the ID token names no subject".to_string());
    }
    Ok(claims)
}

/// The account's ORCID iD in `claims`, normalized. The claim may hold an iD or
/// its URL.
fn orcid_in(claims: &Value, claim: &str) -> Option<String> {
    profile::normalize_orcid(text(claims, claim)?)
}

/// Finish a sign-in: exchange `code` for tokens.
pub async fn signed_in_orcid(
    http: &reqwest::Client,
    cfg: &OidcConfig,
    provider: &Provider,
    redirect_uri: &str,
    code: &str,
    pending: &PendingLogin,
) -> Result<SignedIn, String> {
    let mut form = vec![
        ("grant_type", "authorization_code"),
        ("code", code),
        ("redirect_uri", redirect_uri),
        ("client_id", cfg.client_id.as_str()),
        ("code_verifier", pending.verifier.as_str()),
    ];
    if let Some(secret) = &cfg.client_secret {
        form.push(("client_secret", secret.as_str()));
    }
    let body = serde_urlencoded::to_string(&form).map_err(|e| e.to_string())?;
    let request = http
        .post(&provider.token_endpoint)
        .header("content-type", "application/x-www-form-urlencoded")
        .body(body);
    let tokens = get_json(request, "token exchange").await?;
    let id_token = text(&tokens, "id_token").ok_or("no ID token in the token response")?;
    let now = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |d| d.as_secs());
    let claims = verify_id_token(id_token, cfg, &pending.nonce, now)?;
    let signed_in = |orcid| SignedIn {
        orcid,
        id_token: id_token.to_string(),
    };
    if let Some(orcid) = orcid_in(&claims, &cfg.orcid_claim) {
        return Ok(signed_in(Some(orcid)));
    }
    // Providers may map a claim to the userinfo response only.
    let (Some(url), Some(access_token)) = (
        provider.userinfo_endpoint.as_ref(),
        text(&tokens, "access_token"),
    ) else {
        return Ok(signed_in(None));
    };
    let info = get_json(http.get(url).bearer_auth(access_token), "userinfo").await?;
    if text(&info, "sub") != text(&claims, "sub") {
        return Err("userinfo is about another account".to_string());
    }
    Ok(signed_in(orcid_in(&info, &cfg.orcid_claim)))
}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    const ORCID: &str = "0000-0003-1419-2405";
    const ISSUER: &str = "https://auth.example.org/realms/r";

    fn config() -> OidcConfig {
        OidcConfig::new(ISSUER, "defter", None, "orcid", "Keycloak").unwrap()
    }

    fn token(claims: Value) -> String {
        let part = |v: &Value| URL_SAFE_NO_PAD.encode(v.to_string());
        format!("{}.{}.sig", part(&json!({"alg": "RS256"})), part(&claims))
    }

    fn good() -> Value {
        json!({"iss": ISSUER, "aud": "defter", "azp": "defter", "exp": 2000, "nonce": "n",
               "sub": "abc", "orcid": ORCID})
    }

    #[test]
    fn checks_the_settings() {
        let new = |issuer| OidcConfig::new(issuer, "c", None, "orcid", "K");
        let cfg = new("https://auth.example.org/realms/r/").unwrap();
        assert_eq!(cfg.issuer, ISSUER);
        for issuer in ["http://auth.example.org", "ftp://auth.example.org", ""] {
            assert!(new(issuer).is_err(), "{issuer}");
        }
        assert!(new("http://127.0.0.1:8080/realms/r").is_ok());
        assert!(new("http://[::1]:8080/realms/r").is_ok());
        assert!(new("http://localhost/realms/r").is_ok());
        // A plain HTTP endpoint is only for a local issuer.
        assert!(!secure_url("http://127.0.0.1/token", ISSUER));
        // Hosts that only start like this machine's.
        for remote in [
            "http://localhost.example.org/realms/r",
            "http://127.0.0.1.nip.io/realms/r",
            "http://localhost@example.org/realms/r",
            "http://127.0.0.1:80@example.org/realms/r",
            "http://[::1].example.org/realms/r",
        ] {
            assert!(new(remote).is_err(), "{remote}");
            assert!(!secure_url(remote, "http://127.0.0.1"), "{remote}");
        }
        // Empty settings mean the defaults, and no secret for a public client.
        let cfg = OidcConfig::new(ISSUER, "c", Some(" ".to_string()), "", " ").unwrap();
        assert_eq!(cfg.orcid_claim, "orcid");
        assert_eq!(cfg.name, "Keycloak");
        assert_eq!(cfg.client_secret, None);
        assert!(OidcConfig::new(ISSUER, " ", None, "", "").is_err());
    }

    #[test]
    fn computes_the_pkce_challenge() {
        // The example of RFC 7636, appendix B.
        assert_eq!(
            challenge("dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"),
            "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"
        );
    }

    #[test]
    fn verifies_the_id_token() {
        let check = |claims: Value| verify_id_token(&token(claims), &config(), "n", 1000);
        assert_eq!(check(good()).unwrap()["sub"], "abc");
        // An audience list naming this client, a trailing slash, clock skew.
        let mut list = good();
        list["aud"] = json!(["other", "defter"]);
        assert!(check(list).is_ok());
        let mut slash = good();
        slash["iss"] = json!(format!("{ISSUER}/"));
        assert!(check(slash).is_ok());
        let mut skew = good();
        skew["exp"] = json!(1000 - CLOCK_SKEW + 1);
        assert!(check(skew).is_ok());

        for (field, bad) in [
            ("iss", json!("https://evil.example/realms/r")),
            ("aud", json!("other")),
            ("aud", json!(["other"])),
            ("azp", json!("other")),
            ("exp", json!(1000 - CLOCK_SKEW)),
            ("nonce", json!("other")),
            ("sub", json!("")),
        ] {
            let mut claims = good();
            claims[field] = bad.clone();
            assert!(check(claims).is_err(), "{field}: {bad}");
        }
        for missing in ["iss", "aud", "exp", "nonce", "sub"] {
            let mut claims = good();
            claims.as_object_mut().unwrap().remove(missing);
            assert!(check(claims).is_err(), "no {missing}");
        }
        for broken in ["", "nodots", "a.%%%.c", "a.bm90anNvbg.c"] {
            assert!(
                verify_id_token(broken, &config(), "n", 1000).is_err(),
                "{broken}"
            );
        }
    }

    #[test]
    fn reads_the_orcid_claim() {
        let orcid = |v: Value| orcid_in(&json!({"orcid": v}), "orcid");
        assert_eq!(orcid(json!(ORCID)).as_deref(), Some(ORCID));
        assert_eq!(
            orcid(json!("https://orcid.org/0000-0003-1419-2405")).as_deref(),
            Some(ORCID)
        );
        assert_eq!(orcid(json!("0000-0003-1419-2404")), None);
        assert_eq!(orcid(json!(1)), None);
        assert_eq!(orcid_in(&json!({}), "orcid"), None);
    }
}