Password reset, rate limiting, policy settings
Browse files at this commit6099ac7ed48f46e0c71af4b2431fe30deaef0883Parent: 794c3a4- feat
- password reset, rate limiting, policy settings
- fix
- connection mutex, row alignment
16 changed files +1154 -435
- crates/im-core/src/accounts.rs +398 -113
- crates/im-core/src/events.rs +4 -4
- crates/im-core/src/keys.rs +17 -19
- crates/im-core/src/oidc.rs +129 -132
- crates/im-core/src/sessions.rs +116 -111
- crates/im-core/src/settings.rs +134 -16
- crates/im-core/src/store.rs +25 -11
- crates/im-core/src/totp.rs +16 -18
- crates/im-web/assets/main.css +4 -0
- crates/im-web/src/admin.rs +65 -0
- crates/im-web/src/auth.rs +87 -6
- crates/im-web/src/mailer.rs +17 -0
- crates/im-web/src/oidc.rs +2 -1
- crates/im-web/src/pages.rs +123 -0
- crates/im-web/src/server.rs +10 -4
- style/main.scss +7 -0
crates/im-core/src/accounts.rsmodified+398 -113
| @@ -67,10 +67,14 @@ pub enum AccountError { | ||
| 67 | 67 | InvalidCredentials, |
| 68 | 68 | #[error("this invite is not valid")] |
| 69 | 69 | InviteInvalid, |
| 70 | - #[error("this invite has expired")] | |
| 71 | - InviteExpired, | |
| 70 | + /// Unknown, spent or expired — one refusal for all three, so the page | |
| 71 | + /// never says which. | |
| 72 | + #[error("this reset link is not valid")] | |
| 73 | + ResetInvalid, | |
| 72 | 74 | #[error("this invite was already used")] |
| 73 | 75 | InviteSpent, |
| 76 | + #[error("this invite has expired")] | |
| 77 | + InviteExpired, | |
| 74 | 78 | #[error("an account with this address already exists")] |
| 75 | 79 | EmailTaken, |
| 76 | 80 | #[error("password: {0}")] |
| @@ -240,31 +244,32 @@ pub async fn create_invite( | ||
| 240 | 244 | } |
| 241 | 245 | let token = Token::mint(); |
| 242 | 246 | let now = store::now(); |
| 243 | - let expires = now + time::Duration::days(INVITE_DAYS); | |
| 244 | - store | |
| 245 | - .conn | |
| 246 | - .execute( | |
| 247 | - "INSERT INTO invites (token, email, invited_by, admin, created_at, expires_at) \ | |
| 247 | + // The panel's Settings section owns this number now; the constant is the | |
| 248 | + // fresh-database default, not the value. | |
| 249 | + let expires = now + time::Duration::days(crate::settings::invite_days(store).await?); | |
| 250 | + let conn = store.conn.lock().await; | |
| 251 | + conn.execute( | |
| 252 | + "INSERT INTO invites (token, email, invited_by, admin, created_at, expires_at) \ | |
| 248 | 253 | VALUES (?1, ?2, ?3, ?4, ?5, ?6)", |
| 249 | - turso::params![ | |
| 250 | - token.hash(), | |
| 251 | - email, | |
| 252 | - invited_by.map(|id| id.to_string()), | |
| 253 | - admin as i64, | |
| 254 | - store::stamp(now)?, | |
| 255 | - store::stamp(expires)?, | |
| 256 | - ], | |
| 257 | - ) | |
| 258 | - .await | |
| 259 | - .map_err(backend)?; | |
| 254 | + turso::params![ | |
| 255 | + token.hash(), | |
| 256 | + email, | |
| 257 | + invited_by.map(|id| id.to_string()), | |
| 258 | + admin as i64, | |
| 259 | + store::stamp(now)?, | |
| 260 | + store::stamp(expires)?, | |
| 261 | + ], | |
| 262 | + ) | |
| 263 | + .await | |
| 264 | + .map_err(backend)?; | |
| 260 | 265 | Ok(token) |
| 261 | 266 | } |
| 262 | 267 | |
| 263 | 268 | /// Looks an invite up by its raw token. Expiry and spent-ness are the |
| 264 | 269 | /// caller's to rule on — this answers what the row says. |
| 265 | 270 | pub async fn invite_by_token(store: &Store, token: &str) -> Result<Option<Invite>> { |
| 266 | - let mut rows = store | |
| 267 | - .conn | |
| 271 | + let conn = store.conn.lock().await; | |
| 272 | + let mut rows = conn | |
| 268 | 273 | .query( |
| 269 | 274 | "SELECT email, invited_by, admin, created_at, expires_at, accepted_at \ |
| 270 | 275 | FROM invites WHERE token = ?1", |
| @@ -303,8 +308,8 @@ pub struct PendingInvite { | ||
| 303 | 308 | |
| 304 | 309 | /// Invites not yet accepted and not yet expired, oldest first. |
| 305 | 310 | pub async fn list_pending_invites(store: &Store) -> Result<Vec<PendingInvite>> { |
| 306 | - let mut rows = store | |
| 307 | - .conn | |
| 311 | + let conn = store.conn.lock().await; | |
| 312 | + let mut rows = conn | |
| 308 | 313 | .query( |
| 309 | 314 | "SELECT token, email, admin, created_at, expires_at FROM invites \ |
| 310 | 315 | WHERE accepted_at IS NULL AND expires_at > ?1 ORDER BY created_at", |
| @@ -328,8 +333,8 @@ pub async fn list_pending_invites(store: &Store) -> Result<Vec<PendingInvite>> { | ||
| 328 | 333 | /// Invalidates an invite: the row is gone, the link reads "not valid" from |
| 329 | 334 | /// that moment on. Returns the address it was made out to, for the log line. |
| 330 | 335 | pub async fn revoke_invite(store: &Store, token_hash: &str) -> Result<Option<String>> { |
| 331 | - let mut rows = store | |
| 332 | - .conn | |
| 336 | + let conn = store.conn.lock().await; | |
| 337 | + let mut rows = conn | |
| 333 | 338 | .query( |
| 334 | 339 | "SELECT email FROM invites WHERE token = ?1", |
| 335 | 340 | turso::params![token_hash], |
| @@ -340,14 +345,12 @@ pub async fn revoke_invite(store: &Store, token_hash: &str) -> Result<Option<Str | ||
| 340 | 345 | return Ok(None); |
| 341 | 346 | }; |
| 342 | 347 | let email = store::text(&row, 0)?; |
| 343 | - store | |
| 344 | - .conn | |
| 345 | - .execute( | |
| 346 | - "DELETE FROM invites WHERE token = ?1", | |
| 347 | - turso::params![token_hash], | |
| 348 | - ) | |
| 349 | - .await | |
| 350 | - .map_err(backend)?; | |
| 348 | + conn.execute( | |
| 349 | + "DELETE FROM invites WHERE token = ?1", | |
| 350 | + turso::params![token_hash], | |
| 351 | + ) | |
| 352 | + .await | |
| 353 | + .map_err(backend)?; | |
| 351 | 354 | Ok(Some(email)) |
| 352 | 355 | } |
| 353 | 356 | |
| @@ -380,59 +383,256 @@ pub async fn create_user_from_invite( | ||
| 380 | 383 | created_at: store::now(), |
| 381 | 384 | }; |
| 382 | 385 | let password_hash = hash_password(password)?; |
| 386 | + // The lock is taken only now — the reads above (`invite_by_token`) lock | |
| 387 | + // for themselves, and the transaction holds it alone. | |
| 388 | + let conn = store.conn.lock().await; | |
| 383 | 389 | |
| 384 | - store | |
| 385 | - .conn | |
| 386 | - .execute("BEGIN IMMEDIATE", ()) | |
| 387 | - .await | |
| 388 | - .map_err(backend)?; | |
| 390 | + conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?; | |
| 389 | 391 | let outcome = async { |
| 390 | - store | |
| 391 | - .conn | |
| 392 | - .execute( | |
| 393 | - "INSERT INTO users (id, email, name, password_hash, admin, created_at) \ | |
| 392 | + conn.execute( | |
| 393 | + "INSERT INTO users (id, email, name, password_hash, admin, created_at) \ | |
| 394 | 394 | VALUES (?1, ?2, ?3, ?4, ?5, ?6)", |
| 395 | - turso::params![ | |
| 396 | - user.id.to_string(), | |
| 397 | - user.email.clone(), | |
| 398 | - user.name.clone(), | |
| 399 | - password_hash, | |
| 400 | - user.admin as i64, | |
| 401 | - store::stamp(user.created_at)?, | |
| 402 | - ], | |
| 403 | - ) | |
| 404 | - .await | |
| 405 | - .map_err(|e| { | |
| 406 | - let text = e.to_string().to_lowercase(); | |
| 407 | - if text.contains("constraint") || text.contains("unique") { | |
| 408 | - AccountError::EmailTaken | |
| 409 | - } else { | |
| 410 | - AccountError::Backend(e.to_string()) | |
| 411 | - } | |
| 412 | - })?; | |
| 413 | - store | |
| 414 | - .conn | |
| 415 | - .execute( | |
| 416 | - "UPDATE invites SET accepted_at = ?1 WHERE token = ?2 AND accepted_at IS NULL", | |
| 417 | - turso::params![store::stamp(store::now())?, hash_token(token)], | |
| 395 | + turso::params![ | |
| 396 | + user.id.to_string(), | |
| 397 | + user.email.clone(), | |
| 398 | + user.name.clone(), | |
| 399 | + password_hash, | |
| 400 | + user.admin as i64, | |
| 401 | + store::stamp(user.created_at)?, | |
| 402 | + ], | |
| 403 | + ) | |
| 404 | + .await | |
| 405 | + .map_err(|e| { | |
| 406 | + let text = e.to_string().to_lowercase(); | |
| 407 | + if text.contains("constraint") || text.contains("unique") { | |
| 408 | + AccountError::EmailTaken | |
| 409 | + } else { | |
| 410 | + AccountError::Backend(e.to_string()) | |
| 411 | + } | |
| 412 | + })?; | |
| 413 | + conn.execute( | |
| 414 | + "UPDATE invites SET accepted_at = ?1 WHERE token = ?2 AND accepted_at IS NULL", | |
| 415 | + turso::params![store::stamp(store::now())?, hash_token(token)], | |
| 416 | + ) | |
| 417 | + .await | |
| 418 | + .map_err(|e| AccountError::Backend(e.to_string()))?; | |
| 419 | + Ok::<_, AccountError>(()) | |
| 420 | + } | |
| 421 | + .await; | |
| 422 | + match outcome { | |
| 423 | + Ok(()) => { | |
| 424 | + conn.execute("COMMIT", ()).await.map_err(backend)?; | |
| 425 | + Ok(user) | |
| 426 | + } | |
| 427 | + Err(e) => { | |
| 428 | + let _ = conn.execute("ROLLBACK", ()).await; | |
| 429 | + Err(e) | |
| 430 | + } | |
| 431 | + } | |
| 432 | +} | |
| 433 | + | |
| 434 | +// --------------------------------------------------------------------------- | |
| 435 | +// Password reset | |
| 436 | +// --------------------------------------------------------------------------- | |
| 437 | + | |
| 438 | +/// Mints a reset link for the account at `email`, retiring every previous | |
| 439 | +/// live one first: two reset mails means the first is already dead — the | |
| 440 | +/// newest link is the only door. `None` for an address with no account, so | |
| 441 | +/// the web layer can answer every address identically. | |
| 442 | +pub async fn create_reset( | |
| 443 | + store: &Store, | |
| 444 | + email: &str, | |
| 445 | +) -> std::result::Result<Option<Token>, AccountError> { | |
| 446 | + let Some(user) = user_by_email(store, email).await? else { | |
| 447 | + return Ok(None); | |
| 448 | + }; | |
| 449 | + let token = Token::mint(); | |
| 450 | + let now = store::now(); | |
| 451 | + let expires = now + time::Duration::minutes(crate::settings::reset_minutes(store).await?); | |
| 452 | + let conn = store.conn.lock().await; | |
| 453 | + conn.execute( | |
| 454 | + "DELETE FROM reset_links WHERE user_id = ?1 AND used_at IS NULL", | |
| 455 | + turso::params![user.id.to_string()], | |
| 456 | + ) | |
| 457 | + .await | |
| 458 | + .map_err(backend)?; | |
| 459 | + conn.execute( | |
| 460 | + "INSERT INTO reset_links (token, user_id, created_at, expires_at) \ | |
| 461 | + VALUES (?1, ?2, ?3, ?4)", | |
| 462 | + turso::params![ | |
| 463 | + token.hash(), | |
| 464 | + user.id.to_string(), | |
| 465 | + store::stamp(now)?, | |
| 466 | + store::stamp(expires)?, | |
| 467 | + ], | |
| 468 | + ) | |
| 469 | + .await | |
| 470 | + .map_err(backend)?; | |
| 471 | + Ok(Some(token)) | |
| 472 | +} | |
| 473 | + | |
| 474 | +/// Turns a valid reset link into a new password. The link is spent, the hash | |
| 475 | +/// replaced, and every session revoked in one transaction — the old | |
| 476 | +/// password's doors close the moment the new one exists. | |
| 477 | +pub async fn redeem_reset( | |
| 478 | + store: &Store, | |
| 479 | + token: &str, | |
| 480 | + password: &str, | |
| 481 | +) -> std::result::Result<User, AccountError> { | |
| 482 | + let hash = hash_token(token); | |
| 483 | + // Short-held read first: the row says whether the link may be redeemed. | |
| 484 | + let (user_id, expires_at, used) = { | |
| 485 | + let conn = store.conn.lock().await; | |
| 486 | + let mut rows = conn | |
| 487 | + .query( | |
| 488 | + "SELECT user_id, expires_at, used_at FROM reset_links WHERE token = ?1", | |
| 489 | + turso::params![hash.clone()], | |
| 418 | 490 | ) |
| 419 | 491 | .await |
| 420 | - .map_err(|e| AccountError::Backend(e.to_string()))?; | |
| 492 | + .map_err(backend)?; | |
| 493 | + let Some(row) = rows.next().await.map_err(backend)? else { | |
| 494 | + return Err(AccountError::ResetInvalid); | |
| 495 | + }; | |
| 496 | + ( | |
| 497 | + UserId::from(store::text(&row, 0)?), | |
| 498 | + store::parse_stamp(&store::text(&row, 1)?)?, | |
| 499 | + store::opt_text(&row, 2)?.is_some(), | |
| 500 | + ) | |
| 501 | + }; | |
| 502 | + if used || expires_at < store::now() { | |
| 503 | + return Err(AccountError::ResetInvalid); | |
| 504 | + } | |
| 505 | + let user = user_by_id(store, &user_id) | |
| 506 | + .await? | |
| 507 | + .ok_or(AccountError::ResetInvalid)?; | |
| 508 | + check_password(password, &user.email, &user.name)?; | |
| 509 | + let password_hash = hash_password(password)?; | |
| 510 | + | |
| 511 | + // The write half holds the lock across its transaction; revocation comes | |
| 512 | + // after COMMIT because `revoke_user_sessions` locks for itself. | |
| 513 | + let conn = store.conn.lock().await; | |
| 514 | + conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?; | |
| 515 | + let outcome = async { | |
| 516 | + conn.execute( | |
| 517 | + "UPDATE reset_links SET used_at = ?1 WHERE token = ?2 AND used_at IS NULL", | |
| 518 | + turso::params![store::stamp(store::now())?, hash], | |
| 519 | + ) | |
| 520 | + .await | |
| 521 | + .map_err(|e| AccountError::Backend(e.to_string()))?; | |
| 522 | + conn.execute( | |
| 523 | + "UPDATE users SET password_hash = ?1 WHERE id = ?2", | |
| 524 | + turso::params![password_hash, user.id.to_string()], | |
| 525 | + ) | |
| 526 | + .await | |
| 527 | + .map_err(|e| AccountError::Backend(e.to_string()))?; | |
| 421 | 528 | Ok::<_, AccountError>(()) |
| 422 | 529 | } |
| 423 | 530 | .await; |
| 424 | 531 | match outcome { |
| 425 | 532 | Ok(()) => { |
| 426 | - store.conn.execute("COMMIT", ()).await.map_err(backend)?; | |
| 533 | + conn.execute("COMMIT", ()).await.map_err(backend)?; | |
| 534 | + drop(conn); | |
| 535 | + crate::sessions::revoke_user_sessions(store, &user.id) | |
| 536 | + .await | |
| 537 | + .map_err(|e| AccountError::Backend(e.to_string()))?; | |
| 538 | + // Owning the mailbox is the proof; past failures stop counting. | |
| 539 | + clear_login_failures(store, &user.email).await?; | |
| 427 | 540 | Ok(user) |
| 428 | 541 | } |
| 429 | 542 | Err(e) => { |
| 430 | - let _ = store.conn.execute("ROLLBACK", ()).await; | |
| 543 | + let _ = conn.execute("ROLLBACK", ()).await; | |
| 431 | 544 | Err(e) |
| 432 | 545 | } |
| 433 | 546 | } |
| 434 | 547 | } |
| 435 | 548 | |
| 549 | +// --------------------------------------------------------------------------- | |
| 550 | +// Sign-in rate limiting | |
| 551 | +// --------------------------------------------------------------------------- | |
| 552 | + | |
| 553 | +/// The counter is a rolling hour of failures per key — the address for | |
| 554 | +/// passwords, `totp:{user}` for second factors. Reads and writes both sweep | |
| 555 | +/// their own key's stale rows, so the table never grows without bound. | |
| 556 | +async fn sweep_attempts(store: &Store, key: &str) -> Result<()> { | |
| 557 | + let conn = store.conn.lock().await; | |
| 558 | + let cutoff = store::stamp(store::now() - time::Duration::hours(1))?; | |
| 559 | + conn.execute( | |
| 560 | + "DELETE FROM login_attempts WHERE key = ?1 AND at < ?2", | |
| 561 | + turso::params![key, cutoff], | |
| 562 | + ) | |
| 563 | + .await | |
| 564 | + .map_err(backend)?; | |
| 565 | + Ok(()) | |
| 566 | +} | |
| 567 | + | |
| 568 | +/// True when the key has burned through the panel's per-hour allowance. | |
| 569 | +pub async fn login_blocked(store: &Store, key: &str) -> Result<bool> { | |
| 570 | + sweep_attempts(store, key).await?; | |
| 571 | + let cutoff = store::stamp(store::now() - time::Duration::hours(1))?; | |
| 572 | + let count = { | |
| 573 | + let conn = store.conn.lock().await; | |
| 574 | + let mut rows = conn | |
| 575 | + .query( | |
| 576 | + "SELECT COUNT(*) FROM login_attempts WHERE key = ?1 AND at >= ?2", | |
| 577 | + turso::params![key, cutoff], | |
| 578 | + ) | |
| 579 | + .await | |
| 580 | + .map_err(backend)?; | |
| 581 | + match rows.next().await.map_err(backend)? { | |
| 582 | + Some(row) => store::int(&row, 0)?, | |
| 583 | + None => 0, | |
| 584 | + } | |
| 585 | + }; | |
| 586 | + // The limit reads settings, which locks for itself — the count's guard is | |
| 587 | + // already gone. | |
| 588 | + Ok(count >= crate::settings::login_attempts_per_hour(store).await?) | |
| 589 | +} | |
| 590 | + | |
| 591 | +/// Writes down a failure. Success is the caller's job to record too — by | |
| 592 | +/// clearing, with [`clear_login_failures`]. | |
| 593 | +pub async fn record_login_failure(store: &Store, key: &str) -> Result<()> { | |
| 594 | + sweep_attempts(store, key).await?; | |
| 595 | + let conn = store.conn.lock().await; | |
| 596 | + conn.execute( | |
| 597 | + "INSERT INTO login_attempts (key, at) VALUES (?1, ?2)", | |
| 598 | + turso::params![key, store::stamp(store::now())?], | |
| 599 | + ) | |
| 600 | + .await | |
| 601 | + .map_err(backend)?; | |
| 602 | + Ok(()) | |
| 603 | +} | |
| 604 | + | |
| 605 | +/// A success wipes the slate: the next failure starts from zero. | |
| 606 | +pub async fn clear_login_failures(store: &Store, key: &str) -> Result<()> { | |
| 607 | + let conn = store.conn.lock().await; | |
| 608 | + conn.execute( | |
| 609 | + "DELETE FROM login_attempts WHERE key = ?1", | |
| 610 | + turso::params![key], | |
| 611 | + ) | |
| 612 | + .await | |
| 613 | + .map_err(backend)?; | |
| 614 | + Ok(()) | |
| 615 | +} | |
| 616 | + | |
| 617 | +/// Whether the reset page may stand: the link exists, unspent, unexpired. | |
| 618 | +/// Redemption re-checks in its transaction — this is only the page's | |
| 619 | +/// early answer, so a dead link never shows a working form. | |
| 620 | +pub async fn reset_link_valid(store: &Store, token: &str) -> Result<bool> { | |
| 621 | + let conn = store.conn.lock().await; | |
| 622 | + let mut rows = conn | |
| 623 | + .query( | |
| 624 | + "SELECT expires_at, used_at FROM reset_links WHERE token = ?1", | |
| 625 | + turso::params![hash_token(token)], | |
| 626 | + ) | |
| 627 | + .await | |
| 628 | + .map_err(backend)?; | |
| 629 | + let Some(row) = rows.next().await.map_err(backend)? else { | |
| 630 | + return Ok(false); | |
| 631 | + }; | |
| 632 | + let expires_at = store::parse_stamp(&store::text(&row, 0)?)?; | |
| 633 | + Ok(store::opt_text(&row, 1)?.is_none() && expires_at >= store::now()) | |
| 634 | +} | |
| 635 | + | |
| 436 | 636 | /// Verifies an email+password pair, returning the user on success. Disabled |
| 437 | 637 | /// accounts are refused with the same wording as a wrong password, and every |
| 438 | 638 | /// miss path burns an Argon2 run so timing does not say which one it was. |
| @@ -441,8 +641,8 @@ pub async fn verify_login( | ||
| 441 | 641 | email: &str, |
| 442 | 642 | password: &str, |
| 443 | 643 | ) -> std::result::Result<User, AccountError> { |
| 444 | - let mut rows = store | |
| 445 | - .conn | |
| 644 | + let conn = store.conn.lock().await; | |
| 645 | + let mut rows = conn | |
| 446 | 646 | .query( |
| 447 | 647 | "SELECT id, email, name, password_hash, totp_confirmed, admin, disabled, created_at \ |
| 448 | 648 | FROM users WHERE email = ?1 COLLATE NOCASE", |
| @@ -481,8 +681,8 @@ pub async fn change_password( | ||
| 481 | 681 | current: &str, |
| 482 | 682 | new: &str, |
| 483 | 683 | ) -> std::result::Result<(), AccountError> { |
| 484 | - let mut rows = store | |
| 485 | - .conn | |
| 684 | + let conn = store.conn.lock().await; | |
| 685 | + let mut rows = conn | |
| 486 | 686 | .query( |
| 487 | 687 | "SELECT password_hash FROM users WHERE id = ?1", |
| 488 | 688 | turso::params![user.id.to_string()], |
| @@ -500,37 +700,38 @@ pub async fn change_password( | ||
| 500 | 700 | if verify_password(new, &phc) { |
| 501 | 701 | return Err(PasswordProblem::IsCurrent.into()); |
| 502 | 702 | } |
| 503 | - store | |
| 504 | - .conn | |
| 505 | - .execute( | |
| 506 | - "UPDATE users SET password_hash = ?1 WHERE id = ?2", | |
| 507 | - turso::params![hash_password(new)?, user.id.to_string()], | |
| 508 | - ) | |
| 509 | - .await | |
| 510 | - .map_err(backend)?; | |
| 703 | + conn.execute( | |
| 704 | + "UPDATE users SET password_hash = ?1 WHERE id = ?2", | |
| 705 | + turso::params![hash_password(new)?, user.id.to_string()], | |
| 706 | + ) | |
| 707 | + .await | |
| 708 | + .map_err(backend)?; | |
| 511 | 709 | Ok(()) |
| 512 | 710 | } |
| 513 | 711 | |
| 514 | 712 | /// Looks a user up by email — the CLI's revoke path resolves names this way. |
| 515 | 713 | pub async fn user_by_email(store: &Store, email: &str) -> Result<Option<User>> { |
| 516 | - let mut rows = store | |
| 517 | - .conn | |
| 518 | - .query( | |
| 519 | - "SELECT id FROM users WHERE email = ?1 COLLATE NOCASE", | |
| 520 | - turso::params![email], | |
| 521 | - ) | |
| 522 | - .await | |
| 523 | - .map_err(backend)?; | |
| 524 | - let Some(row) = rows.next().await.map_err(backend)? else { | |
| 525 | - return Ok(None); | |
| 714 | + let id = { | |
| 715 | + let conn = store.conn.lock().await; | |
| 716 | + let mut rows = conn | |
| 717 | + .query( | |
| 718 | + "SELECT id FROM users WHERE email = ?1 COLLATE NOCASE", | |
| 719 | + turso::params![email], | |
| 720 | + ) | |
| 721 | + .await | |
| 722 | + .map_err(backend)?; | |
| 723 | + match rows.next().await.map_err(backend)? { | |
| 724 | + Some(row) => UserId::from(store::text(&row, 0)?), | |
| 725 | + None => return Ok(None), | |
| 726 | + } | |
| 526 | 727 | }; |
| 527 | - let id = UserId::from(store::text(&row, 0)?); | |
| 728 | + // The id is in hand; the full row's lookup locks for itself. | |
| 528 | 729 | user_by_id(store, &id).await |
| 529 | 730 | } |
| 530 | 731 | |
| 531 | 732 | pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> { |
| 532 | - let mut rows = store | |
| 533 | - .conn | |
| 733 | + let conn = store.conn.lock().await; | |
| 734 | + let mut rows = conn | |
| 534 | 735 | .query( |
| 535 | 736 | "SELECT id, email, name, totp_confirmed, admin, disabled, created_at \ |
| 536 | 737 | FROM users WHERE id = ?1", |
| @@ -557,6 +758,7 @@ pub async fn user_by_id(store: &Store, id: &UserId) -> Result<Option<User>> { | ||
| 557 | 758 | /// account should not exist" — the OIDC subject dies with it, and if the |
| 558 | 759 | /// person returns they get a fresh one. |
| 559 | 760 | pub async fn delete_user(store: &Store, user: &UserId) -> Result<()> { |
| 761 | + let conn = store.conn.lock().await; | |
| 560 | 762 | let id = user.to_string(); |
| 561 | 763 | for sql in [ |
| 562 | 764 | "DELETE FROM app_sessions WHERE user_id = ?1", |
| @@ -565,9 +767,7 @@ pub async fn delete_user(store: &Store, user: &UserId) -> Result<()> { | ||
| 565 | 767 | "UPDATE invites SET invited_by = NULL WHERE invited_by = ?1", |
| 566 | 768 | "DELETE FROM users WHERE id = ?1", |
| 567 | 769 | ] { |
| 568 | - store | |
| 569 | - .conn | |
| 570 | - .execute(sql, turso::params![id.clone()]) | |
| 770 | + conn.execute(sql, turso::params![id.clone()]) | |
| 571 | 771 | .await |
| 572 | 772 | .map_err(backend)?; |
| 573 | 773 | } |
| @@ -576,8 +776,8 @@ pub async fn delete_user(store: &Store, user: &UserId) -> Result<()> { | ||
| 576 | 776 | |
| 577 | 777 | /// Every user, oldest first — the admin panel's roster. |
| 578 | 778 | pub async fn list_users(store: &Store) -> Result<Vec<User>> { |
| 579 | - let mut rows = store | |
| 580 | - .conn | |
| 779 | + let conn = store.conn.lock().await; | |
| 780 | + let mut rows = conn | |
| 581 | 781 | .query( |
| 582 | 782 | "SELECT id, email, name, totp_confirmed, admin, disabled, created_at \ |
| 583 | 783 | FROM users ORDER BY created_at", |
| @@ -604,28 +804,26 @@ pub async fn list_users(store: &Store) -> Result<Vec<User>> { | ||
| 604 | 804 | /// sessions resolve to nobody, and introspection says inactive — every door |
| 605 | 805 | /// closes on the same flag. |
| 606 | 806 | pub async fn set_disabled(store: &Store, user: &UserId, disabled: bool) -> Result<()> { |
| 607 | - store | |
| 608 | - .conn | |
| 609 | - .execute( | |
| 610 | - "UPDATE users SET disabled = ?1 WHERE id = ?2", | |
| 611 | - turso::params![disabled as i64, user.to_string()], | |
| 612 | - ) | |
| 613 | - .await | |
| 614 | - .map_err(backend)?; | |
| 807 | + let conn = store.conn.lock().await; | |
| 808 | + conn.execute( | |
| 809 | + "UPDATE users SET disabled = ?1 WHERE id = ?2", | |
| 810 | + turso::params![disabled as i64, user.to_string()], | |
| 811 | + ) | |
| 812 | + .await | |
| 813 | + .map_err(backend)?; | |
| 615 | 814 | Ok(()) |
| 616 | 815 | } |
| 617 | 816 | |
| 618 | 817 | /// Grants or revokes im's admin flag. Never crosses a token — this is im's |
| 619 | 818 | /// own panel, not a claim apps ever see. |
| 620 | 819 | pub async fn set_admin(store: &Store, user: &UserId, admin: bool) -> Result<()> { |
| 621 | - store | |
| 622 | - .conn | |
| 623 | - .execute( | |
| 624 | - "UPDATE users SET admin = ?1 WHERE id = ?2", | |
| 625 | - turso::params![admin as i64, user.to_string()], | |
| 626 | - ) | |
| 627 | - .await | |
| 628 | - .map_err(backend)?; | |
| 820 | + let conn = store.conn.lock().await; | |
| 821 | + conn.execute( | |
| 822 | + "UPDATE users SET admin = ?1 WHERE id = ?2", | |
| 823 | + turso::params![admin as i64, user.to_string()], | |
| 824 | + ) | |
| 825 | + .await | |
| 826 | + .map_err(backend)?; | |
| 629 | 827 | Ok(()) |
| 630 | 828 | } |
| 631 | 829 | |
| @@ -845,4 +1043,91 @@ mod tests { | ||
| 845 | 1043 | .is_ok() |
| 846 | 1044 | ); |
| 847 | 1045 | } |
| 1046 | + | |
| 1047 | + #[tokio::test] | |
| 1048 | + async fn a_second_reset_link_kills_the_first() { | |
| 1049 | + let store = fixture().await; | |
| 1050 | + let invite = create_invite(&store, "ann@example.com", None, false) | |
| 1051 | + .await | |
| 1052 | + .unwrap(); | |
| 1053 | + let user = create_user_from_invite(&store, invite.expose(), "Ann", "tDLr9!mZQ2xv") | |
| 1054 | + .await | |
| 1055 | + .unwrap(); | |
| 1056 | + let session = crate::sessions::create_session(&store, &user.id) | |
| 1057 | + .await | |
| 1058 | + .unwrap(); | |
| 1059 | + | |
| 1060 | + // No account, no link — and nothing learned. | |
| 1061 | + assert!( | |
| 1062 | + create_reset(&store, "nobody@example.com") | |
| 1063 | + .await | |
| 1064 | + .unwrap() | |
| 1065 | + .is_none() | |
| 1066 | + ); | |
| 1067 | + | |
| 1068 | + let first = create_reset(&store, "ann@example.com") | |
| 1069 | + .await | |
| 1070 | + .unwrap() | |
| 1071 | + .unwrap(); | |
| 1072 | + let second = create_reset(&store, "ann@example.com") | |
| 1073 | + .await | |
| 1074 | + .unwrap() | |
| 1075 | + .unwrap(); | |
| 1076 | + // The first mail's link died the moment the second was minted. | |
| 1077 | + assert!(matches!( | |
| 1078 | + redeem_reset(&store, first.expose(), "Xk9#mQ2vLpR7").await, | |
| 1079 | + Err(AccountError::ResetInvalid) | |
| 1080 | + )); | |
| 1081 | + | |
| 1082 | + let changed = redeem_reset(&store, second.expose(), "Xk9#mQ2vLpR7") | |
| 1083 | + .await | |
| 1084 | + .unwrap(); | |
| 1085 | + assert_eq!(changed.id, user.id); | |
| 1086 | + // Spent links cannot be replayed, and the old password's sessions | |
| 1087 | + // died with the change. | |
| 1088 | + assert!(matches!( | |
| 1089 | + redeem_reset(&store, second.expose(), "an0ther!Pass99").await, | |
| 1090 | + Err(AccountError::ResetInvalid) | |
| 1091 | + )); | |
| 1092 | + assert!( | |
| 1093 | + crate::sessions::resolve_session(&store, session.expose()) | |
| 1094 | + .await | |
| 1095 | + .unwrap() | |
| 1096 | + .is_none() | |
| 1097 | + ); | |
| 1098 | + assert!( | |
| 1099 | + verify_login(&store, "ann@example.com", "Xk9#mQ2vLpR7") | |
| 1100 | + .await | |
| 1101 | + .is_ok() | |
| 1102 | + ); | |
| 1103 | + } | |
| 1104 | + | |
| 1105 | + #[tokio::test] | |
| 1106 | + async fn rate_limit_blocks_and_success_clears() { | |
| 1107 | + let store = fixture().await; | |
| 1108 | + crate::settings::set_policy( | |
| 1109 | + &store, | |
| 1110 | + &crate::settings::Policy { | |
| 1111 | + login_attempts_per_hour: 3, | |
| 1112 | + ..Default::default() | |
| 1113 | + }, | |
| 1114 | + ) | |
| 1115 | + .await | |
| 1116 | + .unwrap(); | |
| 1117 | + | |
| 1118 | + assert!(!login_blocked(&store, "ann@example.com").await.unwrap()); | |
| 1119 | + for _ in 0..3 { | |
| 1120 | + record_login_failure(&store, "ann@example.com") | |
| 1121 | + .await | |
| 1122 | + .unwrap(); | |
| 1123 | + } | |
| 1124 | + assert!(login_blocked(&store, "ann@example.com").await.unwrap()); | |
| 1125 | + // A different address is untouched. | |
| 1126 | + assert!(!login_blocked(&store, "bob@example.com").await.unwrap()); | |
| 1127 | + | |
| 1128 | + clear_login_failures(&store, "ann@example.com") | |
| 1129 | + .await | |
| 1130 | + .unwrap(); | |
| 1131 | + assert!(!login_blocked(&store, "ann@example.com").await.unwrap()); | |
| 1132 | + } | |
| 848 | 1133 | } |
crates/im-core/src/events.rsmodified+4 -4
| @@ -17,8 +17,8 @@ pub struct Event { | ||
| 17 | 17 | /// Appends an event. Never fails the caller's operation: a log that cannot |
| 18 | 18 | /// be written is printed, not propagated. |
| 19 | 19 | pub async fn log(store: &Store, kind: &str, actor: Option<&str>, detail: Option<&str>) { |
| 20 | - let outcome = store | |
| 21 | - .conn | |
| 20 | + let conn = store.conn.lock().await; | |
| 21 | + let outcome = conn | |
| 22 | 22 | .execute( |
| 23 | 23 | "INSERT INTO events (id, at, kind, actor, detail) VALUES (?1, ?2, ?3, ?4, ?5)", |
| 24 | 24 | turso::params![ |
| @@ -37,8 +37,8 @@ pub async fn log(store: &Store, kind: &str, actor: Option<&str>, detail: Option< | ||
| 37 | 37 | |
| 38 | 38 | /// Newest-first page of the log for the admin panel. |
| 39 | 39 | pub async fn list(store: &Store, limit: i64) -> Result<Vec<Event>> { |
| 40 | - let mut rows = store | |
| 41 | - .conn | |
| 40 | + let conn = store.conn.lock().await; | |
| 41 | + let mut rows = conn | |
| 42 | 42 | .query( |
| 43 | 43 | "SELECT id, at, kind, actor, detail FROM events ORDER BY at DESC, id DESC LIMIT ?1", |
| 44 | 44 | turso::params![limit], |
crates/im-core/src/keys.rsmodified+17 -19
| @@ -19,8 +19,8 @@ use crate::store::{self, Result, Store, StoreError, backend}; | ||
| 19 | 19 | /// `kid` is a fingerprint of the public half, so a key's id is stable across |
| 20 | 20 | /// restarts and a JWKS consumer can match header to key without guessing. |
| 21 | 21 | pub async fn active_signing_key(store: &Store) -> Result<(String, RsaPrivateKey)> { |
| 22 | - let mut rows = store | |
| 23 | - .conn | |
| 22 | + let conn = store.conn.lock().await; | |
| 23 | + let mut rows = conn | |
| 24 | 24 | .query( |
| 25 | 25 | "SELECT kid, private_der_enc FROM signing_keys WHERE active = 1 \ |
| 26 | 26 | ORDER BY created_at DESC LIMIT 1", |
| @@ -53,20 +53,18 @@ pub async fn active_signing_key(store: &Store) -> Result<(String, RsaPrivateKey) | ||
| 53 | 53 | .as_bytes() |
| 54 | 54 | .to_vec(); |
| 55 | 55 | let kid = kid_of(&public_der); |
| 56 | - store | |
| 57 | - .conn | |
| 58 | - .execute( | |
| 59 | - "INSERT INTO signing_keys (kid, private_der_enc, public_der, created_at) \ | |
| 56 | + conn.execute( | |
| 57 | + "INSERT INTO signing_keys (kid, private_der_enc, public_der, created_at) \ | |
| 60 | 58 | VALUES (?1, ?2, ?3, ?4)", |
| 61 | - turso::params![ | |
| 62 | - kid.clone(), | |
| 63 | - secret::seal(store.key(), &private_der), | |
| 64 | - public_der, | |
| 65 | - store::stamp(store::now())?, | |
| 66 | - ], | |
| 67 | - ) | |
| 68 | - .await | |
| 69 | - .map_err(backend)?; | |
| 59 | + turso::params![ | |
| 60 | + kid.clone(), | |
| 61 | + secret::seal(store.key(), &private_der), | |
| 62 | + public_der, | |
| 63 | + store::stamp(store::now())?, | |
| 64 | + ], | |
| 65 | + ) | |
| 66 | + .await | |
| 67 | + .map_err(backend)?; | |
| 70 | 68 | Ok((kid, key)) |
| 71 | 69 | } |
| 72 | 70 | |
| @@ -77,9 +75,9 @@ fn kid_of(public_der: &[u8]) -> String { | ||
| 77 | 75 | |
| 78 | 76 | /// Every active public key as a JWKS document. |
| 79 | 77 | pub async fn jwks(store: &Store) -> Result<serde_json::Value> { |
| 78 | + let conn = store.conn.lock().await; | |
| 80 | 79 | use base64::Engine; |
| 81 | - let mut rows = store | |
| 82 | - .conn | |
| 80 | + let mut rows = conn | |
| 83 | 81 | .query( |
| 84 | 82 | "SELECT kid, public_der FROM signing_keys WHERE active = 1 ORDER BY created_at", |
| 85 | 83 | (), |
| @@ -107,8 +105,8 @@ pub async fn jwks(store: &Store) -> Result<serde_json::Value> { | ||
| 107 | 105 | |
| 108 | 106 | /// The public half of an active key, by id — what JWT verification looks up. |
| 109 | 107 | pub async fn public_key_by_kid(store: &Store, kid: &str) -> Result<Option<RsaPublicKey>> { |
| 110 | - let mut rows = store | |
| 111 | - .conn | |
| 108 | + let conn = store.conn.lock().await; | |
| 109 | + let mut rows = conn | |
| 112 | 110 | .query( |
| 113 | 111 | "SELECT public_der FROM signing_keys WHERE kid = ?1 AND active = 1", |
| 114 | 112 | turso::params![kid], |
crates/im-core/src/oidc.rsmodified+129 -132
| @@ -61,31 +61,30 @@ pub async fn create_client( | ||
| 61 | 61 | name: &str, |
| 62 | 62 | redirect_uris: Vec<String>, |
| 63 | 63 | ) -> Result<(ClientId, Token)> { |
| 64 | + let conn = store.conn.lock().await; | |
| 64 | 65 | let id = ClientId::mint(); |
| 65 | 66 | let secret = Token::mint(); |
| 66 | - store | |
| 67 | - .conn | |
| 68 | - .execute( | |
| 69 | - "INSERT INTO oidc_clients (client_id, name, secret_hash, redirect_uris, created_at) \ | |
| 67 | + conn.execute( | |
| 68 | + "INSERT INTO oidc_clients (client_id, name, secret_hash, redirect_uris, created_at) \ | |
| 70 | 69 | VALUES (?1, ?2, ?3, ?4, ?5)", |
| 71 | - turso::params![ | |
| 72 | - id.to_string(), | |
| 73 | - name, | |
| 74 | - secret.hash(), | |
| 75 | - serde_json::to_string(&redirect_uris) | |
| 76 | - .map_err(|e| StoreError::Corrupt(format!("redirect_uris: {e}")))?, | |
| 77 | - store::stamp(store::now())?, | |
| 78 | - ], | |
| 79 | - ) | |
| 80 | - .await | |
| 81 | - .map_err(backend)?; | |
| 70 | + turso::params![ | |
| 71 | + id.to_string(), | |
| 72 | + name, | |
| 73 | + secret.hash(), | |
| 74 | + serde_json::to_string(&redirect_uris) | |
| 75 | + .map_err(|e| StoreError::Corrupt(format!("redirect_uris: {e}")))?, | |
| 76 | + store::stamp(store::now())?, | |
| 77 | + ], | |
| 78 | + ) | |
| 79 | + .await | |
| 80 | + .map_err(backend)?; | |
| 82 | 81 | Ok((id, secret)) |
| 83 | 82 | } |
| 84 | 83 | |
| 85 | 84 | /// Looks a client up by its public id. |
| 86 | 85 | pub async fn client_by_id(store: &Store, client_id: &str) -> Result<Option<OidcClient>> { |
| 87 | - let mut rows = store | |
| 88 | - .conn | |
| 86 | + let conn = store.conn.lock().await; | |
| 87 | + let mut rows = conn | |
| 89 | 88 | .query( |
| 90 | 89 | "SELECT client_id, name, secret_hash, redirect_uris, created_at \ |
| 91 | 90 | FROM oidc_clients WHERE client_id = ?1", |
| @@ -131,9 +130,9 @@ pub async fn create_auth_code( | ||
| 131 | 130 | challenge: &str, |
| 132 | 131 | session_hash: &str, |
| 133 | 132 | ) -> Result<Token> { |
| 133 | + let conn = store.conn.lock().await; | |
| 134 | 134 | let code = Token::mint(); |
| 135 | - store | |
| 136 | - .conn | |
| 135 | + conn | |
| 137 | 136 | .execute( |
| 138 | 137 | "INSERT INTO auth_codes \ |
| 139 | 138 | (code_hash, client_id, user_id, redirect_uri, nonce, code_challenge, session_hash, expires_at) \ |
| @@ -158,15 +157,11 @@ pub async fn create_auth_code( | ||
| 158 | 157 | /// `consumed_at` stamp run inside one immediate transaction, so two parallel |
| 159 | 158 | /// exchanges of the same code cannot both succeed. |
| 160 | 159 | pub async fn consume_auth_code(store: &Store, code: &str) -> Result<Option<AuthCode>> { |
| 160 | + let conn = store.conn.lock().await; | |
| 161 | 161 | let hash = hash_token(code); |
| 162 | - store | |
| 163 | - .conn | |
| 164 | - .execute("BEGIN IMMEDIATE", ()) | |
| 165 | - .await | |
| 166 | - .map_err(backend)?; | |
| 162 | + conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?; | |
| 167 | 163 | let outcome = async { |
| 168 | - let mut rows = store | |
| 169 | - .conn | |
| 164 | + let mut rows = conn | |
| 170 | 165 | .query( |
| 171 | 166 | "SELECT client_id, user_id, redirect_uri, nonce, code_challenge, session_hash, \ |
| 172 | 167 | expires_at, consumed_at FROM auth_codes WHERE code_hash = ?1", |
| @@ -183,14 +178,12 @@ pub async fn consume_auth_code(store: &Store, code: &str) -> Result<Option<AuthC | ||
| 183 | 178 | if store::parse_stamp(&store::text(&row, 6)?)? < store::now() { |
| 184 | 179 | return Ok(None); |
| 185 | 180 | } |
| 186 | - store | |
| 187 | - .conn | |
| 188 | - .execute( | |
| 189 | - "UPDATE auth_codes SET consumed_at = ?1 WHERE code_hash = ?2", | |
| 190 | - turso::params![store::stamp(store::now())?, hash], | |
| 191 | - ) | |
| 192 | - .await | |
| 193 | - .map_err(backend)?; | |
| 181 | + conn.execute( | |
| 182 | + "UPDATE auth_codes SET consumed_at = ?1 WHERE code_hash = ?2", | |
| 183 | + turso::params![store::stamp(store::now())?, hash], | |
| 184 | + ) | |
| 185 | + .await | |
| 186 | + .map_err(backend)?; | |
| 194 | 187 | Ok(Some(AuthCode { |
| 195 | 188 | client_id: ClientId::from(store::text(&row, 0)?), |
| 196 | 189 | user_id: UserId::from(store::text(&row, 1)?), |
| @@ -204,11 +197,11 @@ pub async fn consume_auth_code(store: &Store, code: &str) -> Result<Option<AuthC | ||
| 204 | 197 | .await; |
| 205 | 198 | match outcome { |
| 206 | 199 | Ok(found) => { |
| 207 | - store.conn.execute("COMMIT", ()).await.map_err(backend)?; | |
| 200 | + conn.execute("COMMIT", ()).await.map_err(backend)?; | |
| 208 | 201 | Ok(found) |
| 209 | 202 | } |
| 210 | 203 | Err(e) => { |
| 211 | - let _ = store.conn.execute("ROLLBACK", ()).await; | |
| 204 | + let _ = conn.execute("ROLLBACK", ()).await; | |
| 212 | 205 | Err(e) |
| 213 | 206 | } |
| 214 | 207 | } |
| @@ -226,23 +219,22 @@ pub async fn issue_refresh( | ||
| 226 | 219 | client_id: &ClientId, |
| 227 | 220 | session_hash: &str, |
| 228 | 221 | ) -> Result<Token> { |
| 222 | + let conn = store.conn.lock().await; | |
| 229 | 223 | let token = Token::mint(); |
| 230 | - store | |
| 231 | - .conn | |
| 232 | - .execute( | |
| 233 | - "INSERT INTO refresh_tokens \ | |
| 224 | + conn.execute( | |
| 225 | + "INSERT INTO refresh_tokens \ | |
| 234 | 226 | (token_hash, user_id, client_id, session_hash, expires_at) \ |
| 235 | 227 | VALUES (?1, ?2, ?3, ?4, ?5)", |
| 236 | - turso::params![ | |
| 237 | - token.hash(), | |
| 238 | - user.to_string(), | |
| 239 | - client_id.to_string(), | |
| 240 | - session_hash, | |
| 241 | - store::stamp(store::now() + time::Duration::days(REFRESH_DAYS))?, | |
| 242 | - ], | |
| 243 | - ) | |
| 244 | - .await | |
| 245 | - .map_err(backend)?; | |
| 228 | + turso::params![ | |
| 229 | + token.hash(), | |
| 230 | + user.to_string(), | |
| 231 | + client_id.to_string(), | |
| 232 | + session_hash, | |
| 233 | + store::stamp(store::now() + time::Duration::days(REFRESH_DAYS))?, | |
| 234 | + ], | |
| 235 | + ) | |
| 236 | + .await | |
| 237 | + .map_err(backend)?; | |
| 246 | 238 | Ok(token) |
| 247 | 239 | } |
| 248 | 240 | |
| @@ -251,15 +243,11 @@ pub async fn issue_refresh( | ||
| 251 | 243 | /// come back. `None` for unknown, expired, or revoked tokens — and for tokens |
| 252 | 244 | /// whose central session is gone, which is what makes SSO logout global. |
| 253 | 245 | pub async fn rotate_refresh(store: &Store, token: &str) -> Result<Option<(Token, RefreshToken)>> { |
| 246 | + let conn = store.conn.lock().await; | |
| 254 | 247 | let hash = hash_token(token); |
| 255 | - store | |
| 256 | - .conn | |
| 257 | - .execute("BEGIN IMMEDIATE", ()) | |
| 258 | - .await | |
| 259 | - .map_err(backend)?; | |
| 248 | + conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?; | |
| 260 | 249 | let outcome = async { |
| 261 | - let mut rows = store | |
| 262 | - .conn | |
| 250 | + let mut rows = conn | |
| 263 | 251 | .query( |
| 264 | 252 | "SELECT user_id, client_id, session_hash, expires_at, revoked_at \ |
| 265 | 253 | FROM refresh_tokens WHERE token_hash = ?1", |
| @@ -283,8 +271,7 @@ pub async fn rotate_refresh(store: &Store, token: &str) -> Result<Option<(Token, | ||
| 283 | 271 | expires_at: store::parse_stamp(&store::text(&row, 3)?)?, |
| 284 | 272 | }; |
| 285 | 273 | // The session that minted this token must still be alive. |
| 286 | - let mut sessions = store | |
| 287 | - .conn | |
| 274 | + let mut sessions = conn | |
| 288 | 275 | .query( |
| 289 | 276 | "SELECT expires_at, revoked_at FROM sessions WHERE token_hash = ?1", |
| 290 | 277 | turso::params![record.session_hash.clone()], |
| @@ -302,31 +289,39 @@ pub async fn rotate_refresh(store: &Store, token: &str) -> Result<Option<(Token, | ||
| 302 | 289 | } |
| 303 | 290 | |
| 304 | 291 | let now = store::stamp(store::now())?; |
| 305 | - store | |
| 306 | - .conn | |
| 307 | - .execute( | |
| 308 | - "UPDATE refresh_tokens SET revoked_at = ?1 WHERE token_hash = ?2", | |
| 309 | - turso::params![now.clone(), hash.clone()], | |
| 310 | - ) | |
| 311 | - .await | |
| 312 | - .map_err(backend)?; | |
| 313 | - let fresh = issue_refresh( | |
| 314 | - store, | |
| 315 | - &record.user_id, | |
| 316 | - &record.client_id, | |
| 317 | - &record.session_hash, | |
| 292 | + conn.execute( | |
| 293 | + "UPDATE refresh_tokens SET revoked_at = ?1 WHERE token_hash = ?2", | |
| 294 | + turso::params![now.clone(), hash.clone()], | |
| 318 | 295 | ) |
| 319 | - .await?; | |
| 296 | + .await | |
| 297 | + .map_err(backend)?; | |
| 298 | + // Inlined from `issue_refresh`: the transaction already holds the | |
| 299 | + // connection, and the helper locks for itself. | |
| 300 | + let fresh = Token::mint(); | |
| 301 | + conn.execute( | |
| 302 | + "INSERT INTO refresh_tokens \ | |
| 303 | + (token_hash, user_id, client_id, session_hash, expires_at) \ | |
| 304 | + VALUES (?1, ?2, ?3, ?4, ?5)", | |
| 305 | + turso::params![ | |
| 306 | + fresh.hash(), | |
| 307 | + record.user_id.to_string(), | |
| 308 | + record.client_id.to_string(), | |
| 309 | + record.session_hash.clone(), | |
| 310 | + store::stamp(store::now() + time::Duration::days(REFRESH_DAYS))?, | |
| 311 | + ], | |
| 312 | + ) | |
| 313 | + .await | |
| 314 | + .map_err(backend)?; | |
| 320 | 315 | Ok(Some((fresh, record))) |
| 321 | 316 | } |
| 322 | 317 | .await; |
| 323 | 318 | match outcome { |
| 324 | 319 | Ok(found) => { |
| 325 | - store.conn.execute("COMMIT", ()).await.map_err(backend)?; | |
| 320 | + conn.execute("COMMIT", ()).await.map_err(backend)?; | |
| 326 | 321 | Ok(found) |
| 327 | 322 | } |
| 328 | 323 | Err(e) => { |
| 329 | - let _ = store.conn.execute("ROLLBACK", ()).await; | |
| 324 | + let _ = conn.execute("ROLLBACK", ()).await; | |
| 330 | 325 | Err(e) |
| 331 | 326 | } |
| 332 | 327 | } |
| @@ -428,25 +423,24 @@ pub async fn issue_app_session( | ||
| 428 | 423 | client_id: &ClientId, |
| 429 | 424 | session_hash: &str, |
| 430 | 425 | ) -> Result<Token> { |
| 426 | + let conn = store.conn.lock().await; | |
| 431 | 427 | let token = Token::mint(); |
| 432 | 428 | let now = store::now(); |
| 433 | - store | |
| 434 | - .conn | |
| 435 | - .execute( | |
| 436 | - "INSERT INTO app_sessions \ | |
| 429 | + conn.execute( | |
| 430 | + "INSERT INTO app_sessions \ | |
| 437 | 431 | (token_hash, user_id, client_id, session_hash, created_at, expires_at) \ |
| 438 | 432 | VALUES (?1, ?2, ?3, ?4, ?5, ?6)", |
| 439 | - turso::params![ | |
| 440 | - token.hash(), | |
| 441 | - user.to_string(), | |
| 442 | - client_id.to_string(), | |
| 443 | - session_hash, | |
| 444 | - store::stamp(now)?, | |
| 445 | - store::stamp(now + time::Duration::days(APP_SESSION_DAYS))?, | |
| 446 | - ], | |
| 447 | - ) | |
| 448 | - .await | |
| 449 | - .map_err(backend)?; | |
| 433 | + turso::params![ | |
| 434 | + token.hash(), | |
| 435 | + user.to_string(), | |
| 436 | + client_id.to_string(), | |
| 437 | + session_hash, | |
| 438 | + store::stamp(now)?, | |
| 439 | + store::stamp(now + time::Duration::days(APP_SESSION_DAYS))?, | |
| 440 | + ], | |
| 441 | + ) | |
| 442 | + .await | |
| 443 | + .map_err(backend)?; | |
| 450 | 444 | Ok(token) |
| 451 | 445 | } |
| 452 | 446 | |
| @@ -458,49 +452,52 @@ pub async fn introspect_app_session( | ||
| 458 | 452 | token: &str, |
| 459 | 453 | client_id: &str, |
| 460 | 454 | ) -> Result<Option<serde_json::Value>> { |
| 461 | - let mut rows = store | |
| 462 | - .conn | |
| 463 | - .query( | |
| 464 | - "SELECT user_id, client_id, session_hash, expires_at, revoked_at \ | |
| 465 | - FROM app_sessions WHERE token_hash = ?1", | |
| 466 | - turso::params![hash_token(token)], | |
| 467 | - ) | |
| 468 | - .await | |
| 469 | - .map_err(backend)?; | |
| 470 | - let Some(row) = rows.next().await.map_err(backend)? else { | |
| 471 | - return Ok(None); | |
| 472 | - }; | |
| 473 | - if store::opt_text(&row, 4)?.is_some() { | |
| 474 | - return Ok(None); | |
| 475 | - } | |
| 476 | - let expires = store::parse_stamp(&store::text(&row, 3)?)?; | |
| 477 | - if expires < store::now() { | |
| 478 | - return Ok(None); | |
| 479 | - } | |
| 480 | - if store::text(&row, 1)? != client_id { | |
| 481 | - return Ok(None); | |
| 482 | - } | |
| 483 | - // The central session must still be alive — this is what makes admin | |
| 484 | - // revocation immediate. | |
| 485 | - let session_hash = store::text(&row, 2)?; | |
| 486 | - let mut sessions = store | |
| 487 | - .conn | |
| 488 | - .query( | |
| 489 | - "SELECT expires_at, revoked_at FROM sessions WHERE token_hash = ?1", | |
| 490 | - turso::params![session_hash], | |
| 491 | - ) | |
| 492 | - .await | |
| 493 | - .map_err(backend)?; | |
| 494 | - let Some(session) = sessions.next().await.map_err(backend)? else { | |
| 495 | - return Ok(None); | |
| 455 | + // Both rows are read under one short-held guard; the user lookup locks | |
| 456 | + // for itself after it drops. | |
| 457 | + let (user_id, expires) = { | |
| 458 | + let conn = store.conn.lock().await; | |
| 459 | + let mut rows = conn | |
| 460 | + .query( | |
| 461 | + "SELECT user_id, client_id, session_hash, expires_at, revoked_at \ | |
| 462 | + FROM app_sessions WHERE token_hash = ?1", | |
| 463 | + turso::params![hash_token(token)], | |
| 464 | + ) | |
| 465 | + .await | |
| 466 | + .map_err(backend)?; | |
| 467 | + let Some(row) = rows.next().await.map_err(backend)? else { | |
| 468 | + return Ok(None); | |
| 469 | + }; | |
| 470 | + if store::opt_text(&row, 4)?.is_some() { | |
| 471 | + return Ok(None); | |
| 472 | + } | |
| 473 | + let expires = store::parse_stamp(&store::text(&row, 3)?)?; | |
| 474 | + if expires < store::now() { | |
| 475 | + return Ok(None); | |
| 476 | + } | |
| 477 | + if store::text(&row, 1)? != client_id { | |
| 478 | + return Ok(None); | |
| 479 | + } | |
| 480 | + // The central session must still be alive — this is what makes admin | |
| 481 | + // revocation immediate. | |
| 482 | + let session_hash = store::text(&row, 2)?; | |
| 483 | + let mut sessions = conn | |
| 484 | + .query( | |
| 485 | + "SELECT expires_at, revoked_at FROM sessions WHERE token_hash = ?1", | |
| 486 | + turso::params![session_hash], | |
| 487 | + ) | |
| 488 | + .await | |
| 489 | + .map_err(backend)?; | |
| 490 | + let Some(session) = sessions.next().await.map_err(backend)? else { | |
| 491 | + return Ok(None); | |
| 492 | + }; | |
| 493 | + if store::opt_text(&session, 1)?.is_some() { | |
| 494 | + return Ok(None); | |
| 495 | + } | |
| 496 | + if store::parse_stamp(&store::text(&session, 0)?)? < store::now() { | |
| 497 | + return Ok(None); | |
| 498 | + } | |
| 499 | + (UserId::from(store::text(&row, 0)?), expires) | |
| 496 | 500 | }; |
| 497 | - if store::opt_text(&session, 1)?.is_some() { | |
| 498 | - return Ok(None); | |
| 499 | - } | |
| 500 | - if store::parse_stamp(&store::text(&session, 0)?)? < store::now() { | |
| 501 | - return Ok(None); | |
| 502 | - } | |
| 503 | - let user_id = UserId::from(store::text(&row, 0)?); | |
| 504 | 501 | let Some(user) = crate::accounts::user_by_id(store, &user_id).await? else { |
| 505 | 502 | return Ok(None); |
| 506 | 503 | }; |
crates/im-core/src/sessions.rsmodified+116 -111
| @@ -9,7 +9,9 @@ use crate::accounts::{Token, hash_token}; | ||
| 9 | 9 | use crate::model::{User, UserId}; |
| 10 | 10 | use crate::store::{self, Result, Store, backend}; |
| 11 | 11 | |
| 12 | -/// How long a central session lives. | |
| 12 | +/// The default central-session lifetime. The panel's Settings section can | |
| 13 | +/// move it; the constant stays the fresh-database answer and the cookie's | |
| 14 | +/// Max-Age (which is set before the store is in hand). | |
| 13 | 15 | pub const SESSION_DAYS: i64 = 30; |
| 14 | 16 | |
| 15 | 17 | /// Creates a session for `user`, returning the raw cookie token. The row |
| @@ -17,44 +19,50 @@ pub const SESSION_DAYS: i64 = 30; | ||
| 17 | 19 | pub async fn create_session(store: &Store, user: &UserId) -> Result<Token> { |
| 18 | 20 | let token = Token::mint(); |
| 19 | 21 | let now = store::now(); |
| 20 | - store | |
| 21 | - .conn | |
| 22 | - .execute( | |
| 23 | - "INSERT INTO sessions (token_hash, user_id, created_at, expires_at) \ | |
| 22 | + let days = crate::settings::policy(store).await?.session_days; | |
| 23 | + let conn = store.conn.lock().await; | |
| 24 | + conn.execute( | |
| 25 | + "INSERT INTO sessions (token_hash, user_id, created_at, expires_at) \ | |
| 24 | 26 | VALUES (?1, ?2, ?3, ?4)", |
| 25 | - turso::params![ | |
| 26 | - token.hash(), | |
| 27 | - user.to_string(), | |
| 28 | - store::stamp(now)?, | |
| 29 | - store::stamp(now + time::Duration::days(SESSION_DAYS))?, | |
| 30 | - ], | |
| 31 | - ) | |
| 32 | - .await | |
| 33 | - .map_err(backend)?; | |
| 27 | + turso::params![ | |
| 28 | + token.hash(), | |
| 29 | + user.to_string(), | |
| 30 | + store::stamp(now)?, | |
| 31 | + store::stamp(now + time::Duration::days(days))?, | |
| 32 | + ], | |
| 33 | + ) | |
| 34 | + .await | |
| 35 | + .map_err(backend)?; | |
| 34 | 36 | Ok(token) |
| 35 | 37 | } |
| 36 | 38 | |
| 37 | 39 | /// Resolves a raw cookie token to its user. `None` for unknown, expired, |
| 38 | 40 | /// revoked, or disabled — every one of them is "please log in again". |
| 39 | 41 | pub async fn resolve_session(store: &Store, token: &str) -> Result<Option<User>> { |
| 40 | - let mut rows = store | |
| 41 | - .conn | |
| 42 | - .query( | |
| 43 | - "SELECT user_id, expires_at, revoked_at FROM sessions WHERE token_hash = ?1", | |
| 44 | - turso::params![hash_token(token)], | |
| 45 | - ) | |
| 46 | - .await | |
| 47 | - .map_err(backend)?; | |
| 48 | - let Some(row) = rows.next().await.map_err(backend)? else { | |
| 49 | - return Ok(None); | |
| 42 | + // The session row is read under a short-held guard; the user lookup locks | |
| 43 | + // for itself once the guard is dropped. | |
| 44 | + let found = { | |
| 45 | + let conn = store.conn.lock().await; | |
| 46 | + let mut rows = conn | |
| 47 | + .query( | |
| 48 | + "SELECT user_id, expires_at, revoked_at FROM sessions WHERE token_hash = ?1", | |
| 49 | + turso::params![hash_token(token)], | |
| 50 | + ) | |
| 51 | + .await | |
| 52 | + .map_err(backend)?; | |
| 53 | + match rows.next().await.map_err(backend)? { | |
| 54 | + Some(row) | |
| 55 | + if store::opt_text(&row, 2)?.is_none() | |
| 56 | + && store::parse_stamp(&store::text(&row, 1)?)? >= store::now() => | |
| 57 | + { | |
| 58 | + Some(UserId::from(store::text(&row, 0)?)) | |
| 59 | + } | |
| 60 | + _ => None, | |
| 61 | + } | |
| 50 | 62 | }; |
| 51 | - if store::opt_text(&row, 2)?.is_some() { | |
| 52 | - return Ok(None); | |
| 53 | - } | |
| 54 | - if store::parse_stamp(&store::text(&row, 1)?)? < store::now() { | |
| 63 | + let Some(user_id) = found else { | |
| 55 | 64 | return Ok(None); |
| 56 | - } | |
| 57 | - let user_id = UserId::from(store::text(&row, 0)?); | |
| 65 | + }; | |
| 58 | 66 | match crate::accounts::user_by_id(store, &user_id).await? { |
| 59 | 67 | Some(user) if !user.disabled => Ok(Some(user)), |
| 60 | 68 | _ => Ok(None), |
| @@ -71,31 +79,26 @@ pub async fn revoke_session(store: &Store, token: &str) -> Result<()> { | ||
| 71 | 79 | /// The hash-level half of [`revoke_session`], shared with the admin's |
| 72 | 80 | /// revoke-everything below. |
| 73 | 81 | pub(crate) async fn revoke_session_hash(store: &Store, hash: &str) -> Result<()> { |
| 82 | + let conn = store.conn.lock().await; | |
| 74 | 83 | let now = store::stamp(store::now())?; |
| 75 | - store | |
| 76 | - .conn | |
| 77 | - .execute( | |
| 78 | - "UPDATE sessions SET revoked_at = ?1 WHERE token_hash = ?2 AND revoked_at IS NULL", | |
| 79 | - turso::params![now.clone(), hash], | |
| 80 | - ) | |
| 81 | - .await | |
| 82 | - .map_err(backend)?; | |
| 83 | - store | |
| 84 | - .conn | |
| 85 | - .execute( | |
| 86 | - "UPDATE refresh_tokens SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL", | |
| 87 | - turso::params![now.clone(), hash], | |
| 88 | - ) | |
| 89 | - .await | |
| 90 | - .map_err(backend)?; | |
| 91 | - store | |
| 92 | - .conn | |
| 93 | - .execute( | |
| 94 | - "UPDATE app_sessions SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL", | |
| 95 | - turso::params![now, hash], | |
| 96 | - ) | |
| 97 | - .await | |
| 98 | - .map_err(backend)?; | |
| 84 | + conn.execute( | |
| 85 | + "UPDATE sessions SET revoked_at = ?1 WHERE token_hash = ?2 AND revoked_at IS NULL", | |
| 86 | + turso::params![now.clone(), hash], | |
| 87 | + ) | |
| 88 | + .await | |
| 89 | + .map_err(backend)?; | |
| 90 | + conn.execute( | |
| 91 | + "UPDATE refresh_tokens SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL", | |
| 92 | + turso::params![now.clone(), hash], | |
| 93 | + ) | |
| 94 | + .await | |
| 95 | + .map_err(backend)?; | |
| 96 | + conn.execute( | |
| 97 | + "UPDATE app_sessions SET revoked_at = ?1 WHERE session_hash = ?2 AND revoked_at IS NULL", | |
| 98 | + turso::params![now, hash], | |
| 99 | + ) | |
| 100 | + .await | |
| 101 | + .map_err(backend)?; | |
| 99 | 102 | Ok(()) |
| 100 | 103 | } |
| 101 | 104 | |
| @@ -104,18 +107,23 @@ pub(crate) async fn revoke_session_hash(store: &Store, hash: &str) -> Result<()> | ||
| 104 | 107 | /// live app session down with them. Introspection is per-request, so the |
| 105 | 108 | /// next call any app makes on their behalf comes back inactive — no ghost. |
| 106 | 109 | pub async fn revoke_user_sessions(store: &Store, user: &UserId) -> Result<u64> { |
| 107 | - let mut rows = store | |
| 108 | - .conn | |
| 109 | - .query( | |
| 110 | - "SELECT token_hash FROM sessions WHERE user_id = ?1 AND revoked_at IS NULL", | |
| 111 | - turso::params![user.to_string()], | |
| 112 | - ) | |
| 113 | - .await | |
| 114 | - .map_err(backend)?; | |
| 115 | - let mut hashes = Vec::new(); | |
| 116 | - while let Some(row) = rows.next().await.map_err(backend)? { | |
| 117 | - hashes.push(store::text(&row, 0)?); | |
| 118 | - } | |
| 110 | + // Read under a short guard; the per-session revokes and the final sweep | |
| 111 | + // lock for themselves. | |
| 112 | + let hashes = { | |
| 113 | + let conn = store.conn.lock().await; | |
| 114 | + let mut rows = conn | |
| 115 | + .query( | |
| 116 | + "SELECT token_hash FROM sessions WHERE user_id = ?1 AND revoked_at IS NULL", | |
| 117 | + turso::params![user.to_string()], | |
| 118 | + ) | |
| 119 | + .await | |
| 120 | + .map_err(backend)?; | |
| 121 | + let mut hashes = Vec::new(); | |
| 122 | + while let Some(row) = rows.next().await.map_err(backend)? { | |
| 123 | + hashes.push(store::text(&row, 0)?); | |
| 124 | + } | |
| 125 | + hashes | |
| 126 | + }; | |
| 119 | 127 | let count = hashes.len() as u64; |
| 120 | 128 | for hash in hashes { |
| 121 | 129 | revoke_session_hash(store, &hash).await?; |
| @@ -123,22 +131,19 @@ pub async fn revoke_user_sessions(store: &Store, user: &UserId) -> Result<u64> { | ||
| 123 | 131 | // Sessions already revoked earlier still own live app sessions; sweep |
| 124 | 132 | // those too so nothing outlives the person being signed out. |
| 125 | 133 | let now = store::stamp(store::now())?; |
| 126 | - store | |
| 127 | - .conn | |
| 128 | - .execute( | |
| 129 | - "UPDATE app_sessions SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL", | |
| 130 | - turso::params![now.clone(), user.to_string()], | |
| 131 | - ) | |
| 132 | - .await | |
| 133 | - .map_err(backend)?; | |
| 134 | - store | |
| 135 | - .conn | |
| 136 | - .execute( | |
| 137 | - "UPDATE refresh_tokens SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL", | |
| 138 | - turso::params![now, user.to_string()], | |
| 139 | - ) | |
| 140 | - .await | |
| 141 | - .map_err(backend)?; | |
| 134 | + let conn = store.conn.lock().await; | |
| 135 | + conn.execute( | |
| 136 | + "UPDATE app_sessions SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL", | |
| 137 | + turso::params![now.clone(), user.to_string()], | |
| 138 | + ) | |
| 139 | + .await | |
| 140 | + .map_err(backend)?; | |
| 141 | + conn.execute( | |
| 142 | + "UPDATE refresh_tokens SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL", | |
| 143 | + turso::params![now, user.to_string()], | |
| 144 | + ) | |
| 145 | + .await | |
| 146 | + .map_err(backend)?; | |
| 142 | 147 | Ok(count) |
| 143 | 148 | } |
| 144 | 149 | |
| @@ -151,19 +156,22 @@ pub async fn revoke_user_sessions_except( | ||
| 151 | 156 | keep_token: &str, |
| 152 | 157 | ) -> Result<u64> { |
| 153 | 158 | let keep = hash_token(keep_token); |
| 154 | - let mut rows = store | |
| 155 | - .conn | |
| 156 | - .query( | |
| 157 | - "SELECT token_hash FROM sessions \ | |
| 158 | - WHERE user_id = ?1 AND revoked_at IS NULL AND token_hash != ?2", | |
| 159 | - turso::params![user.to_string(), keep.clone()], | |
| 160 | - ) | |
| 161 | - .await | |
| 162 | - .map_err(backend)?; | |
| 163 | - let mut hashes = Vec::new(); | |
| 164 | - while let Some(row) = rows.next().await.map_err(backend)? { | |
| 165 | - hashes.push(store::text(&row, 0)?); | |
| 166 | - } | |
| 159 | + let hashes = { | |
| 160 | + let conn = store.conn.lock().await; | |
| 161 | + let mut rows = conn | |
| 162 | + .query( | |
| 163 | + "SELECT token_hash FROM sessions \ | |
| 164 | + WHERE user_id = ?1 AND revoked_at IS NULL AND token_hash != ?2", | |
| 165 | + turso::params![user.to_string(), keep.clone()], | |
| 166 | + ) | |
| 167 | + .await | |
| 168 | + .map_err(backend)?; | |
| 169 | + let mut hashes = Vec::new(); | |
| 170 | + while let Some(row) = rows.next().await.map_err(backend)? { | |
| 171 | + hashes.push(store::text(&row, 0)?); | |
| 172 | + } | |
| 173 | + hashes | |
| 174 | + }; | |
| 167 | 175 | let count = hashes.len() as u64; |
| 168 | 176 | for hash in &hashes { |
| 169 | 177 | revoke_session_hash(store, hash).await?; |
| @@ -171,24 +179,21 @@ pub async fn revoke_user_sessions_except( | ||
| 171 | 179 | // The kept session is the only one allowed to keep its app sessions and |
| 172 | 180 | // refresh tokens; everything else of this user's is swept. |
| 173 | 181 | let now = store::stamp(store::now())?; |
| 174 | - store | |
| 175 | - .conn | |
| 176 | - .execute( | |
| 177 | - "UPDATE app_sessions SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL \ | |
| 182 | + let conn = store.conn.lock().await; | |
| 183 | + conn.execute( | |
| 184 | + "UPDATE app_sessions SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL \ | |
| 178 | 185 | AND session_hash != ?3", |
| 179 | - turso::params![now.clone(), user.to_string(), keep.clone()], | |
| 180 | - ) | |
| 181 | - .await | |
| 182 | - .map_err(backend)?; | |
| 183 | - store | |
| 184 | - .conn | |
| 185 | - .execute( | |
| 186 | - "UPDATE refresh_tokens SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL \ | |
| 186 | + turso::params![now.clone(), user.to_string(), keep.clone()], | |
| 187 | + ) | |
| 188 | + .await | |
| 189 | + .map_err(backend)?; | |
| 190 | + conn.execute( | |
| 191 | + "UPDATE refresh_tokens SET revoked_at = ?1 WHERE user_id = ?2 AND revoked_at IS NULL \ | |
| 187 | 192 | AND session_hash != ?3", |
| 188 | - turso::params![now, user.to_string(), keep], | |
| 189 | - ) | |
| 190 | - .await | |
| 191 | - .map_err(backend)?; | |
| 193 | + turso::params![now, user.to_string(), keep], | |
| 194 | + ) | |
| 195 | + .await | |
| 196 | + .map_err(backend)?; | |
| 192 | 197 | Ok(count) |
| 193 | 198 | } |
| 194 | 199 |
crates/im-core/src/settings.rsmodified+134 -16
| @@ -38,8 +38,8 @@ impl Smtp { | ||
| 38 | 38 | } |
| 39 | 39 | |
| 40 | 40 | async fn get(store: &Store, key: &str) -> Result<Option<String>> { |
| 41 | - let mut rows = store | |
| 42 | - .conn | |
| 41 | + let conn = store.conn.lock().await; | |
| 42 | + let mut rows = conn | |
| 43 | 43 | .query( |
| 44 | 44 | "SELECT value FROM settings WHERE key = ?1", |
| 45 | 45 | turso::params![key], |
| @@ -53,13 +53,20 @@ async fn get(store: &Store, key: &str) -> Result<Option<String>> { | ||
| 53 | 53 | } |
| 54 | 54 | |
| 55 | 55 | async fn set(store: &Store, key: &str, value: &str) -> Result<()> { |
| 56 | - store | |
| 57 | - .conn | |
| 58 | - .execute( | |
| 59 | - "INSERT INTO settings (key, value) VALUES (?1, ?2) \ | |
| 56 | + let conn = store.conn.lock().await; | |
| 57 | + conn.execute( | |
| 58 | + "INSERT INTO settings (key, value) VALUES (?1, ?2) \ | |
| 60 | 59 | ON CONFLICT(key) DO UPDATE SET value = excluded.value", |
| 61 | - turso::params![key, value], | |
| 62 | - ) | |
| 60 | + turso::params![key, value], | |
| 61 | + ) | |
| 62 | + .await | |
| 63 | + .map_err(backend)?; | |
| 64 | + Ok(()) | |
| 65 | +} | |
| 66 | + | |
| 67 | +async fn remove(store: &Store, key: &str) -> Result<()> { | |
| 68 | + let conn = store.conn.lock().await; | |
| 69 | + conn.execute("DELETE FROM settings WHERE key = ?1", turso::params![key]) | |
| 63 | 70 | .await |
| 64 | 71 | .map_err(backend)?; |
| 65 | 72 | Ok(()) |
| @@ -177,10 +184,9 @@ pub async fn last_check(store: &Store) -> Result<Option<SenderCheck>> { | ||
| 177 | 184 | /// A saved sender cannot borrow the last probe's verdict: the check is |
| 178 | 185 | /// cleared on every settings write, like izlek's. |
| 179 | 186 | async fn clear_check(store: &Store) -> Result<()> { |
| 187 | + let conn = store.conn.lock().await; | |
| 180 | 188 | for key in ["smtp_check_at", "smtp_check_ms", "smtp_check_error"] { |
| 181 | - store | |
| 182 | - .conn | |
| 183 | - .execute("DELETE FROM settings WHERE key = ?1", turso::params![key]) | |
| 189 | + conn.execute("DELETE FROM settings WHERE key = ?1", turso::params![key]) | |
| 184 | 190 | .await |
| 185 | 191 | .map_err(backend)?; |
| 186 | 192 | } |
| @@ -201,11 +207,7 @@ pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Res | ||
| 201 | 207 | "smtp_check_ms", |
| 202 | 208 | "smtp_check_error", |
| 203 | 209 | ] { |
| 204 | - store | |
| 205 | - .conn | |
| 206 | - .execute("DELETE FROM settings WHERE key = ?1", turso::params![key]) | |
| 207 | - .await | |
| 208 | - .map_err(backend)?; | |
| 210 | + remove(store, key).await?; | |
| 209 | 211 | } |
| 210 | 212 | return Ok(()); |
| 211 | 213 | } |
| @@ -229,6 +231,122 @@ pub async fn set_smtp(store: &Store, smtp: &Smtp, password: Option<&str>) -> Res | ||
| 229 | 231 | Ok(()) |
| 230 | 232 | } |
| 231 | 233 | |
| 234 | +/// The panel-tunable policy, with the defaults the code was born with. Every | |
| 235 | +/// reader falls back to the default when the key is absent, so a fresh | |
| 236 | +/// database behaves exactly like the pre-settings build. | |
| 237 | +#[derive(Debug, Clone, PartialEq, Eq)] | |
| 238 | +pub struct Policy { | |
| 239 | + pub invite_days: i64, | |
| 240 | + pub session_days: i64, | |
| 241 | + pub pending_minutes: i64, | |
| 242 | + pub reset_minutes: i64, | |
| 243 | + pub login_attempts_per_hour: i64, | |
| 244 | +} | |
| 245 | + | |
| 246 | +impl Default for Policy { | |
| 247 | + fn default() -> Self { | |
| 248 | + Self { | |
| 249 | + invite_days: 7, | |
| 250 | + session_days: 30, | |
| 251 | + pending_minutes: 10, | |
| 252 | + reset_minutes: 60, | |
| 253 | + login_attempts_per_hour: 10, | |
| 254 | + } | |
| 255 | + } | |
| 256 | +} | |
| 257 | + | |
| 258 | +async fn number(store: &Store, key: &str, default: i64) -> Result<i64> { | |
| 259 | + Ok(get(store, key) | |
| 260 | + .await? | |
| 261 | + .and_then(|raw| raw.parse().ok()) | |
| 262 | + .unwrap_or(default)) | |
| 263 | +} | |
| 264 | + | |
| 265 | +/// The policy as stored, defaults filled in. | |
| 266 | +pub async fn policy(store: &Store) -> Result<Policy> { | |
| 267 | + let defaults = Policy::default(); | |
| 268 | + Ok(Policy { | |
| 269 | + invite_days: number(store, "invite_days", defaults.invite_days).await?, | |
| 270 | + session_days: number(store, "session_days", defaults.session_days).await?, | |
| 271 | + pending_minutes: number(store, "pending_minutes", defaults.pending_minutes).await?, | |
| 272 | + reset_minutes: number(store, "reset_minutes", defaults.reset_minutes).await?, | |
| 273 | + login_attempts_per_hour: number( | |
| 274 | + store, | |
| 275 | + "login_attempts_per_hour", | |
| 276 | + defaults.login_attempts_per_hour, | |
| 277 | + ) | |
| 278 | + .await?, | |
| 279 | + }) | |
| 280 | +} | |
| 281 | + | |
| 282 | +/// Writes the policy. Values under one are refused by the panel before they | |
| 283 | +/// get here; zero or negative would be a door that never opens, so they are | |
| 284 | +/// clamped to the default rather than stored. | |
| 285 | +pub async fn set_policy(store: &Store, policy: &Policy) -> Result<()> { | |
| 286 | + let defaults = Policy::default(); | |
| 287 | + let clamp = |value: i64, default: i64| if value >= 1 { value } else { default }; | |
| 288 | + set( | |
| 289 | + store, | |
| 290 | + "invite_days", | |
| 291 | + &clamp(policy.invite_days, defaults.invite_days).to_string(), | |
| 292 | + ) | |
| 293 | + .await?; | |
| 294 | + set( | |
| 295 | + store, | |
| 296 | + "session_days", | |
| 297 | + &clamp(policy.session_days, defaults.session_days).to_string(), | |
| 298 | + ) | |
| 299 | + .await?; | |
| 300 | + set( | |
| 301 | + store, | |
| 302 | + "pending_minutes", | |
| 303 | + &clamp(policy.pending_minutes, defaults.pending_minutes).to_string(), | |
| 304 | + ) | |
| 305 | + .await?; | |
| 306 | + set( | |
| 307 | + store, | |
| 308 | + "reset_minutes", | |
| 309 | + &clamp(policy.reset_minutes, defaults.reset_minutes).to_string(), | |
| 310 | + ) | |
| 311 | + .await?; | |
| 312 | + set( | |
| 313 | + store, | |
| 314 | + "login_attempts_per_hour", | |
| 315 | + &clamp( | |
| 316 | + policy.login_attempts_per_hour, | |
| 317 | + defaults.login_attempts_per_hour, | |
| 318 | + ) | |
| 319 | + .to_string(), | |
| 320 | + ) | |
| 321 | + .await?; | |
| 322 | + Ok(()) | |
| 323 | +} | |
| 324 | + | |
| 325 | +/// Days an invite link stays valid. | |
| 326 | +pub async fn invite_days(store: &Store) -> Result<i64> { | |
| 327 | + number(store, "invite_days", Policy::default().invite_days).await | |
| 328 | +} | |
| 329 | + | |
| 330 | +/// Minutes between password and second factor before the pending marker dies. | |
| 331 | +pub async fn pending_minutes(store: &Store) -> Result<i64> { | |
| 332 | + number(store, "pending_minutes", Policy::default().pending_minutes).await | |
| 333 | +} | |
| 334 | + | |
| 335 | +/// Minutes a password-reset link stays valid. | |
| 336 | +pub async fn reset_minutes(store: &Store) -> Result<i64> { | |
| 337 | + number(store, "reset_minutes", Policy::default().reset_minutes).await | |
| 338 | +} | |
| 339 | + | |
| 340 | +/// Failed sign-ins per address per hour before the door refuses to listen. | |
| 341 | +pub async fn login_attempts_per_hour(store: &Store) -> Result<i64> { | |
| 342 | + number( | |
| 343 | + store, | |
| 344 | + "login_attempts_per_hour", | |
| 345 | + Policy::default().login_attempts_per_hour, | |
| 346 | + ) | |
| 347 | + .await | |
| 348 | +} | |
| 349 | + | |
| 232 | 350 | #[cfg(test)] |
| 233 | 351 | mod tests { |
| 234 | 352 | use super::*; |
crates/im-core/src/store.rsmodified+25 -11
| @@ -104,6 +104,18 @@ CREATE TABLE IF NOT EXISTS events ( | ||
| 104 | 104 | actor TEXT, |
| 105 | 105 | detail TEXT |
| 106 | 106 | ); |
| 107 | +CREATE TABLE IF NOT EXISTS reset_links ( | |
| 108 | + token TEXT PRIMARY KEY, | |
| 109 | + user_id TEXT NOT NULL REFERENCES users(id), | |
| 110 | + created_at TEXT NOT NULL, | |
| 111 | + expires_at TEXT NOT NULL, | |
| 112 | + used_at TEXT | |
| 113 | +); | |
| 114 | +CREATE TABLE IF NOT EXISTS login_attempts ( | |
| 115 | + key TEXT NOT NULL, | |
| 116 | + at TEXT NOT NULL | |
| 117 | +); | |
| 118 | +CREATE INDEX IF NOT EXISTS login_attempts_key ON login_attempts(key, at); | |
| 107 | 119 | CREATE TABLE IF NOT EXISTS settings ( |
| 108 | 120 | key TEXT PRIMARY KEY, |
| 109 | 121 | value TEXT NOT NULL |
| @@ -113,7 +125,7 @@ CREATE TABLE IF NOT EXISTS settings ( | ||
| 113 | 125 | /// One database handle with the at-rest key beside it. Turso is a |
| 114 | 126 | /// single-writer engine; one connection per store, like izlek-core. |
| 115 | 127 | pub struct Store { |
| 116 | - pub(crate) conn: Connection, | |
| 128 | + pub(crate) conn: tokio::sync::Mutex<Connection>, | |
| 117 | 129 | pub(crate) key: Key, |
| 118 | 130 | } |
| 119 | 131 | |
| @@ -127,7 +139,7 @@ impl Store { | ||
| 127 | 139 | let db = Builder::new_local(raw).build().await.map_err(backend)?; |
| 128 | 140 | let conn = db.connect().map_err(backend)?; |
| 129 | 141 | let store = Store { |
| 130 | - conn, | |
| 142 | + conn: tokio::sync::Mutex::new(conn), | |
| 131 | 143 | key: load_key(path)?, |
| 132 | 144 | }; |
| 133 | 145 | store.migrate().await?; |
| @@ -136,15 +148,15 @@ impl Store { | ||
| 136 | 148 | |
| 137 | 149 | /// Applies the schema inside one immediate transaction; safe to re-run. |
| 138 | 150 | pub async fn migrate(&self) -> Result<()> { |
| 139 | - self.conn | |
| 140 | - .execute("BEGIN IMMEDIATE", ()) | |
| 141 | - .await | |
| 142 | - .map_err(backend)?; | |
| 143 | - if let Err(e) = self.conn.execute_batch(SCHEMA).await { | |
| 144 | - let _ = self.conn.execute("ROLLBACK", ()).await; | |
| 151 | + // One guard for the whole transaction — nothing interleaves with a | |
| 152 | + // schema write. | |
| 153 | + let conn = self.conn.lock().await; | |
| 154 | + conn.execute("BEGIN IMMEDIATE", ()).await.map_err(backend)?; | |
| 155 | + if let Err(e) = conn.execute_batch(SCHEMA).await { | |
| 156 | + let _ = conn.execute("ROLLBACK", ()).await; | |
| 145 | 157 | return Err(backend(e)); |
| 146 | 158 | } |
| 147 | - self.conn.execute("COMMIT", ()).await.map_err(backend)?; | |
| 159 | + conn.execute("COMMIT", ()).await.map_err(backend)?; | |
| 148 | 160 | Ok(()) |
| 149 | 161 | } |
| 150 | 162 | |
| @@ -217,8 +229,8 @@ mod tests { | ||
| 217 | 229 | let store = Store::open(&path).await.unwrap(); |
| 218 | 230 | store.migrate().await.unwrap(); |
| 219 | 231 | store.migrate().await.unwrap(); |
| 220 | - let mut rows = store | |
| 221 | - .conn | |
| 232 | + let conn = store.conn.lock().await; | |
| 233 | + let mut rows = conn | |
| 222 | 234 | .query("SELECT name FROM sqlite_master WHERE type = 'table'", ()) |
| 223 | 235 | .await |
| 224 | 236 | .unwrap(); |
| @@ -234,6 +246,8 @@ mod tests { | ||
| 234 | 246 | "auth_codes", |
| 235 | 247 | "refresh_tokens", |
| 236 | 248 | "signing_keys", |
| 249 | + "reset_links", | |
| 250 | + "login_attempts", | |
| 237 | 251 | ] { |
| 238 | 252 | assert!(tables.contains(&expected.to_string()), "missing {expected}"); |
| 239 | 253 | } |
crates/im-core/src/totp.rsmodified+16 -18
| @@ -84,28 +84,26 @@ pub fn verify_totp(secret: &[u8; 20], code: &str, at: OffsetDateTime) -> bool { | ||
| 84 | 84 | /// Stores a freshly generated secret, sealed, unconfirmed until the user |
| 85 | 85 | /// proves their app agrees (`confirm_totp`). |
| 86 | 86 | pub async fn set_totp(store: &Store, user: &UserId, secret_bytes: &[u8; 20]) -> Result<()> { |
| 87 | + let conn = store.conn.lock().await; | |
| 87 | 88 | let sealed = secret::seal(store.key(), secret_bytes); |
| 88 | - store | |
| 89 | - .conn | |
| 90 | - .execute( | |
| 91 | - "UPDATE users SET totp_secret = ?1, totp_confirmed = 0 WHERE id = ?2", | |
| 92 | - turso::params![sealed, user.to_string()], | |
| 93 | - ) | |
| 94 | - .await | |
| 95 | - .map_err(backend)?; | |
| 89 | + conn.execute( | |
| 90 | + "UPDATE users SET totp_secret = ?1, totp_confirmed = 0 WHERE id = ?2", | |
| 91 | + turso::params![sealed, user.to_string()], | |
| 92 | + ) | |
| 93 | + .await | |
| 94 | + .map_err(backend)?; | |
| 96 | 95 | Ok(()) |
| 97 | 96 | } |
| 98 | 97 | |
| 99 | 98 | /// Marks the stored secret confirmed — called after one successful code. |
| 100 | 99 | pub async fn confirm_totp(store: &Store, user: &UserId) -> Result<()> { |
| 101 | - store | |
| 102 | - .conn | |
| 103 | - .execute( | |
| 104 | - "UPDATE users SET totp_confirmed = 1 WHERE id = ?1", | |
| 105 | - turso::params![user.to_string()], | |
| 106 | - ) | |
| 107 | - .await | |
| 108 | - .map_err(backend)?; | |
| 100 | + let conn = store.conn.lock().await; | |
| 101 | + conn.execute( | |
| 102 | + "UPDATE users SET totp_confirmed = 1 WHERE id = ?1", | |
| 103 | + turso::params![user.to_string()], | |
| 104 | + ) | |
| 105 | + .await | |
| 106 | + .map_err(backend)?; | |
| 109 | 107 | Ok(()) |
| 110 | 108 | } |
| 111 | 109 | |
| @@ -113,8 +111,8 @@ pub async fn confirm_totp(store: &Store, user: &UserId) -> Result<()> { | ||
| 113 | 111 | /// TOTP was never set up. A sealed value that no longer opens (wrong key, |
| 114 | 112 | /// damaged ciphertext) reads as `None` — the user re-enrolls. |
| 115 | 113 | pub async fn totp_secret(store: &Store, user: &UserId) -> Result<Option<([u8; 20], bool)>> { |
| 116 | - let mut rows = store | |
| 117 | - .conn | |
| 114 | + let conn = store.conn.lock().await; | |
| 115 | + let mut rows = conn | |
| 118 | 116 | .query( |
| 119 | 117 | "SELECT totp_secret, totp_confirmed FROM users WHERE id = ?1", |
| 120 | 118 | turso::params![user.to_string()], |
crates/im-web/assets/main.cssmodified+4 -0
| @@ -548,9 +548,13 @@ body:has(.admin-shell) { | ||
| 548 | 548 | |
| 549 | 549 | .admin-confirm { |
| 550 | 550 | position: relative; |
| 551 | + display: inline-flex; | |
| 551 | 552 | } |
| 552 | 553 | .admin-confirm summary { |
| 553 | 554 | list-style: none; |
| 555 | + display: inline-flex; | |
| 556 | + align-items: center; | |
| 557 | + box-sizing: border-box; | |
| 554 | 558 | } |
| 555 | 559 | .admin-confirm summary::-webkit-details-marker { |
| 556 | 560 | display: none; |
crates/im-web/src/admin.rsmodified+65 -0
| @@ -135,6 +135,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> { | ||
| 135 | 135 | ("account", "Account"), |
| 136 | 136 | ("users", "Users"), |
| 137 | 137 | ("mail", "Mail"), |
| 138 | + ("settings", "Settings"), | |
| 138 | 139 | ("logs", "Logs"), |
| 139 | 140 | ] |
| 140 | 141 | .into_iter() |
| @@ -149,6 +150,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> { | ||
| 149 | 150 | |
| 150 | 151 | let section_html = match section.as_str() { |
| 151 | 152 | "mail" => mail_section(cx).await?, |
| 153 | + "settings" => settings_section(cx).await?, | |
| 152 | 154 | "logs" => logs_section(cx).await?, |
| 153 | 155 | "users" => users_section(cx, &me, invited.as_deref()).await?, |
| 154 | 156 | _ => account_section(&me), |
| @@ -167,6 +169,7 @@ async fn admin_page(cx: &Cx) -> Result<Response> { | ||
| 167 | 169 | "password" => "Password changed — every other device is signed out.", |
| 168 | 170 | "uninvited" => "Invite invalidated — the link is dead.", |
| 169 | 171 | "deleted" => "Account deleted.", |
| 172 | + "settings" => "Settings saved.", | |
| 170 | 173 | _ => "Done.", |
| 171 | 174 | } |
| 172 | 175 | )), |
| @@ -344,6 +347,68 @@ async fn users_section( | ||
| 344 | 347 | )) |
| 345 | 348 | } |
| 346 | 349 | |
| 350 | +/// The knobs the code shipped with, now the panel's: invite and reset link | |
| 351 | +/// lifetimes, the sign-in session's days, the pending marker's minutes, and | |
| 352 | +/// the sign-in failure ceiling. Same form skin as Mail. | |
| 353 | +async fn settings_section(cx: &Cx) -> Result<String, topcoat::Error> { | |
| 354 | + let policy = settings::policy(&app(cx).store).await?; | |
| 355 | + Ok(format!( | |
| 356 | + r#"<div class="admin-card"> | |
| 357 | + <div class="auth-title">Settings</div> | |
| 358 | + <div class="auth-sub">The rules identity lives by. They apply from the next invite, sign-in or link — nothing already minted is rewritten.</div> | |
| 359 | + <form method="post" action="/admin/settings" class="admin-form"> | |
| 360 | + <label class="auth-field"><span class="auth-label">Invite link, days</span> | |
| 361 | + <input class="auth-input auth-input-mono" type="number" name="invite_days" min="1" value="{}"></label> | |
| 362 | + <label class="auth-field"><span class="auth-label">Sign-in session, days</span> | |
| 363 | + <input class="auth-input auth-input-mono" type="number" name="session_days" min="1" value="{}"></label> | |
| 364 | + <label class="auth-field"><span class="auth-label">Second-factor window, minutes</span> | |
| 365 | + <input class="auth-input auth-input-mono" type="number" name="pending_minutes" min="1" value="{}"></label> | |
| 366 | + <label class="auth-field"><span class="auth-label">Reset link, minutes</span> | |
| 367 | + <input class="auth-input auth-input-mono" type="number" name="reset_minutes" min="1" value="{}"></label> | |
| 368 | + <label class="auth-field"><span class="auth-label">Failed sign-ins per address per hour</span> | |
| 369 | + <input class="auth-input auth-input-mono" type="number" name="login_attempts_per_hour" min="1" value="{}"></label> | |
| 370 | + <button class="auth-submit admin-action-wide" type="submit"><span class="auth-submit-text">Save</span></button> | |
| 371 | + </form> | |
| 372 | +</div>"#, | |
| 373 | + policy.invite_days, | |
| 374 | + policy.session_days, | |
| 375 | + policy.pending_minutes, | |
| 376 | + policy.reset_minutes, | |
| 377 | + policy.login_attempts_per_hour, | |
| 378 | + )) | |
| 379 | +} | |
| 380 | + | |
| 381 | +#[derive(Deserialize)] | |
| 382 | +struct PolicyForm { | |
| 383 | + invite_days: i64, | |
| 384 | + session_days: i64, | |
| 385 | + pending_minutes: i64, | |
| 386 | + reset_minutes: i64, | |
| 387 | + login_attempts_per_hour: i64, | |
| 388 | +} | |
| 389 | + | |
| 390 | +#[route(POST "/admin/settings")] | |
| 391 | +async fn settings_save(cx: &Cx, Form(input): Form<PolicyForm>) -> Result<Response> { | |
| 392 | + let me = match require_admin(cx).await { | |
| 393 | + Ok(me) => me, | |
| 394 | + Err(redirect) => return Ok(redirect), | |
| 395 | + }; | |
| 396 | + let store = &app(cx).store; | |
| 397 | + settings::set_policy( | |
| 398 | + store, | |
| 399 | + &settings::Policy { | |
| 400 | + invite_days: input.invite_days, | |
| 401 | + session_days: input.session_days, | |
| 402 | + pending_minutes: input.pending_minutes, | |
| 403 | + reset_minutes: input.reset_minutes, | |
| 404 | + login_attempts_per_hour: input.login_attempts_per_hour, | |
| 405 | + }, | |
| 406 | + ) | |
| 407 | + .await?; | |
| 408 | + server::log_event(cx, "settings_updated", Some(&me.email), None).await; | |
| 409 | + back(cx, "settings", "&ok=settings") | |
| 410 | +} | |
| 411 | + | |
| 347 | 412 | async fn mail_section(cx: &Cx) -> Result<String, topcoat::Error> { |
| 348 | 413 | let store = &app(cx).store; |
| 349 | 414 | let smtp = settings::smtp(store).await?; |
crates/im-web/src/auth.rsmodified+87 -6
| @@ -55,10 +55,21 @@ pub struct LoginForm { | ||
| 55 | 55 | async fn login(cx: &Cx, Form(input): Form<LoginForm>) -> Redirect { |
| 56 | 56 | let back = safe_back(input.back.as_deref().unwrap_or("/")).to_string(); |
| 57 | 57 | let store = &server::app(cx).store; |
| 58 | + // The door stops listening after the panel's per-hour allowance of | |
| 59 | + // failures. The refusal says nothing about which step refused, as always. | |
| 60 | + let key = input.email.trim().to_lowercase(); | |
| 61 | + if accounts::login_blocked(store, &key).await? { | |
| 62 | + server::log_event(cx, "login_limited", Some(&key), None).await; | |
| 63 | + return see(format!( | |
| 64 | + "/login?error=rate_limited&back={}", | |
| 65 | + urlencode(&back) | |
| 66 | + )); | |
| 67 | + } | |
| 58 | 68 | match accounts::verify_login(store, &input.email, &input.password).await { |
| 59 | 69 | Ok(user) if user.totp_confirmed => { |
| 60 | - let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Login, back); | |
| 61 | - server::set_pending_cookie(cx, sealed); | |
| 70 | + let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Login, back).await; | |
| 71 | + server::set_pending_cookie(cx, sealed).await; | |
| 72 | + let _ = accounts::clear_login_failures(store, &key).await; | |
| 62 | 73 | see("/login/totp".to_string()) |
| 63 | 74 | } |
| 64 | 75 | Ok(user) => { |
| @@ -69,13 +80,15 @@ async fn login(cx: &Cx, Form(input): Form<LoginForm>) -> Redirect { | ||
| 69 | 80 | let secret = im_core::totp::generate_secret(); |
| 70 | 81 | im_core::totp::set_totp(store, &user.id, &secret).await?; |
| 71 | 82 | } |
| 72 | - let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, back); | |
| 73 | - server::set_pending_cookie(cx, sealed); | |
| 83 | + let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, back).await; | |
| 84 | + server::set_pending_cookie(cx, sealed).await; | |
| 85 | + let _ = accounts::clear_login_failures(store, &key).await; | |
| 74 | 86 | see("/enroll".to_string()) |
| 75 | 87 | } |
| 76 | 88 | Err(_) => { |
| 77 | 89 | // The failure is logged against the address tried, never the |
| 78 | 90 | // password — and never whether the address exists. |
| 91 | + let _ = accounts::record_login_failure(store, &key).await; | |
| 79 | 92 | server::log_event(cx, "login_fail", Some(&input.email), None).await; |
| 80 | 93 | see(format!("/login?error=bad_login&back={}", urlencode(&back))) |
| 81 | 94 | } |
| @@ -111,10 +124,20 @@ async fn login_totp(cx: &Cx, Form(input): Form<TotpForm>) -> Redirect { | ||
| 111 | 124 | }, |
| 112 | 125 | None => false, |
| 113 | 126 | }; |
| 127 | + // The second factor gets the same ceiling as the first, keyed on the | |
| 128 | + // account, so an attacker past the password cannot grind codes either. | |
| 129 | + let totp_key = format!("totp:{}", pending.user); | |
| 130 | + if accounts::login_blocked(store, &totp_key).await? { | |
| 131 | + server::log_event(cx, "login_limited", None, Some("2fa")).await; | |
| 132 | + server::clear_pending_cookie(cx); | |
| 133 | + return see("/login?error=rate_limited".to_string()); | |
| 134 | + } | |
| 114 | 135 | if !ok { |
| 136 | + let _ = accounts::record_login_failure(store, &totp_key).await; | |
| 115 | 137 | server::log_event(cx, "totp_fail", None, Some("login")).await; |
| 116 | 138 | return see("/login/totp?error=bad_code".to_string()); |
| 117 | 139 | } |
| 140 | + let _ = accounts::clear_login_failures(store, &totp_key).await; | |
| 118 | 141 | let token = im_core::sessions::create_session(store, &user_id).await?; |
| 119 | 142 | let email = accounts::user_by_id(store, &user_id) |
| 120 | 143 | .await? |
| @@ -173,8 +196,8 @@ async fn invite(cx: &Cx, Form(input): Form<InviteForm>) -> Redirect { | ||
| 173 | 196 | // enrolment page is the only way forward. |
| 174 | 197 | let secret = im_core::totp::generate_secret(); |
| 175 | 198 | im_core::totp::set_totp(store, &user.id, &secret).await?; |
| 176 | - let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, "/".to_string()); | |
| 177 | - server::set_pending_cookie(cx, sealed); | |
| 199 | + let sealed = server::mint_pending(cx, &user.id, PendingPurpose::Enroll, "/".to_string()).await; | |
| 200 | + server::set_pending_cookie(cx, sealed).await; | |
| 178 | 201 | server::log_event(cx, "invite_accepted", Some(&user.email), None).await; |
| 179 | 202 | see("/enroll".to_string()) |
| 180 | 203 | } |
| @@ -226,3 +249,61 @@ async fn logout(cx: &Cx) -> Redirect { | ||
| 226 | 249 | server::clear_session_cookie(cx); |
| 227 | 250 | see("/".to_string()) |
| 228 | 251 | } |
| 252 | + | |
| 253 | +#[derive(Deserialize)] | |
| 254 | +pub struct ForgotForm { | |
| 255 | + email: String, | |
| 256 | +} | |
| 257 | + | |
| 258 | +/// The self-serve reset ask. It answers every address the same — the mail | |
| 259 | +/// either exists or it doesn't, and the page never says which. Each ask | |
| 260 | +/// retires the address's previous live link: the newest mail is the only | |
| 261 | +/// door. | |
| 262 | +#[route(POST "/forgot")] | |
| 263 | +async fn forgot(cx: &Cx, Form(input): Form<ForgotForm>) -> Redirect { | |
| 264 | + let store = &server::app(cx).store; | |
| 265 | + let email = input.email.trim().to_string(); | |
| 266 | + if let Some(token) = accounts::create_reset(store, &email).await? { | |
| 267 | + let issuer = server::app(cx).config.issuer.clone(); | |
| 268 | + if crate::mailer::send_reset(store, &issuer, &email, token.expose()) | |
| 269 | + .await | |
| 270 | + .is_ok() | |
| 271 | + { | |
| 272 | + server::log_event(cx, "reset_sent", Some(&email), None).await; | |
| 273 | + } | |
| 274 | + } | |
| 275 | + see("/forgot?ok=sent".to_string()) | |
| 276 | +} | |
| 277 | + | |
| 278 | +#[derive(Deserialize)] | |
| 279 | +pub struct ResetForm { | |
| 280 | + token: String, | |
| 281 | + password: String, | |
| 282 | + password_confirm: String, | |
| 283 | +} | |
| 284 | + | |
| 285 | +/// Redeems a reset link: new password in, every session out. A dead link is | |
| 286 | +/// sent back to the ask — the form it came from is gone with it. | |
| 287 | +#[route(POST "/reset")] | |
| 288 | +async fn reset(cx: &Cx, Form(input): Form<ResetForm>) -> Redirect { | |
| 289 | + if input.password != input.password_confirm { | |
| 290 | + return see(format!("/reset/{}?error=passwords_differ", input.token)); | |
| 291 | + } | |
| 292 | + let store = &server::app(cx).store; | |
| 293 | + match accounts::redeem_reset(store, &input.token, &input.password).await { | |
| 294 | + Ok(user) => { | |
| 295 | + server::log_event(cx, "password_reset", Some(&user.email), None).await; | |
| 296 | + see("/login?ok=reset".to_string()) | |
| 297 | + } | |
| 298 | + Err(AccountError::Password(problem)) => { | |
| 299 | + let code = match problem { | |
| 300 | + im_core::accounts::PasswordProblem::TooShort => "password_too_short", | |
| 301 | + im_core::accounts::PasswordProblem::LooksLikeYou => "password_personal", | |
| 302 | + _ => "passwords_differ", | |
| 303 | + }; | |
| 304 | + see(format!("/reset/{}?error={code}", input.token)) | |
| 305 | + } | |
| 306 | + Err(AccountError::ResetInvalid) => see("/forgot?error=reset_invalid".to_string()), | |
| 307 | + Err(e) => Err(topcoat::Error::from(std::io::Error::other(e.to_string()))), | |
| 308 | + } | |
| 309 | +} |
crates/im-web/src/mailer.rsmodified+17 -0
| @@ -87,6 +87,23 @@ pub async fn send_invite(store: &Store, issuer: &str, email: &str, token: &str) | ||
| 87 | 87 | Ok(link) |
| 88 | 88 | } |
| 89 | 89 | |
| 90 | +/// The reset mail: the link is the whole payload, and sending it retires | |
| 91 | +/// every previous link for the address (see `accounts::create_reset`). | |
| 92 | +pub async fn send_reset(store: &Store, issuer: &str, email: &str, token: &str) -> Result<String> { | |
| 93 | + let link = format!("{issuer}/reset/{token}"); | |
| 94 | + let minutes = settings::reset_minutes(store).await?; | |
| 95 | + send( | |
| 96 | + store, | |
| 97 | + email, | |
| 98 | + "Reset your password", | |
| 99 | + format!( | |
| 100 | + "A password reset was asked for this address. The link is yours for {minutes} minutes:\n\n{link}\n\nIf that wasn't you, this mail changes nothing.\n" | |
| 101 | + ), | |
| 102 | + ) | |
| 103 | + .await?; | |
| 104 | + Ok(link) | |
| 105 | +} | |
| 106 | + | |
| 90 | 107 | /// Dials the mail server without sending anything: connect, TLS, hello, |
| 91 | 108 | /// authenticate, NOOP, hang up. A pass proves the host, the port, the |
| 92 | 109 | /// encryption and the password; it says nothing about whether the |
crates/im-web/src/oidc.rsmodified+2 -1
| @@ -302,7 +302,8 @@ async fn exchange(cx: &Cx, Form(input): Form<TokenForm>) -> Result<Response> { | ||
| 302 | 302 | &consumed.session_hash, |
| 303 | 303 | ) |
| 304 | 304 | .await?; |
| 305 | - server::log_event(cx, | |
| 305 | + server::log_event( | |
| 306 | + cx, | |
| 306 | 307 | "code_exchanged", |
| 307 | 308 | Some(&user.email), |
| 308 | 309 | Some(&format!("via {}", client.name)), |
crates/im-web/src/pages.rsmodified+123 -0
| @@ -33,10 +33,20 @@ pub fn error_text(code: &str) -> &'static str { | ||
| 33 | 33 | "smtp_test" => "The test mail could not be sent.", |
| 34 | 34 | "password_wrong" => "That's not your current password.", |
| 35 | 35 | "password_same" => "That's already your password.", |
| 36 | + "rate_limited" => "Too many tries — wait a while and try again.", | |
| 37 | + "reset_invalid" => "This reset link is not valid — ask for a fresh one.", | |
| 36 | 38 | _ => "Something went wrong. Try again.", |
| 37 | 39 | } |
| 38 | 40 | } |
| 39 | 41 | |
| 42 | +/// The good news, where a page carries an `ok` code in its URL. | |
| 43 | +pub fn ok_text(code: &str) -> &'static str { | |
| 44 | + match code { | |
| 45 | + "reset" => "Password changed — sign in with the new one.", | |
| 46 | + _ => "Done.", | |
| 47 | + } | |
| 48 | +} | |
| 49 | + | |
| 40 | 50 | /// The refusal this request carries back, if any. Values come percent- |
| 41 | 51 | /// decoded: `redirect_uri=http%3A%2F%2F…` must equal the registered URI. |
| 42 | 52 | pub fn query_value(query: &str, key: &str) -> Option<String> { |
| @@ -107,6 +117,7 @@ async fn login_card(cx: &Cx) -> Result { | ||
| 107 | 117 | let query = current_query(cx); |
| 108 | 118 | let back = query_value(&query, "back").unwrap_or_else(|| "/".to_string()); |
| 109 | 119 | let error = query_value(&query, "error"); |
| 120 | + let ok = query_value(&query, "ok"); | |
| 110 | 121 | let stage = view! { |
| 111 | 122 | cx => |
| 112 | 123 | <main class="auth-stage"> |
| @@ -117,6 +128,9 @@ async fn login_card(cx: &Cx) -> Result { | ||
| 117 | 128 | <div class="auth-title">"Sign in"</div> |
| 118 | 129 | <div class="auth-sub">"One account for everything Dizey."</div> |
| 119 | 130 | </div> |
| 131 | + if let Some(code) = ok { | |
| 132 | + <div class="auth-ok">(ok_text(&code))</div> | |
| 133 | + } | |
| 120 | 134 | if let Some(code) = error { |
| 121 | 135 | <div class="auth-problem">(error_text(&code))</div> |
| 122 | 136 | } |
| @@ -146,6 +160,7 @@ async fn login_card(cx: &Cx) -> Result { | ||
| 146 | 160 | <span class="auth-submit-text">"Sign in"</span> |
| 147 | 161 | </button> |
| 148 | 162 | </form> |
| 163 | + <a class="auth-alt" href="/forgot">"Forgot it?"</a> | |
| 149 | 164 | </div> |
| 150 | 165 | <div class="auth-footer">"im · Dizey SSO"</div> |
| 151 | 166 | </div> |
| @@ -421,3 +436,111 @@ async fn signed_in(cx: &Cx, user: &im_core::model::User) -> Result { | ||
| 421 | 436 | }; |
| 422 | 437 | shell(cx, "im", stage).await |
| 423 | 438 | } |
| 439 | + | |
| 440 | +/// "Forgot it?" — the self-serve reset ask. It answers the same whether the | |
| 441 | +/// address has an account: one quiet note, the same one for every address. | |
| 442 | +#[page("/forgot")] | |
| 443 | +async fn forgot(cx: &Cx) -> Result { | |
| 444 | + let query = current_query(cx); | |
| 445 | + let error = query_value(&query, "error"); | |
| 446 | + let sent = query_value(&query, "ok").as_deref() == Some("sent"); | |
| 447 | + let stage = view! { | |
| 448 | + cx => | |
| 449 | + <main class="auth-stage"> | |
| 450 | + <div class="auth-column"> | |
| 451 | + (wordmark(cx).await?) | |
| 452 | + <div class="auth-card"> | |
| 453 | + <div class="auth-head"> | |
| 454 | + <div class="auth-title">"Forgot it?"</div> | |
| 455 | + <div class="auth-sub">"Your address gets a reset link, good for one password change. A fresh ask retires the last link."</div> | |
| 456 | + </div> | |
| 457 | + if sent { | |
| 458 | + <div class="auth-ok">"If that address has an account, a link is on its way."</div> | |
| 459 | + } | |
| 460 | + if let Some(code) = error { | |
| 461 | + <div class="auth-problem">(error_text(&code))</div> | |
| 462 | + } | |
| 463 | + <form method="post" action="/forgot"> | |
| 464 | + <label class="auth-field"> | |
| 465 | + <span class="auth-label">"Email"</span> | |
| 466 | + <input | |
| 467 | + class="auth-input auth-input-mono" | |
| 468 | + type="email" | |
| 469 | + name="email" | |
| 470 | + autocomplete="email" | |
| 471 | + required="" | |
| 472 | + > | |
| 473 | + </label> | |
| 474 | + <button class="auth-submit" type="submit"> | |
| 475 | + <span class="auth-submit-text">"Send the link"</span> | |
| 476 | + </button> | |
| 477 | + </form> | |
| 478 | + <a class="auth-alt" href="/">"Back to sign-in"</a> | |
| 479 | + </div> | |
| 480 | + <div class="auth-footer">"im · Dizey SSO"</div> | |
| 481 | + </div> | |
| 482 | + </main> | |
| 483 | + }; | |
| 484 | + shell(cx, "Forgot it? · im", stage).await | |
| 485 | +} | |
| 486 | + | |
| 487 | +/// The reset link's destination: a new password, twice. A dead link never | |
| 488 | +/// shows a working form — it goes back to the ask with the refusal named. | |
| 489 | +#[route(GET "/reset/{token}")] | |
| 490 | +async fn reset_page(cx: &Cx) -> Result<Response> { | |
| 491 | + let token: &str = path_param::<Token>(cx); | |
| 492 | + if !im_core::accounts::reset_link_valid(&server::app(cx).store, token).await? { | |
| 493 | + return see_other("/forgot?error=reset_invalid").into_response(cx); | |
| 494 | + } | |
| 495 | + let query = current_query(cx); | |
| 496 | + let error = query_value(&query, "error"); | |
| 497 | + let stage = view! { | |
| 498 | + cx => | |
| 499 | + <main class="auth-stage"> | |
| 500 | + <div class="auth-column"> | |
| 501 | + (wordmark(cx).await?) | |
| 502 | + <div class="auth-card"> | |
| 503 | + <div class="auth-head"> | |
| 504 | + <div class="auth-title">"A fresh password"</div> | |
| 505 | + <div class="auth-sub">"The change signs every device out, this one included."</div> | |
| 506 | + </div> | |
| 507 | + if let Some(code) = error { | |
| 508 | + <div class="auth-problem">(error_text(&code))</div> | |
| 509 | + } | |
| 510 | + <form method="post" action="/reset"> | |
| 511 | + <input type="hidden" name="token" value=(token.to_string())> | |
| 512 | + <label class="auth-field"> | |
| 513 | + <span class="auth-label">"New password"</span> | |
| 514 | + <input | |
| 515 | + class="auth-input auth-input-mono" | |
| 516 | + type="password" | |
| 517 | + name="password" | |
| 518 | + autocomplete="new-password" | |
| 519 | + minlength=(MIN_PASSWORD_CHARS.to_string()) | |
| 520 | + required="" | |
| 521 | + > | |
| 522 | + </label> | |
| 523 | + <label class="auth-field"> | |
| 524 | + <span class="auth-label">"New password, again"</span> | |
| 525 | + <input | |
| 526 | + class="auth-input auth-input-mono" | |
| 527 | + type="password" | |
| 528 | + name="password_confirm" | |
| 529 | + autocomplete="new-password" | |
| 530 | + minlength=(MIN_PASSWORD_CHARS.to_string()) | |
| 531 | + required="" | |
| 532 | + > | |
| 533 | + </label> | |
| 534 | + <button class="auth-submit" type="submit"> | |
| 535 | + <span class="auth-submit-text">"Change password"</span> | |
| 536 | + </button> | |
| 537 | + </form> | |
| 538 | + </div> | |
| 539 | + <div class="auth-footer">"im · Dizey SSO"</div> | |
| 540 | + </div> | |
| 541 | + </main> | |
| 542 | + }; | |
| 543 | + shell(cx, "A fresh password · im", stage) | |
| 544 | + .await? | |
| 545 | + .into_response(cx) | |
| 546 | +} |
crates/im-web/src/server.rsmodified+10 -4
| @@ -85,13 +85,16 @@ pub fn set_session_cookie(cx: &Cx, token: &str) { | ||
| 85 | 85 | }); |
| 86 | 86 | } |
| 87 | 87 | |
| 88 | -pub fn set_pending_cookie(cx: &Cx, sealed: String) { | |
| 88 | +pub async fn set_pending_cookie(cx: &Cx, sealed: String) { | |
| 89 | + let minutes = im_core::settings::pending_minutes(&app(cx).store) | |
| 90 | + .await | |
| 91 | + .unwrap_or(PENDING_MINUTES); | |
| 89 | 92 | app_cookies(cx).add(cookie! { |
| 90 | 93 | PENDING_COOKIE = sealed; |
| 91 | 94 | Path = "/"; |
| 92 | 95 | HttpOnly; |
| 93 | 96 | SameSite = Lax; |
| 94 | - MaxAge = time::Duration::minutes(PENDING_MINUTES) | |
| 97 | + MaxAge = time::Duration::minutes(minutes) | |
| 95 | 98 | }); |
| 96 | 99 | } |
| 97 | 100 | |
| @@ -137,17 +140,20 @@ pub struct Pending { | ||
| 137 | 140 | pub exp: i64, |
| 138 | 141 | } |
| 139 | 142 | |
| 140 | -pub fn mint_pending( | |
| 143 | +pub async fn mint_pending( | |
| 141 | 144 | cx: &Cx, |
| 142 | 145 | user: &im_core::model::UserId, |
| 143 | 146 | purpose: PendingPurpose, |
| 144 | 147 | back: String, |
| 145 | 148 | ) -> String { |
| 149 | + let minutes = im_core::settings::pending_minutes(&app(cx).store) | |
| 150 | + .await | |
| 151 | + .unwrap_or(PENDING_MINUTES); | |
| 146 | 152 | let pending = Pending { |
| 147 | 153 | user: user.to_string(), |
| 148 | 154 | purpose, |
| 149 | 155 | back, |
| 150 | - exp: time::OffsetDateTime::now_utc().unix_timestamp() + PENDING_MINUTES * 60, | |
| 156 | + exp: time::OffsetDateTime::now_utc().unix_timestamp() + minutes * 60, | |
| 151 | 157 | }; |
| 152 | 158 | let json = serde_json::to_string(&pending).expect("Pending is plain data"); |
| 153 | 159 | app(cx).store.seal_value(json.as_bytes()) |
style/main.scssmodified+7 -0
| @@ -590,9 +590,16 @@ body:has(.admin-shell) { | ||
| 590 | 590 | // button skin; the popover names the cost and holds the real button. |
| 591 | 591 | .admin-confirm { |
| 592 | 592 | position: relative; |
| 593 | + display: inline-flex; | |
| 593 | 594 | |
| 595 | + // The summary wears the button skin verbatim — a native summary is a | |
| 596 | + // list-item, and without inline-flex it stands a few pixels off the real | |
| 597 | + // buttons beside it. | |
| 594 | 598 | summary { |
| 595 | 599 | list-style: none; |
| 600 | + display: inline-flex; | |
| 601 | + align-items: center; | |
| 602 | + box-sizing: border-box; | |
| 596 | 603 | |
| 597 | 604 | &::-webkit-details-marker { display: none; } |
| 598 | 605 | } |