OXYGENHUB
◆ v0.1.0 oxygenhub / crates / hub / tests / recovery.rs
10.7 KiB · Rust · last changed Password reset and email verification: single-use hashed links, reset by verified email or an administrator's link, verification on every address change, notification mail only to verified addresses, and a file:// mail transport for development 1 month ago source blame history raw
1
//! Email verification and password reset (hub spec §5.1.1), with mail
2
//! written to a directory (`file://`) so the test reads what was sent.
3
4
use axum::body::Body;
5
use axum::http::{header, Request, StatusCode};
6
use http_body_util::BodyExt;
7
use oxygenhub::config::Config;
8
use oxygenhub::{db, Shared};
9
use std::path::{Path, PathBuf};
10
use tower::ServiceExt;
11
12
fn hermetic() {
13
    static ONCE: std::sync::Once = std::sync::Once::new();
14
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
15
    ONCE.call_once(|| {
16
        let d = tempfile::tempdir().unwrap();
17
        std::env::set_var("OXY_HOME", d.path());
18
        DIR.set(d).ok();
19
    });
20
}
21
22
struct Hub {
23
    app: Shared,
24
    mailbox: PathBuf,
25
    _dir: tempfile::TempDir,
26
}
27
28
async fn hub(mail: bool) -> Hub {
29
    hermetic();
30
    let dir = tempfile::tempdir().unwrap();
31
    let mailbox = dir.path().join("mailbox");
32
    std::fs::create_dir_all(&mailbox).unwrap();
33
    let mut config = Config::load(dir.path()).unwrap();
34
    config.server.base_url = "http://hub.test".into();
35
    config.registration.mode = "open".into();
36
    if mail {
37
        config.email.smtp = format!("file://{}", mailbox.display());
38
        config.email.from = "OxygenHub <[email protected]>".into();
39
    }
40
    let app = oxygenhub::build(config).await.unwrap();
41
    Hub { app, mailbox, _dir: dir }
42
}
43
44
struct Res {
45
    status: StatusCode,
46
    body: String,
47
    cookie: Option<String>,
48
    location: String,
49
}
50
51
async fn send(app: &Shared, method: &str, path: &str, cookie: Option<&str>, form: Option<&str>) -> Res {
52
    let mut req = Request::builder().method(method).uri(path);
53
    if let Some(c) = cookie {
54
        req = req.header(header::COOKIE, format!("oxyhub={c}"));
55
    }
56
    let body = match form {
57
        Some(f) => {
58
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
59
            Body::from(f.to_string())
60
        }
61
        None => Body::empty(),
62
    };
63
    let res = oxygenhub::router(app.clone()).oneshot(req.body(body).unwrap()).await.unwrap();
64
    let status = res.status();
65
    let h = |k| res.headers().get(k).and_then(|v: &axum::http::HeaderValue| v.to_str().ok()).map(String::from);
66
    let cookie = h(header::SET_COOKIE).and_then(|v| v.split(';').next().and_then(|kv| kv.split_once('=')).map(|(_, v)| v.to_string()));
67
    let location = h(header::LOCATION).unwrap_or_default();
68
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
69
    Res { status, body: String::from_utf8_lossy(&bytes).into_owned(), cookie, location }
70
}
71
72
async fn get(app: &Shared, path: &str, cookie: Option<&str>) -> Res {
73
    send(app, "GET", path, cookie, None).await
74
}
75
76
async fn post(app: &Shared, path: &str, cookie: Option<&str>, form: &str) -> Res {
77
    send(app, "POST", path, cookie, Some(form)).await
78
}
79
80
fn csrf_of(page: &str) -> String {
81
    let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
82
    page[i..].split('"').next().unwrap().to_string()
83
}
84
85
/// Every message so far, oldest first, as text.
86
fn mail(dir: &Path) -> Vec<String> {
87
    let mut names: Vec<_> = std::fs::read_dir(dir).unwrap().flatten().map(|e| e.path()).collect();
88
    names.sort();
89
    names.iter().map(|p| std::fs::read_to_string(p).unwrap()).collect()
90
}
91
92
/// Mail is sent in the background for resets; wait for `n` messages.
93
async fn mail_count(dir: &Path, n: usize) -> Vec<String> {
94
    for _ in 0..100 {
95
        let m = mail(dir);
96
        if m.len() >= n {
97
            return m;
98
        }
99
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
100
    }
101
    mail(dir)
102
}
103
104
/// The path of the first `http://hub.test/…` link in a message.
105
fn link(message: &str, prefix: &str) -> String {
106
    let i = message.find(&format!("http://hub.test{prefix}")).expect("a link") + "http://hub.test".len();
107
    message[i..].split_whitespace().next().unwrap().to_string()
108
}
109
110
async fn account(app: &Shared, name: &str) -> db::accounts::Account {
111
    db::accounts::account_by_name(&app.db, name).await.unwrap().unwrap()
112
}
113
114
#[tokio::test(flavor = "multi_thread")]
115
async fn verification_and_reset() {
116
    let h = hub(true).await;
117
    let app = &h.app;
118
    let r = post(app, "/register", None, "username=andy&email=andy%40example.com&password=correct-horse-battery").await;
119
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
120
    let old_session = r.cookie.unwrap();
121
122
    // Registration sends a verification link; until it is used, no reset mail.
123
    let m = mail(&h.mailbox);
124
    assert_eq!(m.len(), 1);
125
    assert!(m[0].contains("To: andy <[email protected]>") && m[0].contains("Subject: [OxygenHub] Confirm your email address"), "{}", m[0]);
126
    let verify = link(&m[0], "/verify/");
127
    assert!(!account(app, "andy").await.email_verified);
128
    let settings = get(app, "/settings", Some(&old_session)).await;
129
    assert!(settings.body.contains("Not verified yet") && settings.body.contains("send a new one"));
130
    let sent = post(app, "/login/reset", None, "who=andy").await;
131
    assert!(sent.body.contains("Check your email"));
132
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
133
    assert_eq!(mail(&h.mailbox).len(), 1, "no reset to an unverified address");
134
135
    // The link verifies once.
136
    assert!(get(app, &verify, None).await.body.contains("Email verified"));
137
    assert!(account(app, "andy").await.email_verified);
138
    assert!(get(app, &verify, None).await.body.contains("already used"), "single use");
139
    assert!(get(app, "/verify/00ff", None).await.body.contains("already used"));
140
141
    // Reset by verified email (any case); a second request within two minutes sends nothing.
142
    let unknown = post(app, "/login/reset", None, "who=nobody").await;
143
    let known = post(app, "/login/reset", None, "who=ANDY%40example.com").await;
144
    assert_eq!(unknown.body, known.body, "the answer does not reveal accounts");
145
    let m = mail_count(&h.mailbox, 2).await;
146
    assert_eq!(m.len(), 2);
147
    assert!(m[1].contains("Subject: [OxygenHub] Reset your password"));
148
    let reset = link(&m[1], "/login/reset/");
149
    post(app, "/login/reset", None, "who=andy").await;
150
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
151
    assert_eq!(mail(&h.mailbox).len(), 2, "rate limited");
152
153
    // Choosing the new password: checks, then every session ends.
154
    let form = get(app, &reset, None).await;
155
    assert!(form.body.contains("Choose a new password") && form.body.contains("andy"));
156
    let differ = post(app, &reset, None, "password=new-password-long-enough&confirm=other-password-long").await;
157
    assert!(differ.body.contains("The two passwords differ"));
158
    let weak = post(app, &reset, None, "password=short&confirm=short").await;
159
    assert!(weak.body.contains("class=\"error\""), "password rules apply");
160
    let done = post(app, &reset, None, "password=new-password-long-enough&confirm=new-password-long-enough").await;
161
    assert_eq!((done.status, done.location.as_str()), (StatusCode::SEE_OTHER, "/login?reset=1"));
162
    assert!(get(app, "/login?reset=1", None).await.body.contains("Your password is set"));
163
    assert!(get(app, &reset, None).await.body.contains("expired or was already used"), "single use");
164
    let stale = get(app, "/settings", Some(&old_session)).await;
165
    assert!(stale.status.is_redirection() || !stale.body.contains("name=\"_csrf\""), "the old session ended");
166
    let wrong = post(app, "/login", None, "username=andy&password=correct-horse-battery").await;
167
    assert!(wrong.body.contains("Wrong username or password"));
168
    let signed = post(app, "/login", None, "username=andy&password=new-password-long-enough").await;
169
    assert_eq!(signed.status, StatusCode::SEE_OTHER);
170
    let session = signed.cookie.unwrap();
171
    let audit = db::accounts::audit_rows(&app.db, 50).await.unwrap();
172
    assert!(audit.iter().any(|a| a.action == "password.reset" && a.detail == "emailed link"));
173
174
    // Changing the email unverifies it; only the link for the current address counts.
175
    let page = get(app, "/settings", Some(&session)).await;
176
    let csrf = csrf_of(&page.body);
177
    let save = |email: &'static str| {
178
        let csrf = csrf.clone();
179
        let session = session.clone();
180
        async move {
181
            post(app, "/settings", Some(&session), &format!("_csrf={csrf}&display_name=Andy&email={email}&bio=&website=&location=")).await
182
        }
183
    };
184
    let saved = save("b%40example.com").await;
185
    assert!(saved.body.contains("A verification link is on its way to [email protected]"), "{}", saved.body);
186
    assert!(!account(app, "andy").await.email_verified);
187
    let to_b = link(mail(&h.mailbox).last().unwrap(), "/verify/");
188
    save("c%40example.com").await;
189
    let to_c = link(mail(&h.mailbox).last().unwrap(), "/verify/");
190
    assert!(get(app, &to_b, None).await.body.contains("no longer has"), "an old address's link does nothing");
191
    assert!(!account(app, "andy").await.email_verified);
192
    assert!(get(app, &to_c, None).await.body.contains("Email verified"));
193
    assert_eq!(account(app, "andy").await.email, "[email protected]");
194
    // A second link to the same address within two minutes is refused.
195
    save("d%40example.com").await;
196
    let again = post(app, "/settings/email/verify", Some(&session), &format!("_csrf={csrf}")).await;
197
    assert!(again.body.contains("less than two minutes ago"), "{}", again.body);
198
199
    // An administrator's link, for an account without a verified email.
200
    post(app, "/register", None, "username=bob&email=&password=bob-password-long-enough").await;
201
    let admin = get(app, "/admin", Some(&session)).await;
202
    assert!(admin.body.contains("value=\"reset_link\""));
203
    let r = post(app, "/admin/account", Some(&session), &format!("_csrf={}&username=bob&action=reset_link", csrf_of(&admin.body))).await;
204
    assert!(r.body.contains("Reset link for bob"), "{}", r.body);
205
    let i = r.body.find("http://hub.test/login/reset/").unwrap() + "http://hub.test".len();
206
    let bob_link: String = r.body[i..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '/').collect();
207
    assert_eq!(post(app, &bob_link, None, "password=bob-new-password-ok&confirm=bob-new-password-ok").await.location, "/login?reset=1");
208
    let audit = db::accounts::audit_rows(&app.db, 50).await.unwrap();
209
    assert!(audit.iter().any(|a| a.action == "admin.account.reset_link" && a.target == "bob"));
210
    assert!(audit.iter().any(|a| a.action == "password.reset" && a.target == "bob" && a.detail == "administrator's link"));
211
}
212
213
#[tokio::test(flavor = "multi_thread")]
214
async fn without_mail_an_administrator_resets() {
215
    let h = hub(false).await;
216
    let page = get(&h.app, "/login/reset", None).await;
217
    assert!(page.body.contains("does not send email") && !page.body.contains("SEND A RESET LINK"));
218
    let sent = post(&h.app, "/login/reset", None, "who=andy").await;
219
    assert!(!sent.body.contains("Check your email"));
220
    assert!(get(&h.app, "/login", None).await.body.contains("href=\"/login/reset\""));
221
}