OXYGENHUB
◆ v0.5.1 oxygenhub / crates / hub / tests / recovery.rs
11.0 KiB · Rust · last changed Format the emoji subject lines 22 days 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
/// Each message written to `dir`, as a reader sees it: MIME's
87
/// quoted-printable soft breaks joined and `=3D` decoded (#182).
88
fn mail(dir: &Path) -> Vec<String> {
89
    let mut names: Vec<_> = std::fs::read_dir(dir).unwrap().flatten().map(|e| e.path()).collect();
90
    names.sort();
91
    names.iter().map(|p| std::fs::read_to_string(p).unwrap().replace("=\r\n", "").replace("=\n", "").replace("=3D", "=")).collect()
92
}
93
94
/// Mail is sent in the background for resets; wait for `n` messages.
95
async fn mail_count(dir: &Path, n: usize) -> Vec<String> {
96
    for _ in 0..100 {
97
        let m = mail(dir);
98
        if m.len() >= n {
99
            return m;
100
        }
101
        tokio::time::sleep(std::time::Duration::from_millis(20)).await;
102
    }
103
    mail(dir)
104
}
105
106
/// The path of the first `http://hub.test/…` link in a message.
107
fn link(message: &str, prefix: &str) -> String {
108
    let i = message.find(&format!("http://hub.test{prefix}")).expect("a link") + "http://hub.test".len();
109
    message[i..].split_whitespace().next().unwrap().to_string()
110
}
111
112
async fn account(app: &Shared, name: &str) -> db::accounts::Account {
113
    db::accounts::account_by_name(&app.db, name).await.unwrap().unwrap()
114
}
115
116
#[tokio::test(flavor = "multi_thread")]
117
async fn verification_and_reset() {
118
    let h = hub(true).await;
119
    let app = &h.app;
120
    let r = post(app, "/register", None, "username=andy&email=andy%40example.com&password=correct-horse-battery").await;
121
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
122
    let old_session = r.cookie.unwrap();
123
124
    // Registration sends a verification link; until it is used, no reset mail.
125
    let m = mail(&h.mailbox);
126
    assert_eq!(m.len(), 1);
127
    assert!(
128
        m[0].contains("To: andy <[email protected]>")
129
            && m[0].contains("Subject: [OxygenHub] =?utf-8?b?4pyJ77iP?= Confirm your email address"),
130
        "{}",
131
        m[0]
132
    );
133
    let verify = link(&m[0], "/verify/");
134
    assert!(!account(app, "andy").await.email_verified);
135
    let settings = get(app, "/settings", Some(&old_session)).await;
136
    assert!(settings.body.contains("Not verified yet") && settings.body.contains("send a new one"));
137
    let sent = post(app, "/login/reset", None, "who=andy").await;
138
    assert!(sent.body.contains("Check your email"));
139
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
140
    assert_eq!(mail(&h.mailbox).len(), 1, "no reset to an unverified address");
141
142
    // The link verifies once.
143
    assert!(get(app, &verify, None).await.body.contains("Email verified"));
144
    assert!(account(app, "andy").await.email_verified);
145
    assert!(get(app, &verify, None).await.body.contains("already used"), "single use");
146
    assert!(get(app, "/verify/00ff", None).await.body.contains("already used"));
147
148
    // Reset by verified email (any case); a second request within two minutes sends nothing.
149
    let unknown = post(app, "/login/reset", None, "who=nobody").await;
150
    let known = post(app, "/login/reset", None, "who=ANDY%40example.com").await;
151
    assert_eq!(unknown.body, known.body, "the answer does not reveal accounts");
152
    let m = mail_count(&h.mailbox, 2).await;
153
    assert_eq!(m.len(), 2);
154
    assert!(m[1].contains("Subject: [OxygenHub] =?utf-8?b?") && m[1].contains("?= Reset your password"), "an emoji, then the subject");
155
    let reset = link(&m[1], "/login/reset/");
156
    post(app, "/login/reset", None, "who=andy").await;
157
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
158
    assert_eq!(mail(&h.mailbox).len(), 2, "rate limited");
159
160
    // Choosing the new password: checks, then every session ends.
161
    let form = get(app, &reset, None).await;
162
    assert!(form.body.contains("Choose a new password") && form.body.contains("andy"));
163
    let differ = post(app, &reset, None, "password=new-password-long-enough&confirm=other-password-long").await;
164
    assert!(differ.body.contains("The two passwords differ"));
165
    let weak = post(app, &reset, None, "password=short&confirm=short").await;
166
    assert!(weak.body.contains("class=\"error\""), "password rules apply");
167
    let done = post(app, &reset, None, "password=new-password-long-enough&confirm=new-password-long-enough").await;
168
    assert_eq!((done.status, done.location.as_str()), (StatusCode::SEE_OTHER, "/login?reset=1"));
169
    assert!(get(app, "/login?reset=1", None).await.body.contains("Your password is set"));
170
    assert!(get(app, &reset, None).await.body.contains("expired or was already used"), "single use");
171
    let stale = get(app, "/settings", Some(&old_session)).await;
172
    assert!(stale.status.is_redirection() || !stale.body.contains("name=\"_csrf\""), "the old session ended");
173
    let wrong = post(app, "/login", None, "username=andy&password=correct-horse-battery").await;
174
    assert!(wrong.body.contains("Wrong username or password"));
175
    let signed = post(app, "/login", None, "username=andy&password=new-password-long-enough").await;
176
    assert_eq!(signed.status, StatusCode::SEE_OTHER);
177
    let session = signed.cookie.unwrap();
178
    let audit = db::accounts::audit_rows(&app.db, 50).await.unwrap();
179
    assert!(audit.iter().any(|a| a.action == "password.reset" && a.detail == "emailed link"));
180
181
    // Changing the email unverifies it; only the link for the current address counts.
182
    let page = get(app, "/settings", Some(&session)).await;
183
    let csrf = csrf_of(&page.body);
184
    let save = |email: &'static str| {
185
        let csrf = csrf.clone();
186
        let session = session.clone();
187
        async move {
188
            post(app, "/settings", Some(&session), &format!("_csrf={csrf}&display_name=Andy&email={email}&bio=&website=&location=")).await
189
        }
190
    };
191
    let saved = save("b%40example.com").await;
192
    assert!(saved.body.contains("A verification link is on its way to [email protected]"), "{}", saved.body);
193
    assert!(!account(app, "andy").await.email_verified);
194
    let to_b = link(mail(&h.mailbox).last().unwrap(), "/verify/");
195
    save("c%40example.com").await;
196
    let to_c = link(mail(&h.mailbox).last().unwrap(), "/verify/");
197
    assert!(get(app, &to_b, None).await.body.contains("no longer has"), "an old address's link does nothing");
198
    assert!(!account(app, "andy").await.email_verified);
199
    assert!(get(app, &to_c, None).await.body.contains("Email verified"));
200
    assert_eq!(account(app, "andy").await.email, "[email protected]");
201
    // A second link to the same address within two minutes is refused.
202
    save("d%40example.com").await;
203
    let again = post(app, "/settings/email/verify", Some(&session), &format!("_csrf={csrf}")).await;
204
    assert!(again.body.contains("less than two minutes ago"), "{}", again.body);
205
206
    // An administrator's link, for an account without a verified email.
207
    post(app, "/register", None, "username=bob&email=&password=bob-password-long-enough").await;
208
    let admin = get(app, "/admin", Some(&session)).await;
209
    assert!(admin.body.contains("value=\"reset_link\""));
210
    let r = post(app, "/admin/account", Some(&session), &format!("_csrf={}&username=bob&action=reset_link", csrf_of(&admin.body))).await;
211
    assert!(r.body.contains("Reset link for bob"), "{}", r.body);
212
    let i = r.body.find("http://hub.test/login/reset/").unwrap() + "http://hub.test".len();
213
    let bob_link: String = r.body[i..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '/').collect();
214
    assert_eq!(post(app, &bob_link, None, "password=bob-new-password-ok&confirm=bob-new-password-ok").await.location, "/login?reset=1");
215
    let audit = db::accounts::audit_rows(&app.db, 50).await.unwrap();
216
    assert!(audit.iter().any(|a| a.action == "admin.account.reset_link" && a.target == "bob"));
217
    assert!(audit.iter().any(|a| a.action == "password.reset" && a.target == "bob" && a.detail == "administrator's link"));
218
}
219
220
#[tokio::test(flavor = "multi_thread")]
221
async fn without_mail_an_administrator_resets() {
222
    let h = hub(false).await;
223
    let page = get(&h.app, "/login/reset", None).await;
224
    assert!(page.body.contains("does not send email") && !page.body.contains("SEND A RESET LINK"));
225
    let sent = post(&h.app, "/login/reset", None, "who=andy").await;
226
    assert!(!sent.body.contains("Check your email"));
227
    assert!(get(&h.app, "/login", None).await.body.contains("href=\"/login/reset\""));
228
}