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
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};
const COOKIE: &str = "__Host-gitv";
const DEVICE_COOKIE: &str = "__Host-gitv-device";
const SESSION_LIFETIME: Duration = Duration::from_secs(12 * 60 * 60);
pub struct Login {
path: PathBuf,
loaded: Mutex<Option<Loaded>>,
sessions: Mutex<HashMap<[u8; 32], Session>>,
throttle: Mutex<Throttle>,
hashing: Arc<tokio::sync::Semaphore>,
admission: Arc<tokio::sync::Semaphore>,
#[cfg(test)]
checks_started: std::sync::atomic::AtomicUsize,
}
const ADMITTED_ATTEMPTS: usize = 32;
pub const FORM_LIMIT: usize = 8 * 1024;
const CONCURRENT_CHECKS: usize = 2;
enum Checked {
Right,
Wrong,
Locked(Duration),
Unavailable,
}
struct Loaded {
stamp: (u64, i64, i64, u64),
credentials: Arc<Credentials>,
}
#[derive(Clone)]
struct Session {
expires: Instant,
fingerprint: [u8; 32],
csrf: String,
}
#[derive(Clone, Copy)]
struct Asker {
client: Client,
trusted: bool,
}
#[derive(Clone)]
pub struct SignedIn {
token_hash: [u8; 32],
csrf: String,
}
impl Login {
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),
}
}
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(¤t.credentials));
}
let credentials = Arc::new(Credentials::load(&self.path)?);
*loaded = Some(Loaded { stamp, credentials: Arc::clone(&credentials) });
Ok(credentials)
}
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() })
}
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())
}
fn locked_for(&self, Asker { client, trusted }: Asker) -> Option<Duration> {
self.throttle().locked_for(client, Instant::now(), trusted)
}
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()))
}
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)
}
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
}
}
}
}
}
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('='))
}
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())
}
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"),
),
)
}
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())), &[])
}
#[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(),
)
}
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());
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 {
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);
}
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.");
}
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,
}
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");
redirect("/login", &[clear])
}
#[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())
}
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.");
}
}
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.");
}
};
{
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())
}
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;
}
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() {
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);
}
}
}