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
mod common;
use std::path::PathBuf;
use std::process::Command;
use std::sync::OnceLock;
use common::{Host, Server, scratch, session_cookie, stderr};
fn repos() -> &'static PathBuf {
static REPOS: OnceLock<PathBuf> = OnceLock::new();
REPOS.get_or_init(|| {
let host = Host::new("auth-host");
assert!(host.admin(&["create", "ada", "notes"]).status.success());
assert!(host.admin(&["create", "fonts", "notes"]).status.success());
host.repos.clone()
})
}
fn sign_in(s: &Server, user: &str, password: &str, code: &str, next: &str) -> common::Response {
s.post_signed_out("/login", &[("user", user), ("password", password), ("code", code), ("next", next)])
}
mod signed_out {
use super::*;
#[test]
fn pages_redirect_to_sign_in_and_remember_where_you_were_going() {
let s = Server::start_signed_out(repos());
let response = s.get_signed_out("/ada/notes/tree?ref=main");
assert_eq!(response.status, 303);
assert_eq!(response.header("location"), "/login?next=/ada/notes/tree%3Fref%3Dmain");
}
#[test]
fn nothing_private_is_reachable() {
let s = Server::start_signed_out(repos());
for path in ["/ada/notes", "/ada/notes/raw?path=x", "/ada/notes/log", "/account", "/nope", "/login/../"] {
let response = s.get_signed_out(path);
assert_eq!(response.status, 303, "{path} was served");
assert!(response.header("location").starts_with("/login"), "{path}");
}
}
#[test]
fn an_owner_named_like_an_asset_folder_stays_private() {
let s = Server::start_signed_out(repos());
for path in ["/fonts/notes/tree", "/fonts/notes", "/fonts/notes/log", "/fonts/text.woff2/x"] {
let response = s.get_signed_out(path);
assert_eq!(response.status, 303, "{path} was served signed out");
}
}
#[test]
fn writes_are_refused_before_anything_else() {
let s = Server::start_signed_out(repos());
assert_eq!(s.post_signed_out("/logout", &[("csrf", "x")]).status, 303);
assert_eq!(s.post_signed_out("/account", &[("csrf", "x")]).status, 303);
}
#[test]
fn the_sign_in_page_and_its_assets_are_public() {
let s = Server::start_signed_out(repos());
for path in ["/login", "/style.css", "/favicon.svg", "/fonts/text.woff2"] {
assert_eq!(s.get_signed_out(path).status, 200, "{path}");
}
}
#[test]
fn the_sign_in_page_reveals_no_repositories() {
let s = Server::start_signed_out(repos());
let html = s.get_signed_out("/login").text();
assert!(html.contains(r#"<form class="panel form" method="post" action="/login">"#), "{html}");
assert!(!html.contains("notes") && !html.contains("/account"), "{html}");
}
#[test]
fn the_sign_in_page_sends_the_security_headers() {
let s = Server::start_signed_out(repos());
let csp = s.get_signed_out("/login").header("content-security-policy").to_string();
assert!(csp.contains("default-src 'none'") && csp.contains("form-action 'self'"), "{csp}");
}
}
mod signing_in {
use super::*;
#[test]
fn the_right_details_start_a_hardened_session() {
let s = Server::start_signed_out(repos());
let response = sign_in(&s, "Um9i", &s.account.password, &s.account.code(0), "/ada/notes/tree");
assert_eq!((response.status, response.header("location")), (303, "/ada/notes/tree"));
let cookie = response.header("set-cookie");
for part in ["__Host-gitv=", "Path=/", "HttpOnly", "Secure", "SameSite=Strict", "Max-Age=43200"] {
assert!(cookie.contains(part), "{part} missing from {cookie}");
}
}
#[test]
fn the_session_opens_private_pages() {
let s = Server::start(repos());
assert_eq!(s.get("/ada/notes/tree").status, 200);
}
#[test]
fn every_wrong_detail_gets_the_same_answer() {
let s = Server::start_signed_out(repos());
let password = s.account.password.clone();
let cases = [
("wrong user", "um9i", password.as_str(), s.account.code(0)),
("wrong password", "Um9i", "not the password", s.account.code(0)),
("wrong code", "Um9i", password.as_str(), "000000".to_string()),
("old code", "Um9i", password.as_str(), s.account.code(-3)),
];
for (name, user, password, code) in &cases {
let response = sign_in(&s, user, password, code, "/");
assert_eq!(response.status, 401, "{name}");
assert!(response.text().contains("That username, password or code isn’t right."), "{name}");
assert!(session_cookie(&response).is_none(), "{name} got a session");
}
}
#[test]
fn a_code_works_only_once() {
let s = Server::start_signed_out(repos());
let code = s.account.code(0);
assert_eq!(sign_in(&s, "Um9i", &s.account.password, &code, "/").status, 303);
assert_eq!(sign_in(&s, "Um9i", &s.account.password, &code, "/").status, 401);
}
#[test]
fn a_code_sent_by_many_requests_at_once_lets_one_in() {
let s = Server::start_signed_out(repos());
let code = s.account.code(0);
let statuses: Vec<u16> = std::thread::scope(|scope| {
let attempts: Vec<_> =
(0..8).map(|_| scope.spawn(|| sign_in(&s, "Um9i", &s.account.password, &code, "/").status)).collect();
attempts.into_iter().map(|a| a.join().unwrap()).collect()
});
assert_eq!(statuses.iter().filter(|s| **s == 303).count(), 1, "{statuses:?}");
}
#[test]
fn a_burst_of_guesses_meets_the_lock() {
let s = Server::start_signed_out(repos());
let statuses: Vec<u16> = std::thread::scope(|scope| {
let attempts: Vec<_> =
(0..20).map(|_| scope.spawn(|| sign_in(&s, "Um9i", "a wrong guess", "123456", "/").status)).collect();
attempts.into_iter().map(|a| a.join().unwrap()).collect()
});
let judged = statuses.iter().filter(|s| **s == 401).count();
assert!(judged <= 5 + 2, "{judged} guesses were checked: {statuses:?}");
assert!(statuses.iter().all(|s| *s == 401 || *s == 429), "{statuses:?}");
}
#[test]
fn a_used_code_stays_used_after_a_restart() {
let first = Server::start_signed_out(repos());
let code = first.account.code(0);
assert_eq!(sign_in(&first, "Um9i", &first.account.password, &code, "/").status, 303);
let account = first.account.clone();
drop(first);
let restarted = Server::start_signed_out_as(repos(), account);
assert_eq!(sign_in(&restarted, "Um9i", &restarted.account.password, &code, "/").status, 401);
}
#[test]
fn two_servers_on_one_account_accept_a_code_once() {
let one = Server::start_signed_out(repos());
let two = Server::start_signed_out_as(repos(), one.account.clone());
let code = one.account.code(0);
let statuses: Vec<u16> = std::thread::scope(|scope| {
let attempts: Vec<_> = [&one, &two, &one, &two]
.into_iter()
.map(|s| scope.spawn(|| sign_in(s, "Um9i", &s.account.password, &code, "/").status))
.collect();
attempts.into_iter().map(|a| a.join().unwrap()).collect()
});
assert_eq!(statuses.iter().filter(|s| **s == 303).count(), 1, "{statuses:?}");
}
#[test]
fn oversized_forms_are_refused_unread() {
let s = Server::start_signed_out(repos());
let huge = "x".repeat(64 * 1024);
assert_eq!(sign_in(&s, "Um9i", &huge, "123456", "/").status, 413);
}
#[test]
fn the_next_code_still_works_after_one_is_used() {
let s = Server::start_signed_out(repos());
assert_eq!(sign_in(&s, "Um9i", &s.account.password, &s.account.code(0), "/").status, 303);
assert_eq!(sign_in(&s, "Um9i", &s.account.password, &s.account.code(1), "/").status, 303);
}
#[test]
fn it_never_sends_you_to_another_site() {
let s = Server::start_signed_out(repos());
let response = sign_in(&s, "Um9i", &s.account.password, &s.account.code(0), "//evil.example/");
assert_eq!(response.header("location"), "/");
}
#[test]
fn too_many_failures_lock_it_even_for_the_right_details() {
let s = Server::start_signed_out(repos());
for _ in 0..5 {
assert_eq!(sign_in(&s, "Um9i", "wrong password", &s.account.code(0), "/").status, 401);
}
assert_eq!(sign_in(&s, "Um9i", "wrong password", &s.account.code(0), "/").status, 429);
let response = sign_in(&s, "Um9i", &s.account.password, &s.account.code(0), "/");
assert_eq!(response.status, 429, "the lock let the right details in");
assert!(response.text().contains("Too many failed sign-ins. Try again in 1 minute."), "{}", response.text());
}
#[test]
fn one_clients_failures_dont_lock_out_another() {
let s = Server::start_signed_out(repos());
let attempt = |address: &str, password: &str, code: &str| {
let form = [("user", "Um9i"), ("password", password), ("code", code), ("next", "/")];
s.post_signed_out_from(address, "/login", &form).status
};
for _ in 0..5 {
assert_eq!(attempt("203.0.113.7", "wrong password", "000000"), 401);
}
assert_eq!(attempt("203.0.113.7", "wrong password", "000000"), 429, "the attacker is locked out");
assert_eq!(attempt("2001:db8:1:2::99", &s.account.password, &s.account.code(0)), 303, "the owner isn't");
for _ in 0..5 {
assert_eq!(attempt("2001:db8:9:9::1", "wrong password", "000000"), 401);
}
assert_eq!(attempt("2001:db8:9:9::2", "wrong password", "000000"), 429);
}
#[test]
fn many_addresses_together_cant_lock_out_a_browser_that_signed_in_before() {
let s = Server::start_signed_out(repos());
let form = |password: &str, code: &str| {
[("user", "Um9i".to_string()), ("password", password.into()), ("code", code.into()), ("next", "/".into())]
};
let post = |address: &str, device: Option<&str>, fields: &[(&str, String)]| {
let fields: Vec<(&str, &str)> = fields.iter().map(|(k, v)| (*k, v.as_str())).collect();
match device {
Some(device) => s.post_from_device(address, device, "/login", &fields),
None => s.post_signed_out_from(address, "/login", &fields),
}
};
let first = post("198.51.100.1", None, &form(&s.account.password, &s.account.code(0)));
assert_eq!(first.status, 303);
let device = common::set_cookie(&first, "__Host-gitv-device").expect("a trusted-device cookie");
assert!(first.header("set-cookie").contains("Max-Age=7776000"), "{}", first.header("set-cookie"));
for n in 0..12 {
for _ in 0..5 {
let status = post(&format!("203.0.113.{n}"), None, &form("wrong password", "000000")).status;
assert!(matches!(status, 401 | 429), "{status}");
}
}
let fresh = post("198.51.100.2", None, &form(&s.account.password, &s.account.code(1)));
assert_eq!(fresh.status, 429, "a browser never seen before waits out the attack");
let known = post("198.51.100.2", Some(&device), &form(&s.account.password, &s.account.code(1)));
assert_eq!(known.status, 303, "the owner's browser gets in: {}", known.text());
let forged = post("198.51.100.3", Some("AAAAAAAAAAA"), &form(&s.account.password, &s.account.code(1)));
assert_eq!(forged.status, 429, "a made-up device cookie earns nothing");
}
#[test]
fn attempts_are_logged_with_their_client_and_what_was_wrong() {
let s = Server::start_signed_out(repos());
let attempt = |address: &str, password: &str, code: &str| {
let form = [("user", "Um9i"), ("password", password), ("code", code), ("next", "/")];
s.post_signed_out_from(address, "/login", &form).status
};
assert_eq!(attempt("203.0.113.7", "wrong password", "000000"), 401);
let valid = [s.account.code(-1), s.account.code(0), s.account.code(1)];
let wrong_code =
["000000", "111111", "222222", "333333"].into_iter().find(|c| !valid.iter().any(|v| v == c)).unwrap();
assert_eq!(attempt("203.0.113.8", &s.account.password, wrong_code), 401);
assert_eq!(attempt("2001:db8:1:2::5", &s.account.password, &s.account.code(0)), 303);
let log = s.logged();
assert!(log.contains("sign-in failed from 203.0.113.7 (wrong password)"), "{log}");
assert!(log.contains("sign-in failed from 203.0.113.8 (right password, wrong code)"), "{log}");
assert!(log.contains("sign-in succeeded from 2001:db8:1:2::/64"), "{log}");
assert!(!log.contains(&s.account.password), "the password never reaches the log");
}
#[test]
fn a_forged_cookie_is_not_a_session() {
let mut s = Server::start_signed_out(repos());
s.cookie = Some("AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA".into());
assert_eq!(s.get("/account").status, 303);
}
}
mod signing_out {
use super::*;
fn csrf(s: &Server) -> String {
let html = s.get("/account").text();
let start = html.find(r#"name="csrf" value=""#).expect("a csrf field") + r#"name="csrf" value=""#.len();
html[start..start + html[start..].find('"').unwrap()].to_string()
}
#[test]
fn ends_the_session() {
let s = Server::start(repos());
let response = s.post("/logout", &[("csrf", &csrf(&s))]);
assert_eq!((response.status, response.header("location")), (303, "/login"));
assert!(response.header("set-cookie").contains("Max-Age=0"));
assert_eq!(s.get("/account").status, 303, "the old cookie still works");
}
#[test]
fn needs_the_form_token() {
let s = Server::start(repos());
assert_eq!(s.post("/logout", &[("csrf", "forged")]).status, 403);
assert_eq!(s.get("/account").status, 200, "a forged sign-out ended the session");
}
}
mod changing_the_password {
use super::*;
fn csrf(s: &Server) -> String {
let html = s.get("/account").text();
let start = html.find(r#"name="csrf" value=""#).expect("a csrf field") + r#"name="csrf" value=""#.len();
html[start..start + html[start..].find('"').unwrap()].to_string()
}
fn change(s: &Server, csrf: &str, current: &str, new: &str, repeat: &str, code: &str) -> common::Response {
s.post("/account", &[("csrf", csrf), ("current", current), ("new", new), ("repeat", repeat), ("code", code)])
}
#[test]
fn works_and_keeps_this_session() {
let s = Server::start(repos());
let response = change(
&s,
&csrf(&s),
&s.account.password,
"a brand new password",
"a brand new password",
&s.account.code(1),
);
assert_eq!(response.status, 200, "{}", response.text());
assert!(response.text().contains("Password changed."));
assert_eq!(s.get("/account").status, 200);
}
#[test]
fn the_new_password_works_and_the_old_one_does_not() {
let s = Server::start(repos());
let old = s.account.password.clone();
let new = "another new password";
assert_eq!(change(&s, &csrf(&s), &old, new, new, &s.account.code(1)).status, 200);
assert_eq!(sign_in(&s, "Um9i", &old, &s.account.code(1), "/").status, 401);
let loaded = gitv_web::auth::Credentials::load(&s.account.file).unwrap();
assert!(loaded.verify_password(new) && !loaded.verify_password(&old));
}
#[test]
fn signs_out_every_other_session() {
let mut first = Server::start_signed_out(repos());
let response = sign_in(&first, "Um9i", &first.account.password, &first.account.code(-1), "/");
first.cookie = session_cookie(&response);
let response = sign_in(&first, "Um9i", &first.account.password, &first.account.code(0), "/");
let mut second = Server::start_signed_out(repos());
second.port = first.port;
second.cookie = session_cookie(&response);
assert_eq!(second.get("/account").status, 200);
let new = "yet another new password";
let response = change(&first, &csrf(&first), &first.account.password, new, new, &first.account.code(1));
assert_eq!(response.status, 200, "{}", response.text());
assert_eq!(second.get("/account").status, 303, "the other session survived");
assert_eq!(first.get("/account").status, 200, "this session was ended");
}
#[test]
fn needs_the_current_password() {
let s = Server::start(repos());
let response =
change(&s, &csrf(&s), "not it", "a brand new password", "a brand new password", &s.account.code(1));
assert_eq!(response.status, 401);
assert!(gitv_web::auth::Credentials::load(&s.account.file).unwrap().verify_password(&s.account.password));
}
#[test]
fn needs_a_code() {
let s = Server::start(repos());
let response =
change(&s, &csrf(&s), &s.account.password, "a brand new password", "a brand new password", "000000");
assert_eq!(response.status, 401);
}
#[test]
fn needs_the_form_token() {
let s = Server::start(repos());
let response = change(
&s,
"forged",
&s.account.password,
"a brand new password",
"a brand new password",
&s.account.code(1),
);
assert_eq!(response.status, 403);
}
#[test]
fn refuses_mismatched_new_passwords() {
let s = Server::start(repos());
let response = change(
&s,
&csrf(&s),
&s.account.password,
"a brand new password",
"a brand new passw0rd",
&s.account.code(1),
);
assert_eq!(response.status, 400);
assert!(response.text().contains("The new passwords don’t match."));
}
#[test]
fn refuses_short_new_passwords() {
let s = Server::start(repos());
let response = change(&s, &csrf(&s), &s.account.password, "too short", "too short", &s.account.code(1));
assert_eq!(response.status, 400);
assert!(response.text().contains("use at least 12 characters"), "{}", response.text());
}
#[test]
fn on_the_server_signs_everyone_out() {
let s = Server::start(repos());
assert_eq!(s.get("/account").status, 200);
let mut credentials = gitv_web::auth::Credentials::load(&s.account.file).unwrap();
credentials.set_password("changed on the server").unwrap();
credentials.save(&s.account.file, None).unwrap();
assert_eq!(s.get("/account").status, 303);
}
}
mod setup {
use super::*;
#[test]
fn root_setup_refuses_an_unwritable_custom_directory_before_publication() {
let Some(_) = gitv_web::auth::service_owner().unwrap() else { return };
let dir = scratch("auth-setup-root-owned");
std::fs::set_permissions(&dir, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
let out =
Command::new(&*common::GITV_WEB).arg("setup").env("GITV_WEB_AUTH", dir.join("login")).output().unwrap();
assert!(!out.status.success());
assert!(stderr(&out).contains("write and search access"));
assert_eq!(std::fs::read_dir(dir).unwrap().count(), 0);
}
#[test]
fn refuses_to_replace_an_account_without_force() {
let dir = scratch("auth-setup-twice");
common::Account::create(&dir);
let out =
Command::new(&*common::GITV_WEB).arg("setup").env("GITV_WEB_AUTH", dir.join("login")).output().unwrap();
assert!(!out.status.success());
assert!(stderr(&out).contains("already set up"), "{}", stderr(&out));
}
#[test]
fn two_setups_at_once_leave_one_account() {
let dir = scratch("auth-setup-race");
let file = dir.join("login");
let results: Vec<bool> = std::thread::scope(|scope| {
let runs: Vec<_> = (0..4)
.map(|_| {
scope.spawn(|| {
Command::new(&*common::GITV_WEB).arg("setup").env("GITV_WEB_AUTH", &file).output().unwrap()
})
})
.collect();
runs.into_iter().map(|r| r.join().unwrap().status.success()).collect()
});
assert_eq!(results.iter().filter(|ok| **ok).count(), 1, "{results:?}");
assert!(gitv_web::auth::Credentials::load(&file).is_ok());
}
#[test]
fn with_force_replaces_it_and_signs_everyone_out() {
let s = Server::start(repos());
let out = Command::new(&*common::GITV_WEB)
.args(["setup", "--force"])
.env("GITV_WEB_AUTH", &s.account.file)
.output()
.unwrap();
assert!(out.status.success(), "{}", stderr(&out));
assert_eq!(s.get("/account").status, 303);
}
#[test]
fn refuses_user_names_that_would_not_read_back_and_keeps_the_account() {
let dir = scratch("auth-setup-bad-user");
let account = common::Account::create(&dir);
for user in ["", "two words", "line\nbreak"] {
let out = Command::new(&*common::GITV_WEB)
.args(["setup", "--force", "--user", user])
.env("GITV_WEB_AUTH", &account.file)
.output()
.unwrap();
assert!(!out.status.success(), "{user:?} was accepted");
assert!(stderr(&out).contains("user name"), "{}", stderr(&out));
}
let kept = gitv_web::auth::Credentials::load(&account.file).unwrap();
assert!(kept.verify_password(&account.password), "a refused setup replaced the account");
}
#[test]
fn names_the_first_account_admin_and_keeps_the_name_when_replacing_it() {
let dir = scratch("auth-setup-user");
let file = dir.join("login");
let setup = |args: &[&str]| {
let out =
Command::new(&*common::GITV_WEB).arg("setup").args(args).env("GITV_WEB_AUTH", &file).output().unwrap();
assert!(out.status.success(), "{}", stderr(&out));
gitv_web::auth::Credentials::load(&file).unwrap().user().to_string()
};
assert_eq!(setup(&[]), "admin");
assert_eq!(setup(&["--force", "--user", "Um9i"]), "Um9i");
assert_eq!(setup(&["--force"]), "Um9i", "a replaced account keeps its name");
}
#[test]
fn without_an_account_the_site_says_how_to_set_one_up() {
let s = Server::start_signed_out(repos());
std::fs::remove_file(&s.account.file).unwrap();
let index = s.get_signed_out("/");
assert_eq!(index.status, 200);
assert!(index.text().contains("No public repositories yet"));
let response = s.get_signed_out("/account");
assert_eq!(response.status, 503);
assert!(response.text().contains("gitv-web setup"));
}
}