auth: e-mail + password login with e-mailed password links
CI / test (push) Failing after 1m39s
CI / build (push) Skipped
CI / deploy (push) Skipped

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
This commit is contained in:
feco
2026-11-21 18:24:48 +00:00
co-authored by Claude Opus 5.5
parent a63f8f9928
commit 7d6a6c3d92
11 changed files with 651 additions and 192 deletions
+102 -70
View File
@@ -278,17 +278,32 @@ impl TestApp {
/// Registers a user; returns the session token.
async fn register(&self, email: &str, name: &str) -> String {
self.register_with(json!({"email": email, "display_name": name})).await
}
/// Signs up with `body` and sets the password through the e-mailed link;
/// returns the session token.
async fn register_with(&self, body: Value) -> String {
let r = self.post("/v1/auth/register", None, body.clone()).await;
assert_eq!(r.status, StatusCode::ACCEPTED, "{}", r.body);
let email = body["email"].as_str().unwrap().trim().to_lowercase();
let url = self.outbox_url(&email, "verify_email").await;
let r = self
.post(
"/v1/auth/register",
None,
json!({"email": email, "password": "titkos-jelszo-123", "display_name": name}),
)
.post("/v1/auth/set-password", None, json!({"token": token_param(&url), "password": "titkos-jelszo-123"}))
.await;
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
r.body["session"]["token"].as_str().unwrap().to_string()
}
async fn outbox_count(&self, email: &str, template: &str) -> i64 {
sqlx::query_scalar("SELECT count(*) FROM email_outbox WHERE to_email = $1 AND template = $2")
.bind(email)
.bind(template)
.fetch_one(&self.pool)
.await
.unwrap()
}
/// An admin adds units to their own account (admins use units too).
async fn add_own_units(&self, admin: &str, unit: &str, delta: i32) {
let id = self.get("/v1/me", Some(admin)).await.body["user"]["id"].as_str().unwrap().to_string();
@@ -333,38 +348,48 @@ fn token_param(url: &str) -> &str {
#[sqlx::test(migrator = "db::MIGRATOR")]
async fn register_login_verify_logout(pool: PgPool) {
let app = TestApp::new(pool).await;
let r = app
.post("/v1/auth/register", None, json!({"email": "Anna@Example.com", "password": "titkos-jelszo-123"}))
.await;
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
// Sign-up takes no password: it is set through the e-mailed link.
let r =
app.post("/v1/auth/register", None, json!({"email": "x@example.com", "password": "titkos-jelszo-123"})).await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
let r = app.post("/v1/auth/register", None, json!({"email": "Anna@Example.com", "display_name": "Anna"})).await;
assert_eq!((r.status, &r.body["sent"]), (StatusCode::ACCEPTED, &json!(true)), "{}", r.body);
assert!(r.headers.get("set-cookie").is_none(), "no session before the link");
let url = app.outbox_url("anna@example.com", "verify_email").await;
assert!(url.starts_with("https://sorsfonalak.test/jelszo?token="));
// no login before the password is set
let r =
app.post("/v1/auth/login", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"})).await;
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
// a too short password does not use up the link
let set = |password: &'static str| {
app.post("/v1/auth/set-password", None, json!({"token": token_param(&url), "password": password}))
};
assert_eq!(set("rovid").await.status, StatusCode::BAD_REQUEST);
let r = set("titkos-jelszo-123").await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
let cookie = r.headers.get("set-cookie").unwrap().to_str().unwrap();
assert!(cookie.starts_with("sf_session=") && cookie.contains("HttpOnly") && cookie.contains("Secure"));
assert_eq!(r.body["user"]["email"], "anna@example.com");
assert_eq!(r.body["user"]["roles"], json!(["user"]));
assert_eq!(r.body["user"]["email_verified"], false);
assert_eq!(r.body["user"]["email_verified"], true);
let token = r.body["session"]["token"].as_str().unwrap().to_string();
// duplicate, short password
let r = app
.post("/v1/auth/register", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"}))
.await;
assert_eq!((r.status, r.body["error"]["code"].as_str()), (StatusCode::CONFLICT, Some("email_taken")));
let r = app.post("/v1/auth/register", None, json!({"email": "b@example.com", "password": "rovid"})).await;
assert_eq!(r.status, StatusCode::BAD_REQUEST);
assert_eq!(set("masik-jelszo-123").await.body["error"]["code"], "invalid_token");
let r = app.get("/v1/me", Some(&token)).await;
assert_eq!(r.status, StatusCode::OK);
assert_eq!(r.body["providers"], json!(["password"]));
assert_eq!(r.body["analyses_left"], json!({"natal": 0, "synastry": 0, "forecast": 0, "question": 0, "tarot": 0}));
// e-mail verification through the queued e-mail's link
let url = app.outbox_url("anna@example.com", "verify_email").await;
assert!(url.starts_with("https://sorsfonalak.test/verify-email?token="));
let r = app.post("/v1/auth/verify-email", None, json!({"token": token_param(&url)})).await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
let r = app.post("/v1/auth/verify-email", None, json!({"token": token_param(&url)})).await;
assert_eq!(r.body["error"]["code"], "invalid_token");
assert_eq!(app.get("/v1/me", Some(&token)).await.body["user"]["email_verified"], true);
// signing up again with the address: the same answer, and the owner gets
// a link instead (once a minute at most)
for _ in 0..2 {
let r = app.post("/v1/auth/register", None, json!({"email": "anna@example.com"})).await;
assert_eq!(r.status, StatusCode::ACCEPTED);
}
assert_eq!(app.outbox_count("anna@example.com", "account_exists").await, 1);
// login
let r =
@@ -400,15 +425,25 @@ async fn password_reset_ends_sessions(pool: PgPool) {
StatusCode::ACCEPTED
);
let url = app.outbox_url("anna@example.com", "reset_password").await;
assert!(url.starts_with("https://sorsfonalak.test/jelszo?token="));
let r = app
.post(
"/v1/auth/password-reset/confirm",
None,
json!({"token": token_param(&url), "password": "uj-titkos-jelszo-456"}),
)
.post("/v1/auth/set-password", None, json!({"token": token_param(&url), "password": "uj-titkos-jelszo-456"}))
.await;
assert_eq!(r.status, StatusCode::NO_CONTENT, "{}", r.body);
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
let fresh = r.body["session"]["token"].as_str().unwrap().to_string();
assert_eq!(app.get("/v1/me", Some(&token)).await.status, StatusCode::UNAUTHORIZED);
assert_eq!(app.get("/v1/me", Some(&fresh)).await.status, StatusCode::OK);
// the sign-up link cannot be used for it any more either
let signup = app.outbox_url("anna@example.com", "verify_email").await;
let r = app
.post("/v1/auth/set-password", None, json!({"token": token_param(&signup), "password": "harmadik-jelszo-789"}))
.await;
assert_eq!(r.body["error"]["code"], "invalid_token");
// a flood of requests sends one more link a minute at most
for _ in 0..3 {
app.post("/v1/auth/password-reset", None, json!({"email": "anna@example.com"})).await;
}
assert_eq!(app.outbox_count("anna@example.com", "reset_password").await, 1);
let r = app
.post("/v1/auth/login", None, json!({"email": "anna@example.com", "password": "uj-titkos-jelszo-456"}))
.await;
@@ -430,31 +465,49 @@ async fn google_login_creates_links_and_rejects(pool: PgPool) {
.await;
assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false)));
// an existing, confirmed password account with the same address gets Google linked
// an existing password account with the same address gets Google linked
// (its address was confirmed when the password was set)
let token = app.register("anna@example.com", "Anna").await;
sqlx::query("UPDATE users SET email_verified_at = now() WHERE email = 'anna@example.com'")
.execute(&app.pool)
.await
.unwrap();
let r = app
.post("/v1/auth/google", None, json!({"id_token": google_token("g-2", "anna@example.com", GOOGLE_CLIENT)}))
.await;
assert_eq!((r.status, &r.body["created"]), (StatusCode::OK, &json!(false)));
assert_eq!(app.get("/v1/me", Some(&token)).await.body["providers"], json!(["password", "google"]));
// an unconfirmed one may be someone else's: its password and sessions go
let squatter = app.register("victim@example.com", "Valaki").await;
// Someone signs up with another person's address: no password, no session.
// When the owner comes with Google, the account is theirs, and the link
// in their mailbox would only let them set their own password.
let r = app.post("/v1/auth/register", None, json!({"email": "victim@example.com", "display_name": "Valaki"})).await;
assert_eq!(r.status, StatusCode::ACCEPTED);
let r = app
.post("/v1/auth/google", None, json!({"id_token": google_token("g-4", "victim@example.com", GOOGLE_CLIENT)}))
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
let owner = r.body["session"]["token"].as_str().unwrap().to_string();
assert_eq!(app.get("/v1/me", Some(&squatter)).await.status, StatusCode::UNAUTHORIZED);
assert_eq!(app.get("/v1/me", Some(&owner)).await.body["providers"], json!(["google"]));
let me = app.get("/v1/me", Some(&owner)).await.body;
assert_eq!((&me["providers"], &me["user"]["email_verified"]), (&json!(["google"]), &json!(true)));
let r =
app.post("/v1/auth/login", None, json!({"email": "victim@example.com", "password": "titkos-jelszo-123"})).await;
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
// An unconfirmed password account from before the links (legacy) cannot
// log in, and Google login removes its password and sessions.
let legacy = app.register("old@example.com", "Régi").await;
sqlx::query("UPDATE users SET email_verified_at = NULL WHERE email = 'old@example.com'")
.execute(&app.pool)
.await
.unwrap();
let r =
app.post("/v1/auth/login", None, json!({"email": "old@example.com", "password": "titkos-jelszo-123"})).await;
assert_eq!(r.status, StatusCode::UNAUTHORIZED);
let r = app
.post("/v1/auth/google", None, json!({"id_token": google_token("g-5", "old@example.com", GOOGLE_CLIENT)}))
.await;
assert_eq!(r.status, StatusCode::OK, "{}", r.body);
assert_eq!(app.get("/v1/me", Some(&legacy)).await.status, StatusCode::UNAUTHORIZED);
let owner = r.body["session"]["token"].as_str().unwrap().to_string();
assert_eq!(app.get("/v1/me", Some(&owner)).await.body["providers"], json!(["google"]));
let r = app
.post("/v1/auth/google", None, json!({"id_token": google_token("g-3", "x@gmail.com", "other-client")}))
.await;
@@ -769,15 +822,15 @@ async fn analyses_spend_units_and_reuse_results(pool: PgPool) {
async fn password_login_can_be_disabled(pool: PgPool) {
let app = TestApp::with_config(pool, |c| c.password_login = false).await;
assert_eq!(app.get("/v1/config", None).await.body["password_login"], false);
let r = app
.post("/v1/auth/register", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"}))
.await;
let r = app.post("/v1/auth/register", None, json!({"email": "anna@example.com"})).await;
assert_eq!(r.status, StatusCode::FORBIDDEN);
let r =
app.post("/v1/auth/login", None, json!({"email": "anna@example.com", "password": "titkos-jelszo-123"})).await;
assert_eq!(r.status, StatusCode::FORBIDDEN);
let r = app.post("/v1/auth/password-reset", None, json!({"email": "anna@example.com"})).await;
assert_eq!(r.status, StatusCode::FORBIDDEN);
let r = app.post("/v1/auth/set-password", None, json!({"token": "x", "password": "titkos-jelszo-123"})).await;
assert_eq!(r.status, StatusCode::FORBIDDEN);
}
#[sqlx::test(migrator = "db::MIGRATOR")]
@@ -880,7 +933,7 @@ async fn export_and_delete_account(pool: PgPool) {
/// config and catalog, shared links, invitation pages, the waitlist and
/// unsubscribing. Every other route (charts, calculations, analyses) needs a
/// logged-in user, so other apps cannot use them.
const PUBLIC_ROUTES: [&str; 17] = [
const PUBLIC_ROUTES: [&str; 16] = [
"/healthz",
// Stripe calls it; the signature proves it.
"/v1/payments/stripe/webhook",
@@ -890,9 +943,8 @@ const PUBLIC_ROUTES: [&str; 17] = [
"/v1/auth/login",
"/v1/auth/google",
"/v1/auth/apple",
"/v1/auth/verify-email",
"/v1/auth/password-reset",
"/v1/auth/password-reset/confirm",
"/v1/auth/set-password",
"/v1/public/shares/{slug}",
"/v1/public/shares/{slug}/visit",
"/v1/public/invites/{token}",
@@ -2296,20 +2348,7 @@ async fn a_new_user_from_a_shared_link_earns_an_analysis(pool: PgPool) {
let before = natal(anna.clone()).await;
let join = |email: String| {
let (app, slug) = (&app, slug.clone());
async move {
let r = app
.post(
"/v1/auth/register",
None,
json!({"email": email, "password": "titkos-jelszo-123", "referral": slug}),
)
.await;
assert_eq!(r.status, StatusCode::CREATED, "{}", r.body);
r.body["token"].as_str().map(str::to_string).unwrap_or_else(|| {
let cookie = r.headers.get("set-cookie").unwrap().to_str().unwrap();
cookie.split(';').next().unwrap().split('=').nth(1).unwrap().to_string()
})
}
async move { app.register_with(json!({"email": email, "referral": slug})).await }
};
// signing up is not enough: the reward comes with their own chart
@@ -2332,14 +2371,7 @@ async fn a_new_user_from_a_shared_link_earns_an_analysis(pool: PgPool) {
// nothing while the rewards are off
let off = TestApp::with_config(pool, |c| c.referral_rewards = false).await;
let r = off
.post(
"/v1/auth/register",
None,
json!({"email": "late@example.com", "password": "titkos-jelszo-123", "referral": slug}),
)
.await;
assert_eq!(r.status, StatusCode::CREATED);
off.register_with(json!({"email": "late@example.com", "referral": slug})).await;
let count: i64 = sqlx::query_scalar(
"SELECT count(*) FROM referrals r JOIN users u ON u.id = r.user_id WHERE u.email = 'late@example.com'",
)