GITv

Don't let a distributed attack lock the owner out of sign-in

Browse files

Once 60 failures an hour came in from any mix of clients, sign-in was refused for everyone, the owner with the right details included, so a dozen addresses could keep it closed indefinitely. A successful sign-in now also sets a 90-day trusted-device cookie: an expiry and an HMAC of it under a key derived from the authenticator secret, so nothing is stored and it outlives restarts and sign-outs. A browser carrying one isn't held to the global cap; its own per-client lock and the password-and-code check still apply. A new authenticator secret (setup --force) voids every token. The test client now keeps repeated headers, so it sees both cookies. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Author
Um9i vulgarmessiah@gmail.com
Date
22 Nov 2026, 22:07
Commit
26d14b54ef6f
Parent
a47d6e4

6 files changed +214−46

+1−1
@@ -49,7 +49,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`).
- 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.
- 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. While that cap is full, only browsers that have signed in before can try: a successful sign-in also sets a trusted-device cookie for 90 days, kept across sign-outs, so an attack spread over many addresses can't lock you out of a browser you've used. `gitv-web setup --force` (a new authenticator secret) forgets every such browser. 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.
@@ -71,6 +71,11 @@ pub enum AuthError {
Ownership { path: PathBuf, source: nix::errno::Errno },
}
/// How long a browser that signed in stays trusted, in seconds: 90 days. A trusted browser
/// isn't held back by the cap on failed sign-ins from every client together, so an attack
/// spread over many addresses can't lock the owner out (see the `throttle` module).
pub const DEVICE_LIFETIME: u64 = 90 * 24 * 60 * 60;
/// Longest account name accepted, in characters.
pub const MAX_USER: usize = 64;
@@ -490,6 +495,35 @@ impl Credentials {
})
}
/// A token marking a browser that has signed in, good for [`DEVICE_LIFETIME`] from
/// `unix_seconds`: the expiry, then an HMAC of it under a key derived from the authenticator
/// secret. Nothing is stored, so it outlives restarts; a new secret (`gitv-web setup
/// --force`) voids every one.
pub fn device_token(&self, unix_seconds: u64) -> String {
let expires = unix_seconds.saturating_add(DEVICE_LIFETIME).to_be_bytes();
let mut token = expires.to_vec();
token.extend_from_slice(&self.device_mac(&expires));
data_encoding::BASE64URL_NOPAD.encode(&token)
}
/// Whether `token` is one [`Credentials::device_token`] made for this account and it hasn't
/// expired at `unix_seconds`. Compared in constant time.
pub fn trusts_device(&self, token: &str, unix_seconds: u64) -> bool {
let Ok(token) = data_encoding::BASE64URL_NOPAD.decode(token.as_bytes()) else { return false };
let Some((expires, tag)) = token.split_first_chunk::<8>() else { return false };
u64::from_be_bytes(*expires) > unix_seconds && bool::from(self.device_mac(expires).as_slice().ct_eq(tag))
}
fn device_mac(&self, expires: &[u8; 8]) -> [u8; 32] {
// A key of its own, derived from the secret, so device tokens and codes never share one.
let mut derive = Hmac::<Sha256>::new_from_slice(&self.totp_secret).expect("HMAC takes any key length");
derive.update(b"gitv-web trusted device v1");
let key = derive.finalize().into_bytes();
let mut mac = Hmac::<Sha256>::new_from_slice(&key).expect("HMAC takes any key length");
mac.update(expires);
mac.finalize().into_bytes().into()
}
/// A digest of the password hash and TOTP secret. Sessions remember it, so changing either
/// (here or with `gitv-web password`/`setup`) signs every other session out.
pub fn fingerprint(&self) -> [u8; 32] {
@@ -874,6 +908,42 @@ mod tests {
}
}
mod device_tokens {
use super::*;
#[test]
fn are_trusted_until_they_expire() {
let token = account().device_token(1_000);
assert!(account().trusts_device(&token, 1_000));
assert!(account().trusts_device(&token, 1_000 + DEVICE_LIFETIME - 1));
assert!(!account().trusts_device(&token, 1_000 + DEVICE_LIFETIME));
}
#[test]
fn are_refused_when_forged_altered_or_from_another_secret() {
let token = account().device_token(1_000);
let mut bytes = data_encoding::BASE64URL_NOPAD.decode(token.as_bytes()).unwrap();
bytes[0] ^= 1; // A later expiry, which the tag no longer matches.
let altered = data_encoding::BASE64URL_NOPAD.encode(&bytes);
let mut other = account();
other.totp_secret = b"another secret of twenty".to_vec();
for forged in ["", "x", &altered, &other.device_token(1_000), &token[..token.len() - 2]] {
assert!(!account().trusts_device(forged, 1_000), "{forged:?}");
}
}
#[test]
fn survive_a_password_change() {
let mut credentials = account();
let token = credentials.device_token(1_000);
credentials.set_password("a whole new password").unwrap();
assert!(
credentials.trusts_device(&token, 1_000),
"devices are tied to the authenticator, not the password"
);
}
}
mod otpauth_uri {
use super::*;
@@ -32,6 +32,9 @@ use super::throttle::{Client, Throttle};
/// 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);
@@ -86,6 +89,14 @@ struct Session {
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 {
@@ -160,9 +171,15 @@ impl Login {
self.throttle.lock().unwrap_or_else(|e| e.into_inner())
}
/// 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())
/// 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.
@@ -175,13 +192,13 @@ impl Login {
self: &Arc<Self>,
purpose: &'static str,
credentials: &Arc<Credentials>,
client: Client,
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(client) {
if let Some(wait) = self.locked_for(asker) {
return Checked::Locked(wait);
}
#[cfg(test)]
@@ -191,7 +208,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(purpose, &creds, client, password_ok, &code)
login.settle(purpose, &creds, asker, password_ok, &code)
})
.await
.unwrap_or(Checked::Wrong)
@@ -208,7 +225,7 @@ impl Login {
&self,
purpose: &'static str,
credentials: &Credentials,
client: Client,
Asker { client, trusted }: Asker,
password_ok: bool,
code: &str,
) -> Checked {
@@ -229,7 +246,7 @@ impl Login {
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) {
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)
@@ -243,14 +260,19 @@ impl Login {
}
}
/// The SHA-256 of the session token in a request's cookie.
fn cookie_token(headers: &HeaderMap) -> Option<[u8; 32]> {
let token = headers
/// 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(COOKIE)?.strip_prefix('='))?;
.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())
}
@@ -269,13 +291,13 @@ fn html(status: StatusCode, body: String) -> Response {
(status, SECURITY, [(header::CONTENT_TYPE, "text/html; charset=utf-8")], body).into_response()
}
fn redirect(to: &str, cookie: Option<String>) -> Response {
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);
}
if let Some(cookie) = cookie.and_then(|c| HeaderValue::from_str(&c).ok()) {
response.headers_mut().insert(header::SET_COOKIE, cookie);
for cookie in cookies.iter().filter_map(|c| HeaderValue::from_str(c).ok()) {
response.headers_mut().append(header::SET_COOKIE, cookie);
}
response
}
@@ -329,7 +351,7 @@ fn challenge(error: Option<AuthError>, uri: &axum::http::Uri) -> Response {
None => {}
}
let wanted = uri.path_and_query().map_or("/", |p| p.as_str());
redirect(&format!("/login?next={}", super::encode(wanted.as_bytes())), None)
redirect(&format!("/login?next={}", super::encode(wanted.as_bytes())), &[])
}
// ---------------------------------------------------------------------------------------------
@@ -371,7 +393,7 @@ pub async fn sign_in_form(State(login): State<Arc<Login>>, headers: HeaderMap, R
if let Ok(credentials) = login.credentials()
&& login.session(&headers, &credentials).is_some()
{
return redirect(safe_next(&next), None);
return redirect(safe_next(&next), &[]);
}
sign_in_page(StatusCode::OK, &next, "")
}
@@ -382,7 +404,8 @@ pub async fn sign_in(State(login): State<Arc<Login>>, request: Request) -> Respo
return sign_in_page(StatusCode::SERVICE_UNAVAILABLE, "/", "Sign-in is busy. Try again in a moment.");
};
let client = Client::of(request.headers(), request.extensions());
if let Some(wait) = login.locked_for(client) {
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.
@@ -400,7 +423,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("sign-in", &credentials, client, Some(form.user), form.password, &form.code).await {
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 => {
@@ -412,7 +435,14 @@ pub async fn sign_in(State(login): State<Arc<Login>>, request: Request) -> Respo
}
}
match login.start_session(credentials.fingerprint()) {
Ok(cookie) => redirect(safe_next(&form.next), Some(cookie)),
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.")
@@ -443,7 +473,8 @@ pub async fn sign_out(
}
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", Some(clear))
// The device cookie stays: signing out doesn't make this browser a stranger.
redirect("/login", &[clear])
}
// ---------------------------------------------------------------------------------------------
@@ -488,15 +519,17 @@ 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(client) {
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 {
@@ -505,7 +538,7 @@ 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("password change", &credentials, client, None, form.current, &form.code).await {
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)));
@@ -702,7 +735,8 @@ mod tests {
.map(|_| {
let (login, credentials) = (Arc::clone(&login), Arc::clone(&credentials));
tokio::spawn(async move {
login.check("sign-in", &credentials, unknown(), None, "a wrong guess".into(), "123456").await
let asker = Asker { client: unknown(), trusted: false };
login.check("sign-in", &credentials, asker, None, "a wrong guess".into(), "123456").await
})
})
.collect();
@@ -7,7 +7,9 @@
//!
//! 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.
//! can never reach it alone. Browsers that have signed in before carry a trusted-device token
//! (see `gitv_web::auth::Credentials::device_token`) and aren't held to this cap, so many
//! addresses together can't lock the owner out; their own per-client lock still applies.
//!
//! Every method takes the current time, so the rules can be tested without waiting.
@@ -124,10 +126,11 @@ pub struct Throttle {
}
impl Throttle {
/// How long `client` must wait before trying again, if at all.
pub fn locked_for(&self, client: Client, now: Instant) -> Option<Duration> {
/// How long `client` must wait before trying again, if at all. A `trusted` browser (one that
/// has signed in before) waits only for its own lock, never the global cap.
pub fn locked_for(&self, client: Client, now: Instant, trusted: bool) -> Option<Duration> {
let own = self.clients.get(&client).and_then(|r| r.locked_for(now));
let global = (self.recent.len() >= GLOBAL_PER_HOUR)
let global = (!trusted && 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());
@@ -178,21 +181,21 @@ mod tests {
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);
assert_eq!(throttle.locked_for(a, now, false), None);
throttle.fail(a, now);
assert_eq!(throttle.locked_for(a, now), Some(Duration::from_secs(60)));
assert_eq!(throttle.locked_for(a, now, false), Some(Duration::from_secs(60)));
throttle.fail(a, now);
assert_eq!(throttle.locked_for(a, now), Some(Duration::from_secs(120)));
assert_eq!(throttle.locked_for(a, now, false), Some(Duration::from_secs(120)));
(0..20).for_each(|_| throttle.fail(a, now));
assert_eq!(throttle.locked_for(a, now), Some(LONGEST_LOCK));
assert_eq!(throttle.locked_for(a, now, false), 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");
assert!(throttle.locked_for(ip("203.0.113.7"), now, false).is_some());
assert_eq!(throttle.locked_for(ip("198.51.100.1"), now, false), None, "the owner elsewhere isn't locked");
}
#[test]
@@ -202,7 +205,7 @@ mod tests {
// 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.locked_for(a, later, false), None);
assert_eq!(throttle.failures(a), 1);
}
@@ -212,9 +215,9 @@ mod tests {
(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);
assert_eq!(throttle.locked_for(a, later, false), None);
throttle.fail(a, later);
assert_eq!(throttle.locked_for(a, later), Some(Duration::from_secs(120)));
assert_eq!(throttle.locked_for(a, later, false), Some(Duration::from_secs(120)));
}
#[test]
@@ -224,7 +227,7 @@ mod tests {
(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");
assert!(throttle.locked_for(ip("203.0.113.7"), now, false).is_some(), "the attacker stays locked");
}
#[test]
@@ -237,10 +240,18 @@ mod tests {
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");
let wait = throttle.locked_for(owner, now, false).expect("the hourly budget is spent");
assert!(wait <= HOUR && wait > HOUR - Duration::from_secs(61), "{wait:?}");
assert_eq!(throttle.locked_for(owner, now, true), None, "a browser that signed in before isn't held");
// As the oldest failures age out of the hour, attempts are allowed again.
assert_eq!(throttle.locked_for(owner, start + HOUR), None);
assert_eq!(throttle.locked_for(owner, start + HOUR, false), None);
}
#[test]
fn a_trusted_browser_is_still_held_by_its_own_lock() {
let (mut throttle, now, typist) = (Throttle::default(), Instant::now(), ip("198.51.100.2"));
(0..=FREE_FAILURES).for_each(|_| throttle.fail(typist, now));
assert!(throttle.locked_for(typist, now, true).is_some());
}
#[test]
@@ -235,6 +235,40 @@ mod signing_in {
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"));
// Twelve addresses, each within its own free failures, spend the hourly budget.
for n in 0..12 {
for _ in 0..5 {
// The failure that fills the budget is itself refused as locked.
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());
@@ -169,13 +169,27 @@ impl Server {
let extra = [("X-Forwarded-For", address)];
request_with(self.port, "POST", path, None, Some(&form_body(form)), &extra)
}
/// Like [`Server::post_signed_out_from`], from a browser carrying the trusted-device token
/// `device`.
pub fn post_from_device(&self, address: &str, device: &str, path: &str, form: &[(&str, &str)]) -> Response {
let cookie = format!("__Host-gitv-device={device}");
let extra = [("X-Forwarded-For", address), ("Cookie", cookie.as_str())];
request_with(self.port, "POST", path, None, Some(&form_body(form)), &extra)
}
}
/// The session token a response's `Set-Cookie` gives, if any.
pub fn session_cookie(response: &Response) -> Option<String> {
set_cookie(response, "__Host-gitv")
}
/// The value a response's `Set-Cookie` headers give the cookie `name`, if any.
pub fn set_cookie(response: &Response, name: &str) -> Option<String> {
response
.header("set-cookie")
.strip_prefix("__Host-gitv=")?
.lines()
.find_map(|line| line.strip_prefix(name)?.strip_prefix('='))?
.split(';')
.next()
.filter(|t| !t.is_empty())
@@ -250,10 +264,15 @@ fn request_with(
let head = String::from_utf8_lossy(&raw[..split]).into_owned();
let mut lines = head.lines();
let status = lines.next().and_then(|l| l.split_whitespace().nth(1)).and_then(|s| s.parse().ok()).unwrap();
let headers: HashMap<String, String> = lines
.filter_map(|l| l.split_once(':'))
.map(|(k, v)| (k.trim().to_ascii_lowercase(), v.trim().to_string()))
.collect();
// A repeated header (Set-Cookie, say) keeps every value, one per line.
let mut headers: HashMap<String, String> = HashMap::new();
for (name, value) in lines.filter_map(|l| l.split_once(':')) {
let entry = headers.entry(name.trim().to_ascii_lowercase()).or_default();
if !entry.is_empty() {
entry.push('\n');
}
entry.push_str(value.trim());
}
let mut body = raw[split + 4..].to_vec();
if headers.get("transfer-encoding").is_some_and(|v| v.eq_ignore_ascii_case("chunked")) {
body = dechunk(&body);