| 1 | use crate::*; |
| 2 | use argon2::{Argon2, PasswordHash, PasswordHasher, PasswordVerifier, password_hash::SaltString}; |
| 3 | use base64::{ |
| 4 | Engine, |
| 5 | engine::general_purpose::{STANDARD, STANDARD_NO_PAD, URL_SAFE_NO_PAD}, |
| 6 | }; |
| 7 | use rusqlite::{Connection, OptionalExtension, params as sql}; |
| 8 | use std::os::unix::fs::PermissionsExt; |
| 9 | use webauthn_rs::prelude::*; |
| 10 | |
| 11 | const COOKIE: &str = "__Host-snow-session"; |
| 12 | const FLOW_COOKIE: &str = "__Host-snow-flow"; |
| 13 | const CSRF_COOKIE: &str = "__Host-snow-csrf"; |
| 14 | const SESSION_TTL: i64 = 30 * 86400; |
| 15 | const GROUPS: &[&str] = &["infra-admin", "media", "media-manage", "metrics", "vm", "ai", "knife-native"]; |
| 16 | |
| 17 | pub struct Store { |
| 18 | pub db: Mutex<Connection>, |
| 19 | pub origin: url::Url, |
| 20 | file: url::Url, |
| 21 | webauthn: Webauthn, |
| 22 | passwords: Semaphore, |
| 23 | } |
| 24 | |
| 25 | pub fn cookie(headers: &HeaderMap, name: &str) -> Option<String> { |
| 26 | headers |
| 27 | .get("cookie")? |
| 28 | .to_str() |
| 29 | .ok()? |
| 30 | .split(';') |
| 31 | .find_map(|part| { |
| 32 | let (key, value) = part.trim().split_once('=')?; |
| 33 | (key == name).then(|| value.to_owned()) |
| 34 | }) |
| 35 | } |
| 36 | pub(crate) fn set_cookie(name: &str, value: &str, ttl: Option<i64>) -> String { |
| 37 | let mut cookie = format!("{name}={value}; Path=/; Secure; HttpOnly; SameSite=Lax"); |
| 38 | if let Some(ttl) = ttl { |
| 39 | cookie.push_str(&format!("; Max-Age={ttl}")); |
| 40 | } |
| 41 | cookie |
| 42 | } |
| 43 | fn row(db: &Connection, statement: &str, key: &str) -> Result<Value> { |
| 44 | let value: Option<String> = db.query_row(statement, [key], |r| r.get(0)).optional()?; |
| 45 | Ok(value |
| 46 | .map(|s| serde_json::from_str(&s)) |
| 47 | .transpose()? |
| 48 | .unwrap_or(Value::Null)) |
| 49 | } |
| 50 | pub(crate) fn pending(db: &Connection, token: &str, kind: &str, consume: bool) -> Result<Value> { |
| 51 | let value: Option<String> = db |
| 52 | .query_row( |
| 53 | "SELECT data FROM pending WHERE hash=? AND kind=? AND expires>?", |
| 54 | sql![mcp::hash(token), kind, now() as i64], |
| 55 | |r| r.get(0), |
| 56 | ) |
| 57 | .optional()?; |
| 58 | if consume && value.is_some() { |
| 59 | db.execute("DELETE FROM pending WHERE hash=?", [mcp::hash(token)])?; |
| 60 | } |
| 61 | Ok(value |
| 62 | .map(|s| serde_json::from_str(&s)) |
| 63 | .transpose()? |
| 64 | .unwrap_or(Value::Null)) |
| 65 | } |
| 66 | pub(crate) fn issue(db: &Connection, kind: &str, value: Value, ttl: i64) -> Result<String> { |
| 67 | db.execute("DELETE FROM pending WHERE expires<=?", [now() as i64])?; |
| 68 | let count: i64 = db.query_row("SELECT count(*) FROM pending", [], |r| r.get(0))?; |
| 69 | if count >= 4096 { |
| 70 | return Err(Error::new( |
| 71 | 429, |
| 72 | "Too many sign-in requests. Try again in a few minutes.", |
| 73 | )); |
| 74 | } |
| 75 | let token = mcp::secret(); |
| 76 | db.execute( |
| 77 | "INSERT INTO pending VALUES (?,?,?,?)", |
| 78 | sql![ |
| 79 | mcp::hash(&token), |
| 80 | kind, |
| 81 | value.to_string(), |
| 82 | now() as i64 + ttl |
| 83 | ], |
| 84 | )?; |
| 85 | Ok(token) |
| 86 | } |
| 87 | pub fn user(db: &Connection, id: &str) -> Result<Value> { |
| 88 | let mut profile = row(db, "SELECT profile FROM users WHERE id=?", id)?; |
| 89 | if profile.is_null() { |
| 90 | return Err(Error::new( |
| 91 | 404, |
| 92 | "This account no longer exists. Sign in again.", |
| 93 | )); |
| 94 | } |
| 95 | profile["id"] = json!(id); |
| 96 | let mut statement = db.prepare("SELECT roles.id, roles.name FROM roles JOIN memberships ON roles.id=memberships.role_id WHERE user_id=? ORDER BY roles.name")?; |
| 97 | profile["groups"] = json!( |
| 98 | statement |
| 99 | .query_map([id], |r| Ok( |
| 100 | json!({"id":r.get::<_,String>(0)?,"name":r.get::<_,String>(1)?}) |
| 101 | ))? |
| 102 | .collect::<std::result::Result<Vec<_>, _>>()? |
| 103 | ); |
| 104 | Ok(profile) |
| 105 | } |
| 106 | pub fn credentials(db: &Connection, id: &str) -> Result<Value> { |
| 107 | let mut statement = db.prepare( |
| 108 | "SELECT id, kind, label, created FROM credentials WHERE user_id=? ORDER BY created", |
| 109 | )?; |
| 110 | Ok(json!(statement.query_map([id], |r| Ok(json!({"id":r.get::<_,String>(0)?,"type":r.get::<_,String>(1)?,"userLabel":r.get::<_,Option<String>>(2)?,"createdDate":r.get::<_,i64>(3)?})))?.collect::<std::result::Result<Vec<_>,_>>()?)) |
| 111 | } |
| 112 | pub fn save_user(db: &Connection, id: &str, mut profile: Value) -> Result<()> { |
| 113 | for key in [ |
| 114 | "id", |
| 115 | "groups", |
| 116 | "sessions", |
| 117 | "credentials", |
| 118 | "picture", |
| 119 | "console", |
| 120 | ] { |
| 121 | profile.as_object_mut().unwrap().remove(key); |
| 122 | } |
| 123 | if profile["emailVerified"] == true { |
| 124 | let conflict: bool = db.query_row("SELECT EXISTS(SELECT 1 FROM commit_emails WHERE email=lower(?) AND verified=1 AND user_id!=?)", sql![string(&profile["email"]),id], |r| r.get(0))?; |
| 125 | if conflict { return Err(Error::new(409, "This email belongs to another account. Ask an admin to check its owner.")); } |
| 126 | } |
| 127 | db.execute( |
| 128 | "UPDATE users SET profile=? WHERE id=?", |
| 129 | sql![profile.to_string(), id], |
| 130 | ) |
| 131 | .map_err(|_| Error::new(409, "That username is already taken. Choose another."))?; |
| 132 | Ok(()) |
| 133 | } |
| 134 | pub fn password_hash(password: &str) -> Result<String> { |
| 135 | let salt = SaltString::encode_b64(&rand::random::<[u8; 16]>()) |
| 136 | .map_err(|_| Error::new(500, "Couldn't prepare password storage."))?; |
| 137 | Ok(Argon2::default() |
| 138 | .hash_password(password.as_bytes(), &salt) |
| 139 | .map_err(|_| Error::new(500, "Couldn't store the password."))? |
| 140 | .to_string()) |
| 141 | } |
| 142 | pub fn set_password(db: &Connection, id: &str, hash: &str) -> Result<()> { |
| 143 | db.execute( |
| 144 | "DELETE FROM credentials WHERE user_id=? AND kind='password'", |
| 145 | [id], |
| 146 | )?; |
| 147 | db.execute( |
| 148 | "INSERT INTO credentials VALUES (?,?,?,?,?,?)", |
| 149 | sql![ |
| 150 | uuid::Uuid::new_v4().to_string(), |
| 151 | id, |
| 152 | "password", |
| 153 | Option::<String>::None, |
| 154 | (now() * 1000.0) as i64, |
| 155 | json!({"phc":hash}).to_string() |
| 156 | ], |
| 157 | )?; |
| 158 | Ok(()) |
| 159 | } |
| 160 | |
| 161 | impl Store { |
| 162 | pub fn new(data: &std::path::Path, origin: &str, file: &str, rp: &str) -> Result<Self> { |
| 163 | let origin = url::Url::parse(origin)?; |
| 164 | let file = url::Url::parse(file)?; |
| 165 | if origin.scheme() != "https" |
| 166 | || file.scheme() != "https" |
| 167 | || origin.path() != "/" |
| 168 | || file.path() != "/" |
| 169 | || origin.origin() == file.origin() |
| 170 | { |
| 171 | return Err(Error::new( |
| 172 | 500, |
| 173 | "Set separate HTTPS origins for Snow Globe and Files.", |
| 174 | )); |
| 175 | } |
| 176 | let rp_origin = url::Url::parse(&format!("https://{rp}"))?; |
| 177 | let webauthn = WebauthnBuilder::new(rp, &rp_origin)? |
| 178 | .append_allowed_origin(&origin) |
| 179 | .rp_name("snow globe") |
| 180 | .build()?; |
| 181 | std::fs::create_dir_all(data)?; |
| 182 | let path = data.canonicalize()?.join("accounts.sqlite"); |
| 183 | let db = Connection::open_with_flags( |
| 184 | &path, |
| 185 | rusqlite::OpenFlags::SQLITE_OPEN_READ_WRITE |
| 186 | | rusqlite::OpenFlags::SQLITE_OPEN_CREATE |
| 187 | | rusqlite::OpenFlags::SQLITE_OPEN_NOFOLLOW, |
| 188 | )?; |
| 189 | std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?; |
| 190 | db.execute_batch("PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; PRAGMA busy_timeout=5000; |
| 191 | CREATE TABLE IF NOT EXISTS users (id TEXT PRIMARY KEY, profile TEXT NOT NULL, username TEXT GENERATED ALWAYS AS (json_extract(profile,'$.username')) STORED UNIQUE); |
| 192 | CREATE UNIQUE INDEX IF NOT EXISTS verified_email ON users(lower(json_extract(profile,'$.email'))) WHERE json_extract(profile,'$.emailVerified')=1 AND json_extract(profile,'$.email') IS NOT NULL; |
| 193 | CREATE TABLE IF NOT EXISTS roles (id TEXT PRIMARY KEY, name TEXT NOT NULL UNIQUE); |
| 194 | CREATE TABLE IF NOT EXISTS memberships (user_id TEXT REFERENCES users(id) ON DELETE CASCADE, role_id TEXT REFERENCES roles(id), PRIMARY KEY(user_id,role_id)); |
| 195 | CREATE TABLE IF NOT EXISTS credentials (id TEXT PRIMARY KEY,user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,kind TEXT NOT NULL,label TEXT,created INTEGER NOT NULL,data TEXT NOT NULL); |
| 196 | CREATE TABLE IF NOT EXISTS sessions (hash TEXT PRIMARY KEY,user_id TEXT NOT NULL REFERENCES users(id) ON DELETE CASCADE,client TEXT NOT NULL CHECK(client IN ('dashboard','file')),expires INTEGER NOT NULL,ip TEXT NOT NULL,created INTEGER NOT NULL,last_used INTEGER NOT NULL,auth_time INTEGER NOT NULL); |
| 197 | CREATE TABLE IF NOT EXISTS pending (hash TEXT PRIMARY KEY,kind TEXT NOT NULL,data TEXT NOT NULL,expires INTEGER NOT NULL); |
| 198 | CREATE TABLE IF NOT EXISTS migration (digest TEXT PRIMARY KEY); |
| 199 | CREATE TABLE IF NOT EXISTS attempts (key TEXT PRIMARY KEY,count INTEGER NOT NULL,expires INTEGER NOT NULL);")?; |
| 200 | identity::initialise(&db)?; |
| 201 | oidc::initialise(&db)?; |
| 202 | guest::initialise(&db)?; |
| 203 | for name in GROUPS { |
| 204 | let added = db.execute( |
| 205 | "INSERT OR IGNORE INTO roles(id,name) VALUES (?,?)", |
| 206 | sql![uuid::Uuid::new_v4().to_string(), name], |
| 207 | )?; |
| 208 | if *name == "knife-native" && added != 0 { |
| 209 | db.execute("INSERT OR IGNORE INTO memberships SELECT users.id,roles.id FROM users,roles WHERE users.username='snow' AND roles.name='knife-native'", [])?; |
| 210 | } |
| 211 | } |
| 212 | Ok(Self { |
| 213 | db: Mutex::new(db), |
| 214 | origin, |
| 215 | file, |
| 216 | webauthn, |
| 217 | passwords: Semaphore::new(2), |
| 218 | }) |
| 219 | } |
| 220 | pub fn ready(&self) -> bool { |
| 221 | self.db |
| 222 | .lock() |
| 223 | .unwrap() |
| 224 | .query_row("SELECT EXISTS(SELECT 1 FROM users)", [], |r| r.get(0)) |
| 225 | .unwrap_or(false) |
| 226 | } |
| 227 | pub fn import(&self, export: Value) -> Result<Value> { |
| 228 | if self |
| 229 | .webauthn |
| 230 | .get_allowed_origins() |
| 231 | .first() |
| 232 | .and_then(|u| u.host_str()) |
| 233 | != export["rpId"].as_str() |
| 234 | { |
| 235 | return Err(Error::new( |
| 236 | 400, |
| 237 | "The export's passkey domain does not match this server.", |
| 238 | )); |
| 239 | } |
| 240 | let mut db = self.db.lock().unwrap(); |
| 241 | let digest = mcp::hash(&export.to_string()); |
| 242 | if db.query_row( |
| 243 | "SELECT EXISTS(SELECT 1 FROM migration WHERE digest=?)", |
| 244 | [&digest], |
| 245 | |r| r.get::<_, bool>(0), |
| 246 | )? { |
| 247 | return Ok( |
| 248 | json!({"accounts":array(&export["users"]).len(),"credentials":array(&export["users"]).iter().map(|u|array(&u["credentials"]).len()).sum::<usize>()}), |
| 249 | ); |
| 250 | } |
| 251 | if db.query_row("SELECT count(*) FROM users", [], |r| r.get::<_, i64>(0))? != 0 { |
| 252 | return Err(Error::new( |
| 253 | 409, |
| 254 | "Accounts already exist. Import into an empty store.", |
| 255 | )); |
| 256 | } |
| 257 | let transaction = db.transaction()?; |
| 258 | for role in array(&export["roles"]) { |
| 259 | if GROUPS.contains(&string(&role["name"])) { |
| 260 | transaction.execute( |
| 261 | "INSERT INTO roles VALUES (?,?) ON CONFLICT(name) DO UPDATE SET id=excluded.id", |
| 262 | sql![string(&role["id"]), string(&role["name"])], |
| 263 | )?; |
| 264 | } |
| 265 | } |
| 266 | let mut count = 0; |
| 267 | for profile in array(&export["users"]) { |
| 268 | let id = string(&profile["id"]); |
| 269 | uuid::Uuid::parse_str(id)?; |
| 270 | string(&profile["username"]) |
| 271 | .parse::<axum::http::HeaderValue>() |
| 272 | .map_err(|_| Error::new(400, "The source has an invalid username."))?; |
| 273 | let mut value = profile.clone(); |
| 274 | value["requiredActions"] = json!( |
| 275 | array(&profile["requiredActions"]) |
| 276 | .iter() |
| 277 | .filter(|v| **v == "UPDATE_PASSWORD" || **v == "UPDATE_PROFILE") |
| 278 | .collect::<Vec<_>>() |
| 279 | ); |
| 280 | for key in ["id", "roles", "credentials"] { |
| 281 | value.as_object_mut().unwrap().remove(key); |
| 282 | } |
| 283 | transaction.execute( |
| 284 | "INSERT INTO users(id,profile) VALUES (?,?)", |
| 285 | sql![id, value.to_string()], |
| 286 | )?; |
| 287 | for role in array(&profile["roles"]) { |
| 288 | transaction.execute( |
| 289 | "INSERT INTO memberships SELECT ?,id FROM roles WHERE id=?", |
| 290 | sql![id, string(role)], |
| 291 | )?; |
| 292 | } |
| 293 | for credential in array(&profile["credentials"]) { |
| 294 | let kind = string(&credential["type"]); |
| 295 | let source = &credential["credentialData"]; |
| 296 | let data = match kind { |
| 297 | "password" => { |
| 298 | if source["algorithm"] != "argon2" |
| 299 | || source["additionalParameters"]["type"][0] != "id" |
| 300 | { |
| 301 | return Err(Error::new( |
| 302 | 500, |
| 303 | "The source uses an unsupported password format.", |
| 304 | )); |
| 305 | } |
| 306 | let parameters = &source["additionalParameters"]; |
| 307 | let salt = STANDARD_NO_PAD |
| 308 | .encode(STANDARD.decode(string(&credential["secretData"]["salt"]))?); |
| 309 | let hash = STANDARD_NO_PAD |
| 310 | .encode(STANDARD.decode(string(&credential["secretData"]["value"]))?); |
| 311 | let phc = format!( |
| 312 | "$argon2id$v=19$m={},t={},p={}${}${}", |
| 313 | string(&parameters["memory"][0]), |
| 314 | source["hashIterations"], |
| 315 | string(&parameters["parallelism"][0]), |
| 316 | salt, |
| 317 | hash |
| 318 | ); |
| 319 | PasswordHash::new(&phc).map_err(|_| { |
| 320 | Error::new(500, "The source password hash couldn't be imported.") |
| 321 | })?; |
| 322 | json!({"phc":phc}) |
| 323 | } |
| 324 | "webauthn-passwordless" => { |
| 325 | let key: serde_cbor_2::Value = serde_cbor_2::from_slice( |
| 326 | &URL_SAFE_NO_PAD.decode(string(&source["credentialPublicKey"]))?, |
| 327 | )?; |
| 328 | let public_key = COSEKey::try_from(&key)?; |
| 329 | let cred = Credential { |
| 330 | cred_id: STANDARD.decode(string(&source["credentialId"]))?.into(), |
| 331 | cred: public_key, |
| 332 | counter: source["counter"].as_u64().unwrap_or(0).try_into()?, |
| 333 | transports: serde_json::from_value(source["transports"].clone()) |
| 334 | .unwrap_or(None), |
| 335 | user_verified: true, |
| 336 | backup_eligible: false, |
| 337 | backup_state: false, |
| 338 | registration_policy: serde_json::from_value(json!("required"))?, |
| 339 | extensions: Default::default(), |
| 340 | attestation: Default::default(), |
| 341 | attestation_format: AttestationFormat::None, |
| 342 | }; |
| 343 | // Keycloak omits backup flags; learn them only from the first verified assertion. |
| 344 | json!({"passkey":Passkey::from(cred),"handle":URL_SAFE_NO_PAD.encode(id.as_bytes()),"backupUnknown":true}) |
| 345 | } |
| 346 | _ => { |
| 347 | return Err(Error::new( |
| 348 | 500, |
| 349 | "The source has a credential type this import doesn't support.", |
| 350 | )); |
| 351 | } |
| 352 | }; |
| 353 | transaction.execute( |
| 354 | "INSERT INTO credentials VALUES (?,?,?,?,?,?)", |
| 355 | sql![ |
| 356 | string(&credential["id"]), |
| 357 | id, |
| 358 | kind, |
| 359 | credential["userLabel"].as_str(), |
| 360 | credential["createdDate"].as_i64().unwrap_or(0), |
| 361 | data.to_string() |
| 362 | ], |
| 363 | )?; |
| 364 | count += 1; |
| 365 | } |
| 366 | } |
| 367 | transaction.execute("INSERT INTO migration VALUES (?)", [digest])?; |
| 368 | transaction.commit()?; |
| 369 | Ok(json!({"accounts":array(&export["users"]).len(),"credentials":count})) |
| 370 | } |
| 371 | pub fn session(&self, headers: &HeaderMap, client: &str) -> Result<Value> { |
| 372 | let Some(token) = cookie(headers, COOKIE) else { |
| 373 | return Ok(Value::Null); |
| 374 | }; |
| 375 | let db = self.db.lock().unwrap(); |
| 376 | let id: Option<String> = db |
| 377 | .query_row( |
| 378 | "SELECT user_id FROM sessions WHERE hash=? AND client=? AND expires>?", |
| 379 | sql![mcp::hash(&token), client, now() as i64], |
| 380 | |r| r.get(0), |
| 381 | ) |
| 382 | .optional()?; |
| 383 | let Some(id) = id else { |
| 384 | return Ok(Value::Null); |
| 385 | }; |
| 386 | let user = user(&db, &id)?; |
| 387 | if user["enabled"] != true || (client == "file" && guest::is_guest(&user)) { |
| 388 | return Ok(Value::Null); |
| 389 | } |
| 390 | db.execute( |
| 391 | "UPDATE sessions SET last_used=? WHERE hash=? AND last_used<?", |
| 392 | sql![ |
| 393 | (now() * 1000.0) as i64, |
| 394 | mcp::hash(&token), |
| 395 | (now() * 1000.0) as i64 - 60000 |
| 396 | ], |
| 397 | )?; |
| 398 | Ok(user) |
| 399 | } |
| 400 | pub(crate) fn create_session( |
| 401 | &self, |
| 402 | id: &str, |
| 403 | client: &str, |
| 404 | headers: &HeaderMap, |
| 405 | password: Option<&Value>, |
| 406 | ) -> Result<String> { |
| 407 | let token = mcp::secret(); |
| 408 | let db = self.db.lock().unwrap(); |
| 409 | let profile = user(&db, id)?; |
| 410 | if profile["enabled"] != true || (client == "file" && guest::is_guest(&profile)) { |
| 411 | return Err(Error::new(403, "This account is disabled.")); |
| 412 | } |
| 413 | if let Some(expected) = password { |
| 414 | if row( |
| 415 | &db, |
| 416 | "SELECT data FROM credentials WHERE user_id=? AND kind='password'", |
| 417 | id, |
| 418 | )? != *expected |
| 419 | { |
| 420 | return Err(Error::new(401, "Your password changed. Sign in again.")); |
| 421 | } |
| 422 | } |
| 423 | db.execute("DELETE FROM sessions WHERE expires<=?", [now() as i64])?; |
| 424 | let ip = headers |
| 425 | .get("X-Snowglobe-Client-IP") |
| 426 | .and_then(|v| v.to_str().ok()) |
| 427 | .unwrap_or("unknown"); |
| 428 | db.execute( |
| 429 | "INSERT INTO sessions VALUES (?,?,?,?,?,?,?,?)", |
| 430 | sql![ |
| 431 | mcp::hash(&token), |
| 432 | id, |
| 433 | client, |
| 434 | now() as i64 + SESSION_TTL, |
| 435 | ip, |
| 436 | (now() * 1000.0) as i64, |
| 437 | (now() * 1000.0) as i64, |
| 438 | now() as i64 |
| 439 | ], |
| 440 | )?; |
| 441 | Ok(set_cookie(COOKIE, &token, Some(SESSION_TTL))) |
| 442 | } |
| 443 | pub(crate) fn limit(&self, headers: &HeaderMap, name: &str) -> Result<()> { |
| 444 | let ip = headers |
| 445 | .get("X-Snowglobe-Client-IP") |
| 446 | .and_then(|v| v.to_str().ok()) |
| 447 | .unwrap_or("unknown"); |
| 448 | let db = self.db.lock().unwrap(); |
| 449 | db.execute("DELETE FROM attempts WHERE expires<=?", [now() as i64])?; |
| 450 | let address = mcp::hash(ip); |
| 451 | db.execute( |
| 452 | "INSERT INTO attempts VALUES (?,1,?) ON CONFLICT(key) DO UPDATE SET count=count+1", |
| 453 | sql![address, now() as i64 + 300], |
| 454 | )?; |
| 455 | let total: i64 = |
| 456 | db.query_row("SELECT count FROM attempts WHERE key=?", [address], |r| { |
| 457 | r.get(0) |
| 458 | })?; |
| 459 | if total > 100 { |
| 460 | return Err(Error::new( |
| 461 | 429, |
| 462 | "Too many attempts. Try again in five minutes.", |
| 463 | )); |
| 464 | } |
| 465 | let key = mcp::hash(&format!("{ip}:{name}")); |
| 466 | db.execute( |
| 467 | "INSERT INTO attempts VALUES (?,1,?) ON CONFLICT(key) DO UPDATE SET count=count+1", |
| 468 | sql![key, now() as i64 + 300], |
| 469 | )?; |
| 470 | let count: i64 = db.query_row("SELECT count FROM attempts WHERE key=?", [key], |r| { |
| 471 | r.get(0) |
| 472 | })?; |
| 473 | if count > 20 { |
| 474 | return Err(Error::new( |
| 475 | 429, |
| 476 | "Too many attempts. Try again in five minutes.", |
| 477 | )); |
| 478 | } |
| 479 | Ok(()) |
| 480 | } |
| 481 | fn csrf(&self, headers: &HeaderMap, body: &Value) -> Result<()> { |
| 482 | if headers.get("origin").and_then(|v| v.to_str().ok()) |
| 483 | != Some(self.origin.origin().ascii_serialization().as_str()) |
| 484 | { |
| 485 | return Err(Error::new(403, "Open sign-in on Snow Globe and try again.")); |
| 486 | } |
| 487 | let cookie = cookie(headers, CSRF_COOKIE).unwrap_or_default(); |
| 488 | if cookie.is_empty() |
| 489 | || !bool::from(cookie.as_bytes().ct_eq(string(&body["csrf"]).as_bytes())) |
| 490 | { |
| 491 | return Err(Error::new(403, "Reload the page to sign in.")); |
| 492 | } |
| 493 | Ok(()) |
| 494 | } |
| 495 | pub(crate) fn next(&self, id: &str, flow: &str, path: &str) -> Result<String> { |
| 496 | if !array(&user(&self.db.lock().unwrap(), id)?["requiredActions"]).is_empty() { |
| 497 | return Ok("/account".into()); |
| 498 | } |
| 499 | if flow.is_empty() { |
| 500 | if !path.starts_with('/') |
| 501 | || path.starts_with("//") |
| 502 | || path.contains('\\') |
| 503 | || path.chars().any(char::is_control) |
| 504 | { |
| 505 | return Ok("/".into()); |
| 506 | } |
| 507 | return Ok(path.to_owned()); |
| 508 | } |
| 509 | let db = self.db.lock().unwrap(); |
| 510 | if guest::is_guest(&user(&db, id)?) { |
| 511 | return Err(Error::new( |
| 512 | 403, |
| 513 | "Guest accounts can use Shale. Open Shale to continue.", |
| 514 | )); |
| 515 | } |
| 516 | let value = pending(&db, flow, "file", false)?; |
| 517 | if value.is_null() { |
| 518 | return Err(Error::new( |
| 519 | 400, |
| 520 | "File sign-in expired. Open Files and try again.", |
| 521 | )); |
| 522 | } |
| 523 | let code = issue(&db, "handoff", json!({"user":id,"flow":flow}), 60)?; |
| 524 | Ok(format!( |
| 525 | "{}auth/file/callback?code={}", |
| 526 | self.file, |
| 527 | encoded(&code) |
| 528 | )) |
| 529 | } |
| 530 | pub fn sessions(db: &Connection, id: &str) -> Result<Value> { |
| 531 | let mut statement = db.prepare("SELECT hash,ip,created,last_used,client FROM sessions WHERE user_id=? AND expires>? ORDER BY last_used DESC")?; |
| 532 | Ok(json!(statement.query_map(sql![id,now() as i64],|r|Ok(json!({"id":r.get::<_,String>(0)?,"ipAddress":r.get::<_,String>(1)?,"start":r.get::<_,i64>(2)?,"lastAccess":r.get::<_,i64>(3)?,"clients":{"snow":r.get::<_,String>(4)?}})))?.collect::<std::result::Result<Vec<_>,_>>()?)) |
| 533 | } |
| 534 | pub async fn hash_password(&self, password: &str) -> Result<String> { |
| 535 | let _slot = self |
| 536 | .passwords |
| 537 | .try_acquire() |
| 538 | .map_err(|_| Error::new(429, "Sign-in is busy. Try again in a moment."))?; |
| 539 | let password = password.to_owned(); |
| 540 | tokio::task::spawn_blocking(move || password_hash(&password)).await? |
| 541 | } |
| 542 | pub fn recent(&self, headers: &HeaderMap) -> Result<()> { |
| 543 | let token = cookie(headers, COOKIE).unwrap_or_default(); |
| 544 | let valid: bool = self.db.lock().unwrap().query_row("SELECT EXISTS(SELECT 1 FROM sessions WHERE hash=? AND client='dashboard' AND expires>? AND auth_time>?)",sql![mcp::hash(&token),now() as i64,now() as i64-900],|r|r.get(0))?; |
| 545 | if !valid { |
| 546 | return Err(Error::new( |
| 547 | 403, |
| 548 | "Sign out and sign in again before changing sign-in methods.", |
| 549 | )); |
| 550 | } |
| 551 | Ok(()) |
| 552 | } |
| 553 | pub fn setup_link(&self, id: &str) -> Result<String> { |
| 554 | let db = self.db.lock().unwrap(); |
| 555 | let profile = user(&db, id)?; |
| 556 | if guest::is_guest(&profile) { |
| 557 | return Err(Error::new( |
| 558 | 400, |
| 559 | "Guests sign in with their provider. Use the Shale sign-in page.", |
| 560 | )); |
| 561 | } |
| 562 | if profile["enabled"] != true { |
| 563 | return Err(Error::new( |
| 564 | 400, |
| 565 | "Enable this account before creating a setup link.", |
| 566 | )); |
| 567 | } |
| 568 | db.execute( |
| 569 | "DELETE FROM pending WHERE kind='setup' AND json_extract(data,'$.user')=?", |
| 570 | [id], |
| 571 | )?; |
| 572 | let token = issue(&db, "setup", json!({"user":id}), 86400)?; |
| 573 | Ok(format!("{}sign-in?setup={}", self.origin, token)) |
| 574 | } |
| 575 | } |
| 576 | |
| 577 | fn file_groups(user: &Value) -> Option<String> { |
| 578 | if user["enabled"] != true |
| 579 | || !array(&user["requiredActions"]).is_empty() |
| 580 | || guest::is_guest(user) |
| 581 | || user["kind"] == "ai" |
| 582 | { |
| 583 | return None; |
| 584 | } |
| 585 | let id = uuid::Uuid::parse_str(string(&user["id"])).ok()?; |
| 586 | let mut groups = array(&user["groups"]) |
| 587 | .iter() |
| 588 | .map(|g| string(&g["name"]).to_owned()) |
| 589 | .collect::<Vec<_>>(); |
| 590 | groups.push(format!("snow-user-{id}")); |
| 591 | Some(groups.join(",")) |
| 592 | } |
| 593 | |
| 594 | pub async fn route(State(app): State<Arc<App>>, request: Request) -> Result<Response> { |
| 595 | if request.uri().path() == "/auth/shale/page" { |
| 596 | return shale_page::proxy(app, request).await; |
| 597 | } |
| 598 | if request.uri().path().starts_with("/auth/guest/") { |
| 599 | return Ok(guest::route(State(app), request).await); |
| 600 | } |
| 601 | if request.uri().path().starts_with("/auth/oidc/") { |
| 602 | return Ok(oidc::route(State(app), request).await); |
| 603 | } |
| 604 | let auth = &app.auth; |
| 605 | let path = request.uri().path().to_owned(); |
| 606 | let method = request.method().clone(); |
| 607 | let query: HashMap<String, String> = |
| 608 | url::form_urlencoded::parse(request.uri().query().unwrap_or_default().as_bytes()) |
| 609 | .into_owned() |
| 610 | .collect(); |
| 611 | let headers = request.headers().clone(); |
| 612 | if path == "/auth/file/check" && method == Method::GET { |
| 613 | let user = auth.session(&headers, "file")?; |
| 614 | let Some(groups) = file_groups(&user) else { |
| 615 | return Ok(StatusCode::UNAUTHORIZED.into_response()); |
| 616 | }; |
| 617 | return Ok(( |
| 618 | StatusCode::NO_CONTENT, |
| 619 | [ |
| 620 | ( |
| 621 | "X-Auth-Request-Preferred-Username", |
| 622 | string(&user["username"]).to_owned(), |
| 623 | ), |
| 624 | ("X-Auth-Request-Groups", groups), |
| 625 | ], |
| 626 | ) |
| 627 | .into_response()); |
| 628 | } |
| 629 | if path == "/auth/file/sign-in" && method == Method::GET { |
| 630 | let target = query |
| 631 | .get("rd") |
| 632 | .map(String::as_str) |
| 633 | .unwrap_or(auth.file.as_str()); |
| 634 | let destination = auth.file.join(target)?; |
| 635 | if destination.origin() != auth.file.origin() |
| 636 | || !destination.username().is_empty() |
| 637 | || destination.password().is_some() |
| 638 | { |
| 639 | return Err(Error::new(400, "Open Files to sign in.")); |
| 640 | } |
| 641 | let flow = issue( |
| 642 | &auth.db.lock().unwrap(), |
| 643 | "file", |
| 644 | json!({"next":destination}), |
| 645 | 300, |
| 646 | )?; |
| 647 | return Ok(( |
| 648 | StatusCode::FOUND, |
| 649 | [ |
| 650 | ( |
| 651 | "location", |
| 652 | format!("{}auth/continue?flow={flow}", auth.origin), |
| 653 | ), |
| 654 | ("set-cookie", set_cookie(FLOW_COOKIE, &flow, Some(300))), |
| 655 | ], |
| 656 | ) |
| 657 | .into_response()); |
| 658 | } |
| 659 | if path == "/auth/continue" && method == Method::GET { |
| 660 | let flow = query.get("flow").cloned().unwrap_or_default(); |
| 661 | let user = auth.session(&headers, "dashboard")?; |
| 662 | let next = if user.is_null() { |
| 663 | format!("/sign-in?flow={}", encoded(&flow)) |
| 664 | } else { |
| 665 | auth.next(string(&user["id"]), &flow, "/")? |
| 666 | }; |
| 667 | return Ok((StatusCode::FOUND, [("location", next)]).into_response()); |
| 668 | } |
| 669 | if path == "/auth/file/callback" && method == Method::GET { |
| 670 | let token = query.get("code").cloned().unwrap_or_default(); |
| 671 | let (id, next) = { |
| 672 | let mut db = auth.db.lock().unwrap(); |
| 673 | let transaction = db.transaction()?; |
| 674 | let code = pending(&transaction, &token, "handoff", false)?; |
| 675 | let flow = cookie(&headers, FLOW_COOKIE).unwrap_or_default(); |
| 676 | if code.is_null() |
| 677 | || flow.is_empty() |
| 678 | || !bool::from(flow.as_bytes().ct_eq(string(&code["flow"]).as_bytes())) |
| 679 | { |
| 680 | return Err(Error::new( |
| 681 | 403, |
| 682 | "File sign-in expired. Open Files and try again.", |
| 683 | )); |
| 684 | } |
| 685 | let target = pending(&transaction, &flow, "file", true)?; |
| 686 | if target.is_null() { |
| 687 | return Err(Error::new( |
| 688 | 403, |
| 689 | "File sign-in expired. Open Files and try again.", |
| 690 | )); |
| 691 | } |
| 692 | pending(&transaction, &token, "handoff", true)?; |
| 693 | let user = user(&transaction, string(&code["user"]))?; |
| 694 | if user["enabled"] != true { |
| 695 | return Err(Error::new(403, "This account is disabled. Contact Clover.")); |
| 696 | } |
| 697 | let result = ( |
| 698 | string(&code["user"]).to_owned(), |
| 699 | string(&target["next"]).to_owned(), |
| 700 | ); |
| 701 | transaction.commit()?; |
| 702 | result |
| 703 | }; |
| 704 | let session = auth.create_session(&id, "file", &headers, None)?; |
| 705 | return Ok(( |
| 706 | StatusCode::FOUND, |
| 707 | [("location", next), ("set-cookie", session)], |
| 708 | ) |
| 709 | .into_response()); |
| 710 | } |
| 711 | if path == "/auth/status" && method == Method::GET { |
| 712 | let csrf = cookie(&headers, CSRF_COOKIE) |
| 713 | .filter(|token| !token.is_empty()) |
| 714 | .unwrap_or_else(mcp::secret); |
| 715 | let mut value = json!({"csrf":csrf,"account":auth.session(&headers,"dashboard")?}); |
| 716 | value["service"] = json!("snow globe"); |
| 717 | if let Some(flow) = query.get("flow") { |
| 718 | if !pending(&auth.db.lock().unwrap(), flow, "file", false)?.is_null() { |
| 719 | value["service"] = json!("copyparty"); |
| 720 | } |
| 721 | } else if let Ok((target, config)) = oidc::sign_in_target( |
| 722 | auth, |
| 723 | query.get("next").map(String::as_str).unwrap_or_default(), |
| 724 | ) { |
| 725 | value["service"] = config["name"].clone(); |
| 726 | if target |
| 727 | .query_pairs() |
| 728 | .any(|(key, value)| key == "client_id" && value == "forward-auth") |
| 729 | { |
| 730 | if let Some(redirect) = target |
| 731 | .query_pairs() |
| 732 | .find(|(key, _)| key == "redirect_uri") |
| 733 | .and_then(|(_, value)| url::Url::parse(&value).ok()) |
| 734 | { |
| 735 | value["service"] = json!( |
| 736 | redirect |
| 737 | .host_str() |
| 738 | .unwrap_or("snow globe") |
| 739 | .split('.') |
| 740 | .next() |
| 741 | .unwrap_or("snow globe") |
| 742 | ); |
| 743 | if let Ok(catalog) = core::launcher(app.clone()).await { |
| 744 | if let Some(service) = array(&catalog.value).iter().find(|service| { |
| 745 | service["urls"].as_object().is_some_and(|urls| { |
| 746 | urls.values().any(|url| { |
| 747 | url.as_str() |
| 748 | == Some(redirect.origin().ascii_serialization().as_str()) |
| 749 | }) |
| 750 | }) |
| 751 | }) { |
| 752 | value["service"] = service["name"].clone(); |
| 753 | } |
| 754 | } |
| 755 | } |
| 756 | } |
| 757 | } |
| 758 | value["providers"] = guest::providers( |
| 759 | auth, |
| 760 | query.get("next").map(String::as_str).unwrap_or_default(), |
| 761 | )?; |
| 762 | if let Some(setup) = query.get("setup") { |
| 763 | let entry = pending(&auth.db.lock().unwrap(), setup, "setup", false)?; |
| 764 | if entry.is_null() { |
| 765 | return Err(Error::new( |
| 766 | 410, |
| 767 | "This link expired. Ask Clover for a new one.", |
| 768 | )); |
| 769 | } |
| 770 | value["setup"] = |
| 771 | user(&auth.db.lock().unwrap(), string(&entry["user"]))?["username"].clone(); |
| 772 | } |
| 773 | return Ok(( |
| 774 | [ |
| 775 | ("set-cookie", set_cookie(CSRF_COOKIE, &csrf, None)), |
| 776 | ("cache-control", "no-store".into()), |
| 777 | ], |
| 778 | axum::Json(value), |
| 779 | ) |
| 780 | .into_response()); |
| 781 | } |
| 782 | let shale_logout = path == "/auth/shale/sign-out"; |
| 783 | if path == "/auth/sign-out" || path == "/auth/file/sign-out" || shale_logout { |
| 784 | if method == Method::GET && path == "/auth/file/sign-out" { |
| 785 | return Ok(axum::response::Html("<!doctype html><html><meta name=viewport content='width=device-width'><title>Sign out of Files</title><body><form method=post action='/auth/file/sign-out'><button>sign out of Files</button></form></body></html>").into_response()); |
| 786 | } |
| 787 | if method |
| 788 | != (if shale_logout { |
| 789 | Method::GET |
| 790 | } else { |
| 791 | Method::POST |
| 792 | }) |
| 793 | { |
| 794 | return Err(Error::new(405, "Use the sign-out button.")); |
| 795 | } |
| 796 | let expected = if shale_logout { |
| 797 | &app.shale.origin |
| 798 | } else if path.contains("/file/") { |
| 799 | &auth.file |
| 800 | } else { |
| 801 | &auth.origin |
| 802 | }; |
| 803 | let source = if shale_logout { |
| 804 | headers |
| 805 | .get("referer") |
| 806 | .and_then(|v| v.to_str().ok()) |
| 807 | .and_then(|v| url::Url::parse(v).ok()) |
| 808 | .map(|v| v.origin().ascii_serialization()) |
| 809 | } else { |
| 810 | headers |
| 811 | .get("origin") |
| 812 | .and_then(|v| v.to_str().ok()) |
| 813 | .map(str::to_owned) |
| 814 | }; |
| 815 | if source.as_deref() != Some(expected.origin().ascii_serialization().as_str()) { |
| 816 | return Err(Error::new(403, "Open your account to sign out.")); |
| 817 | } |
| 818 | if let Some(token) = cookie(&headers, COOKIE) { |
| 819 | auth.db |
| 820 | .lock() |
| 821 | .unwrap() |
| 822 | .execute("DELETE FROM sessions WHERE hash=?", [mcp::hash(&token)])?; |
| 823 | } |
| 824 | if path.contains("/file/") || shale_logout { |
| 825 | return Ok(( |
| 826 | StatusCode::SEE_OTHER, |
| 827 | [ |
| 828 | ("set-cookie", set_cookie(COOKIE, "", Some(0))), |
| 829 | ( |
| 830 | "location", |
| 831 | if shale_logout { |
| 832 | app.shale.origin.to_string() |
| 833 | } else { |
| 834 | "/".into() |
| 835 | }, |
| 836 | ), |
| 837 | ], |
| 838 | ) |
| 839 | .into_response()); |
| 840 | } |
| 841 | return Ok(( |
| 842 | [("set-cookie", set_cookie(COOKIE, "", Some(0)))], |
| 843 | axum::Json(json!({"next":"/sign-in"})), |
| 844 | ) |
| 845 | .into_response()); |
| 846 | } |
| 847 | if method != Method::POST { |
| 848 | return Err(Error::new(404, "No sign-in action here.")); |
| 849 | } |
| 850 | let body: Value = |
| 851 | serde_json::from_slice(&axum::body::to_bytes(request.into_body(), 128 * 1024).await?) |
| 852 | .map_err(|_| Error::new(400, "Reload the form and try again."))?; |
| 853 | auth.csrf(&headers, &body)?; |
| 854 | if path == "/auth/password" || path == "/auth/passkey/start" { |
| 855 | let name = string(&body["username"]).trim().to_lowercase(); |
| 856 | if name.len() > 254 || (name.is_empty() && path == "/auth/password") { |
| 857 | return Err(Error::new(400, "Enter your username.")); |
| 858 | } |
| 859 | auth.limit(&headers, &name)?; |
| 860 | let id: Option<String> = auth.db.lock().unwrap().query_row("SELECT id FROM users WHERE username=? OR (lower(json_extract(profile,'$.email'))=? AND json_extract(profile,'$.emailVerified')=1) ORDER BY username=? DESC LIMIT 1",sql![name,name,name],|r|r.get(0)).optional()?; |
| 861 | let user = id |
| 862 | .as_ref() |
| 863 | .map(|id| user(&auth.db.lock().unwrap(), id)) |
| 864 | .transpose()? |
| 865 | .unwrap_or(Value::Null); |
| 866 | if path == "/auth/password" { |
| 867 | let password = string(&body["password"]).to_owned(); |
| 868 | if password.len() > 1024 { |
| 869 | return Err(Error::new(400, "That password is too long.")); |
| 870 | } |
| 871 | let data = row( |
| 872 | &auth.db.lock().unwrap(), |
| 873 | "SELECT data FROM credentials WHERE user_id=? AND kind='password'", |
| 874 | id.as_deref().unwrap_or(""), |
| 875 | )?; |
| 876 | let phc = string(&data["phc"]).to_owned(); |
| 877 | let _slot = auth |
| 878 | .passwords |
| 879 | .try_acquire() |
| 880 | .map_err(|_| Error::new(429, "Sign-in is busy. Try again in a moment."))?; |
| 881 | let verified = tokio::task::spawn_blocking(move || { |
| 882 | if phc.is_empty() { |
| 883 | let _ = password_hash(&password); |
| 884 | return false; |
| 885 | } |
| 886 | PasswordHash::new(&phc).is_ok_and(|hash| { |
| 887 | Argon2::default() |
| 888 | .verify_password(password.as_bytes(), &hash) |
| 889 | .is_ok() |
| 890 | }) |
| 891 | }) |
| 892 | .await?; |
| 893 | if !verified || user["enabled"] != true { |
| 894 | return Err(Error::new( |
| 895 | 401, |
| 896 | "That username or password doesn't match. Try again.", |
| 897 | )); |
| 898 | } |
| 899 | let id = id.unwrap(); |
| 900 | let mut session = auth.create_session(&id, "dashboard", &headers, Some(&data))?; |
| 901 | if body["remember"] == false { |
| 902 | session = session.replace(&format!("; Max-Age={SESSION_TTL}"), ""); |
| 903 | } |
| 904 | let next = auth.next(&id, string(&body["flow"]), string(&body["next"]))?; |
| 905 | return Ok( |
| 906 | ([("set-cookie", session)], axum::Json(json!({"next":next}))).into_response(), |
| 907 | ); |
| 908 | } |
| 909 | if !name.is_empty() && user["enabled"] != true { |
| 910 | return Err(Error::new( |
| 911 | 401, |
| 912 | "No passkey is available for that username. Try your password.", |
| 913 | )); |
| 914 | } |
| 915 | let keys = if let Some(id) = &id { |
| 916 | passkeys(&auth.db.lock().unwrap(), id)? |
| 917 | } else if name.is_empty() { |
| 918 | let db = auth.db.lock().unwrap(); |
| 919 | let mut statement = |
| 920 | db.prepare("SELECT id FROM users WHERE json_extract(profile,'$.enabled')=1")?; |
| 921 | let ids = statement |
| 922 | .query_map([], |r| r.get::<_, String>(0))? |
| 923 | .collect::<std::result::Result<Vec<_>, _>>()?; |
| 924 | ids.iter() |
| 925 | .map(|id| passkeys(&db, id)) |
| 926 | .collect::<Result<Vec<_>>>()? |
| 927 | .into_iter() |
| 928 | .flatten() |
| 929 | .collect() |
| 930 | } else { |
| 931 | Vec::new() |
| 932 | }; |
| 933 | if keys.is_empty() { |
| 934 | return Err(Error::new( |
| 935 | 401, |
| 936 | "No passkey is available for that username. Try your password.", |
| 937 | )); |
| 938 | } |
| 939 | let (mut options, state) = auth.webauthn.start_passkey_authentication(&keys)?; |
| 940 | if name.is_empty() { |
| 941 | options.public_key.allow_credentials.clear(); |
| 942 | } |
| 943 | let token = issue( |
| 944 | &auth.db.lock().unwrap(), |
| 945 | "authentication", |
| 946 | json!({"user":id,"csrf":body["csrf"],"state":state,"flow":body["flow"],"next":body["next"],"remember":body["remember"]}), |
| 947 | 300, |
| 948 | )?; |
| 949 | return Ok(axum::Json(json!({"options":options,"token":token})).into_response()); |
| 950 | } |
| 951 | if path == "/auth/passkey/finish" { |
| 952 | let value = pending( |
| 953 | &auth.db.lock().unwrap(), |
| 954 | string(&body["token"]), |
| 955 | "authentication", |
| 956 | true, |
| 957 | )?; |
| 958 | if value.is_null() || value["csrf"] != body["csrf"] { |
| 959 | return Err(Error::new(403, "Passkey sign-in expired. Try again.")); |
| 960 | } |
| 961 | let credential: PublicKeyCredential = serde_json::from_value(body["credential"].clone()) |
| 962 | .map_err(|_| Error::new(400, "The browser couldn't return your passkey. Try again."))?; |
| 963 | let id = if let Some(id) = value["user"].as_str() { |
| 964 | id.to_owned() |
| 965 | } else { |
| 966 | let db = auth.db.lock().unwrap(); |
| 967 | let mut statement = db.prepare( |
| 968 | "SELECT user_id,data FROM credentials WHERE kind='webauthn-passwordless'", |
| 969 | )?; |
| 970 | let rows = statement |
| 971 | .query_map([], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))? |
| 972 | .collect::<std::result::Result<Vec<_>, _>>()?; |
| 973 | let mut found = None; |
| 974 | for (id, data) in rows { |
| 975 | let data: Value = serde_json::from_str(&data)?; |
| 976 | let passkey: Passkey = serde_json::from_value(data["passkey"].clone())?; |
| 977 | if passkey.cred_id().as_slice() == credential.get_credential_id() |
| 978 | && body["credential"]["response"]["userHandle"] == data["handle"] |
| 979 | { |
| 980 | if found.is_some() { |
| 981 | return Err(Error::new( |
| 982 | 401, |
| 983 | "That passkey couldn't identify your account.", |
| 984 | )); |
| 985 | } |
| 986 | found = Some(id); |
| 987 | } |
| 988 | } |
| 989 | found.ok_or_else(|| { |
| 990 | Error::new( |
| 991 | 401, |
| 992 | "That passkey couldn't identify your account. Try your password.", |
| 993 | ) |
| 994 | })? |
| 995 | }; |
| 996 | let mut state = value["state"].clone(); |
| 997 | let mut allowed: Vec<Credential> = |
| 998 | serde_json::from_value(state["ast"]["credentials"].clone())?; |
| 999 | { |
| 1000 | let db = auth.db.lock().unwrap(); |
| 1001 | let mut statement = db.prepare( |
| 1002 | "SELECT data FROM credentials WHERE user_id=? AND kind='webauthn-passwordless'", |
| 1003 | )?; |
| 1004 | for stored in statement.query_map([&id], |r| r.get::<_, String>(0))? { |
| 1005 | let stored: Value = serde_json::from_str(&stored?)?; |
| 1006 | let passkey: Passkey = serde_json::from_value(stored["passkey"].clone())?; |
| 1007 | if stored["backupUnknown"] == true |
| 1008 | && passkey.cred_id().as_slice() == credential.get_credential_id() |
| 1009 | { |
| 1010 | let flags = credential |
| 1011 | .response |
| 1012 | .authenticator_data |
| 1013 | .as_slice() |
| 1014 | .get(32) |
| 1015 | .copied() |
| 1016 | .ok_or_else(|| Error::new(400, "The passkey response was incomplete."))?; |
| 1017 | for key in &mut allowed { |
| 1018 | if key.cred_id == *passkey.cred_id() { |
| 1019 | key.backup_eligible = flags & 8 != 0; |
| 1020 | key.backup_state = flags & 16 != 0; |
| 1021 | } |
| 1022 | } |
| 1023 | } |
| 1024 | } |
| 1025 | } |
| 1026 | state["ast"]["credentials"] = json!(allowed); |
| 1027 | let state: PasskeyAuthentication = serde_json::from_value(state)?; |
| 1028 | let result = auth |
| 1029 | .webauthn |
| 1030 | .finish_passkey_authentication(&credential, &state) |
| 1031 | .map_err(|error| { |
| 1032 | eprintln!("passkey authentication: {error:?}"); |
| 1033 | Error::new( |
| 1034 | 401, |
| 1035 | "That passkey couldn't sign in. Try again or use your password.", |
| 1036 | ) |
| 1037 | })?; |
| 1038 | let id = id.as_str(); |
| 1039 | { |
| 1040 | let db = auth.db.lock().unwrap(); |
| 1041 | let user = user(&db, id)?; |
| 1042 | if user["enabled"] != true { |
| 1043 | return Err(Error::new(403, "This account is disabled. Contact Clover.")); |
| 1044 | } |
| 1045 | let mut statement = db.prepare( |
| 1046 | "SELECT id,data FROM credentials WHERE user_id=? AND kind='webauthn-passwordless'", |
| 1047 | )?; |
| 1048 | let rows = statement |
| 1049 | .query_map([id], |r| { |
| 1050 | Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)) |
| 1051 | })? |
| 1052 | .collect::<std::result::Result<Vec<_>, _>>()?; |
| 1053 | let mut matched = false; |
| 1054 | for (key, data) in rows { |
| 1055 | let mut data: Value = serde_json::from_str(&data)?; |
| 1056 | let mut passkey: Passkey = serde_json::from_value(data["passkey"].clone())?; |
| 1057 | if passkey.cred_id() == result.cred_id() { |
| 1058 | if let Some(handle) = body["credential"]["response"]["userHandle"].as_str() { |
| 1059 | if !handle.is_empty() && handle != string(&data["handle"]) { |
| 1060 | return Err(Error::new( |
| 1061 | 401, |
| 1062 | "That passkey belongs to a different account.", |
| 1063 | )); |
| 1064 | } |
| 1065 | } |
| 1066 | matched = true; |
| 1067 | let current: Credential = passkey.clone().into(); |
| 1068 | if (current.counter != 0 || result.counter() != 0) |
| 1069 | && result.counter() <= current.counter |
| 1070 | { |
| 1071 | return Err(Error::new( |
| 1072 | 401, |
| 1073 | "This passkey returned an old counter. Try another sign-in method.", |
| 1074 | )); |
| 1075 | } |
| 1076 | if data["backupUnknown"] == true { |
| 1077 | let mut key: Credential = passkey.into(); |
| 1078 | key.backup_eligible = result.backup_eligible(); |
| 1079 | key.backup_state = result.backup_state(); |
| 1080 | passkey = key.into(); |
| 1081 | data.as_object_mut().unwrap().remove("backupUnknown"); |
| 1082 | } |
| 1083 | passkey.update_credential(&result); |
| 1084 | data["passkey"] = json!(passkey); |
| 1085 | db.execute( |
| 1086 | "UPDATE credentials SET data=? WHERE id=?", |
| 1087 | sql![data.to_string(), key], |
| 1088 | )?; |
| 1089 | break; |
| 1090 | } |
| 1091 | } |
| 1092 | if !matched { |
| 1093 | return Err(Error::new( |
| 1094 | 401, |
| 1095 | "This passkey was removed. Try another sign-in method.", |
| 1096 | )); |
| 1097 | } |
| 1098 | } |
| 1099 | let mut session = auth.create_session(id, "dashboard", &headers, None)?; |
| 1100 | if body.get("remember").unwrap_or(&value["remember"]) == false { |
| 1101 | session = session.replace(&format!("; Max-Age={SESSION_TTL}"), ""); |
| 1102 | } |
| 1103 | let next = auth.next(id, string(&value["flow"]), string(&value["next"]))?; |
| 1104 | return Ok(([("set-cookie", session)], axum::Json(json!({"next":next}))).into_response()); |
| 1105 | } |
| 1106 | if path == "/auth/setup" { |
| 1107 | let email = string(&body["email"]).trim(); |
| 1108 | if !email.contains('@') || email.len() > 254 { |
| 1109 | return Err(Error::new(400, "Enter your email address.")); |
| 1110 | } |
| 1111 | let password = string(&body["password"]).to_owned(); |
| 1112 | if password.chars().count() < 8 || password.len() > 1024 { |
| 1113 | return Err(Error::new( |
| 1114 | 400, |
| 1115 | "Use a password with at least 8 characters.", |
| 1116 | )); |
| 1117 | } |
| 1118 | let _slot = auth |
| 1119 | .passwords |
| 1120 | .try_acquire() |
| 1121 | .map_err(|_| Error::new(429, "Sign-in is busy. Try again in a moment."))?; |
| 1122 | let hash = tokio::task::spawn_blocking(move || password_hash(&password)).await??; |
| 1123 | let id = { |
| 1124 | let mut db = auth.db.lock().unwrap(); |
| 1125 | let transaction = db.transaction()?; |
| 1126 | let entry = pending(&transaction, string(&body["setup"]), "setup", true)?; |
| 1127 | if entry.is_null() { |
| 1128 | return Err(Error::new( |
| 1129 | 410, |
| 1130 | "This link expired. Ask Clover for a new one.", |
| 1131 | )); |
| 1132 | } |
| 1133 | let id = string(&entry["user"]).to_owned(); |
| 1134 | let mut profile = user(&transaction, &id)?; |
| 1135 | profile["email"] = json!(email); |
| 1136 | profile["emailVerified"] = json!(false); |
| 1137 | if profile["enabled"] != true { |
| 1138 | return Err(Error::new( |
| 1139 | 403, |
| 1140 | "This account is disabled. Ask Clover for a new link.", |
| 1141 | )); |
| 1142 | } |
| 1143 | profile["requiredActions"] = json!([]); |
| 1144 | set_password(&transaction, &id, &hash)?; |
| 1145 | save_user(&transaction, &id, profile)?; |
| 1146 | transaction.execute("DELETE FROM sessions WHERE user_id=?", [&id])?; |
| 1147 | transaction.commit()?; |
| 1148 | id |
| 1149 | }; |
| 1150 | users::revoke_connections(&app, &id)?; |
| 1151 | return Ok(( |
| 1152 | [( |
| 1153 | "set-cookie", |
| 1154 | auth.create_session(&id, "dashboard", &headers, None)?, |
| 1155 | )], |
| 1156 | axum::Json(json!({"next":"/account?welcome=1"})), |
| 1157 | ) |
| 1158 | .into_response()); |
| 1159 | } |
| 1160 | let user = auth.session(&headers, "dashboard")?; |
| 1161 | if user.is_null() { |
| 1162 | return Err(Error::new(401, "Sign in to manage your account.")); |
| 1163 | } |
| 1164 | if guest::is_guest(&user) { |
| 1165 | return Err(Error::new( |
| 1166 | 403, |
| 1167 | "Guests sign in with their provider. Use the Shale sign-in page.", |
| 1168 | )); |
| 1169 | } |
| 1170 | let id = string(&user["id"]); |
| 1171 | if path == "/auth/passkey/register" { |
| 1172 | auth.recent(&headers)?; |
| 1173 | let db = auth.db.lock().unwrap(); |
| 1174 | let keys = passkeys(&db, id)?; |
| 1175 | let ids = keys.iter().map(|key| key.cred_id().clone()).collect(); |
| 1176 | let uuid = uuid::Uuid::parse_str(id)?; |
| 1177 | let (options, state) = auth.webauthn.start_passkey_registration( |
| 1178 | uuid, |
| 1179 | string(&user["username"]), |
| 1180 | string(&user["username"]), |
| 1181 | Some(ids), |
| 1182 | )?; |
| 1183 | let token = issue( |
| 1184 | &db, |
| 1185 | "registration", |
| 1186 | json!({"user":id,"csrf":body["csrf"],"state":state}), |
| 1187 | 300, |
| 1188 | )?; |
| 1189 | return Ok(axum::Json(json!({"options":options,"token":token})).into_response()); |
| 1190 | } |
| 1191 | if path == "/auth/passkey/save" { |
| 1192 | auth.recent(&headers)?; |
| 1193 | let db = auth.db.lock().unwrap(); |
| 1194 | let value = pending(&db, string(&body["token"]), "registration", true)?; |
| 1195 | if value.is_null() || value["user"] != user["id"] || value["csrf"] != body["csrf"] { |
| 1196 | return Err(Error::new(403, "Passkey setup expired. Try again.")); |
| 1197 | } |
| 1198 | let credential: RegisterPublicKeyCredential = |
| 1199 | serde_json::from_value(body["credential"].clone()).map_err(|_| { |
| 1200 | Error::new(400, "The browser couldn't create your passkey. Try again.") |
| 1201 | })?; |
| 1202 | let state: PasskeyRegistration = serde_json::from_value(value["state"].clone())?; |
| 1203 | let passkey = auth |
| 1204 | .webauthn |
| 1205 | .finish_passkey_registration(&credential, &state) |
| 1206 | .map_err(|_| Error::new(400, "That passkey couldn't be added. Try again."))?; |
| 1207 | let label = string(&body["label"]).trim(); |
| 1208 | if label.len() > 100 { |
| 1209 | return Err(Error::new(400, "Use a shorter passkey name.")); |
| 1210 | } |
| 1211 | db.execute("INSERT INTO credentials VALUES (?,?,?,?,?,?)",sql![uuid::Uuid::new_v4().to_string(),id,"webauthn-passwordless",if label.is_empty(){"passkey"}else{label},(now()*1000.0) as i64,json!({"passkey":passkey,"handle":URL_SAFE_NO_PAD.encode(uuid::Uuid::parse_str(id)?.as_bytes())}).to_string()])?; |
| 1212 | return Ok(StatusCode::NO_CONTENT.into_response()); |
| 1213 | } |
| 1214 | if path == "/auth/password/change" { |
| 1215 | auth.recent(&headers)?; |
| 1216 | let data = row( |
| 1217 | &auth.db.lock().unwrap(), |
| 1218 | "SELECT data FROM credentials WHERE user_id=? AND kind='password'", |
| 1219 | id, |
| 1220 | )?; |
| 1221 | let phc = string(&data["phc"]).to_owned(); |
| 1222 | let current = string(&body["current"]).to_owned(); |
| 1223 | let password = string(&body["password"]).to_owned(); |
| 1224 | if password.chars().count() < 8 || password.len() > 1024 || current.len() > 1024 { |
| 1225 | return Err(Error::new( |
| 1226 | 400, |
| 1227 | "Use a password with at least 8 characters.", |
| 1228 | )); |
| 1229 | } |
| 1230 | auth.limit(&headers, id)?; |
| 1231 | let _slot = auth |
| 1232 | .passwords |
| 1233 | .try_acquire() |
| 1234 | .map_err(|_| Error::new(429, "Sign-in is busy. Try again in a moment."))?; |
| 1235 | let hash = tokio::task::spawn_blocking(move || { |
| 1236 | if !phc.is_empty() |
| 1237 | && !PasswordHash::new(&phc).is_ok_and(|hash| { |
| 1238 | Argon2::default() |
| 1239 | .verify_password(current.as_bytes(), &hash) |
| 1240 | .is_ok() |
| 1241 | }) |
| 1242 | { |
| 1243 | return Err(Error::new( |
| 1244 | 401, |
| 1245 | "Your current password doesn't match. Try again.", |
| 1246 | )); |
| 1247 | } |
| 1248 | password_hash(&password) |
| 1249 | }) |
| 1250 | .await??; |
| 1251 | { |
| 1252 | let mut db = auth.db.lock().unwrap(); |
| 1253 | let transaction = db.transaction()?; |
| 1254 | let mut profile = self::user(&transaction, id)?; |
| 1255 | if profile["enabled"] != true { |
| 1256 | return Err(Error::new(403, "This account is disabled.")); |
| 1257 | } |
| 1258 | set_password(&transaction, id, &hash)?; |
| 1259 | profile["requiredActions"] = json!( |
| 1260 | array(&user["requiredActions"]) |
| 1261 | .iter() |
| 1262 | .filter(|v| **v != "UPDATE_PASSWORD") |
| 1263 | .collect::<Vec<_>>() |
| 1264 | ); |
| 1265 | save_user(&transaction, id, profile)?; |
| 1266 | transaction.execute("DELETE FROM sessions WHERE user_id=?", [id])?; |
| 1267 | transaction.commit()?; |
| 1268 | } |
| 1269 | users::revoke_connections(&app, id)?; |
| 1270 | return Ok(( |
| 1271 | [( |
| 1272 | "set-cookie", |
| 1273 | auth.create_session(id, "dashboard", &headers, None)?, |
| 1274 | )], |
| 1275 | StatusCode::NO_CONTENT, |
| 1276 | ) |
| 1277 | .into_response()); |
| 1278 | } |
| 1279 | Err(Error::new(404, "No account action here.")) |
| 1280 | } |
| 1281 | |
| 1282 | fn passkeys(db: &Connection, id: &str) -> Result<Vec<Passkey>> { |
| 1283 | let mut statement = db |
| 1284 | .prepare("SELECT data FROM credentials WHERE user_id=? AND kind='webauthn-passwordless'")?; |
| 1285 | statement |
| 1286 | .query_map([id], |r| r.get::<_, String>(0))? |
| 1287 | .map(|data| { |
| 1288 | let value: Value = serde_json::from_str(&data?)?; |
| 1289 | Ok(serde_json::from_value(value["passkey"].clone())?) |
| 1290 | }) |
| 1291 | .collect() |
| 1292 | } |
| 1293 | |
| 1294 | #[cfg(test)] |
| 1295 | mod tests { |
| 1296 | use super::*; |
| 1297 | |
| 1298 | #[test] |
| 1299 | fn folder_identity_tracks_the_account_id_and_requires_an_enabled_regular_account() { |
| 1300 | let mut account = json!({"id":"12345678-1234-1234-1234-123456789abc","username":"snow","enabled":true,"requiredActions":[],"groups":[{"name":"media"}]}); |
| 1301 | assert_eq!(file_groups(&account).unwrap(), "media,snow-user-12345678-1234-1234-1234-123456789abc"); |
| 1302 | account["username"] = json!("different"); |
| 1303 | assert_eq!(file_groups(&account).unwrap(), "media,snow-user-12345678-1234-1234-1234-123456789abc"); |
| 1304 | account["id"] = json!("12345678-1234-1234-1234-123456789abd"); |
| 1305 | assert!(file_groups(&account).unwrap().ends_with("snow-user-12345678-1234-1234-1234-123456789abd")); |
| 1306 | for (field, value) in [("enabled", json!(false)), ("kind", json!("guest")), ("kind", json!("ai")), ("requiredActions", json!(["UPDATE_PASSWORD"])), ("id", json!("x,infra-admin"))] { |
| 1307 | let mut blocked = account.clone(); |
| 1308 | blocked[field] = value; |
| 1309 | assert!(file_groups(&blocked).is_none()); |
| 1310 | } |
| 1311 | } |
| 1312 | } |