Files
sorsfonalak/services/backend/src/routes/auth.rs
T
fecoandClaude Opus 5.5 7d6a6c3d92
CI / test (push) Failing after 1m39s
CI / build (push) Skipped
CI / deploy (push) Skipped
auth: e-mail + password login with e-mailed password links
Sign-up asks no password: a link goes to the address and the password is
set there (also for forgotten passwords), by whoever opens the mailbox.
So nobody can register a password for someone else's address, and linking
Google or Apple to an account with the same address stays safe. Opening
the link confirms the address, ends other sessions and logs in.

Sign-up answers alike for registered addresses (the owner gets an
'account exists' link), links are limited to one per kind a minute and
five an hour, and unconfirmed password accounts cannot log in.
Frontend: login form with sign-up and forgotten password next to the
social buttons, and the /jelszo page for the link. Still behind
PASSWORD_LOGIN (off on prod).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012vLHzh5qUhFtmJhzkcTbXL
2026-11-21 18:24:48 +00:00

623 lines
24 KiB
Rust

//! Registration and login: e-mail + password, Google, Apple; password links,
//! logout.
//!
//! A password can only be set through a link sent to the address (sign-up,
//! forgotten password), by whoever opens it. So every password account has a
//! confirmed address, and nobody can set a password for someone else's
//! address: linking a Google or Apple account with the same address is safe.
use axum::Json;
use axum::extract::State;
use axum::http::{HeaderMap, StatusCode};
use axum::response::IntoResponse;
use axum_extra::extract::{CookieJar, WithRejection};
use db::{Role, USER_COLUMNS, User};
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use sqlx::PgConnection;
use time::OffsetDateTime;
use uuid::Uuid;
use super::{Body, St};
use crate::AppState;
use crate::auth::{
AuthUser, DUMMY_HASH, SessionInfo, create_session, hash_password, removal_cookie, session_cookie, user_agent,
validate_password, verify_password,
};
use crate::error::{ApiError, ApiResult};
use crate::views::UserView;
const VERIFY_EMAIL_TTL: time::Duration = time::Duration::days(3);
const RESET_PASSWORD_TTL: time::Duration = time::Duration::hours(1);
#[derive(Serialize)]
pub struct LoginResponse {
pub user: UserView,
pub session: SessionInfo,
/// `true` when this call created the account.
pub created: bool,
}
pub fn normalize_email(email: &str) -> Result<String, ApiError> {
let email = email.trim().to_lowercase();
let valid = email.len() <= 254
&& email.split_once('@').is_some_and(|(local, domain)| {
!local.is_empty() && domain.contains('.') && !domain.starts_with('.') && !domain.ends_with('.')
})
&& !email.chars().any(char::is_whitespace);
if valid { Ok(email) } else { Err(ApiError::BadRequest("invalid e-mail address".into())) }
}
pub fn validate_locale(state: &AppState, locale: Option<&str>) -> Result<String, ApiError> {
match locale {
None => Ok(state.config.supported_locales[0].clone()),
Some(l) if state.config.supported_locales.iter().any(|s| s == l) => Ok(l.to_string()),
Some(l) => Err(ApiError::BadRequest(format!(
"unsupported locale '{l}'; supported: {}",
state.config.supported_locales.join(", ")
))),
}
}
fn clean_name(name: Option<String>) -> Option<String> {
name.map(|n| n.trim().chars().take(100).collect::<String>()).filter(|n| !n.is_empty())
}
async fn load_user(conn: &mut PgConnection, id: Uuid) -> Result<User, ApiError> {
Ok(sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE id = $1")).bind(id).fetch_one(conn).await?)
}
/// Gives the admin role to addresses listed in `BOOTSTRAP_ADMIN_EMAILS`.
async fn apply_bootstrap_admin(state: &AppState, conn: &mut PgConnection, user: &mut User) -> Result<(), ApiError> {
if !user.has_role(Role::Admin) && state.config.bootstrap_admin_emails.contains(&user.email) {
sqlx::query("UPDATE users SET roles = array_append(roles, 'admin'), updated_at = now() WHERE id = $1")
.bind(user.id)
.execute(&mut *conn)
.await?;
*user = load_user(conn, user.id).await?;
tracing::info!(user = %user.id, "admin role granted from BOOTSTRAP_ADMIN_EMAILS");
}
Ok(())
}
/// One-time token row; returns the secret to put into the e-mail link.
async fn issue_token(
conn: &mut PgConnection,
user_id: Uuid,
purpose: &str,
ttl: time::Duration,
) -> Result<String, ApiError> {
// A new link replaces the earlier unused ones.
sqlx::query("DELETE FROM auth_tokens WHERE user_id = $1 AND purpose = $2 AND used_at IS NULL")
.bind(user_id)
.bind(purpose)
.execute(&mut *conn)
.await?;
let token = db::new_token();
sqlx::query("INSERT INTO auth_tokens (id, user_id, purpose, token_hash, expires_at) VALUES ($1, $2, $3, $4, $5)")
.bind(Uuid::now_v7())
.bind(user_id)
.bind(purpose)
.bind(db::token_hash(&token))
.bind(OffsetDateTime::now_utc() + ttl)
.execute(conn)
.await?;
Ok(token)
}
/// Uses a one-time token of one of `purposes`; returns its user.
async fn consume_token(conn: &mut PgConnection, token: &str, purposes: &[&str]) -> Result<Uuid, ApiError> {
let row: Option<(Uuid,)> = sqlx::query_as(
"UPDATE auth_tokens SET used_at = now() \
WHERE token_hash = $1 AND purpose = ANY($2) AND used_at IS NULL AND expires_at > now() RETURNING user_id",
)
.bind(db::token_hash(token.trim()))
.bind(purposes)
.fetch_optional(conn)
.await?;
row.map(|(id,)| id).ok_or(ApiError::InvalidToken)
}
/// Queues an e-mail to a user for the worker.
pub async fn queue_email(conn: &mut PgConnection, user: &User, template: &str, payload: Value) -> Result<(), ApiError> {
queue_email_to(conn, Some(user.id), &user.email, template, &user.locale, payload).await
}
/// Queues an e-mail to any address (e.g. an invitation) for the worker.
pub async fn queue_email_to(
conn: &mut PgConnection,
user_id: Option<Uuid>,
to: &str,
template: &str,
locale: &str,
payload: Value,
) -> Result<(), ApiError> {
sqlx::query(
"INSERT INTO email_outbox (id, user_id, to_email, template, locale, payload) VALUES ($1, $2, $3, $4, $5, $6)",
)
.bind(Uuid::now_v7())
.bind(user_id)
.bind(to)
.bind(template)
.bind(locale)
.bind(payload)
.execute(conn)
.await?;
Ok(())
}
/// The e-mails that carry a password link.
const LINK_TEMPLATES: [&str; 3] = ["verify_email", "reset_password", "account_exists"];
/// Whether another password link may go to `email` now: one per kind a
/// minute and five an hour, so the forms cannot flood a mailbox.
async fn may_send_link(conn: &mut PgConnection, email: &str, template: &str) -> Result<bool, ApiError> {
let (same_kind, total): (i64, i64) = sqlx::query_as(
"SELECT count(*) FILTER (WHERE template = $2 AND created_at > now() - interval '1 minute'), count(*) \
FROM email_outbox WHERE to_email = $1 AND template = ANY($3) AND created_at > now() - interval '1 hour'",
)
.bind(email)
.bind(template)
.bind(&LINK_TEMPLATES[..])
.fetch_one(conn)
.await?;
Ok(same_kind == 0 && total < 5)
}
/// Sends a link that sets the password: `verify_email` (sign-up, valid for 3
/// days), `reset_password` (forgotten password) or `account_exists` (sign-up
/// with an address that already has an account), the latter two for 1 hour.
async fn queue_password_link(
state: &AppState,
conn: &mut PgConnection,
user: &User,
template: &'static str,
) -> Result<(), ApiError> {
if !may_send_link(conn, &user.email, template).await? {
tracing::info!(user = %user.id, template, "password link not sent: one went out a moment ago");
return Ok(());
}
let (purpose, ttl) = match template {
"verify_email" => ("verify_email", VERIFY_EMAIL_TTL),
_ => ("reset_password", RESET_PASSWORD_TTL),
};
let token = issue_token(conn, user.id, purpose, ttl).await?;
let url = format!("{}/jelszo?token={token}", state.config.public_base_url);
queue_email(conn, user, template, json!({ "url": url, "display_name": user.display_name })).await
}
fn login_response(
state: &AppState,
jar: CookieJar,
user: &User,
session: SessionInfo,
created: bool,
) -> impl IntoResponse + use<> {
let jar = jar.add(session_cookie(&state.config, &session));
let status = if created { StatusCode::CREATED } else { StatusCode::OK };
(status, jar, Json(LoginResponse { user: user.into(), session, created }))
}
// --- e-mail + password -----------------------------------------------------------------
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RegisterRequest {
email: String,
display_name: Option<String>,
locale: Option<String>,
/// The invitation link's token, while sign-up needs an invitation.
invite_token: Option<String>,
/// The slug of the shared link the visitor came from.
referral: Option<String>,
}
/// Password endpoints answer 403 while `PASSWORD_LOGIN` is off.
pub fn password_login_enabled(state: &crate::AppState) -> Result<(), ApiError> {
if state.config.password_login {
Ok(())
} else {
Err(ApiError::Forbidden("e-mail and password login is disabled; use Google, Apple or Facebook".into()))
}
}
/// Sign-up with an e-mail address: no password yet, only a link to the
/// address, where the password is set. Answers 202 the same way whether or
/// not the address already has an account (that one gets a link to set a
/// password instead), so the form does not reveal who is registered.
pub async fn register(
State(state): St,
WithRejection(Json(req), _): Body<RegisterRequest>,
) -> ApiResult<impl IntoResponse> {
password_login_enabled(&state)?;
let email = normalize_email(&req.email)?;
let locale = validate_locale(&state, req.locale.as_deref())?;
let mut tx = state.db.begin().await?;
let existing: Option<User> =
sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1 FOR UPDATE"))
.bind(&email)
.fetch_optional(&mut *tx)
.await?;
match existing {
Some(user) if user.email_verified_at.is_none() => {
queue_password_link(&state, &mut tx, &user, "verify_email").await?;
}
Some(user) => queue_password_link(&state, &mut tx, &user, "account_exists").await?,
None => {
super::invitations::admit(&state, &mut tx, &email, req.invite_token.as_deref()).await?;
let user_id = Uuid::now_v7();
sqlx::query("INSERT INTO users (id, email, display_name, locale) VALUES ($1, $2, $3, $4)")
.bind(user_id)
.bind(&email)
.bind(clean_name(req.display_name))
.bind(&locale)
.execute(&mut *tx)
.await?;
// Packages of invitations go to this account; only whoever opens
// the link in the mailbox can ever log in to it.
super::invitations::mark_accepted(
&mut tx,
user_id,
&email,
req.invite_token.as_deref(),
state.config.free_person_slots,
)
.await?;
super::shares::record_referral(&mut tx, state.config.referral_rewards, user_id, req.referral.as_deref())
.await?;
let user = load_user(&mut tx, user_id).await?;
queue_password_link(&state, &mut tx, &user, "verify_email").await?;
}
}
tx.commit().await?;
Ok((StatusCode::ACCEPTED, Json(json!({ "sent": true }))))
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct LoginRequest {
email: String,
password: String,
}
pub async fn login(
State(state): St,
headers: HeaderMap,
jar: CookieJar,
WithRejection(Json(req), _): Body<LoginRequest>,
) -> ApiResult<impl IntoResponse> {
password_login_enabled(&state)?;
let invalid = || ApiError::InvalidCredentials("wrong e-mail address or password".into());
let email = normalize_email(&req.email).map_err(|_| invalid())?;
state.login_limiter.check(&email)?;
// Passwords are set through e-mailed links, so every password account has
// a confirmed address; an unconfirmed one (made before that) cannot log in.
let row: Option<(Uuid, String)> = sqlx::query_as(
"SELECT u.id, i.password_hash FROM users u \
JOIN auth_identities i ON i.user_id = u.id AND i.provider = 'password' \
WHERE u.email = $1 AND u.email_verified_at IS NOT NULL",
)
.bind(&email)
.fetch_optional(&state.db)
.await?;
let Some((user_id, hash)) = row else {
// Same amount of work as a real check.
let _ = verify_password(req.password, DUMMY_HASH.clone()).await;
state.login_limiter.failed(&email);
return Err(invalid());
};
if !verify_password(req.password, hash).await? {
state.login_limiter.failed(&email);
return Err(invalid());
}
state.login_limiter.succeeded(&email);
let mut conn = state.db.acquire().await?;
sqlx::query("UPDATE auth_identities SET last_used_at = now() WHERE user_id = $1 AND provider = 'password'")
.bind(user_id)
.execute(&mut *conn)
.await?;
let mut user = load_user(&mut conn, user_id).await?;
apply_bootstrap_admin(&state, &mut conn, &mut user).await?;
drop(conn);
let session = create_session(&state.db, &state.config, user.id, user_agent(&headers)).await?;
Ok(login_response(&state, jar, &user, session, false))
}
// --- Google -----------------------------------------------------------------------------
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct GoogleRequest {
/// ID token (JWT) from Google Identity Services.
id_token: String,
/// The invitation link's token, while sign-up needs an invitation.
invite_token: Option<String>,
/// The slug of the shared link the visitor came from.
referral: Option<String>,
}
/// Logs in with Google. An unknown Google account is linked to the existing
/// user with the same (Google-verified) e-mail address, or a new user is created.
pub async fn google(
State(state): St,
headers: HeaderMap,
jar: CookieJar,
WithRejection(Json(req), _): Body<GoogleRequest>,
) -> ApiResult<impl IntoResponse> {
let claims = state.google.verify(&req.id_token).await?;
let signup = Signup {
name: claims.name.clone(),
locale: claims.locale.clone(),
invite_token: req.invite_token,
referral: req.referral,
};
social_login(&state, headers, jar, "google", claims, signup).await
}
// --- Apple ------------------------------------------------------------------------------
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct AppleRequest {
/// ID token (JWT) from Sign in with Apple JS.
id_token: String,
/// The name Apple gives the page at the first sign-in only (it is not in
/// the token): used when the account is created.
name: Option<String>,
invite_token: Option<String>,
referral: Option<String>,
}
/// Logs in with Apple, like [`google`]. The address may be an Apple relay
/// (`…@privaterelay.appleid.com`), which forwards our e-mails.
pub async fn apple(
State(state): St,
headers: HeaderMap,
jar: CookieJar,
WithRejection(Json(req), _): Body<AppleRequest>,
) -> ApiResult<impl IntoResponse> {
let claims = state.apple.verify(&req.id_token).await?;
let signup = Signup { name: req.name, locale: None, invite_token: req.invite_token, referral: req.referral };
social_login(&state, headers, jar, "apple", claims, signup).await
}
/// What a new account starts with.
struct Signup {
name: Option<String>,
locale: Option<String>,
invite_token: Option<String>,
referral: Option<String>,
}
/// Logs in with a verified provider identity: the linked user, else the user
/// with the same (provider-verified) e-mail address, else a new user.
async fn social_login(
state: &AppState,
headers: HeaderMap,
jar: CookieJar,
provider: &'static str,
claims: crate::oidc::IdClaims,
signup: Signup,
) -> ApiResult<impl IntoResponse + use<>> {
let email = match (claims.email.as_deref(), claims.email_verified) {
(Some(e), true) => normalize_email(e)?,
_ => {
return Err(ApiError::InvalidCredentials(format!("the {provider} account has no verified e-mail address")));
}
};
let mut tx = state.db.begin().await?;
let linked: Option<(Uuid,)> =
sqlx::query_as("SELECT user_id FROM auth_identities WHERE provider = $1 AND subject = $2")
.bind(provider)
.bind(&claims.sub)
.fetch_optional(&mut *tx)
.await?;
let (user_id, created) = match linked {
Some((id,)) => {
sqlx::query("UPDATE auth_identities SET last_used_at = now() WHERE provider = $1 AND subject = $2")
.bind(provider)
.bind(&claims.sub)
.execute(&mut *tx)
.await?;
(id, false)
}
None => {
let existing: Option<(Uuid,)> =
sqlx::query_as("SELECT id FROM users WHERE email = $1").bind(&email).fetch_optional(&mut *tx).await?;
let (id, created) = match existing {
Some((id,)) => {
// An account whose address was never confirmed may have
// been made by someone else with this address: its
// password and sessions go, the provider has proven who
// owns the address.
let unverified: bool =
sqlx::query_scalar("SELECT email_verified_at IS NULL FROM users WHERE id = $1 FOR UPDATE")
.bind(id)
.fetch_one(&mut *tx)
.await?;
if unverified {
sqlx::query("DELETE FROM auth_identities WHERE user_id = $1 AND provider = 'password'")
.bind(id)
.execute(&mut *tx)
.await?;
sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(id).execute(&mut *tx).await?;
tracing::warn!(user = %id, provider, "unconfirmed password account taken over by its address's owner");
}
// The provider has verified the address, so it counts as verified here too.
sqlx::query(
"UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1",
)
.bind(id)
.execute(&mut *tx)
.await?;
(id, false)
}
None => {
super::invitations::admit(state, &mut tx, &email, signup.invite_token.as_deref()).await?;
let id = Uuid::now_v7();
let locale = signup
.locale
.as_deref()
.and_then(|l| l.split(['-', '_']).next())
.filter(|l| state.config.supported_locales.iter().any(|s| s == l))
.unwrap_or(&state.config.supported_locales[0])
.to_string();
sqlx::query(
"INSERT INTO users (id, email, email_verified_at, display_name, locale) VALUES ($1, $2, now(), $3, $4)",
)
.bind(id)
.bind(&email)
.bind(clean_name(signup.name))
.bind(locale)
.execute(&mut *tx)
.await?;
super::invitations::mark_accepted(
&mut tx,
id,
&email,
signup.invite_token.as_deref(),
state.config.free_person_slots,
)
.await?;
super::shares::record_referral(
&mut tx,
state.config.referral_rewards,
id,
signup.referral.as_deref(),
)
.await?;
(id, true)
}
};
sqlx::query(
"INSERT INTO auth_identities (id, user_id, provider, subject, email, last_used_at) \
VALUES ($1, $2, $3, $4, $5, now())",
)
.bind(Uuid::now_v7())
.bind(id)
.bind(provider)
.bind(&claims.sub)
.bind(&email)
.execute(&mut *tx)
.await?;
(id, created)
}
};
let mut user = load_user(&mut tx, user_id).await?;
apply_bootstrap_admin(state, &mut tx, &mut user).await?;
tx.commit().await?;
let session = create_session(&state.db, &state.config, user.id, user_agent(&headers)).await?;
Ok(login_response(state, jar, &user, session, created))
}
// --- logout -------------------------------------------------------------------------------
pub async fn logout(State(state): St, auth: AuthUser, jar: CookieJar) -> ApiResult<impl IntoResponse> {
sqlx::query("DELETE FROM sessions WHERE id = $1").bind(auth.session_id).execute(&state.db).await?;
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
}
/// Ends every session of the user (all devices).
pub async fn logout_all(State(state): St, auth: AuthUser, jar: CookieJar) -> ApiResult<impl IntoResponse> {
sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(auth.id()).execute(&state.db).await?;
Ok((StatusCode::NO_CONTENT, jar.add(removal_cookie(&state.config))))
}
// --- password links ---------------------------------------------------------------------
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct ResetRequest {
email: String,
}
/// Forgotten password: a link to set a new one (also adds a password to a
/// Google or Apple account). Always 202, so the response does not reveal
/// whether the address is registered.
pub async fn request_password_reset(
State(state): St,
WithRejection(Json(req), _): Body<ResetRequest>,
) -> ApiResult<StatusCode> {
password_login_enabled(&state)?;
let Ok(email) = normalize_email(&req.email) else { return Ok(StatusCode::ACCEPTED) };
let mut tx = state.db.begin().await?;
let user: Option<User> = sqlx::query_as(&format!("SELECT {USER_COLUMNS} FROM users WHERE email = $1 FOR UPDATE"))
.bind(&email)
.fetch_optional(&mut *tx)
.await?;
if let Some(user) = user {
queue_password_link(&state, &mut tx, &user, "reset_password").await?;
}
tx.commit().await?;
Ok(StatusCode::ACCEPTED)
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
pub struct SetPasswordRequest {
token: String,
password: String,
}
/// Sets the password with an e-mailed link (sign-up or forgotten password):
/// the address counts as confirmed, every other session ends, and this one
/// is logged in.
pub async fn set_password_with_link(
State(state): St,
headers: HeaderMap,
jar: CookieJar,
WithRejection(Json(req), _): Body<SetPasswordRequest>,
) -> ApiResult<impl IntoResponse> {
password_login_enabled(&state)?;
validate_password(&req.password)?;
let hash = hash_password(req.password).await?;
let mut tx = state.db.begin().await?;
let user_id = consume_token(&mut tx, &req.token, &["verify_email", "reset_password"]).await?;
set_password(&mut tx, user_id, &hash).await?;
sqlx::query("UPDATE users SET email_verified_at = COALESCE(email_verified_at, now()) WHERE id = $1")
.bind(user_id)
.execute(&mut *tx)
.await?;
sqlx::query("DELETE FROM sessions WHERE user_id = $1").bind(user_id).execute(&mut *tx).await?;
let mut user = load_user(&mut tx, user_id).await?;
apply_bootstrap_admin(&state, &mut tx, &mut user).await?;
tx.commit().await?;
state.login_limiter.succeeded(&user.email);
let session = create_session(&state.db, &state.config, user.id, user_agent(&headers)).await?;
Ok(login_response(&state, jar, &user, session, false))
}
/// Creates or replaces the password identity.
pub async fn set_password(conn: &mut PgConnection, user_id: Uuid, hash: &str) -> Result<(), ApiError> {
sqlx::query(
"INSERT INTO auth_identities (id, user_id, provider, subject, password_hash, email) \
SELECT $1, u.id, 'password', u.id::text, $2, u.email FROM users u WHERE u.id = $3 \
ON CONFLICT (user_id, provider) DO UPDATE SET password_hash = EXCLUDED.password_hash",
)
.bind(Uuid::now_v7())
.bind(hash)
.bind(user_id)
.execute(conn)
.await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn emails() {
assert_eq!(normalize_email(" Anna@Example.COM ").unwrap(), "anna@example.com");
assert!(normalize_email("anna").is_err());
assert!(normalize_email("anna@localhost").is_err());
assert!(normalize_email("an na@example.com").is_err());
}
}