fix(hub): bind email budget reserve to a bounded resend chain

The global reserve is claimed atomically with the budget check by deleting a live
attempt for the same address (under 5 failures, under 3 resends, chain under 30
minutes), so it cannot fund mail to other addresses, branch or race.
This commit is contained in:
Loki 2026-10-24 17:48:20 +02:00
parent 6ea14d0ec2
commit fea876654b
Signed by: boba
GPG key ID: 253067914055423B
5 changed files with 196 additions and 33 deletions

View file

@ -49,7 +49,7 @@ Eight digits from the OS CSPRNG with rejection sampling, valid for ten minutes,
### Rate limits (SQLite ledger of MACs, atomic check-and-record)
Per address 1 per 60 s and 5 per hour; per source (`X-Forwarded-For`, as GitHub login) 10 per hour, where IPv6 sources are grouped by /64 and IPv4-mapped IPv6 counts as IPv4 (so rotating host bits does not dodge the limit; an attacker with a larger prefix or many networks still can); globally 300 per hour for new sign-ins plus a separate reserve of 100 per hour that only resends can spend, meaning requests carrying the `__Host-vnox_email` cookie of a still-live pending attempt. Flooding the general budget therefore cannot cut off people who are already mid sign-in. It does not protect people who start after the budget is exhausted, and an attacker who first collects live attempts can spend the reserve too (bounded by the per-address and per-source limits). Budget is spent when a request passes validation, even if delivery later fails. The in-memory per-IP limiter used by GitHub (20 per minute, 300 global) also applies to both endpoints. At most 4096 attempts are pending.
Per address 1 per 60 s and 5 per hour; per source (`X-Forwarded-For`, as GitHub login) 10 per hour, where IPv6 sources are grouped by /64 and IPv4-mapped IPv6 counts as IPv4 (so rotating host bits does not dodge the limit; an attacker with a larger prefix or many networks still can); globally 300 per hour for new sign-ins plus a separate reserve of 100 per hour that only qualifying resends can spend. A resend qualifies when its `__Host-vnox_email` cookie belongs to a live attempt for the same normalized address with fewer than 5 failed tries, fewer than 3 earlier resends in its chain, and a chain younger than 30 minutes. The attempt is claimed by deleting it inside the same SQLite transaction that checks and records the send budgets, so the check and the reservation are atomic: parallel resends cannot both claim one attempt, chains cannot branch, and a refused request rolls the claim back. The chain counter and start time are carried to the replacement attempt. Flooding the general budget therefore cannot cut off people who are already mid sign-in, and one live attempt cannot be turned into a stream of reserve-funded mail to other addresses. It does not help people who start after the budget is exhausted; a resend that no longer qualifies, once it passes the normal budget, starts a fresh chain (each such reset costs a normal-budget send). Budget is spent when a request passes validation, even if delivery later fails. The in-memory per-IP limiter used by GitHub (20 per minute, 300 global) also applies to both endpoints. At most 4096 attempts are pending.
### Address handling and accounts

View file

@ -0,0 +1,5 @@
-- Resends from a browser with a live attempt may draw on a reserved global budget, but
-- only along a bounded chain: each attempt records how many resends led to it and when
-- the chain began.
ALTER TABLE email_attempts ADD COLUMN resends INTEGER NOT NULL DEFAULT 0;
ALTER TABLE email_attempts ADD COLUMN chain_started INTEGER NOT NULL DEFAULT 0;

View file

@ -18,6 +18,26 @@ pub const MAX_FAILURES: i64 = 5;
/// Pending attempts kept at once; protects the table from being filled by anonymous traffic.
const MAX_PENDING: i64 = 4096;
const CODE_DIGITS: usize = 8;
/// Resends per chain that may use the reserved global budget.
pub const MAX_RESENDS: i64 = 3;
/// Seconds after which a chain of resends stops qualifying for the reserve.
const CHAIN_LIFETIME: i64 = 1800;
/// Position in a resend chain carried from a claimed attempt to its replacement.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Chain {
resends: i64,
started: i64,
}
/// Result of [`EmailAuth::reserve_send`].
pub enum Reservation {
Denied,
/// `chain` is set when the request replaced a live attempt for the same address.
Allowed {
chain: Option<Chain>,
},
}
/// Delivery boundary. The production implementation is [`crate::mail::Mailer`]; tests
/// inject a recorder so no network traffic or real mail is ever produced.
@ -106,19 +126,43 @@ impl EmailAuth {
self.mac("vnox-email-source-v1", &[source])
}
/// Atomically checks every send budget and records the send in one statement, so
/// concurrent requests cannot overshoot a limit.
/// Checks every send budget and records the send, in one transaction.
///
/// A request carrying the cookie of a live attempt for the *same address* (fewer than
/// [`MAX_FAILURES`] failures, fewer than [`MAX_RESENDS`] earlier resends, chain younger
/// than 30 minutes) claims that attempt by deleting it inside the transaction, which
/// makes the claim exclusive (parallel resends cannot both win it, chains cannot
/// branch) and rolls back with the rest if any budget refuses. Only a claimed request
/// may spend the global reserve.
pub async fn reserve_send(
&self,
pool: &SqlitePool,
email_mac: &str,
source_mac: &str,
resend: bool,
) -> anyhow::Result<bool> {
browser: Option<&str>,
) -> anyhow::Result<Reservation> {
let t = now();
let limits = self.limits;
let mut transaction = pool.begin().await?;
let claimed: Option<(i64, i64)> = match browser {
Some(browser) => {
sqlx::query_as(
"DELETE FROM email_attempts WHERE browser_hash=? AND email_mac=? AND expires_at>? \
AND failures<? AND resends<? AND chain_started>? RETURNING resends,chain_started",
)
.bind(hash(browser))
.bind(email_mac)
.bind(t)
.bind(MAX_FAILURES)
.bind(MAX_RESENDS)
.bind(t - CHAIN_LIFETIME)
.fetch_optional(&mut *transaction)
.await?
}
None => None,
};
let global_limit = limits.global_hour
+ if resend {
+ if claimed.is_some() {
limits.global_resend_reserve
} else {
0
@ -143,21 +187,19 @@ impl EmailAuth {
.bind(limits.per_source_hour)
.bind(t - 3600)
.bind(global_limit)
.execute(pool)
.execute(&mut *transaction)
.await?;
Ok(result.rows_affected() == 1)
if result.rows_affected() != 1 {
transaction.rollback().await?;
return Ok(Reservation::Denied);
}
/// True when this browser cookie maps to an unexpired pending attempt.
pub async fn has_pending(&self, pool: &SqlitePool, browser: &str) -> anyhow::Result<bool> {
let found: Option<i64> = sqlx::query_scalar(
"SELECT 1 FROM email_attempts WHERE browser_hash=? AND expires_at>?",
)
.bind(hash(browser))
.bind(now())
.fetch_optional(pool)
.await?;
Ok(found.is_some())
transaction.commit().await?;
Ok(Reservation::Allowed {
chain: claimed.map(|(resends, started)| Chain {
resends: resends + 1,
started,
}),
})
}
/// Stores a new pending attempt, replacing the one bound to the browser's previous
@ -168,6 +210,7 @@ impl EmailAuth {
email: &str,
browser: &str,
previous_browser: Option<&str>,
chain: Option<Chain>,
) -> anyhow::Result<(String, String)> {
let mut transaction = pool.begin().await?;
if let Some(previous) = previous_browser {
@ -184,13 +227,15 @@ impl EmailAuth {
let code = generate_code();
let email_mac = self.email_mac(email);
sqlx::query(
"INSERT INTO email_attempts(attempt_id,browser_hash,email_mac,code_mac,expires_at) VALUES(?,?,?,?,?)",
"INSERT INTO email_attempts(attempt_id,browser_hash,email_mac,code_mac,expires_at,resends,chain_started) VALUES(?,?,?,?,?,?,?)",
)
.bind(&attempt_id)
.bind(hash(browser))
.bind(&email_mac)
.bind(self.code_mac(&attempt_id, &email_mac, &code))
.bind(now() + CODE_TTL)
.bind(chain.map_or(0, |c| c.resends))
.bind(chain.map_or_else(now, |c| c.started))
.execute(&mut *transaction)
.await?;
transaction.commit().await?;

View file

@ -220,23 +220,26 @@ async fn email_start(
let lang = Lang::from_tag(body.lang.as_deref());
let source = mail.source_mac(&client_ip(&headers));
let previous = cookie(&headers, EMAIL_BROWSER);
let resend = match &previous {
Some(browser) => mail.has_pending(&auth.pool, browser).await.unwrap_or(false),
None => false,
};
let reserved = mail
.reserve_send(&auth.pool, &mail.email_mac(&address), &source, resend)
.await;
match reserved {
Ok(true) => {}
Ok(false) => return failure(StatusCode::TOO_MANY_REQUESTS, "try_later"),
Err(_) => return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
let chain = match mail
.reserve_send(
&auth.pool,
&mail.email_mac(&address),
&source,
previous.as_deref(),
)
.await
{
Ok(email::Reservation::Allowed { chain }) => chain,
Ok(email::Reservation::Denied) => {
return failure(StatusCode::TOO_MANY_REQUESTS, "try_later");
}
Err(_) => return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later"),
};
// Housekeeping failures must not block sign-in; expiry is enforced on every read.
let _ = store::cleanup(&auth.pool).await;
let browser = store::token();
let Ok((attempt_id, code)) = mail
.create_attempt(&auth.pool, &address, &browser, previous.as_deref())
.create_attempt(&auth.pool, &address, &browser, previous.as_deref(), chain)
.await
else {
return failure(StatusCode::SERVICE_UNAVAILABLE, "try_later");

View file

@ -910,3 +910,113 @@ async fn global_reserve_serves_only_resends_from_a_live_attempt() {
assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
assert!(cookies.is_empty());
}
fn reserve_limits() -> EmailLimits {
EmailLimits {
address_cooldown: 0,
per_address_hour: 1000,
per_source_hour: 1000,
global_hour: 1,
global_resend_reserve: 100,
}
}
async fn resend(h: &Harness, cookie: &str, email: &str) -> (StatusCode, Vec<String>) {
let mut request = post("/v1/auth/email/start", json!({"email": email}));
request.cookie = Some(cookie);
let (status, cookies, _) = send(&h.app, request.request()).await;
(status, cookies)
}
#[tokio::test]
async fn reserve_is_not_available_for_a_different_address() {
let h = harness_with(reserve_limits(), false, true).await;
let browser = start(&h, "a@example.com").await;
// The normal budget (1) is spent. A live attempt for a@ must not open the reserve
// for sending to anyone else.
assert_eq!(
resend(&h, &browser, "victim@example.com").await.0,
StatusCode::TOO_MANY_REQUESTS
);
assert_eq!(
resend(&h, &browser, "a@example.com").await.0,
StatusCode::ACCEPTED
);
assert_eq!(h.mail.count(), 2);
}
#[tokio::test]
async fn resend_chain_is_bounded() {
let h = harness_with(reserve_limits(), false, true).await;
let mut browser = start(&h, "a@example.com").await;
for i in 0..3 {
let (status, cookies) = resend(&h, &browser, "a@example.com").await;
assert_eq!(status, StatusCode::ACCEPTED, "resend {i}");
browser = pair(&cookies, "__Host-vnox_email");
}
// Reserve is still plentiful, but the chain has used its three resends.
assert_eq!(
resend(&h, &browser, "a@example.com").await.0,
StatusCode::TOO_MANY_REQUESTS
);
assert_eq!(h.mail.count(), 4);
// The refused request rolled back: the live attempt still verifies.
let code = h.mail.last_code();
assert_eq!(
verify(&h, Some(&browser), "a@example.com", &code).await.0,
StatusCode::OK
);
}
#[tokio::test]
async fn old_chains_and_attempts_with_spent_tries_lose_the_reserve() {
let h = harness_with(reserve_limits(), false, true).await;
let browser = start(&h, "a@example.com").await;
sqlx::query("UPDATE email_attempts SET failures=5")
.execute(&h.state.database)
.await
.unwrap();
assert_eq!(
resend(&h, &browser, "a@example.com").await.0,
StatusCode::TOO_MANY_REQUESTS
);
sqlx::query("UPDATE email_attempts SET failures=0, chain_started=chain_started-3600")
.execute(&h.state.database)
.await
.unwrap();
assert_eq!(
resend(&h, &browser, "a@example.com").await.0,
StatusCode::TOO_MANY_REQUESTS
);
}
#[tokio::test]
async fn parallel_resends_claim_a_live_attempt_only_once() {
let h = harness_with(reserve_limits(), false, true).await;
let browser = start(&h, "a@example.com").await;
let mut tasks = Vec::new();
for _ in 0..6 {
let app = h.app.clone();
let browser = browser.clone();
tasks.push(tokio::spawn(async move {
let mut request = post("/v1/auth/email/start", json!({"email": "a@example.com"}));
request.cookie = Some(&browser);
send(&app, request.request()).await.0
}));
}
let mut accepted = 0;
for task in tasks {
if task.await.unwrap() == StatusCode::ACCEPTED {
accepted += 1;
}
}
assert_eq!(accepted, 1);
assert_eq!(h.mail.count(), 2);
assert_eq!(
sqlx::query_scalar::<_, i64>("SELECT COUNT(*) FROM email_attempts")
.fetch_one(&h.state.database)
.await
.unwrap(),
1
);
}