OXYGENHUB
# 7dbb41b09a99 oxygenhub / crates / hub / tests / recovery.rs
10.8 KiB · Rust · last changed A new hub gives administrator only to whoever brings its setup code 20 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
    // The first account's setup code (oxygenhub#245).
35
    config.registration.setup_code = "test-setup".into();
36
    config.server.base_url = "http://hub.test".into();
37
    config.registration.mode = "open".into();
38
    if mail {
39
        config.email.smtp = format!("file://{}", mailbox.display());
40
        config.email.from = "OxygenHub <[email protected]>".into();
41
    }
42
    let app = oxygenhub::build(config).await.unwrap();
43
    Hub { app, mailbox, _dir: dir }
44
}
45
46
struct Res {
47
    status: StatusCode,
48
    body: String,
49
    cookie: Option<String>,
50
    location: String,
51
}
52
53
async fn send(app: &Shared, method: &str, path: &str, cookie: Option<&str>, form: Option<&str>) -> Res {
54
    let mut req = Request::builder().method(method).uri(path);
55
    if let Some(c) = cookie {
56
        req = req.header(header::COOKIE, format!("oxyhub={c}"));
57
    }
58
    let body = match form {
59
        Some(f) => {
60
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
61
            Body::from(f.to_string())
62
        }
63
        None => Body::empty(),
64
    };
65
    let res = oxygenhub::router(app.clone()).oneshot(req.body(body).unwrap()).await.unwrap();
66
    let status = res.status();
67
    let h = |k| res.headers().get(k).and_then(|v: &axum::http::HeaderValue| v.to_str().ok()).map(String::from);
68
    let cookie = h(header::SET_COOKIE).and_then(|v| v.split(';').next().and_then(|kv| kv.split_once('=')).map(|(_, v)| v.to_string()));
69
    let location = h(header::LOCATION).unwrap_or_default();
70
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
71
    Res { status, body: String::from_utf8_lossy(&bytes).into_owned(), cookie, location }
72
}
73
74
async fn get(app: &Shared, path: &str, cookie: Option<&str>) -> Res {
75
    send(app, "GET", path, cookie, None).await
76
}
77
78
async fn post(app: &Shared, path: &str, cookie: Option<&str>, form: &str) -> Res {
79
    send(app, "POST", path, cookie, Some(form)).await
80
}
81
82
fn csrf_of(page: &str) -> String {
83
    let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
84
    page[i..].split('"').next().unwrap().to_string()
85
}
86
87
/// Every message so far, oldest first, as text.
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()).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&setup=test-setup").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!(m[0].contains("To: andy <[email protected]>") && m[0].contains("Subject: [OxygenHub] Confirm your email address"), "{}", m[0]);
128
    let verify = link(&m[0], "/verify/");
129
    assert!(!account(app, "andy").await.email_verified);
130
    let settings = get(app, "/settings", Some(&old_session)).await;
131
    assert!(settings.body.contains("Not verified yet") && settings.body.contains("send a new one"));
132
    let sent = post(app, "/login/reset", None, "who=andy").await;
133
    assert!(sent.body.contains("Check your email"));
134
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
135
    assert_eq!(mail(&h.mailbox).len(), 1, "no reset to an unverified address");
136
137
    // The link verifies once.
138
    assert!(get(app, &verify, None).await.body.contains("Email verified"));
139
    assert!(account(app, "andy").await.email_verified);
140
    assert!(get(app, &verify, None).await.body.contains("already used"), "single use");
141
    assert!(get(app, "/verify/00ff", None).await.body.contains("already used"));
142
143
    // Reset by verified email (any case); a second request within two minutes sends nothing.
144
    let unknown = post(app, "/login/reset", None, "who=nobody").await;
145
    let known = post(app, "/login/reset", None, "who=ANDY%40example.com").await;
146
    assert_eq!(unknown.body, known.body, "the answer does not reveal accounts");
147
    let m = mail_count(&h.mailbox, 2).await;
148
    assert_eq!(m.len(), 2);
149
    assert!(m[1].contains("Subject: [OxygenHub] Reset your password"));
150
    let reset = link(&m[1], "/login/reset/");
151
    post(app, "/login/reset", None, "who=andy").await;
152
    tokio::time::sleep(std::time::Duration::from_millis(200)).await;
153
    assert_eq!(mail(&h.mailbox).len(), 2, "rate limited");
154
155
    // Choosing the new password: checks, then every session ends.
156
    let form = get(app, &reset, None).await;
157
    assert!(form.body.contains("Choose a new password") && form.body.contains("andy"));
158
    let differ = post(app, &reset, None, "password=new-password-long-enough&confirm=other-password-long").await;
159
    assert!(differ.body.contains("The two passwords differ"));
160
    let weak = post(app, &reset, None, "password=short&confirm=short").await;
161
    assert!(weak.body.contains("class=\"error\""), "password rules apply");
162
    let done = post(app, &reset, None, "password=new-password-long-enough&confirm=new-password-long-enough").await;
163
    assert_eq!((done.status, done.location.as_str()), (StatusCode::SEE_OTHER, "/login?reset=1"));
164
    assert!(get(app, "/login?reset=1", None).await.body.contains("Your password is set"));
165
    assert!(get(app, &reset, None).await.body.contains("expired or was already used"), "single use");
166
    let stale = get(app, "/settings", Some(&old_session)).await;
167
    assert!(stale.status.is_redirection() || !stale.body.contains("name=\"_csrf\""), "the old session ended");
168
    let wrong = post(app, "/login", None, "username=andy&password=correct-horse-battery&setup=test-setup").await;
169
    assert!(wrong.body.contains("Wrong username or password"));
170
    let signed = post(app, "/login", None, "username=andy&password=new-password-long-enough").await;
171
    assert_eq!(signed.status, StatusCode::SEE_OTHER);
172
    let session = signed.cookie.unwrap();
173
    let audit = db::accounts::audit_rows(&app.db, 50).await.unwrap();
174
    assert!(audit.iter().any(|a| a.action == "password.reset" && a.detail == "emailed link"));
175
176
    // Changing the email unverifies it; only the link for the current address counts.
177
    let page = get(app, "/settings", Some(&session)).await;
178
    let csrf = csrf_of(&page.body);
179
    let save = |email: &'static str| {
180
        let csrf = csrf.clone();
181
        let session = session.clone();
182
        async move {
183
            post(app, "/settings", Some(&session), &format!("_csrf={csrf}&display_name=Andy&email={email}&bio=&website=&location=")).await
184
        }
185
    };
186
    let saved = save("b%40example.com").await;
187
    assert!(saved.body.contains("A verification link is on its way to [email protected]"), "{}", saved.body);
188
    assert!(!account(app, "andy").await.email_verified);
189
    let to_b = link(mail(&h.mailbox).last().unwrap(), "/verify/");
190
    save("c%40example.com").await;
191
    let to_c = link(mail(&h.mailbox).last().unwrap(), "/verify/");
192
    assert!(get(app, &to_b, None).await.body.contains("no longer has"), "an old address's link does nothing");
193
    assert!(!account(app, "andy").await.email_verified);
194
    assert!(get(app, &to_c, None).await.body.contains("Email verified"));
195
    assert_eq!(account(app, "andy").await.email, "[email protected]");
196
    // A second link to the same address within two minutes is refused.
197
    save("d%40example.com").await;
198
    let again = post(app, "/settings/email/verify", Some(&session), &format!("_csrf={csrf}")).await;
199
    assert!(again.body.contains("less than two minutes ago"), "{}", again.body);
200
201
    // An administrator's link, for an account without a verified email.
202
    post(app, "/register", None, "username=bob&email=&password=bob-password-long-enough&setup=test-setup").await;
203
    let admin = get(app, "/admin", Some(&session)).await;
204
    assert!(admin.body.contains("value=\"reset_link\""));
205
    let r = post(app, "/admin/account", Some(&session), &format!("_csrf={}&username=bob&action=reset_link", csrf_of(&admin.body))).await;
206
    assert!(r.body.contains("Reset link for bob"), "{}", r.body);
207
    let i = r.body.find("http://hub.test/login/reset/").unwrap() + "http://hub.test".len();
208
    let bob_link: String = r.body[i..].chars().take_while(|c| c.is_ascii_alphanumeric() || *c == '/').collect();
209
    assert_eq!(post(app, &bob_link, None, "password=bob-new-password-ok&confirm=bob-new-password-ok").await.location, "/login?reset=1");
210
    let audit = db::accounts::audit_rows(&app.db, 50).await.unwrap();
211
    assert!(audit.iter().any(|a| a.action == "admin.account.reset_link" && a.target == "bob"));
212
    assert!(audit.iter().any(|a| a.action == "password.reset" && a.target == "bob" && a.detail == "administrator's link"));
213
}
214
215
#[tokio::test(flavor = "multi_thread")]
216
async fn without_mail_an_administrator_resets() {
217
    let h = hub(false).await;
218
    let page = get(&h.app, "/login/reset", None).await;
219
    assert!(page.body.contains("does not send email") && !page.body.contains("SEND A RESET LINK"));
220
    let sent = post(&h.app, "/login/reset", None, "who=andy").await;
221
    assert!(!sent.body.contains("Check your email"));
222
    assert!(get(&h.app, "/login", None).await.body.contains("href=\"/login/reset\""));
223
}