GITv

Throttle sign-in per client so an attacker can't lock the owner out

Browse files

Failed sign-ins were counted globally and never forgotten, so anyone could keep the single account locked, and an old attack turned a later typo into a 15-minute lock. Failures are now counted per client (an IPv4 address or IPv6 /64, taken from Caddy's X-Forwarded-For only on loopback connections), forgotten after a quiet hour, and capped across all clients at 60 an hour rather than locking everyone out. The rules live in their own module, which takes the time as an argument so they are tested without waiting. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 15:54
Commit
de97a29e7b0b
Parent
ca9f486

6 files changed +356−98

+1−1
@@ -47,7 +47,7 @@ It prints a generated password (20 random characters, shown only this once), the
- **Lost the authenticator?** Run `gitv-web setup --force` on the server for a new password and secret.
- The account lives in `/var/lib/gitv-web/login` (or `$GITV_WEB_AUTH`), readable only by its owner. Root-run setup hands the default service directory to `gitv-web`. If you point `GITV_WEB_AUTH` into an existing custom directory, give the service write and search access there first. The password is stored as an Argon2id hash.
- Sessions last up to 12 hours, including across browser restarts. Sign out to end a session on a shared device. The session cookie is `Secure`, so the browser must be reached over HTTPS (or on `localhost`).
- After five failed attempts sign-in locks for a minute, doubling with each further failure up to 15 minutes. A code works once.
- Failed attempts are counted per client: an IPv4 address, or an IPv6 /64. After five, that client is locked out for a minute, doubling with each further failure up to 15 minutes. A client's count is forgotten after an hour without a failure. Someone guessing from elsewhere therefore can't lock you out. Across all clients together, at most 60 failures an hour are judged, which caps a distributed attack without locking anyone out for long. The client's address comes from Caddy's `X-Forwarded-For`, which gitv-web trusts only on loopback connections. A code works once.
Until the account exists, pages requiring sign-in show setup instructions. Public repositories can already be browsed and cloned.
@@ -26,6 +26,7 @@ use serde::Deserialize;
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
use super::throttle::{Client, Throttle};
use super::{SECURITY, layout, page, percent_decode};
/// The session cookie. The `__Host-` prefix makes browsers insist on `Secure`, `Path=/` and no
@@ -33,10 +34,6 @@ use super::{SECURITY, layout, page, percent_decode};
const COOKIE: &str = "__Host-gitv";
/// How long a session lasts from sign-in.
const SESSION_LIFETIME: Duration = Duration::from_secs(12 * 60 * 60);
/// Failed attempts allowed before sign-in locks.
const FREE_FAILURES: u32 = 5;
/// The longest a lock lasts; it starts at a minute and doubles with each further failure.
const LONGEST_LOCK: Duration = Duration::from_secs(15 * 60);
/// Sign-in state shared by every request.
pub struct Login {
@@ -44,7 +41,8 @@ pub struct Login {
loaded: Mutex<Option<Loaded>>,
/// Sessions by the SHA-256 of their token: the token itself is never stored.
sessions: Mutex<HashMap<[u8; 32], Session>>,
guard: Mutex<Guard>,
/// 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>,
@@ -69,7 +67,7 @@ const CONCURRENT_CHECKS: usize = 2;
enum Checked {
Right,
Wrong,
/// Sign-in was locked by the time this attempt's turn came.
/// 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,
@@ -88,14 +86,6 @@ struct Session {
csrf: String,
}
/// Brute-force protection. There is one account, so one counter: an attacker can delay its
/// owner, but can't guess faster than the lock allows.
#[derive(Default)]
struct Guard {
failures: u32,
locked_until: Option<Instant>,
}
/// What [`require_login`] hands a signed-in request.
#[derive(Clone)]
pub struct SignedIn {
@@ -114,7 +104,7 @@ impl Login {
path,
loaded: Mutex::new(None),
sessions: Mutex::new(HashMap::new()),
guard: Mutex::new(Guard::default()),
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)]
@@ -166,41 +156,31 @@ impl Login {
))
}
/// How long sign-in stays locked, if it is.
fn locked_for(&self) -> Option<Duration> {
let guard = self.guard.lock().unwrap_or_else(|e| e.into_inner());
guard.locked_until.and_then(|until| until.checked_duration_since(Instant::now()))
}
#[cfg(test)]
fn record_failure(&self) {
Self::fail(&mut self.guard.lock().unwrap_or_else(|e| e.into_inner()));
fn throttle(&self) -> std::sync::MutexGuard<'_, Throttle> {
self.throttle.lock().unwrap_or_else(|e| e.into_inner())
}
fn fail(guard: &mut Guard) {
guard.failures += 1;
// The first FREE_FAILURES are free; each one after locks for longer.
if let Some(over) = guard.failures.checked_sub(FREE_FAILURES + 1) {
let lock = Duration::from_secs(60).saturating_mul(1 << over.min(10)).min(LONGEST_LOCK);
guard.locked_until = Some(Instant::now() + lock);
}
/// How long `client` must wait to try again, if it must.
fn locked_for(&self, client: Client) -> Option<Duration> {
self.throttle().locked_for(client, Instant::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 sign-in while this attempt waited. The hashing job holds its
/// 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>,
credentials: &Arc<Credentials>,
client: Client,
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() {
if let Some(wait) = self.locked_for(client) {
return Checked::Locked(wait);
}
#[cfg(test)]
@@ -210,7 +190,7 @@ impl Login {
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(&creds, password_ok, &code)
login.settle(&creds, client, password_ok, &code)
})
.await
.unwrap_or(Checked::Wrong)
@@ -219,7 +199,7 @@ impl Login {
/// 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.
fn settle(&self, credentials: &Credentials, password_ok: bool, code: &str) -> Checked {
fn settle(&self, credentials: &Credentials, client: Client, password_ok: bool, code: &str) -> Checked {
let code_ok = password_ok
&& match gitv::auth::consume_code(&self.path, credentials, code, unix_now()) {
Ok(accepted) => accepted,
@@ -228,14 +208,14 @@ impl Login {
return Checked::Unavailable;
}
};
let mut guard = self.guard.lock().unwrap_or_else(|e| e.into_inner());
let mut throttle = self.throttle();
if code_ok {
guard.failures = 0;
guard.locked_until = None;
throttle.succeed(client);
Checked::Right
} else {
Self::fail(&mut guard);
match guard.locked_until.and_then(|until| until.checked_duration_since(Instant::now())) {
let now = Instant::now();
throttle.fail(client, now);
match throttle.locked_for(client, now) {
Some(wait) => Checked::Locked(wait),
None => Checked::Wrong,
}
@@ -350,14 +330,14 @@ fn sign_in_page(status: StatusCode, next: &str, message: &str) -> Response {
)
}
fn locked_page(wait: Duration) -> Response {
/// "Try again in 3 minutes."
fn try_again(wait: Duration) -> String {
let minutes = wait.as_secs().div_ceil(60).max(1);
let plural = if minutes == 1 { "" } else { "s" };
sign_in_page(
StatusCode::TOO_MANY_REQUESTS,
"/",
&format!("Too many failed sign-ins. Try again in {minutes} minute{plural}."),
)
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 {
@@ -380,7 +360,8 @@ pub async fn sign_in(State(login): State<Arc<Login>>, request: Request) -> Respo
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.");
};
if let Some(wait) = login.locked_for() {
let client = Client::of(request.headers(), request.extensions());
if let Some(wait) = login.locked_for(client) {
return locked_page(wait);
}
// Too large (over FORM_LIMIT) or malformed: refused with the rejection's own status.
@@ -398,7 +379,7 @@ pub async fn sign_in(State(login): State<Arc<Login>>, request: Request) -> Respo
return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, &form.next, "Sign-in is unavailable right now.");
}
};
match login.check(&credentials, Some(form.user), form.password, &form.code).await {
match login.check(&credentials, client, Some(form.user), form.password, &form.code).await {
Checked::Right => {}
Checked::Locked(wait) => return locked_page(wait),
Checked::Unavailable => {
@@ -496,6 +477,7 @@ pub async fn account(State(login): State<Arc<Login>>, Extension(signed_in): Exte
pub async fn change_password(
State(login): State<Arc<Login>>,
Extension(signed_in): Extension<SignedIn>,
client: Client,
Form(form): Form<ChangePasswordForm>,
) -> Response {
let Ok(credentials) = login.credentials() else { return not_set_up() };
@@ -504,12 +486,8 @@ pub async fn change_password(
if !csrf_ok(&signed_in, &form.csrf) {
return refuse(StatusCode::FORBIDDEN, "That form has expired. Try again.");
}
if let Some(wait) = login.locked_for() {
let minutes = wait.as_secs().div_ceil(60).max(1);
return refuse(
StatusCode::TOO_MANY_REQUESTS,
&format!("Too many failed attempts. Try again in {minutes} minutes."),
);
if let Some(wait) = login.locked_for(client) {
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.");
@@ -517,14 +495,10 @@ pub async fn change_password(
if let Err(error) = check_new_password(&form.new) {
return refuse(StatusCode::BAD_REQUEST, &format!("Choose a different new password: {error}."));
}
match login.check(&credentials, None, form.current, &form.code).await {
match login.check(&credentials, client, None, form.current, &form.code).await {
Checked::Right => {}
Checked::Locked(wait) => {
let minutes = wait.as_secs().div_ceil(60).max(1);
return refuse(
StatusCode::TOO_MANY_REQUESTS,
&format!("Too many failed attempts. Try again in {minutes} minutes."),
);
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 => {
@@ -701,6 +675,11 @@ mod tests {
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());
@@ -708,7 +687,9 @@ mod tests {
let guesses: Vec<_> = (0..20)
.map(|_| {
let (login, credentials) = (Arc::clone(&login), Arc::clone(&credentials));
tokio::spawn(async move { login.check(&credentials, None, "a wrong guess".into(), "123456").await })
tokio::spawn(async move {
login.check(&credentials, unknown(), None, "a wrong guess".into(), "123456").await
})
})
.collect();
for guess in guesses {
@@ -717,7 +698,10 @@ mod tests {
// 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 <= FREE_FAILURES as usize + CONCURRENT_CHECKS, "{started} password checks ran");
assert!(
started <= crate::throttle::FREE_FAILURES as usize + CONCURRENT_CHECKS,
"{started} password checks ran"
);
}
#[tokio::test]
@@ -738,41 +722,8 @@ mod tests {
.unwrap();
let response = sign_in(State(Arc::clone(&login)), request).await;
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
assert_eq!(login.guard.lock().unwrap().failures, 0, "the attempt was judged anyway");
assert_eq!(login.throttle().failures(unknown()), 0, "the attempt was judged anyway");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn allows_the_first_failures() {
let login = login();
(0..FREE_FAILURES).for_each(|_| login.record_failure());
assert!(login.locked_for().is_none());
}
#[test]
fn locks_after_too_many_failures() {
let login = login();
(0..=FREE_FAILURES).for_each(|_| login.record_failure());
assert!(login.locked_for().is_some_and(|wait| wait <= Duration::from_secs(60)));
}
#[test]
fn grows_but_never_past_the_longest_lock() {
let login = login();
(0..FREE_FAILURES + 30).for_each(|_| login.record_failure());
assert!(login.locked_for().is_some_and(|wait| wait > Duration::from_secs(14 * 60) && wait <= LONGEST_LOCK));
}
#[test]
fn success_clears_it() {
let login = login();
(0..=FREE_FAILURES).for_each(|_| login.record_failure());
{
let mut guard = login.guard.lock().unwrap();
guard.failures = 0;
guard.locked_until = None;
}
assert!(login.locked_for().is_none());
}
}
}
@@ -3,6 +3,7 @@
mod login;
mod templates;
mod throttle;
use std::borrow::Cow;
mod repository;
@@ -1327,6 +1328,8 @@ fn serve(port: u16) -> Result<(), String> {
// Print the bound address (not the requested port), so `--port 0` works for tests.
let address = listener.local_addr().map_err(|e| e.to_string())?;
println!("gitv-web listening on http://{address} (repos: {})", repos_root().display());
// Connection details let sign-in throttle each client separately.
let app = app.into_make_service_with_connect_info::<std::net::SocketAddr>();
axum::serve(listener, app).await.map_err(|e| e.to_string())
})
}
@@ -0,0 +1,265 @@
//! Brute-force protection for sign-in, by client, so one attacker can't lock the owner out.
//!
//! Each client (an IPv4 address, or an IPv6 /64, which one machine usually controls whole) gets
//! [`FREE_FAILURES`] failed attempts; each one after that locks that client out for longer,
//! from a minute up to [`LONGEST_LOCK`]. A client's failures are forgotten after
//! [`FORGET_AFTER`] without one, so an old attack never turns a later typo into a long lock.
//!
//! On top of that, every client together may fail at most [`GLOBAL_PER_HOUR`] times an hour.
//! That caps how fast a distributed attack can guess. One client, held back by its own lock,
//! can never reach it alone, and when many do, sign-in slows to that rate rather than locking.
//!
//! Every method takes the current time, so the rules can be tested without waiting.
use std::collections::{HashMap, VecDeque};
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::time::{Duration, Instant};
use axum::extract::{ConnectInfo, FromRequestParts};
use axum::http::request::Parts;
use axum::http::{Extensions, HeaderMap};
/// Failed attempts a client may make before it is locked out.
pub const FREE_FAILURES: u32 = 5;
/// The longest a client's lock lasts; it starts at a minute and doubles with each failure.
pub const LONGEST_LOCK: Duration = Duration::from_secs(15 * 60);
/// How long without a failure before a client's count starts again.
pub const FORGET_AFTER: Duration = Duration::from_secs(60 * 60);
/// Failures allowed per hour from every client together.
pub const GLOBAL_PER_HOUR: usize = 60;
/// Clients remembered at once. Past this, the one quiet longest is forgotten first.
const MAX_CLIENTS: usize = 4096;
const HOUR: Duration = Duration::from_secs(60 * 60);
/// Who is signing in, as far as throttling is concerned: their address, or their IPv6 /64.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Client(IpAddr);
impl Client {
pub fn new(address: IpAddr) -> Client {
Client(match address {
IpAddr::V6(v6) => match v6.to_ipv4_mapped() {
Some(v4) => IpAddr::V4(v4),
None => {
let prefix = u128::from(v6) & !((1u128 << 64) - 1);
IpAddr::V6(Ipv6Addr::from(prefix))
}
},
v4 => v4,
})
}
/// The client a request came from. gitv-web listens on loopback behind Caddy, which puts
/// the real client's address last in `X-Forwarded-For`; that header is believed only from
/// a loopback peer, since anyone else could write anything there. Without connection
/// details (as in unit tests) every request is one unknown client.
pub fn of(headers: &HeaderMap, extensions: &Extensions) -> Client {
let peer = extensions.get::<ConnectInfo<SocketAddr>>().map(|ConnectInfo(addr)| addr.ip());
let forwarded = || {
let header = headers.get_all("x-forwarded-for").iter().next_back()?.to_str().ok()?;
header.rsplit(',').next()?.trim().parse::<IpAddr>().ok()
};
let address = match peer {
Some(peer) if peer.is_loopback() => forwarded().unwrap_or(peer),
Some(peer) => peer,
None => IpAddr::V4(Ipv4Addr::UNSPECIFIED),
};
Client::new(address)
}
}
impl<S: Send + Sync> FromRequestParts<S> for Client {
type Rejection = std::convert::Infallible;
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Client, Self::Rejection> {
Ok(Client::of(&parts.headers, &parts.extensions))
}
}
/// One client's record.
#[derive(Default)]
struct Record {
failures: u32,
last_failure: Option<Instant>,
locked_until: Option<Instant>,
}
impl Record {
fn locked_for(&self, now: Instant) -> Option<Duration> {
self.locked_until.and_then(|until| until.checked_duration_since(now)).filter(|d| !d.is_zero())
}
fn forgotten(&self, now: Instant) -> bool {
self.locked_for(now).is_none() && self.last_failure.is_none_or(|t| now.duration_since(t) >= FORGET_AFTER)
}
fn fail(&mut self, now: Instant) {
if self.forgotten(now) {
self.failures = 0;
}
self.failures += 1;
self.last_failure = Some(now);
if let Some(over) = self.failures.checked_sub(FREE_FAILURES + 1) {
let lock = Duration::from_secs(60).saturating_mul(1 << over.min(10)).min(LONGEST_LOCK);
self.locked_until = Some(now + lock);
}
}
}
#[derive(Default)]
pub struct Throttle {
clients: HashMap<Client, Record>,
/// When the failures of the last hour happened, oldest first, at most [`GLOBAL_PER_HOUR`].
recent: VecDeque<Instant>,
}
impl Throttle {
/// How long `client` must wait before trying again, if at all.
pub fn locked_for(&self, client: Client, now: Instant) -> Option<Duration> {
let own = self.clients.get(&client).and_then(|r| r.locked_for(now));
let global = (self.recent.len() >= GLOBAL_PER_HOUR)
.then(|| self.recent.front().and_then(|first| (*first + HOUR).checked_duration_since(now)))
.flatten()
.filter(|d| !d.is_zero());
own.max(global)
}
/// Count a failed attempt by `client`.
pub fn fail(&mut self, client: Client, now: Instant) {
while self.recent.front().is_some_and(|t| now.duration_since(*t) >= HOUR) {
self.recent.pop_front();
}
if self.recent.len() >= GLOBAL_PER_HOUR {
self.recent.pop_front();
}
self.recent.push_back(now);
self.clients.retain(|_, record| !record.forgotten(now));
if self.clients.len() >= MAX_CLIENTS && !self.clients.contains_key(&client) {
let quietest = self.clients.iter().min_by_key(|(_, r)| r.last_failure).map(|(c, _)| *c);
if let Some(quietest) = quietest {
self.clients.remove(&quietest);
}
}
self.clients.entry(client).or_default().fail(now);
}
/// `client` got everything right: its own record is cleared. Other clients' are not, and
/// neither is the global count, which other clients' failures still make up.
pub fn succeed(&mut self, client: Client) {
self.clients.remove(&client);
}
#[cfg(test)]
pub fn failures(&self, client: Client) -> u32 {
self.clients.get(&client).map_or(0, |r| r.failures)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn ip(text: &str) -> Client {
Client::new(text.parse().unwrap())
}
#[test]
fn a_client_is_locked_after_its_free_failures_and_longer_each_time() {
let (mut throttle, now, a) = (Throttle::default(), Instant::now(), ip("203.0.113.7"));
(0..FREE_FAILURES).for_each(|_| throttle.fail(a, now));
assert_eq!(throttle.locked_for(a, now), None);
throttle.fail(a, now);
assert_eq!(throttle.locked_for(a, now), Some(Duration::from_secs(60)));
throttle.fail(a, now);
assert_eq!(throttle.locked_for(a, now), Some(Duration::from_secs(120)));
(0..20).for_each(|_| throttle.fail(a, now));
assert_eq!(throttle.locked_for(a, now), Some(LONGEST_LOCK));
}
#[test]
fn one_clients_lock_leaves_the_others_alone() {
let (mut throttle, now) = (Throttle::default(), Instant::now());
(0..20).for_each(|_| throttle.fail(ip("203.0.113.7"), now));
assert!(throttle.locked_for(ip("203.0.113.7"), now).is_some());
assert_eq!(throttle.locked_for(ip("198.51.100.1"), now), None, "the owner elsewhere isn't locked");
}
#[test]
fn failures_are_forgotten_after_a_quiet_hour() {
let (mut throttle, start, a) = (Throttle::default(), Instant::now(), ip("203.0.113.7"));
(0..12).for_each(|_| throttle.fail(a, start));
// Long after the lock ran out and an hour after the last failure, one typo is free.
let later = start + LONGEST_LOCK + FORGET_AFTER;
throttle.fail(a, later);
assert_eq!(throttle.locked_for(a, later), None);
assert_eq!(throttle.failures(a), 1);
}
#[test]
fn failures_inside_the_hour_still_count() {
let (mut throttle, start, a) = (Throttle::default(), Instant::now(), ip("203.0.113.7"));
(0..=FREE_FAILURES).for_each(|_| throttle.fail(a, start));
// The minute's lock is over, but the next failure comes well inside the hour.
let later = start + Duration::from_secs(120);
assert_eq!(throttle.locked_for(a, later), None);
throttle.fail(a, later);
assert_eq!(throttle.locked_for(a, later), Some(Duration::from_secs(120)));
}
#[test]
fn success_clears_only_that_client() {
let (mut throttle, now) = (Throttle::default(), Instant::now());
(0..20).for_each(|_| throttle.fail(ip("203.0.113.7"), now));
(0..3).for_each(|_| throttle.fail(ip("198.51.100.1"), now));
throttle.succeed(ip("198.51.100.1"));
assert_eq!(throttle.failures(ip("198.51.100.1")), 0);
assert!(throttle.locked_for(ip("203.0.113.7"), now).is_some(), "the attacker stays locked");
}
#[test]
fn many_clients_together_are_held_to_the_hourly_rate() {
let (mut throttle, start) = (Throttle::default(), Instant::now());
let owner = ip("198.51.100.1");
// Each attacker address stays within its own free failures.
for i in 0..GLOBAL_PER_HOUR {
let at = start + Duration::from_secs(i as u64);
throttle.fail(Client::new(IpAddr::V4(Ipv4Addr::from(0x0a00_0000 + i as u32))), at);
}
let now = start + Duration::from_secs(GLOBAL_PER_HOUR as u64);
let wait = throttle.locked_for(owner, now).expect("the hourly budget is spent");
assert!(wait <= HOUR && wait > HOUR - Duration::from_secs(61), "{wait:?}");
// As the oldest failures age out of the hour, attempts are allowed again.
assert_eq!(throttle.locked_for(owner, start + HOUR), None);
}
#[test]
fn ipv6_clients_are_grouped_by_their_64_and_mapped_ipv4_is_ipv4() {
assert_eq!(ip("2001:db8:1:2:aaaa::1"), ip("2001:db8:1:2:ffff::9"));
assert_ne!(ip("2001:db8:1:2::1"), ip("2001:db8:1:3::1"));
assert_eq!(ip("::ffff:203.0.113.7"), ip("203.0.113.7"));
}
#[test]
fn forwarded_addresses_are_believed_only_from_loopback() {
let parts = |peer: &str, forwarded: Option<&str>| {
let mut request = axum::http::Request::builder();
if let Some(value) = forwarded {
request = request.header("x-forwarded-for", value);
}
let (mut parts, ()) = request.body(()).unwrap().into_parts();
parts.extensions.insert(ConnectInfo(peer.parse::<SocketAddr>().unwrap()));
parts
};
let of = |peer, forwarded| {
let parts = parts(peer, forwarded);
Client::of(&parts.headers, &parts.extensions)
};
assert_eq!(of("127.0.0.1:5000", Some("203.0.113.7")), ip("203.0.113.7"), "Caddy's word is taken");
assert_eq!(of("127.0.0.1:5000", Some("1.2.3.4, 203.0.113.7")), ip("203.0.113.7"), "the last hop is Caddy's");
assert_eq!(of("127.0.0.1:5000", Some("not an address")), ip("127.0.0.1"));
assert_eq!(of("127.0.0.1:5000", None), ip("127.0.0.1"));
assert_eq!(of("[::1]:5000", Some("2001:db8::1")), ip("2001:db8::1"));
assert_eq!(of("192.0.2.5:5000", Some("203.0.113.7")), ip("192.0.2.5"), "nobody else's is");
}
}
@@ -216,6 +216,25 @@ mod signing_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");
// An attacker's addresses within one IPv6 /64 share a lock.
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 a_forged_cookie_is_not_a_session() {
let mut s = Server::start_signed_out(repos());
@@ -271,6 +271,12 @@ impl Server {
pub fn post_signed_out(&self, path: &str, form: &[(&str, &str)]) -> Response {
request(self.port, "POST", path, None, Some(&form_body(form)))
}
/// POST a form without any cookie, as Caddy forwards one from the client at `address`.
pub fn post_signed_out_from(&self, address: &str, path: &str, form: &[(&str, &str)]) -> Response {
let extra = [("X-Forwarded-For", address)];
request_with(self.port, "POST", path, None, Some(&form_body(form)), &extra)
}
}
/// The session token a response's `Set-Cookie` gives, if any.
@@ -322,8 +328,22 @@ impl Response {
/// A plain HTTP/1.1 request, enough for testing a local server.
fn request(port: u16, method: &str, path: &str, cookie: Option<&str>, form: Option<&str>) -> Response {
request_with(port, method, path, cookie, form, &[])
}
fn request_with(
port: u16,
method: &str,
path: &str,
cookie: Option<&str>,
form: Option<&str>,
extra: &[(&str, &str)],
) -> Response {
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
let mut head = format!("{method} {path} HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n");
for (name, value) in extra {
head += &format!("{name}: {value}\r\n");
}
if let Some(cookie) = cookie {
head += &format!("Cookie: __Host-gitv={cookie}\r\n");
}