GITv
master
auth.rs911 lines, 37.5 KB
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
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
//! Sign-in for the web browser: one account, a password hashed with Argon2id, and a TOTP second
//! factor ([RFC 6238]) that works with any authenticator app.
//!
//! The account lives in one small file (see [`auth_path`]), readable only by its owner:
//!
//! ```text
//! user=admin
//! password=$argon2id$v=19$m=19456,t=2,p=1$...
//! totp=JBSWY3DPEHPK3PXP...
//! ```
//!
//! [RFC 6238]: https://www.rfc-editor.org/rfc/rfc6238

use std::fs;
use std::path::{Path, PathBuf};

use argon2::Argon2;
use argon2::password_hash::phc::PasswordHash;
use argon2::password_hash::{PasswordHasher, PasswordVerifier};
use data_encoding::BASE32_NOPAD;
use hmac::{Hmac, KeyInit, Mac};
use sha1::Sha1;
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;

/// The account name a first `gitv-web setup` uses unless told otherwise.
pub const DEFAULT_USER: &str = "admin";
/// How authenticator apps label the account.
pub const ISSUER: &str = "GITv";
/// Shortest password accepted, in characters.
pub const MIN_PASSWORD: usize = 12;
/// Longest password accepted, in characters: hashing is deliberately slow, so this bounds it.
pub const MAX_PASSWORD: usize = 1024;
/// Seconds per TOTP code.
pub const TOTP_STEP: u64 = 30;
/// Digits per TOTP code.
pub const TOTP_DIGITS: u32 = 6;
/// Bytes in a TOTP secret: 160 bits, as RFC 4226 recommends for HMAC-SHA1.
const TOTP_SECRET_BYTES: usize = 20;
/// Characters for generated passwords: letters and digits without look-alikes (0/O, 1/l/I).
const PASSWORD_ALPHABET: &[u8] = b"abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789";

/// Why sign-in setup or a credential operation failed.
#[derive(Debug, thiserror::Error)]
pub enum AuthError {
    #[error("sign-in isn't set up yet: {} doesn't exist; run `gitv-web setup`", .0.display())]
    NotSetUp(PathBuf),
    #[error("sign-in is already set up in {}; use --force to replace it", .0.display())]
    AlreadySetUp(PathBuf),
    #[error("couldn't read {}: {source}", path.display())]
    Read { path: PathBuf, source: std::io::Error },
    #[error("couldn't write {}: {source}", path.display())]
    Write { path: PathBuf, source: std::io::Error },
    #[error("{} is malformed: {reason}", path.display())]
    Malformed { path: PathBuf, reason: &'static str },
    #[error("use at least {MIN_PASSWORD} characters")]
    PasswordTooShort,
    #[error("use at most {MAX_PASSWORD} characters")]
    PasswordTooLong,
    #[error("couldn't hash the password: {0}")]
    Hash(String),
    #[error("couldn't get random bytes: {0}")]
    Random(String),
    #[error("the account changed meanwhile (someone else changed the password or reset it); nothing was saved")]
    Changed,
    #[error("use a user name of 1 to {MAX_USER} visible characters, without spaces")]
    BadUser,
    #[error("couldn't hand {} to the service account: {source}", path.display())]
    Ownership { path: PathBuf, source: nix::errno::Errno },
}

/// How long a browser that signed in stays trusted, in seconds: 90 days. A trusted browser
/// isn't held back by the cap on failed sign-ins from every client together, so an attack
/// spread over many addresses can't lock the owner out (see the `throttle` module).
pub const DEVICE_LIFETIME: u64 = 90 * 24 * 60 * 60;

/// Longest account name accepted, in characters.
pub const MAX_USER: usize = 64;

/// Check an account name: 1 to [`MAX_USER`] characters, none of them whitespace or control
/// characters, so it reads back from the account file exactly as written.
///
/// # Errors
/// [`AuthError::BadUser`] otherwise.
pub fn check_user(user: &str) -> Result<(), AuthError> {
    let length = user.chars().count();
    let visible = user.chars().all(|c| !c.is_whitespace() && !c.is_control());
    if (1..=MAX_USER).contains(&length) && visible { Ok(()) } else { Err(AuthError::BadUser) }
}

/// Who files written for the web service must belong to. `None` leaves them with whoever
/// writes them; a root-run command passes the service account's ids (see [`service_owner`]).
pub type Owner = Option<(nix::unistd::Uid, nix::unistd::Gid)>;

/// Run as root, the `gitv-web` service account, which must own everything it reads and
/// changes; otherwise (or without that account) `None`.
///
/// # Errors
/// [`AuthError::Read`] if the account database can't be read.
pub fn service_owner() -> Result<Owner, AuthError> {
    if !nix::unistd::geteuid().is_root() {
        return Ok(None);
    }
    let user = nix::unistd::User::from_name("gitv-web")
        .map_err(|e| AuthError::Read { path: PathBuf::from("/etc/passwd"), source: e.into() })?;
    Ok(user.map(|u| (u.uid, u.gid)))
}

/// Give an open file to `owner`, through its handle.
fn hand_over(file: &fs::File, path: &Path, owner: Owner) -> Result<(), AuthError> {
    let Some((uid, gid)) = owner else { return Ok(()) };
    nix::unistd::fchown(file, Some(uid), Some(gid))
        .map_err(|source| AuthError::Ownership { path: path.to_path_buf(), source })
}

/// How [`Credentials`] are published.
enum Publish {
    Replace,
    OnlyIfAbsent,
}

/// Exclusive permission to change the account file, held by every writer (`setup`,
/// `password`, the web Account page) across processes, so their read-check-write steps can't
/// interleave. Released when dropped.
pub struct WriteLock {
    _lock: nix::fcntl::Flock<fs::File>,
}

/// Take the account file's [`WriteLock`], waiting for any other writer to finish. The lock file
/// is given to `owner`, so a root-run command never leaves one the service can't open.
///
/// # Errors
/// [`AuthError::Write`] if the lock file can't be opened or locked.
pub fn lock_for_writing(path: &Path, owner: Owner) -> Result<WriteLock, AuthError> {
    use nix::fcntl::{OFlag, openat};
    use nix::sys::stat::Mode;
    use std::os::unix::fs::MetadataExt;

    let lock_path = sibling(path, "lock");
    let write_error = |source| AuthError::Write { path: lock_path.clone(), source };
    let parent = path.parent().filter(|p| !p.as_os_str().is_empty()).unwrap_or(Path::new("."));
    let directory = gitv_core::open_dir(parent).map_err(write_error)?;
    let name = lock_path.file_name().expect("sibling has a file name");
    let flags = OFlag::O_NOFOLLOW | OFlag::O_CLOEXEC | OFlag::O_NONBLOCK | OFlag::O_WRONLY;
    let private = Mode::S_IRUSR | Mode::S_IWUSR;
    let (fd, created) = match openat(&directory, name, flags | OFlag::O_CREAT | OFlag::O_EXCL, private) {
        Ok(fd) => (fd, true),
        Err(nix::errno::Errno::EEXIST) => {
            (openat(&directory, name, flags, Mode::empty()).map_err(|e| write_error(e.into()))?, false)
        }
        Err(error) => return Err(write_error(error.into())),
    };
    let file = fs::File::from(fd);
    let meta = file.metadata().map_err(write_error)?;
    let expected =
        if created { nix::unistd::geteuid() } else { owner.map_or_else(nix::unistd::geteuid, |(service, _)| service) };
    if !meta.is_file() || meta.nlink() != 1 || meta.mode() & 0o077 != 0 || meta.uid() != expected.as_raw() {
        return Err(write_error(std::io::Error::other("unsafe account lock file")));
    }
    // Only change ownership of an inode this open created exclusively.
    if created {
        hand_over(&file, &lock_path, owner)?;
    }
    let lock = nix::fcntl::Flock::lock(file, nix::fcntl::FlockArg::LockExclusive)
        .map_err(|(_, e)| AuthError::Write { path: lock_path, source: e.into() })?;
    Ok(WriteLock { _lock: lock })
}

/// Change the password, but only if the account is still the one that authorized the change:
/// `authorized` is the [fingerprint](Credentials::fingerprint) the caller checked. A reset or
/// another change in between makes this refuse rather than overwrite it. Returns the new
/// fingerprint.
///
/// # Errors
/// [`AuthError::Changed`] if the account changed since it was checked, a password outside
/// the rules, or any error reading or writing the file.
pub fn change_password(
    path: &Path,
    authorized: [u8; 32],
    new_password: &str,
    owner: Owner,
) -> Result<[u8; 32], AuthError> {
    check_new_password(new_password)?;
    let _lock = lock_for_writing(path, owner)?;
    let mut credentials = Credentials::load(path)?;
    if credentials.fingerprint() != authorized {
        return Err(AuthError::Changed);
    }
    credentials.set_password(new_password)?;
    credentials.save(path, owner)?;
    Ok(credentials.fingerprint())
}

/// Check an authenticator code and use it up, for good: the last accepted time step is kept in
/// a file beside the account (tied to the authenticator secret), read and written under the
/// [`WriteLock`], so a code works once across restarts and across processes. Returns whether
/// the code was accepted.
///
/// # Errors
/// [`AuthError::Write`] or [`AuthError::Read`] if the record can't be read or written; the
/// code is then not accepted.
pub fn consume_code(path: &Path, credentials: &Credentials, code: &str, unix_seconds: u64) -> Result<bool, AuthError> {
    let _lock = lock_for_writing(path, None)?;
    if Credentials::load(path)?.fingerprint() != credentials.fingerprint() {
        return Ok(false);
    }
    let record = sibling(path, "used");
    let secret_id = data_encoding::HEXLOWER.encode(&Sha256::digest(&credentials.totp_secret));
    let last_step = match fs::read_to_string(&record) {
        Ok(text) => {
            let malformed = || AuthError::Malformed { path: record.clone(), reason: "invalid replay record" };
            let (id, step) = text.trim_end_matches('\n').split_once(' ').ok_or_else(malformed)?;
            if id.len() != 64 || !id.bytes().all(|b| b.is_ascii_hexdigit() && !b.is_ascii_uppercase()) {
                return Err(malformed());
            }
            let step = step.parse::<u64>().map_err(|_| malformed())?;
            if id == secret_id { step } else { 0 }
        }
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => 0,
        Err(source) => return Err(AuthError::Read { path: record, source }),
    };
    let Some(step) = credentials.verify_code(code, unix_seconds, last_step) else { return Ok(false) };
    write_replacing(&record, format!("{secret_id} {step}\n").as_bytes(), None)?;
    Ok(true)
}

/// `.NAME.SUFFIX` beside `path`.
fn sibling(path: &Path, suffix: &str) -> PathBuf {
    let name = path.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
    path.with_file_name(format!(".{name}.{suffix}"))
}

/// Write `contents` to `path` atomically through a unique temporary file, private to its
/// owner, replacing what's there.
fn write_replacing(path: &Path, contents: &[u8], owner: Owner) -> Result<(), AuthError> {
    write_atomically(path, contents, owner, Publish::Replace)
}

/// Write through a unique temporary file, given to `owner` by handle before it's published, so
/// the published file is never anyone else's even for a moment.
fn write_atomically(path: &Path, contents: &[u8], owner: Owner, mode: Publish) -> Result<(), AuthError> {
    let replace = matches!(mode, Publish::Replace);
    gitv_core::publish_file(path, contents, 0o600, replace, |file| hand_over(file, path, owner)).map_err(|e| match e {
        // One atomic step that fails if the name exists, so two first setups can't both win.
        gitv_core::PublishError::Exists => AuthError::AlreadySetUp(path.to_path_buf()),
        gitv_core::PublishError::Io(source) => AuthError::Write { path: path.to_path_buf(), source },
        gitv_core::PublishError::Prepare(error) => error,
    })
}

/// Where the account file lives: `$GITV_WEB_AUTH`, or `/var/lib/gitv-web/login`.
pub fn auth_path() -> PathBuf {
    std::env::var_os("GITV_WEB_AUTH").map_or_else(|| PathBuf::from("/var/lib/gitv-web/login"), PathBuf::from)
}

/// `N` bytes from the operating system's secure random source.
///
/// # Errors
/// [`AuthError::Random`] if the source is unavailable.
pub fn random_bytes<const N: usize>() -> Result<[u8; N], AuthError> {
    let mut bytes = [0u8; N];
    getrandom::fill(&mut bytes).map_err(|e| AuthError::Random(e.to_string()))?;
    Ok(bytes)
}

/// A new random password: 20 characters from an alphabet of 56 without look-alikes (about 116
/// bits), in four groups of five so it can be read and typed.
///
/// # Errors
/// [`AuthError::Random`] if the random source is unavailable.
pub fn generate_password() -> Result<String, AuthError> {
    // Rejection sampling: bytes at or above the largest multiple of the alphabet size would
    // favour its first letters, so they're thrown away.
    let limit = 256 - 256 % PASSWORD_ALPHABET.len();
    let mut chars = Vec::with_capacity(20);
    while chars.len() < 20 {
        for byte in random_bytes::<32>()? {
            if usize::from(byte) < limit && chars.len() < 20 {
                chars.push(PASSWORD_ALPHABET[usize::from(byte) % PASSWORD_ALPHABET.len()]);
            }
        }
    }
    let groups: Vec<&str> = chars.chunks(5).map(|g| std::str::from_utf8(g).unwrap_or_default()).collect();
    Ok(groups.join("-"))
}

/// Check a new password against the length rules.
///
/// # Errors
/// [`AuthError::PasswordTooShort`] or [`AuthError::PasswordTooLong`].
pub fn check_new_password(password: &str) -> Result<(), AuthError> {
    match password.chars().count() {
        n if n < MIN_PASSWORD => Err(AuthError::PasswordTooShort),
        n if n > MAX_PASSWORD => Err(AuthError::PasswordTooLong),
        _ => Ok(()),
    }
}

/// Hash a password with Argon2id and a random salt, as a PHC string.
///
/// # Errors
/// [`AuthError::Hash`] if hashing fails.
pub fn hash_password(password: &str) -> Result<String, AuthError> {
    Argon2::default()
        .hash_password(password.as_bytes())
        .map(|h| h.to_string())
        .map_err(|e| AuthError::Hash(e.to_string()))
}

/// The TOTP code for `secret` at time step `step` (HMAC-SHA1, six digits).
pub fn totp_code(secret: &[u8], step: u64) -> u32 {
    let Ok(mut mac) = Hmac::<Sha1>::new_from_slice(secret) else {
        return 0; // Unreachable: HMAC accepts keys of any length.
    };
    mac.update(&step.to_be_bytes());
    let digest = mac.finalize().into_bytes();
    // RFC 4226 dynamic truncation.
    let offset = usize::from(digest[digest.len() - 1] & 0x0f);
    let value = u32::from_be_bytes([digest[offset], digest[offset + 1], digest[offset + 2], digest[offset + 3]]);
    (value & 0x7fff_ffff) % 10u32.pow(TOTP_DIGITS)
}

/// The TOTP time step for a Unix time.
pub fn totp_step(unix_seconds: u64) -> u64 {
    unix_seconds / TOTP_STEP
}

/// The web account: its name, its password's hash and its TOTP secret.
pub struct Credentials {
    user: String,
    password_hash: String,
    totp_secret: Vec<u8>,
}

impl Credentials {
    /// A new account with a new random TOTP secret.
    ///
    /// # Errors
    /// [`AuthError::BadUser`] for an unusable name, [`AuthError::PasswordTooShort`]/
    /// [`AuthError::PasswordTooLong`] for a password outside the rules, [`AuthError::Hash`] or
    /// [`AuthError::Random`] if hashing or randomness fails.
    pub fn new(user: &str, password: &str) -> Result<Credentials, AuthError> {
        check_user(user)?;
        check_new_password(password)?;
        Ok(Credentials {
            user: user.to_string(),
            password_hash: hash_password(password)?,
            totp_secret: random_bytes::<TOTP_SECRET_BYTES>()?.to_vec(),
        })
    }

    /// Read the account file.
    ///
    /// # Errors
    /// [`AuthError::NotSetUp`] if it doesn't exist, [`AuthError::Read`] if it can't be read, and
    /// [`AuthError::Malformed`] if a field is missing or invalid.
    pub fn load(path: &Path) -> Result<Credentials, AuthError> {
        let text = fs::read_to_string(path).map_err(|source| match source.kind() {
            std::io::ErrorKind::NotFound => AuthError::NotSetUp(path.to_path_buf()),
            _ => AuthError::Read { path: path.to_path_buf(), source },
        })?;
        Credentials::parse(&text).map_err(|reason| AuthError::Malformed { path: path.to_path_buf(), reason })
    }

    fn parse(text: &str) -> Result<Credentials, &'static str> {
        let field = |name: &str| {
            text.lines().filter(|l| !l.starts_with('#')).find_map(|l| l.strip_prefix(name)?.strip_prefix('='))
        };
        let user = field("user").filter(|u| check_user(u).is_ok()).ok_or("no valid user")?;
        let password_hash = field("password").ok_or("no password")?;
        PasswordHash::new(password_hash).map_err(|_| "the password hash isn't a PHC string")?;
        let totp_secret =
            BASE32_NOPAD.decode(field("totp").ok_or("no totp secret")?.as_bytes()).map_err(|_| "bad totp secret")?;
        if totp_secret.len() < 16 {
            return Err("the totp secret is too short");
        }
        Ok(Credentials { user: user.to_string(), password_hash: password_hash.to_string(), totp_secret })
    }

    /// Write the account file atomically, replacing any existing one, readable and writable by
    /// its owner only, and given to `owner` before it's published. Hold a [`WriteLock`] around
    /// the read-check-write that leads here.
    ///
    /// # Errors
    /// [`AuthError::Write`] if the file can't be written or renamed, [`AuthError::Ownership`]
    /// if it can't be handed over.
    pub fn save(&self, path: &Path, owner: Owner) -> Result<(), AuthError> {
        write_replacing(path, self.serialize().as_bytes(), owner)
    }

    /// Like [`Credentials::save`], but only if no account file exists yet, so two first-time
    /// setups can't both succeed with different accounts.
    ///
    /// # Errors
    /// [`AuthError::AlreadySetUp`] if an account file appeared, or as [`Credentials::save`].
    pub fn save_new(&self, path: &Path, owner: Owner) -> Result<(), AuthError> {
        write_atomically(path, self.serialize().as_bytes(), owner, Publish::OnlyIfAbsent)
    }

    fn serialize(&self) -> String {
        format!(
            "# GITv web sign-in. Keep this private: anyone who can read it can attack the password offline.\n\
             user={}\npassword={}\ntotp={}\n",
            self.user,
            self.password_hash,
            self.totp_secret_base32()
        )
    }

    /// The account name.
    pub fn user(&self) -> &str {
        &self.user
    }

    /// Whether `user` is the account name, compared in constant time.
    pub fn user_matches(&self, user: &str) -> bool {
        self.user.as_bytes().ct_eq(user.as_bytes()).into()
    }

    /// Whether `password` is the account's password. Deliberately slow (Argon2id).
    pub fn verify_password(&self, password: &str) -> bool {
        PasswordHash::new(&self.password_hash)
            .is_ok_and(|hash| Argon2::default().verify_password(password.as_bytes(), &hash).is_ok())
    }

    /// Replace the password.
    ///
    /// # Errors
    /// [`AuthError::PasswordTooShort`]/[`AuthError::PasswordTooLong`] or [`AuthError::Hash`].
    pub fn set_password(&mut self, password: &str) -> Result<(), AuthError> {
        check_new_password(password)?;
        self.password_hash = hash_password(password)?;
        Ok(())
    }

    /// The TOTP secret in base32, as authenticator apps take it.
    pub fn totp_secret_base32(&self) -> String {
        BASE32_NOPAD.encode(&self.totp_secret)
    }

    /// The `otpauth://` link authenticator apps scan.
    pub fn otpauth_uri(&self) -> String {
        let user = url_component(&self.user);
        format!(
            "otpauth://totp/{ISSUER}:{user}?secret={}&issuer={ISSUER}&algorithm=SHA1&digits={TOTP_DIGITS}&period={TOTP_STEP}",
            self.totp_secret_base32()
        )
    }

    /// The time step a six-digit `code` is valid for, allowing one step of clock drift either
    /// way, and only steps after `after_step` so a code can't be used twice.
    pub fn verify_code(&self, code: &str, unix_seconds: u64, after_step: u64) -> Option<u64> {
        let digits = TOTP_DIGITS as usize;
        if code.len() != digits || !code.bytes().all(|b| b.is_ascii_digit()) {
            return None;
        }
        let now = totp_step(unix_seconds);
        (now.saturating_sub(1)..=now + 1).filter(|step| *step > after_step).find(|step| {
            let expected = format!("{:0digits$}", totp_code(&self.totp_secret, *step));
            bool::from(expected.as_bytes().ct_eq(code.as_bytes()))
        })
    }

    /// A token marking a browser that has signed in, good for [`DEVICE_LIFETIME`] from
    /// `unix_seconds`: the expiry, then an HMAC of it under a key derived from the authenticator
    /// secret. Nothing is stored, so it outlives restarts; a new secret (`gitv-web setup
    /// --force`) voids every one.
    pub fn device_token(&self, unix_seconds: u64) -> String {
        let expires = unix_seconds.saturating_add(DEVICE_LIFETIME).to_be_bytes();
        let mut token = expires.to_vec();
        token.extend_from_slice(&self.device_mac(&expires));
        data_encoding::BASE64URL_NOPAD.encode(&token)
    }

    /// Whether `token` is one [`Credentials::device_token`] made for this account and it hasn't
    /// expired at `unix_seconds`. Compared in constant time.
    pub fn trusts_device(&self, token: &str, unix_seconds: u64) -> bool {
        let Ok(token) = data_encoding::BASE64URL_NOPAD.decode(token.as_bytes()) else { return false };
        let Some((expires, tag)) = token.split_first_chunk::<8>() else { return false };
        u64::from_be_bytes(*expires) > unix_seconds && bool::from(self.device_mac(expires).as_slice().ct_eq(tag))
    }

    fn device_mac(&self, expires: &[u8; 8]) -> [u8; 32] {
        // A key of its own, derived from the secret, so device tokens and codes never share one.
        let mut derive = Hmac::<Sha256>::new_from_slice(&self.totp_secret).expect("HMAC takes any key length");
        derive.update(b"gitv-web trusted device v1");
        let key = derive.finalize().into_bytes();
        let mut mac = Hmac::<Sha256>::new_from_slice(&key).expect("HMAC takes any key length");
        mac.update(expires);
        mac.finalize().into_bytes().into()
    }

    /// A digest of the password hash and TOTP secret. Sessions remember it, so changing either
    /// (here or with `gitv-web password`/`setup`) signs every other session out.
    pub fn fingerprint(&self) -> [u8; 32] {
        let mut hasher = Sha256::new();
        hasher.update(self.user.as_bytes());
        hasher.update([0]);
        hasher.update(self.password_hash.as_bytes());
        hasher.update([0]);
        hasher.update(&self.totp_secret);
        hasher.finalize().into()
    }
}

/// Percent-encode everything but unreserved characters, for the label in an `otpauth://` link.
fn url_component(value: &str) -> String {
    value
        .bytes()
        .map(|b| match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(),
            _ => format!("%{b:02X}"),
        })
        .collect()
}

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

    /// A fresh, empty directory for one test.
    fn scratch(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("gitv-auth-{name}-{}", std::process::id()));
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// The shared secret of RFC 6238's SHA-1 test vectors.
    const RFC_SECRET: &[u8] = b"12345678901234567890";

    fn account() -> Credentials {
        Credentials {
            user: "Um9i".into(),
            password_hash: hash_password("correct horse battery").unwrap(),
            totp_secret: RFC_SECRET.to_vec(),
        }
    }

    mod totp_code {
        use super::*;

        #[test]
        fn matches_the_rfc_6238_test_vectors() {
            // RFC 6238 appendix B gives eight-digit codes; six-digit codes are their last six.
            let vectors = [
                (59, 94_287_082),
                (1_111_111_109, 7_081_804),
                (1_111_111_111, 14_050_471),
                (1_234_567_890, 89_005_924),
                (2_000_000_000, 69_279_037),
                (20_000_000_000, 65_353_130),
            ];
            for (time, eight_digits) in vectors {
                assert_eq!(totp_code(RFC_SECRET, totp_step(time)), eight_digits % 1_000_000, "at time {time}");
            }
        }
    }

    mod verify_code {
        use super::*;

        #[test]
        fn accepts_the_current_code() {
            assert_eq!(account().verify_code("287082", 59, 0), Some(1));
        }

        #[test]
        fn accepts_one_step_of_drift_either_way() {
            let code = format!("{:06}", totp_code(RFC_SECRET, 100));
            assert_eq!(account().verify_code(&code, 101 * TOTP_STEP, 0), Some(100));
            assert_eq!(account().verify_code(&code, 99 * TOTP_STEP, 0), Some(100));
        }

        #[test]
        fn rejects_codes_two_steps_away() {
            let code = format!("{:06}", totp_code(RFC_SECRET, 100));
            assert_eq!(account().verify_code(&code, 102 * TOTP_STEP, 0), None);
        }

        #[test]
        fn rejects_a_code_already_used() {
            assert_eq!(account().verify_code("287082", 59, 1), None);
        }

        #[test]
        fn rejects_malformed_codes() {
            for code in ["", "28708", "2870822", "28708a", " 287082", "287082"] {
                assert_eq!(account().verify_code(code, 59, 0), None, "{code:?}");
            }
        }
    }

    mod passwords {
        use super::*;

        #[test]
        fn generated_passwords_are_four_groups_of_five_from_the_alphabet() {
            let password = generate_password().unwrap();
            let groups: Vec<&str> = password.split('-').collect();
            assert_eq!(groups.iter().map(|g| g.len()).collect::<Vec<_>>(), [5, 5, 5, 5], "{password}");
            assert!(groups.concat().bytes().all(|b| PASSWORD_ALPHABET.contains(&b)), "{password}");
        }

        #[test]
        fn generated_passwords_differ() {
            assert_ne!(generate_password().unwrap(), generate_password().unwrap());
        }

        #[test]
        fn generated_passwords_meet_the_rules() {
            assert!(check_new_password(&generate_password().unwrap()).is_ok());
        }

        #[test]
        fn short_passwords_are_refused() {
            assert!(matches!(check_new_password("eleven char"), Err(AuthError::PasswordTooShort)));
        }

        #[test]
        fn length_counts_characters_not_bytes() {
            // Six two-byte characters are twelve bytes but only six characters.
            assert!(matches!(check_new_password("éééééé"), Err(AuthError::PasswordTooShort)));
        }

        #[test]
        fn overlong_passwords_are_refused() {
            assert!(matches!(check_new_password(&"x".repeat(MAX_PASSWORD + 1)), Err(AuthError::PasswordTooLong)));
        }

        #[test]
        fn the_right_password_verifies() {
            assert!(account().verify_password("correct horse battery"));
        }

        #[test]
        fn a_wrong_password_does_not_verify() {
            assert!(!account().verify_password("correct horse battery!"));
        }

        #[test]
        fn changing_the_password_changes_the_fingerprint() {
            let mut credentials = account();
            let before = credentials.fingerprint();
            credentials.set_password("a whole new password").unwrap();
            assert_ne!(credentials.fingerprint(), before);
        }
    }

    mod user_matches {
        use super::*;

        #[test]
        fn is_exact() {
            let credentials = account();
            assert!(credentials.user_matches("Um9i"));
            assert!(!credentials.user_matches("um9i"), "names are case-sensitive");
            assert!(!credentials.user_matches("Um9i "));
        }
    }

    mod file {
        use super::*;
        use std::os::unix::fs::PermissionsExt;

        #[test]
        fn round_trips() {
            let dir = scratch("round-trip");
            let path = dir.join("login");
            let credentials = account();
            credentials.save(&path, None).unwrap();
            let loaded = Credentials::load(&path).unwrap();
            assert_eq!(loaded.fingerprint(), credentials.fingerprint());
            let _ = fs::remove_dir_all(&dir);
        }

        #[test]
        fn is_private_to_its_owner() {
            let dir = scratch("private");
            let path = dir.join("login");
            account().save(&path, None).unwrap();
            assert_eq!(fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
            let _ = fs::remove_dir_all(&dir);
        }

        #[test]
        fn missing_means_not_set_up() {
            let dir = scratch("missing");
            assert!(matches!(Credentials::load(&dir.join("login")), Err(AuthError::NotSetUp(_))));
            let _ = fs::remove_dir_all(&dir);
        }

        #[test]
        fn malformed_files_are_refused() {
            let cases = [
                (
                    "no user",
                    "password=$argon2id$v=19$m=8,t=1,p=1$c2FsdHNhbHQ$aGFzaA\ntotp=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ\n",
                ),
                ("no password", "user=Um9i\ntotp=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ\n"),
                ("not a hash", "user=Um9i\npassword=hunter2\ntotp=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ\n"),
                ("bad secret", "user=Um9i\npassword=$argon2id$v=19$m=8,t=1,p=1$c2FsdHNhbHQ$aGFzaA\ntotp=not base32!\n"),
                ("short secret", "user=Um9i\npassword=$argon2id$v=19$m=8,t=1,p=1$c2FsdHNhbHQ$aGFzaA\ntotp=GEZDGNA\n"),
            ];
            for (name, text) in cases {
                assert!(Credentials::parse(text).is_err(), "{name} was accepted");
            }
        }
    }

    mod writers {
        use super::*;

        #[test]
        fn a_change_authorized_against_an_older_account_is_refused() {
            let dir = scratch("stale");
            let path = dir.join("login");
            let before = account();
            before.save(&path, None).unwrap();
            let authorized = before.fingerprint();
            // An operator resets the account in between.
            let reset = Credentials::new("Um9i", "the operator's reset").unwrap();
            reset.save(&path, None).unwrap();
            let result = change_password(&path, authorized, "the user's new password", None);
            assert!(matches!(result, Err(AuthError::Changed)), "the stale change went through");
            assert!(
                Credentials::load(&path).unwrap().verify_password("the operator's reset"),
                "the reset was overwritten"
            );
            let _ = fs::remove_dir_all(&dir);
        }

        #[test]
        fn a_current_change_is_saved() {
            let dir = scratch("current");
            let path = dir.join("login");
            let credentials = account();
            credentials.save(&path, None).unwrap();
            let fingerprint = change_password(&path, credentials.fingerprint(), "a fresh password", None).unwrap();
            let saved = Credentials::load(&path).unwrap();
            assert!(saved.verify_password("a fresh password") && saved.fingerprint() == fingerprint);
            let _ = fs::remove_dir_all(&dir);
        }

        #[test]
        fn save_new_never_replaces_an_account() {
            let dir = scratch("new");
            let path = dir.join("login");
            account().save_new(&path, None).unwrap();
            let second = Credentials::new("Um9i", "a different account").unwrap();
            assert!(matches!(second.save_new(&path, None), Err(AuthError::AlreadySetUp(_))));
            assert!(Credentials::load(&path).unwrap().verify_password("correct horse battery"));
            let _ = fs::remove_dir_all(&dir);
        }

        #[test]
        fn concurrent_saves_in_one_process_all_land_whole() {
            let dir = scratch("concurrent");
            let path = dir.join("login");
            let saves: Vec<_> = (0..8)
                .map(|_| {
                    let path = path.clone();
                    std::thread::spawn(move || account().save(&path, None))
                })
                .collect();
            for save in saves {
                save.join().unwrap().unwrap();
            }
            assert!(Credentials::load(&path).is_ok());
            let leftovers: Vec<_> = fs::read_dir(&dir).unwrap().flatten().map(|e| e.file_name()).collect();
            assert_eq!(leftovers, [std::ffi::OsString::from("login")], "temporaries were left behind");
            let _ = fs::remove_dir_all(&dir);
        }
    }

    mod users {
        use super::*;

        #[test]
        fn ordinary_names_are_accepted() {
            for user in ["Um9i", "ada", "a.b-c_d", &"x".repeat(MAX_USER)] {
                assert!(check_user(user).is_ok(), "{user}");
            }
        }

        #[test]
        fn names_that_would_not_read_back_are_refused() {
            for user in ["", "two words", "line\nbreak", "tab\t", " leading", &"x".repeat(MAX_USER + 1), "bell\u{7}"] {
                assert!(matches!(check_user(user), Err(AuthError::BadUser)), "{user:?}");
            }
        }

        #[test]
        fn an_account_with_a_bad_name_is_never_created() {
            assert!(matches!(Credentials::new("", "a long enough password"), Err(AuthError::BadUser)));
        }
    }

    mod codes_across_processes {
        use super::*;

        #[test]
        fn lock_requires_a_private_regular_file_with_one_link() {
            use std::os::unix::fs::{MetadataExt, PermissionsExt, symlink};
            let dir = scratch("lock-links");
            let path = dir.join("login");
            let sentinel = dir.join("sentinel");
            fs::write(&sentinel, b"untouched").unwrap();
            fs::set_permissions(&sentinel, fs::Permissions::from_mode(0o600)).unwrap();
            let before = fs::metadata(&sentinel).unwrap().uid();
            let owner = nix::unistd::geteuid()
                .is_root()
                .then(|| (nix::unistd::Uid::from_raw(65534), nix::unistd::Gid::from_raw(65534)));
            let lock = sibling(&path, "lock");
            symlink(&sentinel, &lock).unwrap();
            assert!(lock_for_writing(&path, owner).is_err());
            fs::remove_file(&lock).unwrap();
            fs::hard_link(&sentinel, &lock).unwrap();
            assert!(lock_for_writing(&path, owner).is_err());
            assert_eq!(fs::metadata(&sentinel).unwrap().uid(), before);
            assert_eq!(fs::read(&sentinel).unwrap(), b"untouched");
            fs::remove_file(&lock).unwrap();
            drop(lock_for_writing(&path, owner).unwrap());
            if let Some((uid, gid)) = owner {
                let handed_over = fs::metadata(&lock).unwrap();
                assert_eq!((handed_over.uid(), handed_over.gid()), (uid.as_raw(), gid.as_raw()));
                drop(lock_for_writing(&path, owner).unwrap());
            }
            fs::remove_dir_all(dir).unwrap();
        }

        #[test]
        fn a_code_is_accepted_once_even_by_a_fresh_reader() {
            let dir = scratch("once");
            let path = dir.join("login");
            let original = account();
            original.save(&path, None).unwrap();
            assert!(consume_code(&path, &original, "287082", 59).unwrap());
            // Nothing in memory carries over: the record on disk refuses it.
            assert!(!consume_code(&path, &original, "287082", 59).unwrap());
            let _ = fs::remove_dir_all(&dir);
        }

        #[test]
        fn a_new_authenticator_secret_starts_afresh() {
            let dir = scratch("fresh");
            let path = dir.join("login");
            let original = account();
            original.save(&path, None).unwrap();
            assert!(consume_code(&path, &original, "287082", 59).unwrap());
            let mut replaced = account();
            replaced.totp_secret = b"another secret of twenty".to_vec();
            replaced.save(&path, None).unwrap();
            let code = format!("{:06}", totp_code(&replaced.totp_secret, 1));
            assert!(consume_code(&path, &replaced, &code, 59).unwrap(), "the old secret's record blocked the new one");
            assert!(!consume_code(&path, &original, "287082", 59).unwrap());
            assert!(!consume_code(&path, &replaced, &code, 59).unwrap());
            fs::write(sibling(&path, "used"), "corrupt").unwrap();
            assert!(consume_code(&path, &replaced, &code, 59).is_err());
            let _ = fs::remove_dir_all(&dir);
        }
    }

    mod device_tokens {
        use super::*;

        #[test]
        fn are_trusted_until_they_expire() {
            let token = account().device_token(1_000);
            assert!(account().trusts_device(&token, 1_000));
            assert!(account().trusts_device(&token, 1_000 + DEVICE_LIFETIME - 1));
            assert!(!account().trusts_device(&token, 1_000 + DEVICE_LIFETIME));
        }

        #[test]
        fn are_refused_when_forged_altered_or_from_another_secret() {
            let token = account().device_token(1_000);
            let mut bytes = data_encoding::BASE64URL_NOPAD.decode(token.as_bytes()).unwrap();
            bytes[0] ^= 1; // A later expiry, which the tag no longer matches.
            let altered = data_encoding::BASE64URL_NOPAD.encode(&bytes);
            let mut other = account();
            other.totp_secret = b"another secret of twenty".to_vec();
            for forged in ["", "x", &altered, &other.device_token(1_000), &token[..token.len() - 2]] {
                assert!(!account().trusts_device(forged, 1_000), "{forged:?}");
            }
        }

        #[test]
        fn survive_a_password_change() {
            let mut credentials = account();
            let token = credentials.device_token(1_000);
            credentials.set_password("a whole new password").unwrap();
            assert!(
                credentials.trusts_device(&token, 1_000),
                "devices are tied to the authenticator, not the password"
            );
        }
    }

    mod otpauth_uri {
        use super::*;

        #[test]
        fn names_the_issuer_account_and_secret() {
            assert_eq!(
                account().otpauth_uri(),
                "otpauth://totp/GITv:Um9i?secret=GEZDGNBVGY3TQOJQGEZDGNBVGY3TQOJQ&issuer=GITv&algorithm=SHA1&digits=6&period=30"
            );
        }
    }
}