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