8.8 KiB · text History 263b40b
//! "Forgot password?" against a live database, through the real routes and
//! templates. Skipped unless `TEST_DATABASE_URL` is set (`just test-db`
//! runs api_db; run this one with `--test password_reset_db`).
use std::sync::Arc;

use axum::Router;
use axum::body::Body;
use axum::http::{Request, StatusCode, header};
use chrono::Utc;
use migration::MigratorTrait;
use neiam_auth::password_reset::{Delivery, Mailer, OutgoingMail, ResetConfig};
use sea_orm::*;
use tokio::sync::mpsc::{UnboundedReceiver, unbounded_channel};
use tower::ServiceExt;
use uuid::Uuid;

use recourse::auth::password_reset::{router, service_with, service_with_mailer};
use recourse::auth::{self, LoginRequest};
use recourse::entities::{api_tokens, user_sessions, users};
use recourse::{AppState, Config};

static MIGRATED: tokio::sync::OnceCell<()> = tokio::sync::OnceCell::const_new();

async fn state() -> Option<AppState> {
    let url = std::env::var("TEST_DATABASE_URL").ok()?;
    let db = Database::connect(&url)
        .await
        .expect("connect to TEST_DATABASE_URL");
    MIGRATED
        .get_or_init(|| async {
            migration::Migrator::up(&db, None).await.expect("migrate");
        })
        .await;
    let mut config = Config::from_env();
    config.database_url = url;
    config.public_url = "https://forum.example".into();
    config.mail_prism_url = None;
    config.mail_prism_api_key = None;
    let config = Arc::new(config);
    Some(AppState {
        env: recourse::web::environment(&config),
        db: Arc::new(db),
        mailer: recourse::mailer::build(&config, false),
        config,
        view_throttle: recourse::new_view_throttle(),
        live: recourse::live::Hub::new(),
    })
}

fn cfg() -> ResetConfig {
    let mut c = ResetConfig::new("recourse", "https://forum.example");
    c.delivery = Delivery::Inline;
    c
}

fn app(state: &AppState) -> (Router, UnboundedReceiver<OutgoingMail>) {
    let (tx, rx) = unbounded_channel();
    (
        router(service_with_mailer(
            state.clone(),
            cfg(),
            Mailer::Channel(tx),
        )),
        rx,
    )
}

async fn user(state: &AppState) -> users::Model {
    let name = format!("reset-{}", &Uuid::now_v7().simple().to_string()[20..]);
    auth::create_user_direct(
        state.db.as_ref(),
        &name,
        &format!("{name}@Example.test"),
        "old-password-1",
        false,
    )
    .await
    .unwrap()
}

async fn send(app: &Router, req: Request<Body>) -> (StatusCode, axum::http::HeaderMap, String) {
    let resp = app.clone().oneshot(req).await.unwrap();
    let (status, headers) = (resp.status(), resp.headers().clone());
    let bytes = axum::body::to_bytes(resp.into_body(), 1 << 22)
        .await
        .unwrap();
    (status, headers, String::from_utf8(bytes.to_vec()).unwrap())
}

fn post(uri: &str, body: String) -> Request<Body> {
    Request::post(uri)
        .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
        .body(Body::from(body))
        .unwrap()
}

fn enc(s: &str) -> String {
    s.bytes()
        .map(|b| match b {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' => (b as char).to_string(),
            _ => format!("%{b:02X}"),
        })
        .collect()
}

fn token_in(mail: &OutgoingMail) -> String {
    let i = mail.text.find("?token=").expect("a link") + 7;
    mail.text[i..i + 43].to_string()
}

#[tokio::test]
async fn forgot_then_reset_signs_out_everywhere() {
    let Some(state) = state().await else { return };
    let (app, mut mail) = app(&state);
    let db = state.db.as_ref();
    let u = user(&state).await;
    let mut am: users::ActiveModel = u.clone().into();
    am.email_verified_at = Set(None);
    let u = am.update(db).await.unwrap();
    auth::create_session(db, u.id, 24).await.unwrap();
    auth::create_api_token(db, u.id, Some("phone".into()), None)
        .await
        .unwrap();

    let (s, _, page) = send(
        &app,
        Request::get("/password/forgot")
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(s, StatusCode::OK);
    assert!(page.contains("action=\"/password/forgot\""));

    let (s, _, page) = send(
        &app,
        post(
            "/password/forgot",
            format!("email={}", enc(&u.email.to_lowercase())),
        ),
    )
    .await;
    assert_eq!(s, StatusCode::OK);
    assert!(page.contains("data-reset-sent"));
    let m = mail.try_recv().expect("a reset mail");
    assert_eq!(m.to, u.email);
    assert!(
        m.text
            .contains("https://forum.example/password/reset?token=")
    );
    let token = token_in(&m);

    let (s, headers, page) = send(
        &app,
        Request::get(format!("/password/reset?token={token}"))
            .body(Body::empty())
            .unwrap(),
    )
    .await;
    assert_eq!(s, StatusCode::OK);
    assert_eq!(headers[header::REFERRER_POLICY], "no-referrer");
    assert!(page.contains(&format!("value=\"{token}\"")));

    // The 8-character rule; the token survives a refusal.
    let (s, _, page) = send(
        &app,
        post(
            "/password/reset",
            format!("token={token}&password=short&password_confirmation=short"),
        ),
    )
    .await;
    assert_eq!(s, StatusCode::UNPROCESSABLE_ENTITY);
    assert!(page.contains("data-reset-error"));

    let (s, headers, _) = send(
        &app,
        post(
            "/password/reset",
            format!("token={token}&password=brand-new-pw&password_confirmation=brand-new-pw"),
        ),
    )
    .await;
    assert_eq!(s, StatusCode::SEE_OTHER);
    assert_eq!(headers[header::LOCATION], "/login?reset=1");

    let ok = auth::authenticate_user(
        db,
        LoginRequest {
            username: u.username.clone(),
            password: "brand-new-pw".into(),
        },
    )
    .await
    .unwrap();
    assert_eq!(ok.as_ref().map(|x| x.id), Some(u.id));
    assert!(
        ok.unwrap().email_verified_at.is_some(),
        "the link proved the address"
    );
    let sessions = user_sessions::Entity::find()
        .filter(user_sessions::Column::UserId.eq(u.id))
        .count(db)
        .await
        .unwrap();
    let devices = api_tokens::Entity::find()
        .filter(api_tokens::Column::UserId.eq(u.id))
        .count(db)
        .await
        .unwrap();
    assert_eq!((sessions, devices), (0, 0));

    let (s, _, page) = send(
        &app,
        post(
            "/password/reset",
            format!("token={token}&password=another-pw-1&password_confirmation=another-pw-1"),
        ),
    )
    .await;
    assert_eq!(s, StatusCode::NOT_FOUND, "single use");
    assert!(page.contains("data-reset-invalid"));
}

#[tokio::test]
async fn the_answer_is_the_same_for_every_address() {
    let Some(state) = state().await else { return };
    let (app, mut mail) = app(&state);
    let db = state.db.as_ref();
    let active = user(&state).await;
    let off = user(&state).await;
    let mut am: users::ActiveModel = off.clone().into();
    am.is_active = Set(false);
    am.update(db).await.unwrap();
    let suspended = user(&state).await;
    let mut am: users::ActiveModel = suspended.clone().into();
    am.suspended_at = Set(Some(Utc::now().into()));
    am.update(db).await.unwrap();

    let ask = |email: &str| post("/password/forgot", format!("email={}", enc(email)));
    let (s0, _, known) = send(&app, ask(&active.email)).await;
    assert!(mail.try_recv().is_ok());
    let nobody = format!("nobody-{}@example.test", Uuid::now_v7().simple());
    for email in [
        off.email.as_str(),
        suspended.email.as_str(),
        nobody.as_str(),
    ] {
        let (s, _, page) = send(&app, ask(email)).await;
        assert_eq!((s, &page), (s0, &known), "{email}");
        assert!(mail.try_recv().is_err(), "no mail for {email}");
    }
}

/// The real wiring: the app's own mailer (the log transport here) and the
/// login page's link.
#[tokio::test]
async fn the_app_mailer_and_the_login_link() {
    let Some(state) = state().await else { return };
    let app = router::<()>(service_with(state.clone(), cfg()));
    let u = user(&state).await;
    let (s, _, _) = send(
        &app,
        post("/password/forgot", format!("email={}", enc(&u.email))),
    )
    .await;
    assert_eq!(s, StatusCode::OK);
    let rows = neiam_auth::sea_orm::password_reset::PasswordResetTokens::find()
        .filter(neiam_auth::sea_orm::password_reset::Column::UserId.eq(u.id))
        .count(state.db.as_ref())
        .await
        .unwrap();
    assert_eq!(rows, 1);

    let web = recourse::web::router(state.db.clone()).with_state(state.clone());
    let (_, _, login) = send(&web, Request::get("/login").body(Body::empty()).unwrap()).await;
    assert!(login.contains("data-forgot-password"));
    let (_, _, login) = send(
        &web,
        Request::get("/login?reset=1").body(Body::empty()).unwrap(),
    )
    .await;
    assert!(login.contains("data-reset-done"));
}