GITv
master
login.rs654 lines, 26.7 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
//! Signing in to the web browser: a password and an authenticator code, then a session cookie.
//!
//! Every page except the sign-in page and the static assets it needs sits behind
//! [`require_login`]. Sessions live in memory (a restart signs everyone out) and remember the
//! account's [fingerprint](gitv_web::auth::Credentials::fingerprint), so changing the password, here
//! or with `gitv-web password`, ends every other session.
//!
//! The command-line account commands (`setup`, `password`) are in `setup.rs`.

use std::collections::HashMap;
use std::os::unix::fs::MetadataExt;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};

use axum::Extension;
use axum::extract::{Form, FromRequest, RawQuery, Request, State};
use axum::http::{HeaderMap, HeaderValue, StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use data_encoding::BASE64URL_NOPAD;
use gitv_core::{percent_decode, unix_now};
use gitv_web::auth::{AuthError, Credentials, MIN_PASSWORD, auth_path, check_new_password, random_bytes};
use serde::Deserialize;
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;

use super::throttle::{Client, Throttle};
use super::{SECURITY, html};

/// The session cookie. The `__Host-` prefix makes browsers insist on `Secure`, `Path=/` and no
/// `Domain`, so no other site or subdomain can set or overwrite it.
const COOKIE: &str = "__Host-gitv";
/// Marks a browser that has signed in, so the cap on everyone's failures together never locks
/// it out (see [`gitv_web::auth::Credentials::device_token`]). Kept across sign-outs.
const DEVICE_COOKIE: &str = "__Host-gitv-device";
/// How long a session lasts from sign-in.
const SESSION_LIFETIME: Duration = Duration::from_secs(12 * 60 * 60);

/// Sign-in state shared by every request.
pub struct Login {
    path: PathBuf,
    loaded: Mutex<Option<Loaded>>,
    /// Sessions by the SHA-256 of their token: the token itself is never stored.
    sessions: Mutex<HashMap<[u8; 32], Session>>,
    /// Failed attempts, by client (see [`Throttle`]).
    throttle: Mutex<Throttle>,
    /// Password checks running at once. Argon2 is deliberately costly in memory and time, and
    /// the sign-in form is open to anyone, so a burst of guesses queues here.
    hashing: Arc<tokio::sync::Semaphore>,
    /// Sign-in attempts admitted at once, waiting or running. Past this, more are turned away
    /// before their bodies are even read, so a flood can't pile up passwords in memory.
    admission: Arc<tokio::sync::Semaphore>,
    /// Password checks started, for tests to confirm the bound holds.
    #[cfg(test)]
    checks_started: std::sync::atomic::AtomicUsize,
}

/// Sign-in attempts admitted at once (see [`Login::admission`]).
const ADMITTED_ATTEMPTS: usize = 32;

/// Largest sign-in or account form accepted, in bytes: far more than the fields need.
pub const FORM_LIMIT: usize = 8 * 1024;

/// Password checks allowed to run at once.
const CONCURRENT_CHECKS: usize = 2;

/// What checking a password and code found.
enum Checked {
    Right,
    Wrong,
    /// This client was locked out by the time this attempt's turn came.
    Locked(Duration),
    /// The record of used codes couldn't be read or written, so no code can be trusted.
    Unavailable,
}

/// The account file as last read, and how to tell whether it has changed since.
struct Loaded {
    stamp: (u64, i64, i64, u64),
    credentials: Arc<Credentials>,
}

#[derive(Clone)]
struct Session {
    expires: Instant,
    fingerprint: [u8; 32],
    csrf: String,
}

/// Who is making a sign-in attempt: their client, and whether their browser has signed in
/// before (see [`Login::trusted`]).
#[derive(Clone, Copy)]
struct Asker {
    client: Client,
    trusted: bool,
}

/// What [`require_login`] hands a signed-in request.
#[derive(Clone)]
pub struct SignedIn {
    token_hash: [u8; 32],
    csrf: String,
}

impl Login {
    /// Sign-in backed by the account file at [`auth_path`].
    pub fn new() -> Arc<Login> {
        Arc::new(Login::at(auth_path()))
    }

    fn at(path: PathBuf) -> Login {
        Login {
            path,
            loaded: Mutex::new(None),
            sessions: Mutex::new(HashMap::new()),
            throttle: Mutex::new(Throttle::default()),
            hashing: Arc::new(tokio::sync::Semaphore::new(CONCURRENT_CHECKS)),
            admission: Arc::new(tokio::sync::Semaphore::new(ADMITTED_ATTEMPTS)),
            #[cfg(test)]
            checks_started: std::sync::atomic::AtomicUsize::new(0),
        }
    }

    /// The account, re-read whenever the file changes (so `gitv-web password` takes effect
    /// at once).
    fn credentials(&self) -> Result<Arc<Credentials>, AuthError> {
        let meta = std::fs::metadata(&self.path).map_err(|source| match source.kind() {
            std::io::ErrorKind::NotFound => AuthError::NotSetUp(self.path.clone()),
            _ => AuthError::Read { path: self.path.clone(), source },
        })?;
        let stamp = (meta.ino(), meta.mtime(), meta.mtime_nsec(), meta.len());
        let mut loaded = self.loaded.lock().unwrap_or_else(|e| e.into_inner());
        if let Some(current) = loaded.as_ref().filter(|l| l.stamp == stamp) {
            return Ok(Arc::clone(&current.credentials));
        }
        let credentials = Arc::new(Credentials::load(&self.path)?);
        *loaded = Some(Loaded { stamp, credentials: Arc::clone(&credentials) });
        Ok(credentials)
    }

    /// The session a request's cookie names, if it's live and the account hasn't changed since.
    fn session(&self, headers: &HeaderMap, credentials: &Credentials) -> Option<SignedIn> {
        let token_hash = cookie_token(headers)?;
        let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
        let session = sessions.get(&token_hash)?;
        if session.expires <= Instant::now() || session.fingerprint != credentials.fingerprint() {
            sessions.remove(&token_hash);
            return None;
        }
        Some(SignedIn { token_hash, csrf: session.csrf.clone() })
    }

    /// Start a session; returns the `Set-Cookie` value.
    fn start_session(&self, fingerprint: [u8; 32]) -> Result<String, AuthError> {
        let token = random_bytes::<32>()?;
        let csrf = BASE64URL_NOPAD.encode(&random_bytes::<32>()?);
        let now = Instant::now();
        let mut sessions = self.sessions.lock().unwrap_or_else(|e| e.into_inner());
        sessions.retain(|_, s| s.expires > now);
        sessions.insert(Sha256::digest(token).into(), Session { expires: now + SESSION_LIFETIME, fingerprint, csrf });
        Ok(format!(
            "{COOKIE}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}",
            BASE64URL_NOPAD.encode(&token),
            SESSION_LIFETIME.as_secs()
        ))
    }

    fn throttle(&self) -> std::sync::MutexGuard<'_, Throttle> {
        self.throttle.lock().unwrap_or_else(|e| e.into_inner())
    }

    /// How long `client` must wait to try again, if it must; see [`Throttle::locked_for`].
    fn locked_for(&self, Asker { client, trusted }: Asker) -> Option<Duration> {
        self.throttle().locked_for(client, Instant::now(), trusted)
    }

    /// Whether the request comes from a browser that has signed in to this account before.
    fn trusted(&self, headers: &HeaderMap) -> bool {
        let Some(token) = cookie_value(headers, DEVICE_COOKIE) else { return false };
        self.credentials().is_ok_and(|c| c.trusts_device(token, unix_now()))
    }

    /// Check a password and authenticator code, counting failures and using up the code.
    ///
    /// Waits for one of [`CONCURRENT_CHECKS`] slots first, then looks at the lock again, since
    /// failures may have locked this client out while this attempt waited. The hashing job holds its
    /// slot until it has recorded its result, so no waiting attempt can start between a failure
    /// and the lock it causes, and a cancelled request still counts.
    async fn check(
        self: &Arc<Self>,
        purpose: &'static str,
        credentials: &Arc<Credentials>,
        asker: Asker,
        user: Option<String>,
        password: String,
        code: &str,
    ) -> Checked {
        let Ok(permit) = Arc::clone(&self.hashing).acquire_owned().await else { return Checked::Wrong };
        if let Some(wait) = self.locked_for(asker) {
            return Checked::Locked(wait);
        }
        #[cfg(test)]
        self.checks_started.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
        let (login, creds, code) = (Arc::clone(self), Arc::clone(credentials), code.to_string());
        tokio::task::spawn_blocking(move || {
            let _permit = permit;
            let user_ok = user.is_none_or(|u| creds.user_matches(&u));
            let password_ok = creds.verify_password(&password) && user_ok;
            login.settle(purpose, &creds, asker, password_ok, &code)
        })
        .await
        .unwrap_or(Checked::Wrong)
    }

    /// Record a check's result. The code is checked and used up in one step, under the account
    /// file's lock and recorded on disk, so it works once: across simultaneous requests,
    /// restarts and processes alike.
    ///
    /// Every judged attempt goes to the log (the journal, under systemd) with the client, and
    /// whether the password or the code was wrong. Visitors only ever hear that something was;
    /// the operator can see a right password with a wrong code, which means the password is known.
    fn settle(
        &self,
        purpose: &'static str,
        credentials: &Credentials,
        Asker { client, trusted }: Asker,
        password_ok: bool,
        code: &str,
    ) -> Checked {
        let code_ok = password_ok
            && match gitv_web::auth::consume_code(&self.path, credentials, code, unix_now()) {
                Ok(accepted) => accepted,
                Err(error) => {
                    eprintln!("gitv-web: checking an authenticator code: {error}");
                    return Checked::Unavailable;
                }
            };
        let mut throttle = self.throttle();
        if code_ok {
            throttle.succeed(client);
            eprintln!("gitv-web: {purpose} succeeded from {client}");
            Checked::Right
        } else {
            let now = Instant::now();
            throttle.fail(client, now);
            let wrong = if password_ok { "right password, wrong code" } else { "wrong password" };
            match throttle.locked_for(client, now, trusted) {
                Some(wait) => {
                    eprintln!("gitv-web: {purpose} failed from {client} ({wrong}); locked out for {}s", wait.as_secs());
                    Checked::Locked(wait)
                }
                None => {
                    eprintln!("gitv-web: {purpose} failed from {client} ({wrong})");
                    Checked::Wrong
                }
            }
        }
    }
}

/// The value of the cookie called `name`, from any of a request's `Cookie` headers.
fn cookie_value<'a>(headers: &'a HeaderMap, name: &str) -> Option<&'a str> {
    headers
        .get_all(header::COOKIE)
        .iter()
        .filter_map(|v| v.to_str().ok())
        .flat_map(|v| v.split(';'))
        .find_map(|pair| pair.trim().strip_prefix(name)?.strip_prefix('='))
}

/// The SHA-256 of the session token in a request's cookie.
fn cookie_token(headers: &HeaderMap) -> Option<[u8; 32]> {
    let token = cookie_value(headers, COOKIE)?;
    let token = BASE64URL_NOPAD.decode(token.as_bytes()).ok().filter(|t| t.len() == 32)?;
    Some(Sha256::digest(token).into())
}

/// Where to go after signing in: a path on this site, never another site (`//evil.example`).
fn safe_next(next: &str) -> &str {
    let local = next.starts_with('/') && !next.starts_with("//") && !next.starts_with("/\\");
    if local && !next.bytes().any(|b| b.is_ascii_control()) { next } else { "/" }
}

fn redirect(to: &str, cookies: &[String]) -> Response {
    let mut response = (StatusCode::SEE_OTHER, SECURITY).into_response();
    if let Ok(location) = HeaderValue::from_str(to) {
        response.headers_mut().insert(header::LOCATION, location);
    }
    for cookie in cookies.iter().filter_map(|c| HeaderValue::from_str(c).ok()) {
        response.headers_mut().append(header::SET_COOKIE, cookie);
    }
    response
}

fn not_set_up() -> Response {
    html(
        StatusCode::SERVICE_UNAVAILABLE,
        notice(
            "Sign-in isn't set up",
            false,
            "Sign-in isn’t set up",
            "Create the account on the server, then reload this page:",
            Some("gitv-web setup"),
        ),
    )
}

/// Let signed-in requests through; send everyone else to the sign-in page. This wraps every
/// route except the few public ones, which are routed separately by exact path, so no prefix
/// rule can ever make a repository page public.
pub async fn require_login(State(login): State<Arc<Login>>, mut request: Request, next: Next) -> Response {
    let credentials = login.credentials();
    if let Ok(creds) = &credentials
        && let Some(session) = login.session(request.headers(), creds)
    {
        request.extensions_mut().insert(session);
        return next.run(request).await;
    }
    challenge(credentials.err(), request.uri())
}

pub async fn browse(State(login): State<Arc<Login>>, mut request: Request, next: Next) -> Response {
    let credentials = login.credentials();
    let signed_in = credentials.as_ref().ok().and_then(|c| login.session(request.headers(), c)).is_some();
    request.extensions_mut().insert(signed_in);
    let uri = request.uri().clone();
    let response = next.run(request).await;
    if response.status() == StatusCode::UNAUTHORIZED { challenge(credentials.err(), &uri) } else { response }
}

fn challenge(error: Option<AuthError>, uri: &axum::http::Uri) -> Response {
    match error {
        Some(AuthError::NotSetUp(_)) => return not_set_up(),
        Some(error) => {
            eprintln!("gitv-web: {error}");
            return html(
                StatusCode::SERVICE_UNAVAILABLE,
                notice("Unavailable", false, "Unavailable", "Sign-in is unavailable.", None),
            );
        }
        None => {}
    }
    let wanted = uri.path_and_query().map_or("/", |p| p.as_str());
    redirect(&format!("/login?next={}", super::encode(wanted.as_bytes())), &[])
}

// ---------------------------------------------------------------------------------------------
// Sign in and out

#[derive(Deserialize)]
pub struct SignInForm {
    user: String,
    password: String,
    code: String,
    #[serde(default)]
    next: String,
}

fn sign_in_page(status: StatusCode, next: &str, message: &str) -> Response {
    html(
        status,
        super::templates::SignIn { title: "Sign in", signed_in: false, next: safe_next(next), message }.to_string(),
    )
}

/// "Try again in 3 minutes."
fn try_again(wait: Duration) -> String {
    let minutes = wait.as_secs().div_ceil(60).max(1);
    format!("Try again in {minutes} minute{}.", if minutes == 1 { "" } else { "s" })
}

fn locked_page(wait: Duration) -> Response {
    sign_in_page(StatusCode::TOO_MANY_REQUESTS, "/", &format!("Too many failed sign-ins. {}", try_again(wait)))
}

pub async fn sign_in_form(State(login): State<Arc<Login>>, headers: HeaderMap, RawQuery(query): RawQuery) -> Response {
    let next = query
        .as_deref()
        .and_then(|q| q.split('&').find_map(|p| p.strip_prefix("next=")))
        .map(|n| String::from_utf8_lossy(&percent_decode(n)).into_owned())
        .unwrap_or_else(|| "/".into());
    // Already signed in: carry on to where they were going.
    if let Ok(credentials) = login.credentials()
        && login.session(&headers, &credentials).is_some()
    {
        return redirect(safe_next(&next), &[]);
    }
    sign_in_page(StatusCode::OK, &next, "")
}

pub async fn sign_in(State(login): State<Arc<Login>>, request: Request) -> Response {
    // Turned away before the body is read when too many attempts are already waiting.
    let Ok(_admitted) = Arc::clone(&login.admission).try_acquire_owned() else {
        return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, "/", "Sign-in is busy. Try again in a moment.");
    };
    let client = Client::of(request.headers(), request.extensions());
    let asker = Asker { client, trusted: login.trusted(request.headers()) };
    if let Some(wait) = login.locked_for(asker) {
        return locked_page(wait);
    }
    // Too large (over FORM_LIMIT) or malformed: refused with the rejection's own status.
    let form = match Form::<SignInForm>::from_request(request, &()).await {
        Ok(Form(form)) => form,
        Err(rejection) => {
            return sign_in_page(rejection.status(), "/", "That sign-in form wasn’t accepted. Try again.");
        }
    };
    let credentials = match login.credentials() {
        Ok(credentials) => credentials,
        Err(AuthError::NotSetUp(_)) => return not_set_up(),
        Err(error) => {
            eprintln!("gitv-web: {error}");
            return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, &form.next, "Sign-in is unavailable right now.");
        }
    };
    match login.check("sign-in", &credentials, asker, Some(form.user), form.password, &form.code).await {
        Checked::Right => {}
        Checked::Locked(wait) => return locked_page(wait),
        Checked::Unavailable => {
            return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, &form.next, "Sign-in is unavailable right now.");
        }
        // One message for every mistake, so a guess reveals nothing about which part was wrong.
        Checked::Wrong => {
            return sign_in_page(StatusCode::UNAUTHORIZED, &form.next, "That username, password or code isn’t right.");
        }
    }
    match login.start_session(credentials.fingerprint()) {
        Ok(cookie) => {
            let device = format!(
                "{DEVICE_COOKIE}={}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age={}",
                credentials.device_token(unix_now()),
                gitv_web::auth::DEVICE_LIFETIME
            );
            redirect(safe_next(&form.next), &[cookie, device])
        }
        Err(error) => {
            eprintln!("gitv-web: {error}");
            sign_in_page(StatusCode::SERVICE_UNAVAILABLE, &form.next, "Sign-in is unavailable right now.")
        }
    }
}

#[derive(Deserialize)]
pub struct CsrfForm {
    csrf: String,
}

/// Whether a form carries this session's token: forms posted from other sites don't.
fn csrf_ok(signed_in: &SignedIn, token: &str) -> bool {
    signed_in.csrf.as_bytes().ct_eq(token.as_bytes()).into()
}

pub async fn sign_out(
    State(login): State<Arc<Login>>,
    Extension(signed_in): Extension<SignedIn>,
    Form(form): Form<CsrfForm>,
) -> Response {
    if !csrf_ok(&signed_in, &form.csrf) {
        return html(
            StatusCode::FORBIDDEN,
            notice("Not allowed", true, "Not allowed", "That form has expired. Go back and try again.", None),
        );
    }
    login.sessions.lock().unwrap_or_else(|e| e.into_inner()).remove(&signed_in.token_hash);
    let clear = format!("{COOKIE}=; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=0");
    // The device cookie stays: signing out doesn't make this browser a stranger.
    redirect("/login", &[clear])
}

// ---------------------------------------------------------------------------------------------
// Account

#[derive(Deserialize)]
pub struct ChangePasswordForm {
    csrf: String,
    current: String,
    new: String,
    repeat: String,
    code: String,
}

fn account_page(status: StatusCode, user: &str, signed_in: &SignedIn, message: &str, ok: bool) -> Response {
    let page = super::templates::Account {
        title: "Account",
        signed_in: true,
        user,
        message,
        ok,
        csrf: &signed_in.csrf,
        min_password: MIN_PASSWORD,
    };
    html(status, page.to_string())
}

/// A page with a heading, a sentence and perhaps a command to copy.
fn notice(title: &str, signed_in: bool, heading: &str, message: &str, code: Option<&str>) -> String {
    super::templates::Notice { title, signed_in, heading, message, code: code.map(str::to_string), link: None }
        .to_string()
}

pub async fn account(State(login): State<Arc<Login>>, Extension(signed_in): Extension<SignedIn>) -> Response {
    match login.credentials() {
        Ok(credentials) => account_page(StatusCode::OK, credentials.user(), &signed_in, "", false),
        Err(_) => not_set_up(),
    }
}

pub async fn change_password(
    State(login): State<Arc<Login>>,
    Extension(signed_in): Extension<SignedIn>,
    client: Client,
    headers: HeaderMap,
    Form(form): Form<ChangePasswordForm>,
) -> Response {
    let asker = Asker { client, trusted: login.trusted(&headers) };
    let Ok(credentials) = login.credentials() else { return not_set_up() };
    let user = credentials.user().to_string();
    let refuse = |status, message: &str| account_page(status, &user, &signed_in, message, false);
    if !csrf_ok(&signed_in, &form.csrf) {
        return refuse(StatusCode::FORBIDDEN, "That form has expired. Try again.");
    }
    if let Some(wait) = login.locked_for(asker) {
        return refuse(StatusCode::TOO_MANY_REQUESTS, &format!("Too many failed attempts. {}", try_again(wait)));
    }
    if form.new != form.repeat {
        return refuse(StatusCode::BAD_REQUEST, "The new passwords don’t match.");
    }
    if let Err(error) = check_new_password(&form.new) {
        return refuse(StatusCode::BAD_REQUEST, &format!("Choose a different new password: {error}."));
    }
    match login.check("password change", &credentials, asker, None, form.current, &form.code).await {
        Checked::Right => {}
        Checked::Locked(wait) => {
            return refuse(StatusCode::TOO_MANY_REQUESTS, &format!("Too many failed attempts. {}", try_again(wait)));
        }
        Checked::Wrong => return refuse(StatusCode::UNAUTHORIZED, "That current password or code isn’t right."),
        Checked::Unavailable => {
            return refuse(StatusCode::SERVICE_UNAVAILABLE, "Changing the password is unavailable right now.");
        }
    }
    // Saved only if the account is still the one just checked: an operator's reset in the
    // meantime wins, rather than being overwritten by a change authorized against the old one.
    let (path, authorized, new) = (login.path.clone(), credentials.fingerprint(), form.new);
    let saved =
        tokio::task::spawn_blocking(move || gitv_web::auth::change_password(&path, authorized, &new, None)).await;
    let fingerprint = match saved {
        Ok(Ok(fingerprint)) => fingerprint,
        Ok(Err(AuthError::Changed)) => {
            return refuse(
                StatusCode::CONFLICT,
                "The account was changed while you were doing this, so nothing was saved. Sign in again.",
            );
        }
        Ok(Err(error)) => {
            eprintln!("gitv-web: changing the password: {error}");
            return refuse(StatusCode::INTERNAL_SERVER_ERROR, "The password couldn’t be saved. It hasn’t changed.");
        }
        Err(error) => {
            eprintln!("gitv-web: changing the password: {error}");
            return refuse(StatusCode::INTERNAL_SERVER_ERROR, "The password couldn’t be saved. It hasn’t changed.");
        }
    };
    // Every other session ends; this one carries on with the new account fingerprint.
    {
        let mut sessions = login.sessions.lock().unwrap_or_else(|e| e.into_inner());
        sessions.retain(|token, _| *token == signed_in.token_hash);
        if let Some(session) = sessions.get_mut(&signed_in.token_hash) {
            session.fingerprint = fingerprint;
        }
    }
    account_page(StatusCode::OK, &user, &signed_in, "Password changed. Other sessions have been signed out.", true)
}

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

    mod safe_next {
        use super::*;

        #[test]
        fn keeps_local_paths() {
            assert_eq!(safe_next("/ada/site/tree?ref=main"), "/ada/site/tree?ref=main");
        }

        #[test]
        fn refuses_other_sites() {
            for next in ["//evil.example/", "/\\evil.example", "https://evil.example/", "evil", "", "/a\r\nb"] {
                assert_eq!(safe_next(next), "/", "{next:?}");
            }
        }
    }

    mod lock {
        use super::*;

        fn login() -> Login {
            Login::at(PathBuf::new())
        }

        /// The client a request without connection details counts as.
        fn unknown() -> Client {
            Client::new(std::net::IpAddr::V4(std::net::Ipv4Addr::UNSPECIFIED))
        }

        #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
        async fn a_burst_of_guesses_hashes_only_until_the_lock_falls() {
            let login = Arc::new(login());
            let credentials = Arc::new(Credentials::new("Um9i", "the real password").unwrap());
            let guesses: Vec<_> = (0..20)
                .map(|_| {
                    let (login, credentials) = (Arc::clone(&login), Arc::clone(&credentials));
                    tokio::spawn(async move {
                        let asker = Asker { client: unknown(), trusted: false };
                        login.check("sign-in", &credentials, asker, None, "a wrong guess".into(), "123456").await
                    })
                })
                .collect();
            for guess in guesses {
                let _ = guess.await;
            }
            // Five free failures lock sign-in on the sixth; at most the other slot's check was
            // already running then. Everyone still waiting sees the lock and hashes nothing.
            let started = login.checks_started.load(std::sync::atomic::Ordering::Relaxed);
            assert!(
                started <= crate::throttle::FREE_FAILURES as usize + CONCURRENT_CHECKS,
                "{started} password checks ran"
            );
        }

        #[tokio::test]
        async fn a_full_queue_turns_sign_ins_away_unread() {
            // A real account, so an attempt that got through would be judged (and fail).
            let dir = std::env::temp_dir().join(format!("gitv-web-admission-{}", std::process::id()));
            let _ = std::fs::remove_dir_all(&dir);
            std::fs::create_dir_all(&dir).unwrap();
            Credentials::new("Um9i", "the real password").unwrap().save(&dir.join("login"), None).unwrap();
            let login = Arc::new(Login::at(dir.join("login")));
            let _taken: Vec<_> =
                (0..ADMITTED_ATTEMPTS).map(|_| Arc::clone(&login.admission).try_acquire_owned().unwrap()).collect();
            let request = Request::builder()
                .method("POST")
                .uri("/login")
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
                .body(axum::body::Body::from("user=Um9i&password=guess&code=123456"))
                .unwrap();
            let response = sign_in(State(Arc::clone(&login)), request).await;
            assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
            assert_eq!(login.throttle().failures(unknown()), 0, "the attempt was judged anyway");
            let _ = std::fs::remove_dir_all(&dir);
        }
    }
}