defter 0.5.2

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
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
//! The control database (`control.sqlite3`): the server's users, and what is
//! known about each library outside it. Each library's data is a database of its
//! own (see `registry`). The schema is `migrations/control`.

use std::path::Path;
use std::sync::Arc;

use rusqlite::{Connection, OptionalExtension, params};

use crate::db::{self, Db};
use crate::error::AppError;
use crate::storage::FileScope;

/// A library: a user's own, or a group's.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum LibraryRef {
    User(u64),
    Group(u64),
}

impl LibraryRef {
    /// `u<id>` or `g<id>`: the name of its database file and its backups.
    pub fn parse(name: &str) -> Option<Self> {
        let (kind, id) = name.split_at_checked(1)?;
        let id = id.parse().ok().filter(|_| !id.starts_with('+'))?;
        match kind {
            "u" => Some(LibraryRef::User(id)),
            "g" => Some(LibraryRef::Group(id)),
            _ => None,
        }
    }
}

impl std::fmt::Display for LibraryRef {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            LibraryRef::User(id) => write!(f, "u{id}"),
            LibraryRef::Group(id) => write!(f, "g{id}"),
        }
    }
}

/// A user of the server.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct User {
    /// Their Zotero userID.
    pub id: u64,
    pub orcid: Option<String>,
    pub username: String,
    pub display_name: Option<String>,
    pub profile_hidden: bool,
    pub disabled: bool,
    /// Their files are under `files/`, from before there were several libraries.
    pub legacy_files: bool,
    /// Their storage quota in bytes; `None` for the server's default.
    pub quota_bytes: Option<i64>,
}

impl User {
    /// What to call them: their name from ORCID, else their user name.
    pub fn name(&self) -> &str {
        self.display_name.as_deref().unwrap_or(&self.username)
    }

    /// Where their library's attachment files are.
    pub fn files(&self) -> FileScope {
        if self.legacy_files {
            FileScope::Legacy
        } else {
            FileScope::User(self.id)
        }
    }
}

pub fn now() -> i64 {
    std::time::SystemTime::now()
        .duration_since(std::time::UNIX_EPOCH)
        .map_or(0, |d| d.as_secs() as i64)
}

/// The control database at `path` (created if needed) as one plain connection,
/// for commands that run without the server, such as `defter migrate`.
pub fn open_connection(path: &Path) -> rusqlite::Result<Connection> {
    let mut conn = Connection::open(path)?;
    conn.busy_timeout(std::time::Duration::from_secs(30))?;
    conn.execute_batch("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;")?;
    db::migrate(&mut conn, db::CONTROL)?;
    Ok(conn)
}

const USER_COLUMNS: &str =
    "id, orcid, username, display_name, profile_hidden, disabled, files_layout, quota_bytes";

fn user_row(r: &rusqlite::Row<'_>) -> rusqlite::Result<User> {
    Ok(User {
        id: r.get::<_, i64>(0)? as u64,
        orcid: r.get(1)?,
        username: r.get(2)?,
        display_name: r.get(3)?,
        profile_hidden: r.get(4)?,
        disabled: r.get(5)?,
        legacy_files: r.get::<_, String>(6)? == "legacy",
        quota_bytes: r.get(7)?,
    })
}

pub fn user(conn: &Connection, id: u64) -> rusqlite::Result<Option<User>> {
    conn.query_row(
        &format!("SELECT {USER_COLUMNS} FROM user WHERE id = ?1"),
        [id as i64],
        user_row,
    )
    .optional()
}

pub fn user_by_orcid(conn: &Connection, orcid: &str) -> rusqlite::Result<Option<User>> {
    conn.query_row(
        &format!("SELECT {USER_COLUMNS} FROM user WHERE orcid = ?1"),
        [orcid],
        user_row,
    )
    .optional()
}

pub fn insert_user(conn: &Connection, user: &User) -> rusqlite::Result<()> {
    conn.execute(
        "INSERT INTO user (id, orcid, username, display_name, profile_hidden, disabled,
                           files_layout, quota_bytes, created_at)
         VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
        params![
            user.id as i64,
            user.orcid,
            user.username,
            user.display_name,
            user.profile_hidden,
            user.disabled,
            if user.legacy_files { "legacy" } else { "user" },
            user.quota_bytes,
            now(),
        ],
    )?;
    Ok(())
}

/// The sha256 of an API key, hex: all that is kept of a key handed out.
pub fn key_hash(key: &str) -> String {
    aws_lc_rs::digest::digest(&aws_lc_rs::digest::SHA256, key.as_bytes())
        .as_ref()
        .iter()
        .map(|b| format!("{b:02x}"))
        .collect()
}

/// How long a key's last use goes unrecorded: often enough to tell a device in
/// use from one long gone, without a write per request.
const KEY_USE_PRECISION: i64 = 3600;

/// An invitation to sign in and get a library.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Invite {
    pub orcid: String,
    pub note: Option<String>,
    pub created_at: i64,
    /// Who it became, once used.
    pub used_by: Option<u64>,
}

/// An API key handed out to a user's device.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ApiKey {
    pub id: i64,
    /// Its first characters, to tell it apart.
    pub prefix: String,
    pub name: String,
    pub write: bool,
    pub created_at: i64,
    pub last_used_at: Option<i64>,
}

/// A minted key a request presented: whose it is and what it may do.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyOwner {
    pub key_id: i64,
    pub user_id: u64,
    pub write: bool,
}

/// What signing in with an ORCID iD came to.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SignIn {
    User(User),
    /// Known, but an admin disabled them.
    Disabled,
    /// Neither a user, nor invited, nor an admin.
    NotInvited,
}

/// A user, with what an admin sees of them.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UserOverview {
    pub user: User,
    /// The bytes of their attachment files, as last counted.
    pub bytes_used: i64,
    /// Their devices' keys that are not revoked.
    pub keys: i64,
}

pub fn user_count(conn: &Connection) -> rusqlite::Result<i64> {
    conn.query_row("SELECT count(*) FROM user", [], |r| r.get(0))
}

/// Every library there is, with where its files are: the users' own.
pub fn libraries(conn: &Connection) -> rusqlite::Result<Vec<(LibraryRef, FileScope)>> {
    let mut stmt = conn.prepare("SELECT id, files_layout FROM user ORDER BY id")?;
    let rows = stmt.query_map([], |r| {
        let id = r.get::<_, i64>(0)? as u64;
        let legacy = r.get::<_, String>(1)? == "legacy";
        Ok((
            LibraryRef::User(id),
            if legacy {
                FileScope::Legacy
            } else {
                FileScope::User(id)
            },
        ))
    })?;
    rows.collect()
}

/// The highest version the library has served, 0 if none is known.
pub fn version_high(conn: &Connection, library: LibraryRef) -> rusqlite::Result<i64> {
    Ok(conn
        .query_row(
            "SELECT version_high FROM library_state WHERE library = ?1",
            [library.to_string()],
            |r| r.get(0),
        )
        .optional()?
        .unwrap_or(0))
}

pub fn note_version(conn: &Connection, library: LibraryRef, version: i64) -> rusqlite::Result<()> {
    conn.execute(
        "INSERT INTO library_state (library, version_high) VALUES (?1, ?2)
         ON CONFLICT (library) DO UPDATE SET version_high = excluded.version_high
         WHERE excluded.version_high > library_state.version_high",
        params![library.to_string(), version],
    )?;
    Ok(())
}

pub fn note_usage(conn: &Connection, library: LibraryRef, bytes: i64) -> rusqlite::Result<()> {
    conn.execute(
        "INSERT INTO library_state (library, bytes_used) VALUES (?1, ?2)
         ON CONFLICT (library) DO UPDATE SET bytes_used = excluded.bytes_used
         WHERE excluded.bytes_used != library_state.bytes_used",
        params![library.to_string(), bytes],
    )?;
    Ok(())
}

/// The `meta` key recording that `--oidc-allowed-orcids` was turned into
/// invitations.
const ALLOWED_SEEDED: &str = "allowed_orcids_invited";

pub struct Control {
    pub db: Arc<Db>,
}

impl Control {
    /// Open (creating if needed) the control database at `path`.
    pub fn open(path: &Path) -> Result<Self, AppError> {
        Ok(Control {
            db: Db::open_with(path, db::CONTROL, 4)?,
        })
    }

    /// The installation's stable `Zotero-Server-ID`.
    pub async fn server_id(&self) -> Result<String, AppError> {
        self.db.server_id().await
    }

    pub async fn user(&self, id: u64) -> Result<Option<User>, AppError> {
        self.db.read(move |c| user(c, id)).await
    }

    /// Make `owner` the first user of a new server; anything else is refused
    /// once there are users, so a changed `--user-id` cannot quietly start an
    /// empty library.
    pub async fn ensure_owner(&self, owner: User) -> Result<(), AppError> {
        let id = owner.id;
        let outcome = self
            .db
            .write(move |c| {
                let tx = c.transaction()?;
                if user(&tx, id)?.is_some() {
                    return Ok(None);
                }
                if user_count(&tx)? > 0 {
                    let ids: Vec<i64> = tx
                        .prepare("SELECT id FROM user ORDER BY id")?
                        .query_map([], |r| r.get(0))?
                        .collect::<rusqlite::Result<_>>()?;
                    return Ok(Some(ids));
                }
                insert_user(&tx, &owner)?;
                tx.commit()?;
                Ok(None)
            })
            .await?;
        match outcome {
            None => Ok(()),
            Some(ids) => Err(AppError::Internal(format!(
                "user {id} (DEFTER_USER_ID) is not among this server's users ({ids:?})"
            ))),
        }
    }

    pub async fn set_profile_hidden(&self, id: u64, hidden: bool) -> Result<(), AppError> {
        self.db
            .write(move |c| {
                c.execute(
                    "UPDATE user SET profile_hidden = ?2 WHERE id = ?1",
                    params![id as i64, hidden],
                )?;
                Ok(())
            })
            .await
    }

    pub async fn meta(&self, key: &'static str) -> Result<Option<String>, AppError> {
        self.db.read(move |c| db::get_meta(c, key)).await
    }

    pub async fn set_meta(&self, values: Vec<(&'static str, String)>) -> Result<(), AppError> {
        self.db
            .write(move |c| {
                let tx = c.transaction()?;
                for (key, value) in &values {
                    db::set_meta(&tx, key, value)?;
                }
                tx.commit()
            })
            .await
    }

    pub async fn user_by_orcid(&self, orcid: &str) -> Result<Option<User>, AppError> {
        let orcid = orcid.to_string();
        self.db.read(move |c| user_by_orcid(c, &orcid)).await
    }

    /// Bring what the settings say into the database: `owner_orcid`
    /// (`--orcid`) is the owner's, and the ORCID iDs once allowed to sign in
    /// that are nobody's yet are invited, once: an invitation withdrawn later
    /// stays withdrawn. Without admins, one allowed iD alone was the owner's, as
    /// it was before there were several users, and becomes it if the owner has
    /// none.
    pub async fn reconcile(
        &self,
        owner: u64,
        owner_orcid: Option<String>,
        allowed: Vec<String>,
        admins: bool,
    ) -> Result<(), AppError> {
        let outcome = self
            .db
            .write(move |c| {
                let tx = c.transaction()?;
                let owner_has_orcid = user(&tx, owner)?.is_some_and(|u| u.orcid.is_some());
                let owner_orcid = match (&owner_orcid, allowed.as_slice()) {
                    (Some(orcid), _) => Some(orcid.clone()),
                    (None, [only]) if !admins && !owner_has_orcid => Some(only.clone()),
                    _ => None,
                };
                if let Some(orcid) = &owner_orcid {
                    match user_by_orcid(&tx, orcid)? {
                        Some(user) if user.id != owner => return Ok(Some(user.id)),
                        Some(_) => {}
                        None => {
                            tx.execute(
                                "UPDATE user SET orcid = ?2 WHERE id = ?1",
                                params![owner as i64, orcid],
                            )?;
                        }
                    }
                }
                if db::get_meta(&tx, ALLOWED_SEEDED)?.is_none() {
                    for orcid in &allowed {
                        if user_by_orcid(&tx, orcid)?.is_none() {
                            tx.execute(
                                "INSERT OR IGNORE INTO invite (orcid, invited_by, note, created_at)
                                 VALUES (?1, ?2, 'allowed to sign in by the settings', ?3)",
                                params![orcid, owner as i64, now()],
                            )?;
                        }
                    }
                    db::set_meta(&tx, ALLOWED_SEEDED, "1")?;
                }
                tx.commit()?;
                Ok(None)
            })
            .await?;
        match outcome {
            None => Ok(()),
            Some(other) => Err(AppError::Internal(format!(
                "--orcid belongs to user {other}, not to the owner"
            ))),
        }
    }

    /// Sign in the account with `orcid`: its user, else a new user if invited or
    /// an admin. An admin's iD becomes the owner's when the owner has none yet,
    /// so the owner of a server from before never gets a second, empty library.
    pub async fn sign_in(&self, orcid: &str, admin: bool, owner: u64) -> Result<SignIn, AppError> {
        let orcid = orcid.to_string();
        self.db
            .write(move |c| {
                let tx = c.transaction()?;
                if let Some(user) = user_by_orcid(&tx, &orcid)? {
                    return Ok(if user.disabled {
                        SignIn::Disabled
                    } else {
                        SignIn::User(user)
                    });
                }
                if admin
                    && let Some(mut owner) = user(&tx, owner)?
                    && owner.orcid.is_none()
                {
                    tx.execute(
                        "UPDATE user SET orcid = ?2 WHERE id = ?1",
                        params![owner.id as i64, orcid],
                    )?;
                    tx.commit()?;
                    owner.orcid = Some(orcid);
                    return Ok(if owner.disabled {
                        SignIn::Disabled
                    } else {
                        SignIn::User(owner)
                    });
                }
                let invited: bool = tx.query_row(
                    "SELECT count(*) > 0 FROM invite WHERE orcid = ?1 AND used_by IS NULL",
                    [&orcid],
                    |r| r.get(0),
                )?;
                if !invited && !admin {
                    return Ok(SignIn::NotInvited);
                }
                let id: i64 =
                    tx.query_row("SELECT coalesce(max(id), 0) + 1 FROM user", [], |r| {
                        r.get(0)
                    })?;
                let user = User {
                    id: id as u64,
                    orcid: Some(orcid.clone()),
                    username: orcid.clone(),
                    display_name: None,
                    // Shown once they choose to.
                    profile_hidden: true,
                    disabled: false,
                    legacy_files: false,
                    quota_bytes: None,
                };
                insert_user(&tx, &user)?;
                tx.execute(
                    "UPDATE invite SET used_by = ?2, used_at = ?3 WHERE orcid = ?1",
                    params![orcid, id, now()],
                )?;
                tx.commit()?;
                Ok(SignIn::User(user))
            })
            .await
    }

    pub async fn set_display_name(&self, id: u64, name: String) -> Result<(), AppError> {
        self.db
            .write(move |c| {
                c.execute(
                    "UPDATE user SET display_name = ?2 WHERE id = ?1",
                    params![id as i64, name],
                )?;
                Ok(())
            })
            .await
    }

    pub async fn set_quota(&self, id: u64, quota_bytes: Option<i64>) -> Result<(), AppError> {
        self.db
            .write(move |c| {
                c.execute(
                    "UPDATE user SET quota_bytes = ?2 WHERE id = ?1",
                    params![id as i64, quota_bytes],
                )?;
                Ok(())
            })
            .await
    }

    /// Disable or enable a user. Disabling also revokes their keys, so their
    /// devices stop syncing at once and need a new login once enabled again.
    pub async fn set_disabled(&self, id: u64, disabled: bool) -> Result<(), AppError> {
        self.db
            .write(move |c| {
                let tx = c.transaction()?;
                tx.execute(
                    "UPDATE user SET disabled = ?2 WHERE id = ?1",
                    params![id as i64, disabled],
                )?;
                if disabled {
                    tx.execute(
                        "UPDATE api_key SET revoked_at = ?2
                         WHERE user_id = ?1 AND revoked_at IS NULL",
                        params![id as i64, now()],
                    )?;
                }
                tx.commit()
            })
            .await
    }

    /// Every user, with their usage and devices, for admins.
    pub async fn users(&self) -> Result<Vec<UserOverview>, AppError> {
        self.db
            .read(|c| {
                let columns = USER_COLUMNS
                    .split(", ")
                    .map(|col| format!("u.{col}"))
                    .collect::<Vec<_>>()
                    .join(", ");
                let mut stmt = c.prepare(&format!(
                    "SELECT {columns},
                            coalesce((SELECT bytes_used FROM library_state
                                      WHERE library = 'u' || u.id), 0),
                            (SELECT count(*) FROM api_key k
                             WHERE k.user_id = u.id AND k.revoked_at IS NULL)
                     FROM user u ORDER BY u.id"
                ))?;
                let rows = stmt.query_map([], |r| {
                    Ok(UserOverview {
                        user: user_row(r)?,
                        bytes_used: r.get(8)?,
                        keys: r.get(9)?,
                    })
                })?;
                rows.collect()
            })
            .await
    }

    pub async fn invites(&self) -> Result<Vec<Invite>, AppError> {
        self.db
            .read(|c| {
                let mut stmt = c.prepare(
                    "SELECT orcid, note, created_at, used_by FROM invite
                     ORDER BY used_by IS NOT NULL, created_at DESC, orcid",
                )?;
                let rows = stmt.query_map([], |r| {
                    Ok(Invite {
                        orcid: r.get(0)?,
                        note: r.get(1)?,
                        created_at: r.get(2)?,
                        used_by: r.get::<_, Option<i64>>(3)?.map(|id| id as u64),
                    })
                })?;
                rows.collect()
            })
            .await
    }

    /// Invite `orcid`. False if they are a user already.
    pub async fn invite(
        &self,
        orcid: String,
        by: u64,
        note: Option<String>,
    ) -> Result<bool, AppError> {
        self.db
            .write(move |c| {
                let tx = c.transaction()?;
                if user_by_orcid(&tx, &orcid)?.is_some() {
                    return Ok(false);
                }
                tx.execute(
                    "INSERT INTO invite (orcid, invited_by, note, created_at) VALUES (?1, ?2, ?3, ?4)
                     ON CONFLICT (orcid) DO UPDATE SET note = excluded.note
                     WHERE invite.used_by IS NULL",
                    params![orcid, by as i64, note, now()],
                )?;
                tx.commit()?;
                Ok(true)
            })
            .await
    }

    /// Take back an invitation not used yet.
    pub async fn uninvite(&self, orcid: String) -> Result<(), AppError> {
        self.db
            .write(move |c| {
                c.execute(
                    "DELETE FROM invite WHERE orcid = ?1 AND used_by IS NULL",
                    [orcid],
                )?;
                Ok(())
            })
            .await
    }

    /// A new key for `user_id`'s device, named `name`. Only its hash is kept:
    /// the key itself is returned once.
    pub async fn mint_key(
        &self,
        user_id: u64,
        name: String,
        write: bool,
    ) -> Result<String, AppError> {
        let key = crate::auth::random_hex(32);
        let (hash, prefix) = (key_hash(&key), key[..8].to_string());
        self.db
            .write(move |c| {
                c.execute(
                    "INSERT INTO api_key (user_id, hash, prefix, name, write, created_at)
                     VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
                    params![user_id as i64, hash, prefix, name, write, now()],
                )?;
                Ok(())
            })
            .await?;
        Ok(key)
    }

    /// Whose minted key `key` is, if it is live and its user enabled. Records
    /// its use, at most once per [`KEY_USE_PRECISION`].
    pub async fn key_owner(&self, key: &str) -> Result<Option<KeyOwner>, AppError> {
        let hash = key_hash(key);
        let found = self
            .db
            .read(move |c| {
                c.query_row(
                    "SELECT k.id, k.user_id, k.write, coalesce(k.last_used_at, 0)
                     FROM api_key k JOIN user u ON u.id = k.user_id
                     WHERE k.hash = ?1 AND k.revoked_at IS NULL AND u.disabled = 0",
                    [hash],
                    |r| {
                        Ok((
                            KeyOwner {
                                key_id: r.get(0)?,
                                user_id: r.get::<_, i64>(1)? as u64,
                                write: r.get(2)?,
                            },
                            r.get::<_, i64>(3)?,
                        ))
                    },
                )
                .optional()
            })
            .await?;
        let Some((owner, last_used)) = found else {
            return Ok(None);
        };
        let at = now();
        if at - last_used >= KEY_USE_PRECISION {
            let id = owner.key_id;
            self.db
                .write(move |c| {
                    c.execute(
                        "UPDATE api_key SET last_used_at = ?2 WHERE id = ?1",
                        params![id, at],
                    )
                })
                .await?;
        }
        Ok(Some(owner))
    }

    /// `user_id`'s keys that are not revoked, newest first.
    pub async fn keys(&self, user_id: u64) -> Result<Vec<ApiKey>, AppError> {
        self.db
            .read(move |c| {
                let mut stmt = c.prepare(
                    "SELECT id, prefix, name, write, created_at, last_used_at FROM api_key
                     WHERE user_id = ?1 AND revoked_at IS NULL ORDER BY created_at DESC, id DESC",
                )?;
                let rows = stmt.query_map([user_id as i64], |r| {
                    Ok(ApiKey {
                        id: r.get(0)?,
                        prefix: r.get(1)?,
                        name: r.get(2)?,
                        write: r.get(3)?,
                        created_at: r.get(4)?,
                        last_used_at: r.get(5)?,
                    })
                })?;
                rows.collect()
            })
            .await
    }

    /// Revoke `user_id`'s key `key_id`; false if they have no such live key.
    pub async fn revoke_key(&self, user_id: u64, key_id: i64) -> Result<bool, AppError> {
        self.db
            .write(move |c| {
                Ok(c.execute(
                    "UPDATE api_key SET revoked_at = ?3
                     WHERE id = ?1 AND user_id = ?2 AND revoked_at IS NULL",
                    params![key_id, user_id as i64, now()],
                )? > 0)
            })
            .await
    }

    pub async fn note_usage(&self, library: LibraryRef, bytes: i64) -> Result<(), AppError> {
        self.db.write(move |c| note_usage(c, library, bytes)).await
    }

    pub async fn version_high(&self, library: LibraryRef) -> Result<i64, AppError> {
        self.db.read(move |c| version_high(c, library)).await
    }

    pub async fn note_version(&self, library: LibraryRef, version: i64) -> Result<(), AppError> {
        self.db
            .write(move |c| note_version(c, library, version))
            .await
    }
}

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

    fn owner(id: u64) -> User {
        User {
            id,
            orcid: None,
            username: "owner".into(),
            display_name: None,
            profile_hidden: false,
            disabled: false,
            legacy_files: false,
            quota_bytes: None,
        }
    }

    #[test]
    fn names_libraries() {
        assert_eq!(LibraryRef::User(12).to_string(), "u12");
        assert_eq!(LibraryRef::parse("g3"), Some(LibraryRef::Group(3)));
        assert_eq!(LibraryRef::parse("u12"), Some(LibraryRef::User(12)));
        for bad in ["", "u", "x1", "u-1", "u+1", "u1.sqlite3", "control"] {
            assert_eq!(LibraryRef::parse(bad), None, "{bad}");
        }
    }

    #[tokio::test]
    async fn keeps_users_and_what_libraries_served() {
        let dir = tempfile::tempdir().unwrap();
        let control = Control::open(&dir.path().join("control.sqlite3")).unwrap();
        control.ensure_owner(owner(7)).await.unwrap();
        // Again is fine; another owner once there are users is not.
        control.ensure_owner(owner(7)).await.unwrap();
        let refused = control.ensure_owner(owner(8)).await.unwrap_err();
        assert!(refused.to_string().contains("[7]"), "{refused}");

        let user = control.user(7).await.unwrap().unwrap();
        assert_eq!(user.files(), FileScope::User(7));
        control.set_profile_hidden(7, true).await.unwrap();
        control
            .reconcile(7, Some("0000-0003-1419-2405".into()), Vec::new(), false)
            .await
            .unwrap();
        assert_eq!(control.user(7).await.unwrap().unwrap().name(), "owner");
        control
            .set_display_name(7, "Ada Example".into())
            .await
            .unwrap();
        let user = control.user(7).await.unwrap().unwrap();
        assert_eq!(user.name(), "Ada Example");
        assert!(user.profile_hidden);
        assert_eq!(user.orcid.as_deref(), Some("0000-0003-1419-2405"));

        let library = LibraryRef::User(7);
        assert_eq!(control.version_high(library).await.unwrap(), 0);
        control.note_version(library, 5).await.unwrap();
        // It never goes down.
        control.note_version(library, 3).await.unwrap();
        assert_eq!(control.version_high(library).await.unwrap(), 5);
    }

    #[tokio::test]
    async fn counts_every_change() {
        let dir = tempfile::tempdir().unwrap();
        let control = Control::open(&dir.path().join("control.sqlite3")).unwrap();
        let revision = || async {
            control
                .db
                .read(|c| c.query_row("SELECT n FROM revision", [], |r| r.get::<_, i64>(0)))
                .await
                .unwrap()
        };
        let before = revision().await;
        control.ensure_owner(owner(1)).await.unwrap();
        control.note_version(LibraryRef::User(1), 2).await.unwrap();
        control
            .set_meta(vec![("schema", "{}".into())])
            .await
            .unwrap();
        assert_eq!(revision().await, before + 3);
        // Reading changes nothing.
        control.user(1).await.unwrap();
        assert_eq!(revision().await, before + 3);
    }
}