OXYGENHUB
◆ v0.5.1 oxygenhub / crates / hub / src / web / signin.rs
12.7 KiB · Rust · last changed Sign in with GitLab, and branded sign-in buttons 21 days ago source blame history raw
83940d53 Andy McCall ↶ 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);
810896d4 Andy McCall ↶ 42
    let to = signin::authorize_url(app, p, &s, &state);
83940d53 Andy McCall ↶ 43
    Ok(([(header::SET_COOKIE, state_cookie(app, &state, 600))], Redirect::to(&to)).into_response())
44
}
45
46
/// `GET /login/{provider}`: sign in with the provider.
47
pub async fn start(State(app): State<Shared>, viewer: Viewer, Path(id): Path<String>) -> Result<Response, Error> {
48
    let shell = Shell::new(&app, "/login", &viewer);
49
    let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?;
50
    if viewer.signed_in() {
51
        return Ok(Redirect::to("/").into_response());
52
    }
53
    begin(&app, p, "in").await.map_err(|m| Error::bad(shell.clone(), m))
54
}
55
56
/// `GET /settings/security/connect/{provider}`: link the provider to the
57
/// signed-in account.
58
pub async fn connect(State(app): State<Shared>, viewer: Viewer, Path(id): Path<String>) -> Result<Response, Error> {
59
    let shell = Shell::new(&app, "/settings/security", &viewer);
60
    let me = require(&viewer, &shell)?;
61
    let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?;
62
    begin(&app, p, &format!("link:{}", me.account.id)).await.map_err(|m| Error::bad(shell.clone(), m))
63
}
64
65
#[derive(Deserialize)]
66
pub struct Callback {
67
    #[serde(default)]
68
    code: String,
69
    #[serde(default)]
70
    state: String,
71
    #[serde(default)]
72
    error: String,
73
    #[serde(default)]
74
    error_description: String,
75
}
76
77
fn to_login(msg: &str) -> Response {
78
    Redirect::to(&format!("/login?error={}", super::settings::urlencode(msg))).into_response()
79
}
80
81
fn to_security(msg: &str, ok: bool) -> Response {
82
    let k = if ok { "notice" } else { "error" };
83
    Redirect::to(&format!("/settings/security?{k}={}", super::settings::urlencode(msg))).into_response()
84
}
85
86
/// `GET /login/{provider}/callback`: the provider sent the person back.
87
pub async fn callback(
88
    State(app): State<Shared>,
89
    viewer: Viewer,
90
    Path(id): Path<String>,
91
    headers: HeaderMap,
92
    Query(q): Query<Callback>,
93
) -> Result<Response, Error> {
94
    let shell = Shell::new(&app, "/login", &viewer);
95
    let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?;
96
    // The state cookie goes, whatever else the answer sets (appended, so a
97
    // session cookie beside it is kept).
98
    let clear = state_cookie(&app, "", 0);
99
    let with_clear = |mut r: Response| {
100
        if let Ok(v) = header::HeaderValue::from_str(&clear) {
101
            r.headers_mut().append(header::SET_COOKIE, v);
102
        }
103
        r
104
    };
105
    if !q.error.is_empty() {
106
        let why = if q.error_description.is_empty() { q.error.clone() } else { q.error_description.clone() };
107
        return Ok(with_clear(to_login(&format!("{} did not sign you in: {why}", p.name))));
108
    }
109
    let Some(cookie) = cookie_value(&headers) else {
110
        return Ok(with_clear(to_login("The sign-in took too long or the browser kept no cookie; try again.")));
111
    };
112
    if cookie != q.state || q.code.is_empty() {
113
        return Ok(with_clear(to_login("The sign-in did not match the one started here; try again.")));
114
    }
115
    let Some(mode) = signin::state_mode(&app, &cookie) else {
116
        return Ok(with_clear(to_login("The sign-in did not match the one started here; try again.")));
117
    };
118
    let s = signin::settings(&app, p.id).await.map_err(|e| Error::from_db(shell.clone(), e))?;
119
    if !s.usable() {
120
        return Ok(with_clear(to_login(&format!("Signing in with {} is not set up on this hub.", p.name))));
121
    }
122
    let who = match signin::identify(&app, p, &s, &q.code).await {
123
        Ok(w) => w,
124
        Err(msg) => return Ok(with_clear(to_login(&msg))),
125
    };
126
    let e = |e| Error::from_db(shell.clone(), e);
127
    // Connecting to a signed-in account.
128
    if let Some(account_id) = mode.strip_prefix("link:").and_then(|i| i.parse::<i64>().ok()) {
129
        let Some(me) = viewer.account().filter(|a| a.id == account_id) else {
130
            return Ok(with_clear(to_security("Sign in first, then connect the account.", false)));
131
        };
132
        if let Some(other) = signin::linked_account(&app.db, p.id, &who.subject).await.map_err(e)? {
133
            if other.id != me.id {
134
                return Ok(with_clear(to_security(&format!("That {} account is connected to {} already.", p.name, other.username), false)));
135
            }
136
        }
137
        signin::link(&app.db, p.id, &who.subject, me.id, &who.login).await.map_err(e)?;
138
        accounts::audit(&app.db, Some(me), "signin.connected", &me.username, p.id).await.ok();
139
        return Ok(with_clear(to_security(&format!("{} connected as {}.", p.name, who.login), true)));
140
    }
141
    // Signing in: a known link, else the account with that verified email,
142
    // else a new account when registration is open.
143
    if let Some(account) = signin::linked_account(&app.db, p.id, &who.subject).await.map_err(e)? {
144
        if account.blocked() {
145
            return Ok(with_clear(to_login("This account cannot sign in.")));
146
        }
147
        accounts::audit(&app.db, Some(&account), "login", &account.username, p.id).await.ok();
148
        return Ok(with_clear(signed_in(&app, &account, "/")));
149
    }
150
    if let Some(email) = &who.email {
151
        if let Some(account) = accounts::account_by_verified_email(&app.db, email).await.map_err(e)? {
152
            if account.blocked() {
153
                return Ok(with_clear(to_login("This account cannot sign in.")));
154
            }
155
            signin::link(&app.db, p.id, &who.subject, account.id, &who.login).await.map_err(e)?;
156
            accounts::audit(&app.db, Some(&account), "signin.connected", &account.username, &format!("{} by email", p.id)).await.ok();
157
            accounts::audit(&app.db, Some(&account), "login", &account.username, p.id).await.ok();
158
            return Ok(with_clear(signed_in(&app, &account, "/")));
159
        }
160
    }
161
    let mode = super::session::registration_mode(&app).await;
162
    if mode != "open" {
163
        return Ok(with_clear(to_login(&format!(
164
            "No account here is connected to that {} account, and registration is {}. Register or sign in first, then connect it under Settings › Security.",
165
            p.name,
166
            if mode == "invite" { "by invitation" } else { "closed" }
167
        ))));
168
    }
169
    let account = register(&app, p, &who).await.map_err(e)?;
170
    Ok(with_clear(signed_in(&app, &account, "/")))
171
}
172
173
/// A new account for someone the provider vouches for: a username from
174
/// their login there, an unusable password, the email verified when the
175
/// provider says so.
176
async fn register(app: &Shared, p: &Provider, who: &External) -> sqlx::Result<accounts::Account> {
177
    let username = signin::free_username(&app.db, &who.login, p.id).await?;
178
    let hash = auth::hash_password(&auth::random_hex(24)).unwrap_or_default();
179
    let first = accounts::account_count(&app.db).await? == 0;
180
    let account =
181
        accounts::create_account(&app.db, &username, who.email.as_deref().unwrap_or(""), &hash, &auth::random_hex(16), first).await?;
182
    if who.email.is_some() {
183
        accounts::set_email_verified(&app.db, account.id, true).await?;
184
    }
185
    if !who.name.is_empty() {
186
        accounts::set_profile(&app.db, account.id, &who.name, who.email.as_deref().unwrap_or("")).await?;
187
        if who.email.is_some() {
188
            accounts::set_email_verified(&app.db, account.id, true).await?;
189
        }
190
    }
191
    signin::link(&app.db, p.id, &who.subject, account.id, &who.login).await?;
192
    accounts::audit(&app.db, Some(&account), "register", &username, &format!("with {}", p.id)).await.ok();
193
    accounts::account_by_id(&app.db, account.id).await.map(|a| a.unwrap_or(account))
194
}
195
196
#[derive(Deserialize)]
197
pub struct DisconnectForm {
198
    #[serde(rename = "_csrf")]
199
    csrf_token: String,
200
}
201
202
/// `POST /settings/security/disconnect/{provider}`.
203
pub async fn disconnect(
204
    State(app): State<Shared>,
205
    viewer: Viewer,
206
    Path(id): Path<String>,
207
    Form(f): Form<DisconnectForm>,
208
) -> Result<Response, Error> {
209
    let shell = Shell::new(&app, "/settings/security", &viewer);
210
    let me = require(&viewer, &shell)?;
211
    csrf(&viewer, &f.csrf_token, &shell)?;
212
    let p = signin::provider(&id).ok_or_else(|| Error::not_found(shell.clone()))?;
213
    if signin::unlink(&app.db, p.id, me.account.id).await.map_err(|e| Error::from_db(shell.clone(), e))? {
214
        accounts::audit(&app.db, Some(&me.account), "signin.disconnected", &me.account.username, p.id).await.ok();
215
    }
216
    Ok(to_security(&format!("{} disconnected.", p.name), true))
217
}
218
219
/// A provider as the admin page shows it.
220
pub struct ProviderView {
221
    pub id: &'static str,
222
    pub name: &'static str,
223
    pub client_id: String,
224
    pub has_secret: bool,
225
    pub enabled: bool,
226
    pub callback: String,
810896d4 Andy McCall ↶ 227
    /// For a self-hostable provider: its default address and the one set.
228
    pub default_base: Option<&'static str>,
229
    pub base: String,
83940d53 Andy McCall ↶ 230
}
231
232
pub async fn provider_views(app: &Shared) -> sqlx::Result<Vec<ProviderView>> {
233
    let mut out = vec![];
234
    for p in &signin::PROVIDERS {
235
        let s = signin::settings(app, p.id).await?;
236
        out.push(ProviderView {
237
            id: p.id,
238
            name: p.name,
239
            client_id: s.client_id,
240
            has_secret: !s.secret.is_empty(),
241
            enabled: s.enabled,
242
            callback: p.callback_url(app),
810896d4 Andy McCall ↶ 243
            default_base: p.default_base,
244
            base: s.base,
83940d53 Andy McCall ↶ 245
        });
246
    }
247
    Ok(out)
248
}
249
250
#[derive(Deserialize)]
251
pub struct ProviderForm {
252
    #[serde(rename = "_csrf")]
253
    pub csrf_token: String,
254
    pub provider: String,
255
    #[serde(default)]
256
    pub client_id: String,
257
    #[serde(default)]
258
    pub secret: String,
259
    #[serde(default)]
260
    pub enabled: Option<String>,
810896d4 Andy McCall ↶ 261
    /// A self-hostable provider's address (GitLab); empty for its default.
262
    #[serde(default)]
263
    pub base: String,
83940d53 Andy McCall ↶ 264
}
265
266
/// Apply the admin form: `Ok(notice)` or `Err(message)`.
267
pub async fn apply(app: &Shared, viewer: &Viewer, f: ProviderForm) -> sqlx::Result<Result<String, String>> {
268
    let Some(p) = signin::provider(&f.provider) else { return Ok(Err("Unknown provider.".into())) };
269
    let client_id = f.client_id.trim();
270
    if client_id.len() > 200 || client_id.contains(char::is_whitespace) && !client_id.is_empty() {
271
        return Ok(Err("A client id is one token.".into()));
272
    }
273
    let secret = f.secret.trim();
274
    let secret = if secret.is_empty() { None } else { Some(secret) };
275
    let enabled = f.enabled.is_some();
810896d4 Andy McCall ↶ 276
    let base = f.base.trim().trim_end_matches('/');
277
    if p.default_base.is_none() && !base.is_empty() {
278
        return Ok(Err(format!("{} has no address to set.", p.name)));
279
    }
280
    if !base.is_empty() && !signin::valid_base(base) {
281
        return Ok(Err(format!("The {} address is an https:// address, like https://gitlab.example.org.", p.name)));
282
    }
283
    signin::save(app, p.id, client_id, secret, enabled, base).await?;
83940d53 Andy McCall ↶ 284
    let s = signin::settings(app, p.id).await?;
285
    accounts::audit(&app.db, viewer.account(), "admin.signin", p.id, if s.usable() { "on" } else { "off" }).await.ok();
286
    Ok(Ok(if s.usable() {
287
        format!("Signing in with {} is on.", p.name)
288
    } else if enabled {
289
        format!("{} is saved but off until it has a client id and secret.", p.name)
290
    } else {
291
        format!("{} is off.", p.name)
292
    }))
293
}
294
295
/// A page's view of what people may sign in with.
296
pub async fn buttons(app: &Shared) -> Vec<(&'static str, &'static str)> {
297
    signin::enabled(app).await.into_iter().map(|p| (p.id, p.name)).collect()
298
}