defter 0.3.3

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
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
//! API keys, the browser login session that hands one to the Zotero client,
//! and the expiring tokens used for uploads and downloads.
//!
//! Keys are provisioned out of band (files or environment) and held in
//! memory, never stored in the database. Each is read/write or read-only.
//! The only path that *hands out* a key is the login session, released only
//! after a human approves it at `/login`, which a deployment puts behind SSO
//! or a private network. Adapted from zhost (<https://github.com/mulatta/zhost>,
//! MIT).

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::Mutex;
use std::time::{Duration, Instant};

use axum::{
    Form, Json,
    extract::{Path as UrlPath, Query, Request, State},
    http::{HeaderMap, Method, StatusCode},
    middleware::Next,
    response::{IntoResponse, Redirect, Response},
};
use serde_json::{Value, json};

use crate::app::AppState;
use crate::ui::{self, LoginView};

/// `bytes` of OS randomness, hex-encoded.
pub fn random_hex(bytes: usize) -> String {
    let mut buf = vec![0u8; bytes];
    getrandom::fill(&mut buf).expect("OS random number generator");
    buf.iter().map(|b| format!("{b:02x}")).collect()
}

// ── keys ─────────────────────────────────────────────────────────────────────

/// What a key may do. Reads are always allowed; `write` gates mutations.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Access {
    pub write: bool,
}

/// Where keys come from, in order of precedence.
#[derive(Debug, Default, Clone)]
pub struct KeySource {
    /// `rw:<path>,ro:<path>,…` — one single-line token file per entry.
    pub manifest: Option<String>,
    /// A single read/write token file.
    pub file: Option<PathBuf>,
    /// A single read/write token (prefer a file: the environment is visible in
    /// `/proc`).
    pub key: Option<String>,
    /// With none of the above: a token kept in this file, generated (mode
    /// 0600) on first start.
    pub generated: PathBuf,
}

#[derive(Debug)]
pub struct Keys {
    map: HashMap<String, Access>,
    /// A read/write key, the one `defter key` prints.
    login_key: String,
}

impl Keys {
    pub fn new(map: HashMap<String, Access>) -> Result<Self, String> {
        let login_key = map
            .iter()
            .filter(|(_, a)| a.write)
            .map(|(k, _)| k.clone())
            .min()
            .ok_or("at least one read/write key must be configured")?;
        Ok(Keys { map, login_key })
    }

    /// Load the keys. Returns them and, when a key was generated, its file.
    pub fn load(source: &KeySource) -> Result<(Self, Option<PathBuf>), String> {
        let mut map = HashMap::new();
        let mut generated = None;
        if let Some(manifest) = source.manifest.as_deref().filter(|m| !m.trim().is_empty()) {
            for entry in manifest.split(',').map(str::trim).filter(|s| !s.is_empty()) {
                let (role, path) = entry
                    .split_once(':')
                    .ok_or_else(|| format!("key entry is not <rw|ro>:<path>: {entry}"))?;
                let write = match role {
                    "rw" => true,
                    "ro" => false,
                    other => return Err(format!("unknown key role '{other}' (rw or ro)")),
                };
                map.insert(read_token(Path::new(path))?, Access { write });
            }
        } else if let Some(file) = &source.file {
            map.insert(read_token(file)?, Access { write: true });
        } else if let Some(key) = source.key.as_deref().filter(|k| !k.trim().is_empty()) {
            map.insert(key.trim().to_string(), Access { write: true });
        } else {
            let (token, created) = generated_token(&source.generated)?;
            if created {
                generated = Some(source.generated.clone());
            }
            map.insert(token, Access { write: true });
        }
        Ok((Keys::new(map)?, generated))
    }

    pub fn access(&self, token: &str) -> Option<Access> {
        self.map.get(token).copied()
    }

    pub fn login_key(&self) -> &str {
        &self.login_key
    }

    /// How many keys are shorter than [`MIN_KEY_LENGTH`].
    pub fn short_keys(&self) -> usize {
        self.map.keys().filter(|k| k.len() < MIN_KEY_LENGTH).count()
    }
}

fn read_token(path: &Path) -> Result<String, String> {
    let token = std::fs::read_to_string(path)
        .map_err(|e| format!("read key file {}: {e}", path.display()))?
        .trim()
        .to_string();
    if token.is_empty() {
        return Err(format!("key file {} is empty", path.display()));
    }
    Ok(token)
}

/// The token in `path`, generating it on first use. Returns whether it was
/// created now.
pub fn generated_token(path: &Path) -> Result<(String, bool), String> {
    if path.exists() {
        return read_token(path).map(|t| (t, false));
    }
    if let Some(dir) = path.parent() {
        std::fs::create_dir_all(dir).map_err(|e| format!("create {}: {e}", dir.display()))?;
    }
    let token = random_hex(32);
    std::fs::write(path, format!("{token}\n"))
        .map_err(|e| format!("write {}: {e}", path.display()))?;
    #[cfg(unix)]
    {
        use std::os::unix::fs::PermissionsExt;
        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o600))
            .map_err(|e| format!("chmod {}: {e}", path.display()))?;
    }
    Ok((token, true))
}

/// The key a request presents: `Zotero-API-Key`, or `Authorization: Bearer`.
pub fn request_key(headers: &HeaderMap) -> Option<&str> {
    headers
        .get("zotero-api-key")
        .and_then(|v| v.to_str().ok())
        .or_else(|| {
            headers
                .get("authorization")
                .and_then(|v| v.to_str().ok())
                .and_then(|v| v.strip_prefix("Bearer "))
        })
        .map(str::trim)
}

/// The `<id>` of a `/users/<id>/…` path.
fn user_segment(path: &str) -> Option<&str> {
    let mut segments = path.split('/');
    segments.find(|s| *s == "users")?;
    segments.next()
}

/// Guard the data API: a known key, write access for mutations, and the
/// configured user's library (`users/0`, the local API's "current user",
/// is accepted as an alias).
pub async fn require_key(State(app): State<AppState>, req: Request, next: Next) -> Response {
    let Some(access) = request_key(req.headers()).and_then(|k| app.keys.access(k)) else {
        return (StatusCode::FORBIDDEN, "Invalid key").into_response();
    };
    let mutating = matches!(
        *req.method(),
        Method::POST | Method::PUT | Method::PATCH | Method::DELETE
    );
    // Unlinking the account in Zotero deletes the key; let a read-only key
    // do that too.
    let unlink = req.method() == Method::DELETE && req.uri().path().ends_with("/keys/current");
    if mutating && !access.write && !unlink {
        return (StatusCode::FORBIDDEN, "Write access denied").into_response();
    }
    if let Some(id) = user_segment(req.uri().path())
        && id != "0"
        && id != app.cfg.user_id.to_string()
    {
        return (StatusCode::FORBIDDEN, "Forbidden").into_response();
    }
    next.run(req).await
}

// ── expiring tokens ──────────────────────────────────────────────────────────

/// Values keyed by unguessable tokens that expire after a fixed lifetime.
/// Expired entries are pruned on insert, so an abandoned one cannot linger.
pub struct Tokens<T> {
    ttl: Duration,
    map: Mutex<HashMap<String, (Instant, T)>>,
}

impl<T: Clone> Tokens<T> {
    pub fn new(ttl: Duration) -> Self {
        Tokens {
            ttl,
            map: Mutex::new(HashMap::new()),
        }
    }

    fn lock(&self) -> std::sync::MutexGuard<'_, HashMap<String, (Instant, T)>> {
        self.map.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// Store `value` under a fresh token. Returns the token and the entries
    /// that had expired.
    pub fn insert(&self, value: T) -> (String, Vec<(String, T)>) {
        let token = random_hex(16);
        let mut map = self.lock();
        let expired_keys: Vec<String> = map
            .iter()
            .filter(|(_, (created, _))| created.elapsed() >= self.ttl)
            .map(|(k, _)| k.clone())
            .collect();
        let expired = expired_keys
            .into_iter()
            .filter_map(|k| map.remove(&k).map(|(_, v)| (k, v)))
            .collect();
        map.insert(token.clone(), (Instant::now(), value));
        (token, expired)
    }

    pub fn get(&self, token: &str) -> Option<T> {
        self.lock()
            .get(token)
            .filter(|(created, _)| created.elapsed() < self.ttl)
            .map(|(_, v)| v.clone())
    }

    /// Change a live entry; false if it is unknown or expired.
    pub fn update(&self, token: &str, f: impl FnOnce(&mut T)) -> bool {
        match self.lock().get_mut(token) {
            Some((created, value)) if created.elapsed() < self.ttl => {
                f(value);
                true
            }
            _ => false,
        }
    }

    pub fn remove(&self, token: &str) -> Option<T> {
        self.lock().remove(token).map(|(_, v)| v)
    }
}

// ── login session ────────────────────────────────────────────────────────────

/// A login session: created pending, approved at `/login` with an API key
/// that may write, which is the key the session then hands to the client.
#[derive(Debug, Clone, Default)]
pub struct LoginSession {
    pub approved_with: Option<String>,
}

/// How long a wrong key on the approval form is answered after: it makes
/// guessing slow, while a person who mistyped hardly notices.
pub const WRONG_KEY_DELAY: Duration = Duration::from_secs(1);

/// The web UI's session cookie, and how long a sign-in lasts.
pub const UI_SESSION_COOKIE: &str = "defter_session";
pub const UI_SESSION_TTL: Duration = Duration::from_secs(7 * 24 * 3600);

/// The value of cookie `name` in the request's `Cookie` headers.
pub fn cookie<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
    headers
        .get_all(axum::http::header::COOKIE)
        .iter()
        .filter_map(|v| v.to_str().ok())
        .flat_map(|v| v.split(';'))
        .filter_map(|pair| pair.trim().split_once('='))
        .find(|(n, _)| *n == name)
        .map(|(_, value)| value)
}

/// Whether a browser sent this request from another site: its `Origin`, when
/// present, is not the public URL's. Requests without one (not from a
/// browser form) pass.
pub fn foreign_origin(headers: &HeaderMap, public_url: &str) -> bool {
    headers
        .get("origin")
        .and_then(|v| v.to_str().ok())
        .is_some_and(|origin| origin.trim_end_matches('/') != public_origin(public_url))
}

/// Keys shorter than this are easy to guess through the approval form.
pub const MIN_KEY_LENGTH: usize = 32;

/// How long a login session stays valid; enrollment is a prompt, one-off act.
pub const SESSION_TTL: Duration = Duration::from_secs(600);

/// `GET /keys/current`: who the key belongs to and what it may do.
pub async fn key_current(State(app): State<AppState>, headers: HeaderMap) -> Response {
    let key = request_key(&headers).unwrap_or_default();
    let write = app.keys.access(key).is_some_and(|a| a.write);
    Json(json!({
        "key": key,
        "userID": app.cfg.user_id,
        "username": app.cfg.username,
        "displayName": app.cfg.username,
        "access": {
            "user": { "library": true, "files": true, "notes": true, "write": write },
            "groups": {}
        },
    }))
    .into_response()
}

/// `DELETE /keys/current`, sent when an account is unlinked in Zotero. Keys
/// are provisioned out of band, so nothing is revoked.
pub async fn key_delete() -> StatusCode {
    StatusCode::NO_CONTENT
}

/// `POST /keys/sessions`: Zotero's "Log In" mints a pending session, opens
/// `loginURL` in the browser, then polls the session for the key.
pub async fn create_session(State(app): State<AppState>) -> Response {
    let (token, _) = app.sessions.insert(LoginSession::default());
    (
        StatusCode::CREATED,
        Json(json!({
            "sessionToken": token,
            "loginURL": format!("{}/login?session={token}", app.cfg.public_url),
        })),
    )
        .into_response()
}

/// `GET /keys/sessions/<token>`: the key once `/login` approved the session;
/// `pending` otherwise, so an unknown or unapproved token never yields one.
pub async fn check_session(
    State(app): State<AppState>,
    UrlPath(token): UrlPath<String>,
) -> Json<Value> {
    let approved = app.sessions.get(&token).and_then(|s| s.approved_with);
    match approved {
        Some(key) => {
            app.sessions.remove(&token);
            Json(json!({
                "status": "completed",
                "apiKey": key,
                "userID": app.cfg.user_id,
                "username": app.cfg.username,
            }))
        }
        None => Json(json!({ "status": "pending" })),
    }
}

pub async fn cancel_session(
    State(app): State<AppState>,
    UrlPath(token): UrlPath<String>,
) -> StatusCode {
    app.sessions.remove(&token);
    StatusCode::NO_CONTENT
}

/// `GET /login?session=<token>`: the consent page Zotero opens in the browser.
/// It only renders the Approve form; approving takes the form's POST.
pub async fn login_page(
    State(app): State<AppState>,
    Query(params): Query<HashMap<String, String>>,
) -> Response {
    if params.get("approved").is_some_and(|v| v == "1") {
        return ui::login_page(StatusCode::OK, LoginView::Approved);
    }
    let Some(token) = params.get("session").filter(|t| !t.is_empty()) else {
        return ui::login_page(StatusCode::BAD_REQUEST, LoginView::Missing);
    };
    match app.sessions.get(token) {
        None => ui::login_page(StatusCode::NOT_FOUND, LoginView::Expired),
        Some(session) if session.approved_with.is_some() => {
            ui::login_page(StatusCode::OK, LoginView::Approved)
        }
        Some(_) => ui::login_page(StatusCode::OK, LoginView::Pending { token, error: None }),
    }
}

/// `POST /login` (form `session=<token>&key=<api key>`): the consent page's
/// Approve button.
///
/// Approving takes an API key that may write. Anyone can create a session, so
/// without that, anyone who reached this page could approve their own session
/// and receive a key. The page itself (`GET /login`) never authorizes, so a
/// prefetch or a cross-site `GET` approves nothing; the POST also rejects a
/// foreign `Origin` and, with `--login-authorized-user`, requires the SSO proxy
/// in front to forward that identity.
pub async fn login_authorize(
    State(app): State<AppState>,
    headers: HeaderMap,
    Form(form): Form<HashMap<String, String>>,
) -> Response {
    if foreign_origin(&headers, &app.cfg.public_url) {
        return ui::login_page(
            StatusCode::FORBIDDEN,
            LoginView::Refused("The approval was sent from another site."),
        );
    }
    if let Some(want) = &app.cfg.login_authorized_user {
        // oauth2-proxy forwards the identity as X-Forwarded-* when it proxies
        // and as X-Auth-Request-* in nginx auth_request mode.
        let identity = [
            "x-auth-request-email",
            "x-forwarded-email",
            "x-auth-request-user",
            "x-forwarded-user",
        ]
        .iter()
        .find_map(|h| headers.get(*h))
        .and_then(|v| v.to_str().ok());
        if !identity.is_some_and(|got| got.eq_ignore_ascii_case(want)) {
            return ui::login_page(
                StatusCode::FORBIDDEN,
                LoginView::Refused("You are not allowed to approve logins to this library."),
            );
        }
    }
    let Some(token) = form.get("session") else {
        return ui::login_page(StatusCode::BAD_REQUEST, LoginView::Missing);
    };
    if app.sessions.get(token).is_none() {
        return ui::login_page(StatusCode::NOT_FOUND, LoginView::Expired);
    }
    let key = form.get("key").map(|k| k.trim()).unwrap_or_default();
    let error = match app.keys.access(key) {
        Some(Access { write: true }) => None,
        Some(Access { write: false }) => {
            Some("This key may only read; approve with one that may write.")
        }
        None => Some("That is not an API key of this library."),
    };
    if let Some(error) = error {
        tracing::warn!("login approval with a wrong or read-only key");
        tokio::time::sleep(WRONG_KEY_DELAY).await;
        return ui::login_page(
            StatusCode::FORBIDDEN,
            LoginView::Pending {
                token,
                error: Some(error),
            },
        );
    }
    let key = key.to_string();
    if app.sessions.update(token, |s| s.approved_with = Some(key)) {
        Redirect::to("/login?approved=1").into_response()
    } else {
        ui::login_page(StatusCode::NOT_FOUND, LoginView::Expired)
    }
}

/// `scheme://host[:port]` of the public URL, as browsers send it in `Origin`.
fn public_origin(public_url: &str) -> &str {
    let url = public_url.trim_end_matches('/');
    let after_scheme = url.find("://").map(|i| i + 3).unwrap_or(0);
    match url[after_scheme..].find('/') {
        Some(i) => &url[..after_scheme + i],
        None => url,
    }
}

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

    #[test]
    fn keys_load_by_precedence() {
        let dir = tempfile::tempdir().unwrap();
        let rw = dir.path().join("rw");
        let ro = dir.path().join("ro");
        std::fs::write(&rw, "write-token\n").unwrap();
        std::fs::write(&ro, "read-token").unwrap();
        let source = KeySource {
            manifest: Some(format!("rw:{},ro:{}", rw.display(), ro.display())),
            key: Some("ignored".into()),
            generated: dir.path().join("api-key"),
            ..Default::default()
        };
        let (keys, generated) = Keys::load(&source).unwrap();
        assert!(generated.is_none());
        assert_eq!(keys.access("write-token"), Some(Access { write: true }));
        assert_eq!(keys.access("read-token"), Some(Access { write: false }));
        assert_eq!(keys.access("ignored"), None);
        assert_eq!(keys.login_key(), "write-token");

        let only_ro = KeySource {
            manifest: Some(format!("ro:{}", ro.display())),
            ..Default::default()
        };
        assert!(Keys::load(&only_ro).is_err());
    }

    #[test]
    fn a_generated_key_is_kept() {
        let dir = tempfile::tempdir().unwrap();
        let source = KeySource {
            generated: dir.path().join("sub/api-key"),
            ..Default::default()
        };
        let (first, generated) = Keys::load(&source).unwrap();
        assert!(generated.is_some());
        let (second, generated) = Keys::load(&source).unwrap();
        assert!(generated.is_none());
        assert_eq!(first.login_key(), second.login_key());
        assert_eq!(first.login_key().len(), 64);
    }

    #[test]
    fn tokens_expire() {
        let tokens = Tokens::new(Duration::from_millis(0));
        let (token, _) = tokens.insert(1);
        assert_eq!(tokens.get(&token), None);
        let (_, expired) = tokens.insert(2);
        assert_eq!(expired, vec![(token, 1)]);

        let tokens = Tokens::new(Duration::from_secs(60));
        let (token, _) = tokens.insert(1);
        assert!(tokens.update(&token, |v| *v = 2));
        assert_eq!(tokens.remove(&token), Some(2));
        assert!(!tokens.update(&token, |v| *v = 3));
    }

    #[test]
    fn paths_and_origins() {
        assert_eq!(user_segment("/api/users/1/items"), Some("1"));
        assert_eq!(user_segment("/users/0/items/top"), Some("0"));
        assert_eq!(user_segment("/keys/current"), None);
        assert_eq!(
            public_origin("https://z.example.org/"),
            "https://z.example.org"
        );
        assert_eq!(
            public_origin("https://z.example.org/sub"),
            "https://z.example.org"
        );
        assert_eq!(
            public_origin("http://127.0.0.1:8189"),
            "http://127.0.0.1:8189"
        );
    }
}