fix(hub): group IPv6 sources by /64 and reserve email budget for resends

Per-source limits no longer dodgeable by rotating IPv6 host bits, and a
separate global reserve lets browsers with a live attempt resend even when
fresh starts exhaust the hourly budget.
This commit is contained in:
Loki 2026-10-24 17:45:36 +02:00
parent cca084b0ae
commit 6ea14d0ec2
Signed by: boba
GPG key ID: 253067914055423B
6 changed files with 140 additions and 240 deletions

View file

@ -48,6 +48,10 @@ pub struct EmailLimits {
pub per_address_hour: i64,
pub per_source_hour: i64,
pub global_hour: i64,
/// Extra global budget usable only by resends from a browser that already holds a
/// live attempt, so exhausting `global_hour` with fresh starts cannot lock out people
/// who are mid sign-in.
pub global_resend_reserve: i64,
}
impl Default for EmailLimits {
@ -57,6 +61,7 @@ impl Default for EmailLimits {
per_address_hour: 5,
per_source_hour: 10,
global_hour: 300,
global_resend_reserve: 100,
}
}
}
@ -108,9 +113,16 @@ impl EmailAuth {
pool: &SqlitePool,
email_mac: &str,
source_mac: &str,
resend: bool,
) -> anyhow::Result<bool> {
let t = now();
let limits = self.limits;
let global_limit = limits.global_hour
+ if resend {
limits.global_resend_reserve
} else {
0
};
let result = sqlx::query(
"INSERT INTO email_send_log(email_mac,source_mac,sent_at) SELECT ?,?,? WHERE \
(SELECT COUNT(*) FROM email_send_log WHERE email_mac=? AND sent_at>?)=0 AND \
@ -130,12 +142,24 @@ impl EmailAuth {
.bind(t - 3600)
.bind(limits.per_source_hour)
.bind(t - 3600)
.bind(limits.global_hour)
.bind(global_limit)
.execute(pool)
.await?;
Ok(result.rows_affected() == 1)
}
/// 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())
}
/// Stores a new pending attempt, replacing the one bound to the browser's previous
/// cookie (a resend). Returns the generated code. Fails when capacity is reached.
pub async fn create_attempt(

View file

@ -75,12 +75,25 @@ fn set_cookie(response: &mut Response, name: &'static str, value: String, ttl: i
}
fn client_ip(headers: &HeaderMap) -> String {
// The loopback-only service trusts only the reverse proxy, which overwrites this header.
headers
// IPv6 sources are grouped by /64 (one subscriber's usual allocation or smaller), and
// IPv4-mapped addresses count as IPv4, so rotating host bits cannot dodge per-source limits.
use std::net::IpAddr;
match headers
.get("x-forwarded-for")
.and_then(|v| v.to_str().ok())
.and_then(|v| v.parse::<std::net::IpAddr>().ok())
.map(|v| v.to_string())
.unwrap_or_else(|| "local".into())
.and_then(|v| v.parse::<IpAddr>().ok())
{
Some(IpAddr::V6(v6)) => match v6.to_ipv4_mapped() {
Some(v4) => v4.to_string(),
None => {
let mut octets = v6.octets();
octets[8..].fill(0);
format!("{}/64", std::net::Ipv6Addr::from(octets))
}
},
Some(v4) => v4.to_string(),
None => "local".into(),
}
}
fn allowed(auth: &AuthService, headers: &HeaderMap) -> bool {
auth.allow(&client_ip(headers))
@ -206,8 +219,13 @@ 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)
.reserve_send(&auth.pool, &mail.email_mac(&address), &source, resend)
.await;
match reserved {
Ok(true) => {}
@ -217,7 +235,6 @@ async fn email_start(
// Housekeeping failures must not block sign-in; expiry is enforced on every read.
let _ = store::cleanup(&auth.pool).await;
let browser = store::token();
let previous = cookie(&headers, EMAIL_BROWSER);
let Ok((attempt_id, code)) = mail
.create_attempt(&auth.pool, &address, &browser, previous.as_deref())
.await