10.3 KiB · text History 263b40b
//! Open sign-up (`REGISTRATION_ENABLED=true`) and its cheap abuse guards.
//!
//! Without an invite, a sign-up must:
//! - leave the honeypot field (`website`, hidden from people) empty;
//! - take at least `REGISTRATION_MIN_FILL_SECS` from loading the form, which
//!   carries a signed timestamp (an HMAC under a key derived from
//!   `LINK_SECRET`; a stamp older than a day is refused too);
//! - come from an address with fewer than `REGISTRATION_PER_IP_PER_DAY`
//!   open sign-ups in the last 24 hours (`ClientIp`, so only trusted proxies'
//!   forwarding headers count).
//!
//! Redeeming an invite skips all three: someone vouched for it.
//!
//! Every self-made account starts unverified (read-only while
//! `REQUIRE_EMAIL_VERIFICATION`). One that never verifies and never posts is
//! deleted after `REGISTRATION_UNVERIFIED_TTL_DAYS` by [`spawn_sweeper`].
use std::net::IpAddr;
use std::sync::Arc;

use chrono::Utc;
use sea_orm::{ConnectionTrait, DatabaseBackend, DatabaseConnection, FromQueryResult, Statement};
use tracing::{error, info};
use uuid::Uuid;

use crate::links::Signer;
use crate::Config;

/// The guards' knobs.
#[derive(Debug, Clone)]
pub struct Guards {
    /// Open sign-ups per client address per 24 hours (0: no limit).
    pub per_ip_per_day: i64,
    /// Seconds a person needs, at least, to fill in the form (0: no check).
    pub min_fill_secs: i64,
    /// Never-verified, never-posted accounts are deleted after this many
    /// days (0: kept).
    pub unverified_ttl_days: i64,
}

impl Default for Guards {
    fn default() -> Self {
        Guards { per_ip_per_day: 3, min_fill_secs: 3, unverified_ttl_days: 7 }
    }
}

impl Guards {
    pub fn from_env() -> Self {
        let d = Guards::default();
        let num = |k: &str, dflt: i64| {
            std::env::var(k).ok().and_then(|v| v.trim().parse().ok()).filter(|n: &i64| *n >= 0).unwrap_or(dflt)
        };
        Guards {
            per_ip_per_day: num("REGISTRATION_PER_IP_PER_DAY", d.per_ip_per_day),
            min_fill_secs: num("REGISTRATION_MIN_FILL_SECS", d.min_fill_secs),
            unverified_ttl_days: num("REGISTRATION_UNVERIFIED_TTL_DAYS", d.unverified_ttl_days),
        }
    }
}

/// A stamp older than this is refused (a bot can't fetch one form and
/// replay its stamp forever).
const STAMP_MAX_AGE_SECS: i64 = 24 * 3600;

fn signer(config: &Config) -> Signer {
    // Its own key, so a form stamp is never a valid `/out` signature.
    Signer::new(&format!("register-form\0{}", config.link_secret))
}

/// The form's hidden `stamp`: when it was served, signed.
pub fn stamp(config: &Config) -> String {
    stamp_at(config, Utc::now().timestamp())
}

fn stamp_at(config: &Config, ts: i64) -> String {
    format!("{ts}.{}", signer(config).sign(&ts.to_string()))
}

/// Why an open sign-up was refused before anything else was looked at.
#[derive(Debug, PartialEq, Eq)]
pub enum Refused {
    Honeypot,
    TooFast,
    /// Missing, forged or stale stamp.
    Stamp,
    TooMany,
}

impl Refused {
    pub fn message(&self) -> &'static str {
        match self {
            Refused::Honeypot => "Registration failed.",
            Refused::TooFast => "That was quick. Check the form and submit it again.",
            Refused::Stamp => "This form has expired. Please submit it again.",
            Refused::TooMany => {
                "Too many accounts were created from your network today. Try again tomorrow, or ask a member for an invite."
            }
        }
    }
}

/// The honeypot and the fill time.
pub fn check_form(config: &Config, honeypot: Option<&str>, stamp: Option<&str>) -> Result<(), Refused> {
    check_form_at(config, honeypot, stamp, Utc::now().timestamp())
}

fn check_form_at(config: &Config, honeypot: Option<&str>, stamp: Option<&str>, now: i64) -> Result<(), Refused> {
    if honeypot.is_some_and(|h| !h.trim().is_empty()) {
        return Err(Refused::Honeypot);
    }
    let (ts, sig) = stamp.and_then(|s| s.split_once('.')).ok_or(Refused::Stamp)?;
    if !signer(config).verify(ts, sig) {
        return Err(Refused::Stamp);
    }
    let ts: i64 = ts.parse().map_err(|_| Refused::Stamp)?;
    let age = now - ts;
    if age > STAMP_MAX_AGE_SECS {
        return Err(Refused::Stamp);
    }
    if age < config.registration.min_fill_secs {
        return Err(Refused::TooFast);
    }
    Ok(())
}

#[derive(FromQueryResult)]
struct Count {
    n: i64,
}

/// Accounts created from `ip` in the last 24 hours that didn't redeem an
/// invite (the address registration records in `user_ips`).
pub async fn open_signups_from<C: ConnectionTrait>(db: &C, ip: IpAddr) -> Result<i64, sea_orm::DbErr> {
    let stmt = Statement::from_sql_and_values(
        DatabaseBackend::Postgres,
        "SELECT count(*) AS n FROM user_ips ui JOIN users u ON u.id = ui.user_id \
         WHERE ui.ip = $1 AND u.created_at > now() - interval '1 day' \
         AND ui.first_seen < u.created_at + interval '10 minutes' \
         AND NOT EXISTS (SELECT 1 FROM registration_tokens r WHERE r.used_by_user_id = u.id)",
        [crate::client_ip::canonical(ip).to_string().into()],
    );
    Ok(Count::find_by_statement(stmt).one(db).await?.map_or(0, |c| c.n))
}

/// The per-address limit.
pub async fn check_rate<C: ConnectionTrait>(db: &C, config: &Config, ip: Option<IpAddr>) -> Result<(), Refused> {
    let limit = config.registration.per_ip_per_day;
    let Some(ip) = ip.filter(|_| limit > 0) else { return Ok(()) };
    match open_signups_from(db, ip).await {
        Ok(n) if n >= limit => Err(Refused::TooMany),
        Ok(_) => Ok(()),
        Err(e) => {
            // Fail open: a broken count shouldn't lock everyone out.
            error!("sign-up rate check failed: {e}");
            Ok(())
        }
    }
}

#[derive(FromQueryResult)]
struct Stale {
    id: Uuid,
    username: String,
}

/// Delete accounts that never verified their email and never wrote
/// anything, older than `days`. Staff are never touched. Each deletion is
/// in the moderation log (`expire_unverified`, by the system). Returns how
/// many went.
pub async fn sweep_unverified(db: &DatabaseConnection, days: i64) -> Result<u64, sea_orm::DbErr> {
    let stmt = Statement::from_sql_and_values(
        DatabaseBackend::Postgres,
        "SELECT u.id, u.username FROM users u \
         WHERE u.email_verified_at IS NULL AND NOT u.is_staff \
         AND u.created_at < now() - make_interval(days => $1) \
         AND NOT EXISTS (SELECT 1 FROM posts p WHERE p.user_id = u.id) \
         AND NOT EXISTS (SELECT 1 FROM topics t WHERE t.user_id = u.id) \
         LIMIT 500",
        [(days as i32).into()],
    );
    let stale = Stale::find_by_statement(stmt).all(db).await?;
    let mut gone = 0;
    for s in stale {
        let del = Statement::from_sql_and_values(
            DatabaseBackend::Postgres,
            "DELETE FROM users WHERE id = $1 AND email_verified_at IS NULL",
            [s.id.into()],
        );
        match db.execute(del).await {
            Ok(r) if r.rows_affected() > 0 => {
                gone += 1;
                crate::moderation::log(
                    db,
                    crate::moderation::Actor::system(),
                    "expire_unverified",
                    "user",
                    Some(s.id),
                    &s.username,
                    Some(&format!("never verified its email within {days} days")),
                )
                .await;
            }
            Ok(_) => {}
            // Something else still points at it: keep it, say so.
            Err(e) => error!("could not remove unverified account {}: {e}", s.username),
        }
    }
    Ok(gone)
}

/// Run [`sweep_unverified`] at start and hourly, when there's anything to
/// sweep: verification required and a TTL set.
pub fn spawn_sweeper(db: Arc<DatabaseConnection>, config: Arc<Config>) {
    let days = config.registration.unverified_ttl_days;
    if days == 0 || !config.require_email_verification {
        return;
    }
    tokio::spawn(async move {
        let mut tick = tokio::time::interval(std::time::Duration::from_secs(3600));
        loop {
            tick.tick().await;
            match sweep_unverified(db.as_ref(), days).await {
                Ok(0) => {}
                Ok(n) => info!("removed {n} never-verified account(s) older than {days} days"),
                Err(e) => error!("unverified-account sweep failed: {e}"),
            }
        }
    });
}

/// Boot-time warnings about a registration setup that can't work as meant.
pub fn boot_warnings(config: &Config) -> Vec<&'static str> {
    let mut w = vec![];
    if config.registration_enabled {
        if !config.require_email_verification {
            w.push(
                "REGISTRATION_ENABLED=true with REQUIRE_EMAIL_VERIFICATION=false: anyone can sign up and post without a working email address",
            );
        }
        if !config.mail_configured() {
            w.push(
                "REGISTRATION_ENABLED=true without MAIL_PRISM_URL/MAIL_PRISM_API_KEY: verification links are only logged, so new accounts can't verify themselves",
            );
        }
    }
    w
}

#[cfg(test)]
mod tests {
    use super::*;

    fn config() -> Config {
        let mut c = Config::from_env();
        c.link_secret = "s".into();
        c.registration = Guards::default();
        c
    }

    #[test]
    fn the_form_stamp_needs_time_a_signature_and_freshness() {
        let c = config();
        let now = 1_800_000_000;
        let ok = stamp_at(&c, now - 10);
        assert_eq!(check_form_at(&c, None, Some(&ok), now), Ok(()));
        assert_eq!(check_form_at(&c, Some(""), Some(&ok), now), Ok(()));
        assert_eq!(check_form_at(&c, Some("http://spam"), Some(&ok), now), Err(Refused::Honeypot));
        assert_eq!(check_form_at(&c, None, Some(&stamp_at(&c, now - 1)), now), Err(Refused::TooFast));
        assert_eq!(check_form_at(&c, None, Some(&stamp_at(&c, now - 2 * 86400)), now), Err(Refused::Stamp));
        assert_eq!(check_form_at(&c, None, None, now), Err(Refused::Stamp));
        // Someone else's key, or a moved timestamp.
        let sig = ok.split_once('.').unwrap().1;
        assert_eq!(check_form_at(&c, None, Some(&format!("{}.{sig}", now - 100)), now), Err(Refused::Stamp));
        let mut other = config();
        other.link_secret = "t".into();
        assert_eq!(check_form_at(&other, None, Some(&ok), now), Err(Refused::Stamp));
        // Not an /out signature.
        assert!(!crate::links::Signer::new("s").verify(&(now - 10).to_string(), sig));
    }
}