OXYGENHUB
◆ v0.9.11 oxygenhub / crates / hub / src / web / signin.rs
14.9 KiB · Rust · last changed A new hub gives administrator only to whoever brings its setup code 19 days ago source blame history raw
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
19
fn state_cookie(app: &Shared, value: &str, max_age: u32) -> String {
20
    let secure = if app.config.base_url().starts_with("https://") { "; Secure" } else { "" };
21
    format!("{STATE_COOKIE}={value}; Path=/login; HttpOnly; SameSite=Lax; Max-Age={max_age}{secure}")
22
}
23
24
fn cookie_value(headers: &HeaderMap) -> Option<String> {
25
    headers
26
        .get_all(header::COOKIE)
27
        .iter()
28
        .filter_map(|v| v.to_str().ok())
29
        .flat_map(|v| v.split(';'))
30
        .filter_map(|c| c.trim().strip_prefix(&format!("{STATE_COOKIE}=")))
31
        .map(String::from)
32
        .next()
33
}
34
35
/// Begin: a state cookie, then off to the provider.
36
async fn begin(app: &Shared, p: &'static Provider, mode: &str) -> Result<Response, String> {
37
    let s = signin::settings(app, p.id).await.map_err(|e| e.to_string())?;
38
    if !s.usable() {
39
        return Err(format!("Signing in with {} is not set up on this hub.", p.name));
40
    }
41
    let state = signin::state_value(app, mode);
42
    let to = signin::authorize_url(app, p, &s, &state);
43
    Ok(([(header::SET_COOKIE, state_cookie(app, &state, 600))], Redirect::to(&to)).into_response())
44
}
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).
54
pub fn invite_code_ok(code: &str) -> bool {
55
    !code.is_empty() && code.len() <= 64 && code.chars().all(|c| c.is_ascii_alphanumeric())
56
}
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.
61
pub async fn start(
62
    State(app): State<Shared>,
63
    viewer: Viewer,
64
    Path(id): Path<String>,
65
    Query(q): Query<StartQuery>,
66
) -> Result<Response, Error> {
67
    let shell = Shell::new(&app, "/login", &viewer);
68
    let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?;
69
    if viewer.signed_in() {
70
        return Ok(Redirect::to("/").into_response());
71
    }
72
    let invite = q.invite.trim();
73
    if invite.is_empty() {
74
        return begin(&app, p, "in").await.map_err(|m| Error::bad(shell.clone(), m));
75
    }
76
    let unused =
77
        invite_code_ok(invite) && accounts::invitation_unused(&app.db, invite).await.map_err(|e| Error::from_db(shell.clone(), e))?;
78
    if !unused {
79
        return Err(Error::bad(shell, "That invitation has been used or does not exist. Ask whoever invited you for a new one."));
80
    }
81
    begin(&app, p, &format!("invite:{invite}")).await.map_err(|m| Error::bad(shell.clone(), m))
82
}
83
84
/// `GET /settings/security/connect/{provider}`: link the provider to the
85
/// signed-in account.
86
pub async fn connect(State(app): State<Shared>, viewer: Viewer, Path(id): Path<String>) -> Result<Response, Error> {
87
    let shell = Shell::new(&app, "/settings/security", &viewer);
88
    let me = require(&viewer, &shell)?;
89
    let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?;
90
    begin(&app, p, &format!("link:{}", me.account.id)).await.map_err(|m| Error::bad(shell.clone(), m))
91
}
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
105
fn to_login(msg: &str) -> Response {
106
    Redirect::to(&format!("/login?error={}", super::settings::urlencode(msg))).into_response()
107
}
108
109
fn to_security(msg: &str, ok: bool) -> Response {
110
    let k = if ok { "notice" } else { "error" };
111
    Redirect::to(&format!("/settings/security?{k}={}", super::settings::urlencode(msg))).into_response()
112
}
113
114
/// `GET /login/{provider}/callback`: the provider sent the person back.
115
pub async fn callback(
116
    State(app): State<Shared>,
117
    viewer: Viewer,
118
    Path(id): Path<String>,
119
    headers: HeaderMap,
120
    Query(q): Query<Callback>,
121
) -> Result<Response, Error> {
122
    let shell = Shell::new(&app, "/login", &viewer);
123
    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).
126
    let clear = state_cookie(&app, "", 0);
127
    let with_clear = |mut r: Response| {
128
        if let Ok(v) = header::HeaderValue::from_str(&clear) {
129
            r.headers_mut().append(header::SET_COOKIE, v);
130
        }
131
        r
132
    };
133
    if !q.error.is_empty() {
134
        let why = if q.error_description.is_empty() { q.error.clone() } else { q.error_description.clone() };
135
        return Ok(with_clear(to_login(&format!("{} did not sign you in: {why}", p.name))));
136
    }
137
    let Some(cookie) = cookie_value(&headers) else {
138
        return Ok(with_clear(to_login("The sign-in took too long or the browser kept no cookie; try again.")));
139
    };
140
    if cookie != q.state || q.code.is_empty() {
141
        return Ok(with_clear(to_login("The sign-in did not match the one started here; try again.")));
142
    }
143
    let Some(mode) = signin::state_mode(&app, &cookie) else {
144
        return Ok(with_clear(to_login("The sign-in did not match the one started here; try again.")));
145
    };
146
    let s = signin::settings(&app, p.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
147
    if !s.usable() {
148
        return Ok(with_clear(to_login(&format!("Signing in with {} is not set up on this hub.", p.name))));
149
    }
150
    let who = match signin::identify(&app, p, &s, &q.code).await {
151
        Ok(w) => w,
152
        Err(msg) => return Ok(with_clear(to_login(&msg))),
153
    };
154
    let e = |e| Error::from_db(shell.clone(), e);
155
    // Connecting to a signed-in account.
156
    if let Some(account_id) = mode.strip_prefix("link:").and_then(|i| i.parse::<i64>().ok()) {
157
        let Some(me) = viewer.account().filter(|a| a.id == account_id) else {
158
            return Ok(with_clear(to_security("Sign in first, then connect the account.", false)));
159
        };
160
        if let Some(other) = signin::linked_account(&app.db, p.id, &who.subject).await.map_err(e)? {
161
            if other.id != me.id {
162
                return Ok(with_clear(to_security(&format!("That {} account is connected to {} already.", p.name, other.username), false)));
163
            }
164
        }
165
        signin::link(&app.db, p.id, &who.subject, me.id, &who.login).await.map_err(e)?;
166
        accounts::audit(&app.db, Some(me), "signin.connected", &me.username, p.id).await.ok();
167
        return Ok(with_clear(to_security(&format!("{} connected as {}.", p.name, who.login), true)));
168
    }
169
    // Signing in: a known link, else the account with that verified email,
170
    // else a new account when registration is open.
171
    if let Some(account) = signin::linked_account(&app.db, p.id, &who.subject).await.map_err(e)? {
172
        if account.blocked() {
173
            return Ok(with_clear(to_login("This account cannot sign in.")));
174
        }
175
        accounts::audit(&app.db, Some(&account), "login", &account.username, p.id).await.ok();
176
        return Ok(with_clear(signed_in(&app, &account, "/").await));
177
    }
178
    if let Some(email) = &who.email {
179
        if let Some(account) = accounts::account_by_verified_email(&app.db, email).await.map_err(e)? {
180
            if account.blocked() {
181
                return Ok(with_clear(to_login("This account cannot sign in.")));
182
            }
183
            signin::link(&app.db, p.id, &who.subject, account.id, &who.login).await.map_err(e)?;
184
            accounts::audit(&app.db, Some(&account), "signin.connected", &account.username, &format!("{} by email", p.id)).await.ok();
185
            accounts::audit(&app.db, Some(&account), "login", &account.username, p.id).await.ok();
186
            return Ok(with_clear(signed_in(&app, &account, "/").await));
187
        }
188
    }
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.
191
    let registration = super::session::registration_mode(&app).await;
192
    let invite = mode.strip_prefix("invite:").filter(|c| invite_code_ok(c));
193
    let allowed = match registration.as_str() {
194
        "open" => true,
195
        "invite" => invite.is_some(),
196
        _ => false,
197
    };
198
    if !allowed {
199
        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,
202
            if registration == "invite" { "by invitation" } else { "closed" }
203
        ))));
204
    }
205
    let by_invitation = (registration == "invite").then_some(invite).flatten();
206
    if let Some(code) = by_invitation {
207
        if !accounts::invitation_unused(&app.db, code).await.map_err(e)? {
208
            return Ok(with_clear(to_login("That invitation was used meanwhile. Ask whoever invited you for a new one.")));
209
        }
210
    }
211
    let account = register(&app, p, &who).await.map_err(e)?;
212
    if let Some(code) = by_invitation {
213
        if !accounts::claim_invitation(&app.db, code, account.id).await.map_err(e)? {
214
            tracing::warn!("invitation {code} was used by someone else while {} signed up", account.username);
215
        }
216
    }
217
    Ok(with_clear(signed_in(&app, &account, "/").await))
218
}
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.
223
async fn register(app: &Shared, p: &Provider, who: &External) -> sqlx::Result<accounts::Account> {
224
    let username = signin::free_username(&app.db, &who.login, p.id).await?;
225
    let hash = auth::hash_password(&auth::random_hex(24)).unwrap_or_default();
226
    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.
229
    if first {
230
        return Err(sqlx::Error::Protocol("this hub has no administrator yet: register the first account with its setup code".into()));
231
    }
232
    let account =
233
        accounts::create_account(&app.db, &username, who.email.as_deref().unwrap_or(""), &hash, &auth::random_hex(16), first).await?;
234
    if who.email.is_some() {
235
        accounts::set_email_verified(&app.db, account.id, true).await?;
236
    }
237
    if !who.name.is_empty() {
238
        accounts::set_profile(&app.db, account.id, &who.name, who.email.as_deref().unwrap_or("")).await?;
239
        if who.email.is_some() {
240
            accounts::set_email_verified(&app.db, account.id, true).await?;
241
        }
242
    }
243
    signin::link(&app.db, p.id, &who.subject, account.id, &who.login).await?;
244
    accounts::audit(&app.db, Some(&account), "register", &username, &format!("with {}", p.id)).await.ok();
245
    accounts::account_by_id(&app.db, account.id).await.map(|a| a.unwrap_or(account))
246
}
247
248
#[derive(Deserialize)]
249
pub struct DisconnectForm {
250
    #[serde(rename = "_csrf")]
251
    csrf_token: String,
252
}
253
254
/// `POST /settings/security/disconnect/{provider}`.
255
pub async fn disconnect(
256
    State(app): State<Shared>,
257
    viewer: Viewer,
258
    Path(id): Path<String>,
259
    Form(f): Form<DisconnectForm>,
260
) -> Result<Response, Error> {
261
    let shell = Shell::new(&app, "/settings/security", &viewer);
262
    let me = require(&viewer, &shell)?;
263
    csrf(&viewer, &f.csrf_token, &shell)?;
264
    let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?;
265
    if signin::unlink(&app.db, p.id, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))? {
266
        accounts::audit(&app.db, Some(&me.account), "signin.disconnected", &me.account.username, p.id).await.ok();
267
    }
268
    Ok(to_security(&format!("{} disconnected.", p.name), true))
269
}
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
284
pub async fn provider_views(app: &Shared) -> sqlx::Result<Vec<ProviderView>> {
285
    let mut out = vec![];
286
    for p in &signin::PROVIDERS {
287
        let s = signin::settings(app, p.id).await?;
288
        out.push(ProviderView {
289
            id: p.id,
290
            name: p.name,
291
            client_id: s.client_id,
292
            has_secret: !s.secret.is_empty(),
293
            enabled: s.enabled,
294
            callback: p.callback_url(app),
295
            default_base: p.default_base,
296
            base: s.base,
297
        });
298
    }
299
    Ok(out)
300
}
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)`.
319
pub async fn apply(app: &Shared, viewer: &Viewer, f: ProviderForm) -> sqlx::Result<Result<String, String>> {
320
    let Some(p) = signin::provider(&f.provider) else { return Ok(Err("Unknown provider.".into())) };
321
    let client_id = f.client_id.trim();
322
    if client_id.len() > 200 || client_id.contains(char::is_whitespace) && !client_id.is_empty() {
323
        return Ok(Err("A client id is one token.".into()));
324
    }
325
    let secret = f.secret.trim();
326
    let secret = if secret.is_empty() { None } else { Some(secret) };
327
    let enabled = f.enabled.is_some();
328
    let base = f.base.trim().trim_end_matches('/');
329
    if p.default_base.is_none() && !base.is_empty() {
330
        return Ok(Err(format!("{} has no address to set.", p.name)));
331
    }
332
    if !base.is_empty() && !signin::valid_base(base) {
333
        return Ok(Err(format!("The {} address is an https:// address, like https://gitlab.example.org.", p.name)));
334
    }
335
    signin::save(app, p.id, client_id, secret, enabled, base).await?;
336
    let s = signin::settings(app, p.id).await?;
337
    accounts::audit(&app.db, viewer.account(), "admin.signin", p.id, if s.usable() { "on" } else { "off" }).await.ok();
338
    Ok(Ok(if s.usable() {
339
        format!("Signing in with {} is on.", p.name)
340
    } else if enabled {
341
        format!("{} is saved but off until it has a client id and secret.", p.name)
342
    } else {
343
        format!("{} is off.", p.name)
344
    }))
345
}
346
347
/// A page's view of what people may sign in with.
348
pub async fn buttons(app: &Shared) -> Vec<(&'static str, &'static str)> {
349
    signin::enabled(app).await.into_iter().map(|p| (p.id, p.name)).collect()
350
}