OXYGENHUB
# aa0bfbd11f02 oxygenhub / crates / hub / src / web / session.rs
11.8 KiB · Rust · last changed Sign-in, 2FA codes, device codes and reset requests slow guessing 20 days ago source blame history raw
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
39
fn safe_next(next: Option<String>) -> String {
40
    match next {
41
        Some(n) if n.starts_with('/') && !n.starts_with("//") => n,
42
        _ => "/".into(),
43
    }
44
}
45
46
pub async fn login_form(State(app): State<Shared>, viewer: Viewer, Query(q): Query<NextQuery>) -> Response {
47
    if viewer.signed_in() {
48
        return Redirect::to(&safe_next(q.next)).into_response();
49
    }
50
    let reset = q.reset.is_some();
51
    let providers = super::signin::buttons(&app).await;
52
    Page(LoginPage {
53
        shell: Shell::new(&app, "/login", &viewer),
54
        error: q.error,
55
        next: safe_next(q.next),
56
        totp_for: None,
57
        pending: String::new(),
58
        reset,
59
        providers,
60
    })
61
    .into_response()
62
}
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
78
pub async fn login(
79
    State(app): State<Shared>,
80
    viewer: Viewer,
81
    headers: axum::http::HeaderMap,
82
    extensions: axum::http::Extensions,
83
    Form(f): Form<LoginForm>,
84
) -> Result<Response, Error> {
85
    let shell = Shell::new(&app, "/login", &viewer);
86
    let next = safe_next(Some(f.next.clone()));
87
    let username = f.username.trim().to_string();
88
    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.
91
    let now_ms = db::now_ms();
92
    let proven = !f.pending.is_empty()
93
        && account.as_ref().is_some_and(|a| auth::pending_login_ok(&app.cookie_key, &a.username, &a.session_salt, &f.pending, now_ms));
94
    let pending = account
95
        .as_ref()
96
        .map(|a| auth::pending_login(&app.cookie_key, &a.username, &a.session_salt, now_ms + PENDING_LOGIN_MS))
97
        .unwrap_or_default();
98
    let fail = |msg: &str, totp_for: Option<String>| {
99
        Page(LoginPage {
100
            shell: shell.clone(),
101
            error: Some(msg.into()),
102
            next: next.clone(),
103
            totp_for,
104
            pending: pending.clone(),
105
            reset: false,
106
            providers: vec![],
107
        })
108
        .into_response()
109
    };
110
    // Guessing is slowed per account and per address (oxygenhub#221),
111
    // before the password is even looked at.
112
    let addr = crate::api::client_addr(&app, &headers, &extensions);
113
    let keys = [Key::account("login", &username), Key::address("login", &addr)];
114
    if let Some(wait) = app.throttle.lock().unwrap().wait(&keys, now_ms) {
115
        return Ok(fail(&throttle::message(wait), proven.then(|| username.clone())));
116
    }
117
    let failed = |app: &Shared| {
118
        let wait = app.throttle.lock().unwrap().failed(&keys, now_ms);
119
        let (app, username, addr) = (app.clone(), username.clone(), addr.clone());
120
        async move {
121
            if let Some(wait) = wait {
122
                let detail = format!("from {} for {}s", if addr.is_empty() { "an unknown address" } else { &addr }, wait / 1000);
123
                accounts::audit(&app.db, None, "login.throttled", &username, &detail).await.ok();
124
            }
125
        }
126
    };
127
    if !f.pending.is_empty() && !proven {
128
        return Ok(fail("That took too long: sign in again.", None));
129
    }
130
    let Some(account) = account.filter(|a| proven || auth::verify_password(&a.password_hash, &f.password)) else {
131
        accounts::audit(&app.db, None, "login.failed", &username, "").await.ok();
132
        failed(&app).await;
133
        return Ok(fail("Wrong username or password.", None));
134
    };
135
    if account.banned {
136
        return Ok(fail("This account is banned.", None));
137
    }
138
    if account.disabled {
139
        accounts::audit(&app.db, None, "login.disabled", &username, "").await.ok();
140
        return Ok(fail("Your account has been disabled. Contact the hub's administrator.", None));
141
    }
142
    if let Some(secret) = &account.totp_secret {
143
        if f.code.trim().is_empty() {
144
            return Ok(fail("Enter the code from your authenticator app.", Some(username)));
145
        }
146
        let now = (db::now_ms() / 1000) as u64;
147
        if !totp::verify(secret, &f.code, now) {
148
            match totp::use_recovery_code(&account.recovery_codes, &f.code) {
149
                Some(rest) => {
150
                    accounts::set_totp(&app.db, account.id, Some(secret), &rest).await.map_err(|e| Error::from_db(shell.clone(), e))?
151
                }
152
                None => {
153
                    accounts::audit(&app.db, Some(&account), "login.totp_failed", &username, "").await.ok();
154
                    failed(&app).await;
155
                    return Ok(fail("That code is not right.", Some(username)));
156
                }
157
            }
158
        }
159
    }
160
    app.throttle.lock().unwrap().cleared(&keys[0]);
161
    accounts::audit(&app.db, Some(&account), "login", &username, "").await.ok();
162
    Ok(signed_in(&app, &account, &next))
163
}
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.
169
pub fn signed_in(app: &Shared, account: &accounts::Account, to: &str) -> Response {
170
    let value = auth::session_value(&app.cookie_key, &account.username, &account.session_salt);
171
    let secure = if app.config.base_url().starts_with("https://") { "; Secure" } else { "" };
172
    let cookie = format!("{}={value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=2592000{secure}", auth::SESSION_COOKIE);
173
    ([(header::SET_COOKIE, cookie)], Redirect::to(to)).into_response()
174
}
175
176
#[derive(Deserialize)]
177
pub struct CsrfForm {
178
    #[serde(rename = "_csrf")]
179
    pub csrf: String,
180
}
181
182
pub async fn logout(State(app): State<Shared>, viewer: Viewer, Form(f): Form<CsrfForm>) -> Response {
183
    if !viewer.csrf_ok(&f.csrf) {
184
        return Redirect::to("/").into_response();
185
    }
186
    if let Some(a) = viewer.account() {
187
        accounts::audit(&app.db, Some(a), "logout", &a.username, "").await.ok();
188
    }
189
    let secure = if app.config.base_url().starts_with("https://") { "; Secure" } else { "" };
190
    let cookie = format!("{}=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0{secure}", auth::SESSION_COOKIE);
191
    ([(header::SET_COOKIE, cookie)], Redirect::to("/")).into_response()
192
}
193
194
#[derive(Template)]
195
#[template(path = "register.html")]
196
pub struct RegisterPage {
197
    shell: Shell,
198
    error: Option<String>,
199
    mode: String,
200
    first: bool,
201
    invite: String,
202
    /// Providers to sign up with, when registration is open (#213).
203
    providers: Vec<(&'static str, &'static str)>,
204
}
205
206
/// The registration mode: the settings table overrides `hub.toml`.
207
pub async fn registration_mode(app: &Shared) -> String {
208
    accounts::setting(&app.db, "registration_mode").await.ok().flatten().unwrap_or_else(|| app.config.registration.mode.clone())
209
}
210
211
#[derive(Deserialize)]
212
pub struct InviteQuery {
213
    invite: Option<String>,
214
}
215
216
pub async fn register_form(State(app): State<Shared>, viewer: Viewer, Query(q): Query<InviteQuery>) -> Result<Response, Error> {
217
    if viewer.signed_in() {
218
        return Ok(Redirect::to("/").into_response());
219
    }
220
    let shell = Shell::new(&app, "/register", &viewer);
221
    let first = accounts::account_count(&app.db).await.map_err(|e| Error::from_db(shell.clone(), e))? == 0;
222
    let mode = registration_mode(&app).await;
223
    let providers = if mode == "open" && !first { super::signin::buttons(&app).await } else { vec![] };
224
    Ok(Page(RegisterPage { shell, error: None, mode, first, invite: q.invite.unwrap_or_default(), providers }).into_response())
225
}
226
227
#[derive(Deserialize)]
228
pub struct RegisterForm {
229
    username: String,
230
    email: String,
231
    password: String,
232
    #[serde(default)]
233
    invite: String,
234
}
235
236
pub async fn register(State(app): State<Shared>, viewer: Viewer, Form(f): Form<RegisterForm>) -> Result<Response, Error> {
237
    let shell = Shell::new(&app, "/register", &viewer);
238
    let first = accounts::account_count(&app.db).await.map_err(|e| Error::from_db(shell.clone(), e))? == 0;
239
    let mode = registration_mode(&app).await;
240
    let fail = |msg: &str| {
241
        Page(RegisterPage {
242
            shell: shell.clone(),
243
            error: Some(msg.into()),
244
            mode: mode.clone(),
245
            first,
246
            invite: f.invite.clone(),
247
            providers: vec![],
248
        })
249
        .into_response()
250
    };
251
    let username = f.username.trim().to_string();
252
    if !crate::repos::names::valid_owner(&username) {
253
        return Ok(fail("A username is letters, digits, dots, dashes and underscores, and is not a reserved word."));
254
    }
255
    if let Err(e) = auth::password_ok(&f.password) {
256
        return Ok(fail(e));
257
    }
258
    if !first {
259
        match mode.as_str() {
260
            "open" => {}
261
            "invite" => {
262
                let ok = !f.invite.trim().is_empty()
263
                    && accounts::invitation_unused(&app.db, f.invite.trim()).await.map_err(|e| Error::from_db(shell.clone(), e))?;
264
                if !ok {
265
                    return Ok(fail("Registration needs a valid invitation code."));
266
                }
267
            }
268
            _ => return Ok(fail("Registration is closed.")),
269
        }
270
    }
271
    if accounts::account_by_name(&app.db, &username).await.map_err(|e| Error::from_db(shell.clone(), e))?.is_some()
272
        || accounts::org_by_name(&app.db, &username).await.map_err(|e| Error::from_db(shell.clone(), e))?.is_some()
273
        || accounts::username_retired(&app.db, &username).await.map_err(|e| Error::from_db(shell.clone(), e))?
274
    {
275
        return Ok(fail("That name is taken."));
276
    }
277
    let hash = auth::hash_password(&f.password).map_err(|e| Error::bad(shell.clone(), e.to_string()))?;
278
    let account = accounts::create_account(&app.db, &username, f.email.trim(), &hash, &auth::random_hex(16), first)
279
        .await
280
        .map_err(|e| Error::from_db(shell.clone(), e))?;
281
    if !first && mode == "invite" {
282
        accounts::use_invitation(&app.db, f.invite.trim(), account.id).await.ok();
283
    }
284
    accounts::audit(&app.db, Some(&account), "register", &username, if first { "first account: administrator" } else { "" }).await.ok();
285
    if let Err(e) = super::recovery::send_verification(&app, &account).await {
286
        tracing::info!("verification for {username}: {e}");
287
    }
288
    // The site's administrators hear of each new account (oxygenhub#183).
289
    if !first {
290
        let admins: Vec<(i64, crate::db::notify::Reason)> = accounts::accounts(&app.db)
291
            .await
292
            .unwrap_or_default()
293
            .into_iter()
294
            .filter(|a| a.is_admin)
295
            .map(|a| (a.id, crate::db::notify::Reason::Participating))
296
            .collect();
297
        let title = format!("New account: {username} signed up on {}", app.config.site.name);
298
        crate::notify::tell(&app, "account.registered", &title, &format!("/{username}"), &username, None, admins).await;
299
    }
300
    Ok(signed_in(&app, &account, "/"))
301
}