OXYGENHUB

Coverage / crates/hub/src/web/session.rs 88.2%

209 of 237 lines run, 24 of 72 functions · run #504 on main · run missed

1
//! Sign in, sign out and registration (hub spec §5.1).
2
3
use super::{Error, Page, Shell};
4
use crate::auth::{self, totp, Viewer};
5
use crate::db::{self, accounts};
6
use crate::throttle::{self, Key};
7
use crate::Shared;
8
use askama::Template;
9
use axum::extract::{Form, Query, State};
10
use axum::http::header;
11
use axum::response::{IntoResponse, Redirect, Response};
12
use serde::Deserialize;
13
14
#[derive(Template)]
15
#[template(path = "login.html")]
16
pub struct LoginPage {
17
    shell: Shell,
18
    error: Option<String>,
19
    next: String,
20
    /// Second step: the password was right, a one-time code is needed.
21
    totp_for: Option<String>,
22
    /// That step's proof of the password (`auth::pending_login`), so it
23
    /// asks only for the code.
24
    pending: String,
25
    /// Arrived from a password reset.
26
    reset: bool,
27
    /// Providers to sign in with (#106): (id, name).
28
    providers: Vec<(&'static str, &'static str)>,
29
}
30
31
#[derive(Deserialize)]
32
pub struct NextQuery {
33
    next: Option<String>,
34
    reset: Option<String>,
35
    #[serde(default)]
36
    error: Option<String>,
37
}
38
3951×
fn safe_next(next: Option<String>) -> String {
4041×
    match next {
4141×
        Some(n) if n.starts_with('/') && !n.starts_with("//") => n,
4251×
        _ => "/".into(),
43
    }
4451×
}
45
4610×
pub async fn login_form(State(app): State<Shared>, viewer: Viewer, Query(q): Query<NextQuery>) -> Response {
4710×
    if viewer.signed_in() {
480×
        return Redirect::to(&safe_next(q.next)).into_response();
4910×
    }
5010×
    let reset = q.reset.is_some();
5110×
    let providers = super::signin::buttons(&app).await;
5210×
    Page(LoginPage {
5310×
        shell: Shell::new(&app, "/login", &viewer),
5410×
        error: q.error,
5510×
        next: safe_next(q.next),
5610×
        totp_for: None,
5710×
        pending: String::new(),
5810×
        reset,
5910×
        providers,
6010×
    })
6110×
    .into_response()
6210×
}
63
64
#[derive(Deserialize)]
65
pub struct LoginForm {
66
    username: String,
67
    #[serde(default)]
68
    password: String,
69
    /// The code step's proof of the password (`auth::pending_login`).
70
    #[serde(default)]
71
    pending: String,
72
    #[serde(default)]
73
    code: String,
74
    #[serde(default)]
75
    next: String,
76
}
77
7841×
pub async fn login(
7941×
    State(app): State<Shared>,
8041×
    viewer: Viewer,
8141×
    headers: axum::http::HeaderMap,
8241×
    extensions: axum::http::Extensions,
8341×
    Form(f): Form<LoginForm>,
8441×
) -> Result<Response, Error> {
8541×
    let shell = Shell::new(&app, "/login", &viewer);
8641×
    let next = safe_next(Some(f.next.clone()));
8741×
    let username = f.username.trim().to_string();
8841×
    let account = accounts::account_by_name(&app.db, &username).await.map_err(|e| Error::from_db(shell.clone(), e))?;
89
    // The code step carries proof of the password, good for a few minutes;
90
    // a fresh one goes with each retry of the code.
9141×
    let now_ms = db::now_ms();
9241×
    let proven = !f.pending.is_empty()
932×
        && account.as_ref().is_some_and(|a| auth::pending_login_ok(&app.cookie_key, &a.username, &a.session_salt, &f.pending, now_ms));
9441×
    let pending = account
9541×
        .as_ref()
9641×
        .map(|a| auth::pending_login(&app.cookie_key, &a.username, &a.session_salt, now_ms + PENDING_LOGIN_MS))
9741×
        .unwrap_or_default();
9841×
    let fail = |msg: &str, totp_for: Option<String>| {
9934×
        Page(LoginPage {
10034×
            shell: shell.clone(),
10134×
            error: Some(msg.into()),
10234×
            next: next.clone(),
10334×
            totp_for,
10434×
            pending: pending.clone(),
10534×
            reset: false,
10634×
            providers: vec![],
10734×
        })
10834×
        .into_response()
10934×
    };
110
    // Guessing is slowed per account and per address (oxygenhub#221),
111
    // before the password is even looked at.
11241×
    let addr = crate::api::client_addr(&app, &headers, &extensions);
11341×
    let keys = [Key::account("login", &username), Key::address("login", &addr)];
11441×
    if let Some(wait) = app.throttle.lock().unwrap().wait(&keys, now_ms) {
1152×
        return Ok(fail(&throttle::message(wait), proven.then(|| username.clone())));
11639×
    }
11739×
    let failed = |app: &Shared| {
11829×
        let wait = app.throttle.lock().unwrap().failed(&keys, now_ms);
11929×
        let (app, username, addr) = (app.clone(), username.clone(), addr.clone());
12029×
        async move {
12129×
            if let Some(wait) = wait {
1222×
                let detail = format!("from {} for {}s", if addr.is_empty() { "an unknown address" } else { &addr }, wait / 1000);
1232×
                accounts::audit(&app.db, None, "login.throttled", &username, &detail).await.ok();
12427×
            }
12529×
        }
12629×
    };
12739×
    if !f.pending.is_empty() && !proven {
1281×
        return Ok(fail("That took too long: sign in again.", None));
12938×
    }
13038×
    let Some(account) = account.filter(|a| proven || auth::verify_password(&a.password_hash, &f.password)) else {
13129×
        accounts::audit(&app.db, None, "login.failed", &username, "").await.ok();
13229×
        failed(&app).await;
13329×
        return Ok(fail("Wrong username or password.", None));
134
    };
1359×
    if account.banned {
1360×
        return Ok(fail("This account is banned.", None));
1379×
    }
1389×
    if account.disabled {
1391×
        accounts::audit(&app.db, None, "login.disabled", &username, "").await.ok();
1401×
        return Ok(fail("Your account has been disabled. Contact the hub's administrator.", None));
1418×
    }
1428×
    if let Some(secret) = &account.totp_secret {
1432×
        if f.code.trim().is_empty() {
1441×
            return Ok(fail("Enter the code from your authenticator app.", Some(username)));
1451×
        }
1461×
        let now = (db::now_ms() / 1000) as u64;
1471×
        if !totp::verify(secret, &f.code, now) {
1480×
            match totp::use_recovery_code(&account.recovery_codes, &f.code) {
1490×
                Some(rest) => {
1500×
                    accounts::set_totp(&app.db, account.id, Some(secret), &rest).await.map_err(|e| Error::from_db(shell.clone(), e))?
151
                }
152
                None => {
1530×
                    accounts::audit(&app.db, Some(&account), "login.totp_failed", &username, "").await.ok();
1540×
                    failed(&app).await;
1550×
                    return Ok(fail("That code is not right.", Some(username)));
156
                }
157
            }
1581×
        }
1596×
    }
1607×
    app.throttle.lock().unwrap().cleared(&keys[0]);
1617×
    accounts::audit(&app.db, Some(&account), "login", &username, "").await.ok();
1627×
    Ok(signed_in(&app, &account, &next).await)
16341×
}
164
165
/// How long the code step of a sign-in may take after the password.
166
const PENDING_LOGIN_MS: i64 = 5 * 60 * 1000;
167
168
/// A redirect that sets the session cookie: a new session each time, so
169
/// signing in (after the code, with two-factor) always rotates it
170
/// (oxygenhub#223).
171137×
pub async fn signed_in(app: &Shared, account: &accounts::Account, to: &str) -> Response {
172137×
    let value = auth::new_session_id();
173137×
    if let Err(e) = db::sessions::create(&app.db, account.id, &auth::token_hash(&value), &account.session_salt).await {
1740×
        tracing::warn!("session for {}: {e}", account.username);
1750×
        return (axum::http::StatusCode::SERVICE_UNAVAILABLE, "Signing in failed for a moment: try again.").into_response();
176137×
    }
177137×
    let secure = if app.config.base_url().starts_with("https://") { "; Secure" } else { "" };
178137×
    let cookie = format!("{}={value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=2592000{secure}", auth::SESSION_COOKIE);
179137×
    ([(header::SET_COOKIE, cookie)], Redirect::to(to)).into_response()
180137×
}
181
182
#[derive(Deserialize)]
183
pub struct CsrfForm {
184
    #[serde(rename = "_csrf")]
185
    pub csrf: String,
186
}
187
1881×
pub async fn logout(State(app): State<Shared>, viewer: Viewer, Form(f): Form<CsrfForm>) -> Response {
1891×
    if !viewer.csrf_ok(&f.csrf) {
1900×
        return Redirect::to("/").into_response();
1911×
    }
1921×
    if let Some(v) = &viewer.0 {
1931×
        db::sessions::end_hash(&app.db, &auth::token_hash(&v.session)).await.ok();
1941×
        accounts::audit(&app.db, Some(&v.account), "logout", &v.account.username, "").await.ok();
1950×
    }
1961×
    let secure = if app.config.base_url().starts_with("https://") { "; Secure" } else { "" };
1971×
    let cookie = format!("{}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0{secure}", auth::SESSION_COOKIE);
1981×
    ([(header::SET_COOKIE, cookie)], Redirect::to("/")).into_response()
1991×
}
200
201
#[derive(Template)]
202
#[template(path = "register.html")]
203
pub struct RegisterPage {
204
    shell: Shell,
205
    error: Option<String>,
206
    mode: String,
207
    first: bool,
208
    invite: String,
209
    /// Providers to sign up with, when registration is open (#213) or
210
    /// the page has a usable invitation (oxygenhub#214).
211
    providers: Vec<(&'static str, &'static str)>,
212
    /// What the provider buttons carry: `?invite=CODE`, or nothing.
213
    provider_query: String,
214
}
215
216
/// The registration mode: the settings table overrides `hub.toml`.
217234×
pub async fn registration_mode(app: &Shared) -> String {
218234×
    accounts::setting(&app.db, "registration_mode").await.ok().flatten().unwrap_or_else(|| app.config.registration.mode.clone())
219234×
}
220
221
#[derive(Deserialize)]
222
pub struct InviteQuery {
223
    invite: Option<String>,
224
}
225
2264×
pub async fn register_form(State(app): State<Shared>, viewer: Viewer, Query(q): Query<InviteQuery>) -> Result<Response, Error> {
2274×
    if viewer.signed_in() {
2280×
        return Ok(Redirect::to("/").into_response());
2294×
    }
2304×
    let shell = Shell::new(&app, "/register", &viewer);
2314×
    let first = accounts::account_count(&app.db).await.map_err(|e| Error::from_db(shell.clone(), e))? == 0;
2324×
    let mode = registration_mode(&app).await;
2334×
    let invite = q.invite.unwrap_or_default().trim().to_string();
2344×
    let usable_invite = mode == "invite"
2354×
        && super::signin::invite_code_ok(&invite)
2362×
        && accounts::invitation_unused(&app.db, &invite).await.map_err(|e| Error::from_db(shell.clone(), e))?;
2374×
    let providers = if !first && (mode == "open" || usable_invite) { super::signin::buttons(&app).await } else { vec![] };
2384×
    let provider_query = if usable_invite { format!("?invite={invite}") } else { String::new() };
2394×
    Ok(Page(RegisterPage { shell, error: None, mode, first, invite, providers, provider_query }).into_response())
2404×
}
241
242
#[derive(Deserialize)]
243
pub struct RegisterForm {
244
    username: String,
245
    email: String,
246
    password: String,
247
    #[serde(default)]
248
    invite: String,
249
    /// The first account's setup code (oxygenhub#245).
250
    #[serde(default)]
251
    setup: String,
252
}
253
254129×
pub async fn register(State(app): State<Shared>, viewer: Viewer, Form(f): Form<RegisterForm>) -> Result<Response, Error> {
255129×
    let shell = Shell::new(&app, "/register", &viewer);
256129×
    let first = accounts::account_count(&app.db).await.map_err(|e| Error::from_db(shell.clone(), e))? == 0;
257129×
    let mode = registration_mode(&app).await;
258129×
    let fail = |msg: &str| {
2595×
        Page(RegisterPage {
2605×
            shell: shell.clone(),
2615×
            error: Some(msg.into()),
2625×
            mode: mode.clone(),
2635×
            first,
2645×
            invite: f.invite.clone(),
2655×
            providers: vec![],
2665×
            provider_query: String::new(),
2675×
        })
2685×
        .into_response()
2695×
    };
270129×
    let username = f.username.trim().to_string();
271129×
    if !crate::repos::names::valid_owner(&username) {
2720×
        return Ok(fail("A username is letters, digits, dots, dashes and underscores, and is not a reserved word."));
273129×
    }
274129×
    if let Err(e) = auth::password_ok(&f.password) {
2750×
        return Ok(fail(e));
276129×
    }
277129×
    if first && !crate::setup::matches(&app, &f.setup) {
2782×
        return Ok(fail(
2792×
            "This hub has no administrator yet. The first account needs the setup code the server logged when it started (also in setup-code in its data directory).",
2802×
        ));
281127×
    }
282127×
    if !first {
28339×
        match mode.as_str() {
28439×
            "open" => {}
28511×
            "invite" => {
28611×
                let ok = !f.invite.trim().is_empty()
2879×
                    && accounts::invitation_unused(&app.db, f.invite.trim()).await.map_err(|e| Error::from_db(shell.clone(), e))?;
28811×
                if !ok {
2892×
                    return Ok(fail("Registration needs a valid invitation code."));
2909×
                }
291
            }
2920×
            _ => return Ok(fail("Registration is closed.")),
293
        }
29488×
    }
295125×
    if accounts::account_by_name(&app.db, &username).await.map_err(|e| Error::from_db(shell.clone(), e))?.is_some()
296125×
        || accounts::org_by_name(&app.db, &username).await.map_err(|e| Error::from_db(shell.clone(), e))?.is_some()
297125×
        || accounts::username_retired(&app.db, &username).await.map_err(|e| Error::from_db(shell.clone(), e))?
298
    {
2991×
        return Ok(fail("That name is taken."));
300124×
    }
301124×
    let hash = auth::hash_password(&f.password).map_err(|e| Error::bad(shell.clone(), e.to_string()))?;
302124×
    let account = accounts::create_account(&app.db, &username, f.email.trim(), &hash, &auth::random_hex(16), first)
303124×
        .await
304124×
        .map_err(|e| Error::from_db(shell.clone(), e))?;
305124×
    if !first && mode == "invite" {
3068×
        accounts::use_invitation(&app.db, f.invite.trim(), account.id).await.ok();
307116×
    }
308124×
    if first {
30988×
        crate::setup::spend(&app);
31088×
    }
311124×
    accounts::audit(&app.db, Some(&account), "register", &username, if first { "first account: administrator" } else { "" }).await.ok();
312124×
    if let Err(e) = super::recovery::send_verification(&app, &account).await {
313122×
        tracing::info!("verification for {username}: {e}");
3142×
    }
315
    // The site's administrators hear of each new account (oxygenhub#183).
316124×
    if !first {
31736×
        let admins: Vec<(i64, crate::db::notify::Reason)> = accounts::accounts(&app.db)
31836×
            .await
31936×
            .unwrap_or_default()
32036×
            .into_iter()
32136×
            .filter(|a| a.is_admin)
32236×
            .map(|a| (a.id, crate::db::notify::Reason::Participating))
32336×
            .collect();
32436×
        let title = format!("New account: {username} signed up on {}", app.config.site.name);
32536×
        crate::notify::tell(&app, "account.registered", &title, &format!("/{username}"), &username, None, admins).await;
32688×
    }
327124×
    Ok(signed_in(&app, &account, "/").await)
328129×
}