OXYGENHUB

Coverage / crates/hub/src/web/signin.rs 85.5%

224 of 262 lines run, 33 of 90 functions · run #508 on main · run missed

1
//! Sign in with GitHub or Google on the web (hub spec §5.1.2, #106):
2
//! the start of the flow, the callback, the administrator's provider
3
//! settings, and connecting or disconnecting a provider from Settings ›
4
//! Security.
5
6
use super::session::signed_in;
7
use super::settings::{csrf, require};
8
use super::{Error, Shell};
9
use crate::auth::{self, Viewer};
10
use crate::db::accounts;
11
use crate::signin::{self, External, Provider, STATE_COOKIE};
12
use crate::Shared;
13
use axum::extract::{Path, Query, State};
14
use axum::http::{header, HeaderMap};
15
use axum::response::{IntoResponse, Redirect, Response};
16
use axum::Form;
17
use serde::Deserialize;
18
1917×
fn state_cookie(app: &Shared, value: &str, max_age: u32) -> String {
2017×
    let secure = if app.config.base_url().starts_with("https://") { "; Secure" } else { "" };
2117×
    format!("{STATE_COOKIE}={value}; Path=/login; HttpOnly; SameSite=Lax; Max-Age={max_age}{secure}")
2217×
}
23
249×
fn cookie_value(headers: &HeaderMap) -> Option<String> {
259×
    headers
269×
        .get_all(header::COOKIE)
279×
        .iter()
289×
        .filter_map(|v| v.to_str().ok())
299×
        .flat_map(|v| v.split(';'))
309×
        .filter_map(|c| c.trim().strip_prefix(&format!("{STATE_COOKIE}=")))
319×
        .map(String::from)
329×
        .next()
339×
}
34
35
/// Begin: a state cookie, then off to the provider.
368×
async fn begin(app: &Shared, p: &'static Provider, mode: &str) -> Result<Response, String> {
378×
    let s = signin::settings(app, p.id).await.map_err(|e| e.to_string())?;
388×
    if !s.usable() {
390×
        return Err(format!("Signing in with {} is not set up on this hub.", p.name));
408×
    }
418×
    let state = signin::state_value(app, mode);
428×
    let to = signin::authorize_url(app, p, &s, &state);
438×
    Ok(([(header::SET_COOKIE, state_cookie(app, &state, 600))], Redirect::to(&to)).into_response())
448×
}
45
46
#[derive(Deserialize)]
47
pub struct StartQuery {
48
    #[serde(default)]
49
    invite: String,
50
}
51
52
/// An invitation code as it may ride in the signed state: letters and
53
/// digits only (the state's parts are separated by dots).
548×
pub fn invite_code_ok(code: &str) -> bool {
55124×
    !code.is_empty() && code.len() <= 64 && code.chars().all(|c| c.is_ascii_alphanumeric())
568×
}
57
58
/// `GET /login/{provider}`: sign in with the provider; with `?invite=`,
59
/// sign up with it through that invitation (oxygenhub#214), which rides
60
/// through the round trip in the signed state.
619×
pub async fn start(
629×
    State(app): State<Shared>,
639×
    viewer: Viewer,
649×
    Path(id): Path<String>,
659×
    Query(q): Query<StartQuery>,
669×
) -> Result<Response, Error> {
679×
    let shell = Shell::new(&app, "/login", &viewer);
689×
    let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?;
699×
    if viewer.signed_in() {
700×
        return Ok(Redirect::to("/").into_response());
719×
    }
729×
    let invite = q.invite.trim();
739×
    if invite.is_empty() {
746×
        return begin(&app, p, "in").await.map_err(|m| Error::bad(shell.clone(), m));
753×
    }
763×
    let unused =
773×
        invite_code_ok(invite) && accounts::invitation_unused(&app.db, invite).await.map_err(|e| Error::from_db(shell.clone(), e))?;
783×
    if !unused {
792×
        return Err(Error::bad(shell, "That invitation has been used or does not exist. Ask whoever invited you for a new one."));
801×
    }
811×
    begin(&app, p, &format!("invite:{invite}")).await.map_err(|m| Error::bad(shell.clone(), m))
829×
}
83
84
/// `GET /settings/security/connect/{provider}`: link the provider to the
85
/// signed-in account.
861×
pub async fn connect(State(app): State<Shared>, viewer: Viewer, Path(id): Path<String>) -> Result<Response, Error> {
871×
    let shell = Shell::new(&app, "/settings/security", &viewer);
881×
    let me = require(&viewer, &shell)?;
891×
    let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?;
901×
    begin(&app, p, &format!("link:{}", me.account.id)).await.map_err(|m| Error::bad(shell.clone(), m))
911×
}
92
93
#[derive(Deserialize)]
94
pub struct Callback {
95
    #[serde(default)]
96
    code: String,
97
    #[serde(default)]
98
    state: String,
99
    #[serde(default)]
100
    error: String,
101
    #[serde(default)]
102
    error_description: String,
103
}
104
1053×
fn to_login(msg: &str) -> Response {
1063×
    Redirect::to(&format!("/login?error={}", super::settings::urlencode(msg))).into_response()
1073×
}
108
1092×
fn to_security(msg: &str, ok: bool) -> Response {
1102×
    let k = if ok { "notice" } else { "error" };
1112×
    Redirect::to(&format!("/settings/security?{k}={}", super::settings::urlencode(msg))).into_response()
1122×
}
113
114
/// `GET /login/{provider}/callback`: the provider sent the person back.
1159×
pub async fn callback(
1169×
    State(app): State<Shared>,
1179×
    viewer: Viewer,
1189×
    Path(id): Path<String>,
1199×
    headers: HeaderMap,
1209×
    Query(q): Query<Callback>,
1219×
) -> Result<Response, Error> {
1229×
    let shell = Shell::new(&app, "/login", &viewer);
1239×
    let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?;
124
    // The state cookie goes, whatever else the answer sets (appended, so a
125
    // session cookie beside it is kept).
1269×
    let clear = state_cookie(&app, "", 0);
1279×
    let with_clear = |mut r: Response| {
1289×
        if let Ok(v) = header::HeaderValue::from_str(&clear) {
1299×
            r.headers_mut().append(header::SET_COOKIE, v);
1309×
        }
1319×
        r
1329×
    };
1339×
    if !q.error.is_empty() {
1340×
        let why = if q.error_description.is_empty() { q.error.clone() } else { q.error_description.clone() };
1350×
        return Ok(with_clear(to_login(&format!("{} did not sign you in: {why}", p.name))));
1369×
    }
1379×
    let Some(cookie) = cookie_value(&headers) else {
1380×
        return Ok(with_clear(to_login("The sign-in took too long or the browser kept no cookie; try again.")));
139
    };
1409×
    if cookie != q.state || q.code.is_empty() {
1411×
        return Ok(with_clear(to_login("The sign-in did not match the one started here; try again.")));
1428×
    }
1438×
    let Some(mode) = signin::state_mode(&app, &cookie) else {
1440×
        return Ok(with_clear(to_login("The sign-in did not match the one started here; try again.")));
145
    };
1468×
    let s = signin::settings(&app, p.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
1478×
    if !s.usable() {
1480×
        return Ok(with_clear(to_login(&format!("Signing in with {} is not set up on this hub.", p.name))));
1498×
    }
1508×
    let who = match signin::identify(&app, p, &s, &q.code).await {
1518×
        Ok(w) => w,
1520×
        Err(msg) => return Ok(with_clear(to_login(&msg))),
153
    };
1548×
    let e = |e| Error::from_db(shell.clone(), e);
155
    // Connecting to a signed-in account.
1568×
    if let Some(account_id) = mode.strip_prefix("link:").and_then(|i| i.parse::<i64>().ok()) {
1571×
        let Some(me) = viewer.account().filter(|a| a.id == account_id) else {
1580×
            return Ok(with_clear(to_security("Sign in first, then connect the account.", false)));
159
        };
1601×
        if let Some(other) = signin::linked_account(&app.db, p.id, &who.subject).await.map_err(e)? {
1610×
            if other.id != me.id {
1620×
                return Ok(with_clear(to_security(&format!("That {} account is connected to {} already.", p.name, other.username), false)));
1630×
            }
1641×
        }
1651×
        signin::link(&app.db, p.id, &who.subject, me.id, &who.login).await.map_err(e)?;
1661×
        accounts::audit(&app.db, Some(me), "signin.connected", &me.username, p.id).await.ok();
1671×
        return Ok(with_clear(to_security(&format!("{} connected as {}.", p.name, who.login), true)));
1687×
    }
169
    // Signing in: a known link, else the account with that verified email,
170
    // else a new account when registration is open.
1717×
    if let Some(account) = signin::linked_account(&app.db, p.id, &who.subject).await.map_err(e)? {
1721×
        if account.blocked() {
1730×
            return Ok(with_clear(to_login("This account cannot sign in.")));
1741×
        }
1751×
        accounts::audit(&app.db, Some(&account), "login", &account.username, p.id).await.ok();
1761×
        return Ok(with_clear(signed_in(&app, &account, "/").await));
1776×
    }
1786×
    if let Some(email) = &who.email {
1796×
        if let Some(account) = accounts::account_by_verified_email(&app.db, email).await.map_err(e)? {
1801×
            if account.blocked() {
1810×
                return Ok(with_clear(to_login("This account cannot sign in.")));
1821×
            }
1831×
            signin::link(&app.db, p.id, &who.subject, account.id, &who.login).await.map_err(e)?;
1841×
            accounts::audit(&app.db, Some(&account), "signin.connected", &account.username, &format!("{} by email", p.id)).await.ok();
1851×
            accounts::audit(&app.db, Some(&account), "login", &account.username, p.id).await.ok();
1861×
            return Ok(with_clear(signed_in(&app, &account, "/").await));
1875×
        }
1880×
    }
189
    // A new account: when registration is open, or by invitation with an
190
    // invitation that came through the round trip and is still unused.
1915×
    let registration = super::session::registration_mode(&app).await;
1925×
    let invite = mode.strip_prefix("invite:").filter(|c| invite_code_ok(c));
1935×
    let allowed = match registration.as_str() {
1945×
        "open" => true,
1953×
        "invite" => invite.is_some(),
1961×
        _ => false,
197
    };
1985×
    if !allowed {
1992×
        return Ok(with_clear(to_login(&format!(
200
            "No account here is connected to that {} account, and registration is {}. Register or sign in first, then connect it under Settings › Security.",
201
            p.name,
2022×
            if registration == "invite" { "by invitation" } else { "closed" }
203
        ))));
2043×
    }
2053×
    let by_invitation = (registration == "invite").then_some(invite).flatten();
2063×
    if let Some(code) = by_invitation {
2071×
        if !accounts::invitation_unused(&app.db, code).await.map_err(e)? {
2080×
            return Ok(with_clear(to_login("That invitation was used meanwhile. Ask whoever invited you for a new one.")));
2091×
        }
2102×
    }
2113×
    let account = register(&app, p, &who).await.map_err(e)?;
2123×
    if let Some(code) = by_invitation {
2131×
        if !accounts::claim_invitation(&app.db, code, account.id).await.map_err(e)? {
2140×
            tracing::warn!("invitation {code} was used by someone else while {} signed up", account.username);
2151×
        }
2162×
    }
2173×
    Ok(with_clear(signed_in(&app, &account, "/").await))
2189×
}
219
220
/// A new account for someone the provider vouches for: a username from
221
/// their login there, an unusable password, the email verified when the
222
/// provider says so.
2233×
async fn register(app: &Shared, p: &Provider, who: &External) -> sqlx::Result<accounts::Account> {
2243×
    let username = signin::free_username(&app.db, &who.login, p.id).await?;
2253×
    let hash = auth::hash_password(&auth::random_hex(24)).unwrap_or_default();
2263×
    let first = accounts::account_count(&app.db).await? == 0;
227
    // The first account brings the setup code (oxygenhub#245): never one a
228
    // sign-in provider vouches for.
2293×
    if first {
2300×
        return Err(sqlx::Error::Protocol("this hub has no administrator yet: register the first account with its setup code".into()));
2313×
    }
2323×
    let account =
2333×
        accounts::create_account(&app.db, &username, who.email.as_deref().unwrap_or(""), &hash, &auth::random_hex(16), first).await?;
2343×
    if who.email.is_some() {
2353×
        accounts::set_email_verified(&app.db, account.id, true).await?;
2360×
    }
2373×
    if !who.name.is_empty() {
2383×
        accounts::set_profile(&app.db, account.id, &who.name, who.email.as_deref().unwrap_or("")).await?;
2393×
        if who.email.is_some() {
2403×
            accounts::set_email_verified(&app.db, account.id, true).await?;
2410×
        }
2420×
    }
2433×
    signin::link(&app.db, p.id, &who.subject, account.id, &who.login).await?;
2443×
    accounts::audit(&app.db, Some(&account), "register", &username, &format!("with {}", p.id)).await.ok();
2453×
    accounts::account_by_id(&app.db, account.id).await.map(|a| a.unwrap_or(account))
2463×
}
247
248
#[derive(Deserialize)]
249
pub struct DisconnectForm {
250
    #[serde(rename = "_csrf")]
251
    csrf_token: String,
252
}
253
254
/// `POST /settings/security/disconnect/{provider}`.
2551×
pub async fn disconnect(
2561×
    State(app): State<Shared>,
2571×
    viewer: Viewer,
2581×
    Path(id): Path<String>,
2591×
    Form(f): Form<DisconnectForm>,
2601×
) -> Result<Response, Error> {
2611×
    let shell = Shell::new(&app, "/settings/security", &viewer);
2621×
    let me = require(&viewer, &shell)?;
2631×
    csrf(&viewer, &f.csrf_token, &shell)?;
2641×
    let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?;
2651×
    if signin::unlink(&app.db, p.id, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))? {
2661×
        accounts::audit(&app.db, Some(&me.account), "signin.disconnected", &me.account.username, p.id).await.ok();
2670×
    }
2681×
    Ok(to_security(&format!("{} disconnected.", p.name), true))
2691×
}
270
271
/// A provider as the admin page shows it.
272
pub struct ProviderView {
273
    pub id: &'static str,
274
    pub name: &'static str,
275
    pub client_id: String,
276
    pub has_secret: bool,
277
    pub enabled: bool,
278
    pub callback: String,
279
    /// For a self-hostable provider: its default address and the one set.
280
    pub default_base: Option<&'static str>,
281
    pub base: String,
282
}
283
28496×
pub async fn provider_views(app: &Shared) -> sqlx::Result<Vec<ProviderView>> {
28596×
    let mut out = vec![];
286288×
    for p in &signin::PROVIDERS {
287288×
        let s = signin::settings(app, p.id).await?;
288288×
        out.push(ProviderView {
289288×
            id: p.id,
290288×
            name: p.name,
291288×
            client_id: s.client_id,
292288×
            has_secret: !s.secret.is_empty(),
293288×
            enabled: s.enabled,
294288×
            callback: p.callback_url(app),
295288×
            default_base: p.default_base,
296288×
            base: s.base,
297288×
        });
298
    }
29996×
    Ok(out)
30096×
}
301
302
#[derive(Deserialize)]
303
pub struct ProviderForm {
304
    #[serde(rename = "_csrf")]
305
    pub csrf_token: String,
306
    pub provider: String,
307
    #[serde(default)]
308
    pub client_id: String,
309
    #[serde(default)]
310
    pub secret: String,
311
    #[serde(default)]
312
    pub enabled: Option<String>,
313
    /// A self-hostable provider's address (GitLab); empty for its default.
314
    #[serde(default)]
315
    pub base: String,
316
}
317
318
/// Apply the admin form: `Ok(notice)` or `Err(message)`.
3196×
pub async fn apply(app: &Shared, viewer: &Viewer, f: ProviderForm) -> sqlx::Result<Result<String, String>> {
3206×
    let Some(p) = signin::provider(&f.provider) else { return Ok(Err("Unknown provider.".into())) };
3216×
    let client_id = f.client_id.trim();
3226×
    if client_id.len() > 200 || client_id.contains(char::is_whitespace) && !client_id.is_empty() {
3230×
        return Ok(Err("A client id is one token.".into()));
3246×
    }
3256×
    let secret = f.secret.trim();
3266×
    let secret = if secret.is_empty() { None } else { Some(secret) };
3276×
    let enabled = f.enabled.is_some();
3286×
    let base = f.base.trim().trim_end_matches('/');
3296×
    if p.default_base.is_none() && !base.is_empty() {
3301×
        return Ok(Err(format!("{} has no address to set.", p.name)));
3315×
    }
3325×
    if !base.is_empty() && !signin::valid_base(base) {
3331×
        return Ok(Err(format!("The {} address is an https:// address, like https://gitlab.example.org.", p.name)));
3344×
    }
3354×
    signin::save(app, p.id, client_id, secret, enabled, base).await?;
3364×
    let s = signin::settings(app, p.id).await?;
3374×
    accounts::audit(&app.db, viewer.account(), "admin.signin", p.id, if s.usable() { "on" } else { "off" }).await.ok();
3384×
    Ok(Ok(if s.usable() {
3394×
        format!("Signing in with {} is on.", p.name)
3400×
    } else if enabled {
3410×
        format!("{} is saved but off until it has a client id and secret.", p.name)
342
    } else {
3430×
        format!("{} is off.", p.name)
344
    }))
3456×
}
346
347
/// A page's view of what people may sign in with.
34811×
pub async fn buttons(app: &Shared) -> Vec<(&'static str, &'static str)> {
34911×
    signin::enabled(app).await.into_iter().map(|p| (p.id, p.name)).collect()
35011×
}