OXYGENHUB
# 705d11b01a2c oxygenhub / crates / hub / tests / accounts.rs
15.1 KiB · Rust · last changed Milestone 0.2: accounts and access 1 month ago source blame history raw
1
//! Milestone 0.2 end to end: registration, sessions, tokens, roles and
2
//! visibility, linked identities with attribution, organisations.
3
4
use axum::body::Body;
5
use axum::http::{header, Request, StatusCode};
6
use http_body_util::BodyExt;
7
use oxy_core::repo::Repo;
8
use oxygenhub::config::Config;
9
use oxygenhub::db;
10
use oxygenhub::Shared;
11
use std::path::Path;
12
use tower::ServiceExt;
13
14
fn hermetic() {
15
    static ONCE: std::sync::Once = std::sync::Once::new();
16
    static DIR: std::sync::OnceLock<tempfile::TempDir> = std::sync::OnceLock::new();
17
    ONCE.call_once(|| {
18
        let d = tempfile::tempdir().unwrap();
19
        std::env::set_var("OXY_HOME", d.path());
20
        DIR.set(d).ok();
21
    });
22
}
23
24
fn write(root: &Path, rel: &str, content: &[u8]) {
25
    let p = root.join(rel);
26
    std::fs::create_dir_all(p.parent().unwrap()).unwrap();
27
    std::fs::write(p, content).unwrap();
28
}
29
30
struct Hub {
31
    app: Shared,
32
    base: String,
33
    _dir: tempfile::TempDir,
34
}
35
36
async fn hub() -> Hub {
37
    hermetic();
38
    let dir = tempfile::tempdir().unwrap();
39
    let mut config = Config::load(dir.path()).unwrap();
40
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
41
    let port = listener.local_addr().unwrap().port();
42
    config.server.base_url = format!("http://127.0.0.1:{port}");
43
    config.registration.mode = "invite".into();
44
    let app = oxygenhub::build(config).await.unwrap();
45
    let router = oxygenhub::router(app.clone());
46
    tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
47
    Hub { app, base: format!("http://127.0.0.1:{port}"), _dir: dir }
48
}
49
50
struct Res {
51
    status: StatusCode,
52
    body: String,
53
    cookie: Option<String>,
54
    location: Option<String>,
55
}
56
57
async fn send(app: &Shared, method: &str, path: &str, cookie: Option<&str>, form: Option<&str>) -> Res {
58
    let mut req = Request::builder().method(method).uri(path);
59
    if let Some(c) = cookie {
60
        req = req.header(header::COOKIE, format!("oxyhub={c}"));
61
    }
62
    let body = match form {
63
        Some(f) => {
64
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
65
            Body::from(f.to_string())
66
        }
67
        None => Body::empty(),
68
    };
69
    let res = oxygenhub::router(app.clone()).oneshot(req.body(body).unwrap()).await.unwrap();
70
    let status = res.status();
71
    let cookie = res
72
        .headers()
73
        .get(header::SET_COOKIE)
74
        .and_then(|v| v.to_str().ok())
75
        .and_then(|v| v.split(';').next())
76
        .and_then(|kv| kv.split_once('='))
77
        .map(|(_, v)| v.to_string());
78
    let location = res.headers().get(header::LOCATION).and_then(|v| v.to_str().ok()).map(String::from);
79
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
80
    Res { status, body: String::from_utf8_lossy(&bytes).into_owned(), cookie, location }
81
}
82
83
async fn get(app: &Shared, path: &str, cookie: Option<&str>) -> Res {
84
    send(app, "GET", path, cookie, None).await
85
}
86
87
async fn post(app: &Shared, path: &str, cookie: Option<&str>, form: &str) -> Res {
88
    send(app, "POST", path, cookie, Some(form)).await
89
}
90
91
/// Register (or sign in) and return the session cookie value.
92
async fn register(app: &Shared, user: &str, invite: &str) -> String {
93
    let r =
94
        post(app, "/register", None, &format!("username={user}&email={user}%40example.com&password=correct-horse-battery&invite={invite}"))
95
            .await;
96
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
97
    r.cookie.expect("session cookie")
98
}
99
100
fn csrf_of(page: &str) -> String {
101
    let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
102
    page[i..].split('"').next().unwrap().to_string()
103
}
104
105
#[tokio::test(flavor = "multi_thread")]
106
async fn accounts_roles_tokens_and_attribution() {
107
    let h = hub().await;
108
    let app = &h.app;
109
110
    // The first account registers without an invitation and is the administrator.
111
    let andy = register(app, "andy", "").await;
112
    let me = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
113
    assert!(me.is_admin);
114
    // A second registration needs an invitation.
115
    let r = post(app, "/register", None, "username=mallory&email=m%40example.com&password=correct-horse-battery&invite=").await;
116
    assert_eq!(r.status, StatusCode::OK);
117
    assert!(r.body.contains("invitation"), "{}", r.body);
118
    let admin_page = get(app, "/admin", Some(&andy)).await;
119
    assert_eq!(admin_page.status, StatusCode::OK);
120
    let csrf = csrf_of(&admin_page.body);
121
    let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={csrf}")).await;
122
    let code = r.body.split("register?invite=").nth(1).unwrap().split('<').next().unwrap().trim().to_string();
123
    let bob = register(app, "bob", &code).await;
124
    assert!(!db::accounts::account_by_name(&app.db, "bob").await.unwrap().unwrap().is_admin);
125
    // Wrong password, banned users and CSRF-less posts are refused.
126
    assert_eq!(post(app, "/login", None, "username=andy&password=nope").await.status, StatusCode::OK);
127
    assert_eq!(post(app, "/settings", Some(&andy), "_csrf=bogus&display_name=x&email=y").await.status, StatusCode::BAD_REQUEST);
128
    assert_eq!(get(app, "/settings", None).await.status, StatusCode::SEE_OTHER, "anonymous settings redirects to sign in");
129
130
    // Andy creates a private repository through the form; Bob cannot see it.
131
    let new_page = get(app, "/new", Some(&andy)).await;
132
    let csrf = csrf_of(&new_page.body);
133
    let r = post(app, "/new", Some(&andy), &format!("_csrf={csrf}&owner=andy&name=secret&description=hush&visibility=private")).await;
134
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
135
    assert_eq!(get(app, "/andy/secret", Some(&andy)).await.status, StatusCode::OK);
136
    assert_eq!(get(app, "/andy/secret", Some(&bob)).await.status, StatusCode::NOT_FOUND);
137
    assert_eq!(get(app, "/andy/secret", None).await.status, StatusCode::NOT_FOUND);
138
    assert!(!get(app, "/", Some(&bob)).await.body.contains("secret"));
139
    assert!(get(app, "/", Some(&andy)).await.body.contains("secret"));
140
141
    // Tokens: a read-only token cannot push; a write token can. Anonymous cannot read a private repository.
142
    let tokens_page = get(app, "/settings/tokens", Some(&andy)).await;
143
    let csrf = csrf_of(&tokens_page.body);
144
    let r = post(app, "/settings/tokens", Some(&andy), &format!("_csrf={csrf}&name=ro&scopes=repo%3Aread")).await;
145
    let ro = r.body.split("oxyhub_").nth(1).map(|s| format!("oxyhub_{}", s.split('<').next().unwrap().trim())).unwrap();
146
    let r = post(app, "/settings/tokens", Some(&andy), &format!("_csrf={csrf}&name=rw&scopes=repo%3Aread&scopes=repo%3Awrite")).await;
147
    let rw = r.body.split("oxyhub_").nth(1).map(|s| format!("oxyhub_{}", s.split('<').next().unwrap().trim())).unwrap();
148
    let work = tempfile::tempdir().unwrap();
149
    let mut client = Repo::init(work.path()).unwrap();
150
    client.create_identity("Andy McCall", "[email protected]", oxy_core::repo::IdentityScope::User).unwrap();
151
    client.config.set("remote.origin.url", &format!("{}/andy/secret", h.base)).unwrap();
152
    client.config.set("core.sign", "change").unwrap();
153
    client.save_config().unwrap();
154
    write(work.path(), "a.txt", b"a\n");
155
    client.snapshot("t").unwrap();
156
    let c1 = client.commit("first", &[]).unwrap();
157
    let err = client.push("origin", false).err().unwrap().to_string();
158
    assert!(err.contains("404"), "anonymous cannot even see it: {err}");
159
    client.config.set("remote.origin.token", &ro).unwrap();
160
    let err = client.push("origin", false).err().unwrap().to_string();
161
    assert!(err.contains("403"), "read-only token cannot push: {err}");
162
    client.config.set("remote.origin.token", &rw).unwrap();
163
    assert!(client.push("origin", false).unwrap().iter().all(|r| r.ok));
164
    // Bob's token cannot read it either.
165
    let bob_tokens = get(app, "/settings/tokens", Some(&bob)).await;
166
    let csrf_b = csrf_of(&bob_tokens.body);
167
    let r = post(app, "/settings/tokens", Some(&bob), &format!("_csrf={csrf_b}&name=b&scopes=repo%3Aread&scopes=repo%3Awrite")).await;
168
    let bob_tok = r.body.split("oxyhub_").nth(1).map(|s| format!("oxyhub_{}", s.split('<').next().unwrap().trim())).unwrap();
169
    std::env::set_var("OXY_TOKEN", &bob_tok);
170
    let err = Repo::clone(&format!("{}/andy/secret", h.base), &work.path().join("bobclone")).err().unwrap().to_string();
171
    std::env::remove_var("OXY_TOKEN");
172
    assert!(err.contains("404"), "{err}");
173
    // The push log names the pusher.
174
    tokio::time::sleep(std::time::Duration::from_millis(150)).await;
175
    let pushes = get(app, "/andy/secret/pushes", Some(&andy)).await.body;
176
    assert!(pushes.contains("andy"), "{pushes}");
177
178
    // Bob becomes a collaborator with write, and can then see and push.
179
    let settings = get(app, "/andy/secret/settings", Some(&andy)).await;
180
    assert_eq!(settings.status, StatusCode::OK);
181
    let csrf = csrf_of(&settings.body);
182
    let r = post(app, "/andy/secret/settings/collaborators", Some(&andy), &format!("_csrf={csrf}&username=bob&role=write")).await;
183
    assert_eq!(r.status, StatusCode::OK, "{}", r.body);
184
    assert_eq!(get(app, "/andy/secret", Some(&bob)).await.status, StatusCode::OK);
185
    assert_eq!(get(app, "/andy/secret/settings", Some(&bob)).await.status, StatusCode::NOT_FOUND, "write is not maintain");
186
    std::env::set_var("OXY_TOKEN", &bob_tok);
187
    let ok = Repo::clone(&format!("{}/andy/secret", h.base), &work.path().join("bobclone2")).is_ok();
188
    std::env::remove_var("OXY_TOKEN");
189
    assert!(ok);
190
191
    // Linking a key: upload the identity, sign the challenge, see attribution.
192
    let (key, identity) = {
193
        let k = client.config.author_key.unwrap();
194
        (k, client.identity(&k).unwrap())
195
    };
196
    let keys_page = get(app, "/settings/keys", Some(&andy)).await;
197
    let csrf = csrf_of(&keys_page.body);
198
    let boundary = "XYZ";
199
    let mut multipart = Vec::new();
200
    multipart.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"_csrf\"\r\n\r\n{csrf}\r\n").as_bytes());
201
    multipart.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"identity\"; filename=\"me.identity\"\r\nContent-Type: application/octet-stream\r\n\r\n").as_bytes());
202
    multipart.extend_from_slice(&identity.encode());
203
    multipart.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
204
    let req = Request::builder()
205
        .method("POST")
206
        .uri("/settings/keys/upload")
207
        .header(header::COOKIE, format!("oxyhub={andy}"))
208
        .header(header::CONTENT_TYPE, format!("multipart/form-data; boundary={boundary}"))
209
        .body(Body::from(multipart))
210
        .unwrap();
211
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
212
    assert_eq!(res.status(), StatusCode::OK);
213
    let body = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
214
    let challenge_hex = body.split("sign-challenge ").nth(1).unwrap().split('<').next().unwrap().trim().to_string();
215
    let challenge_id = body.split("name=\"challenge\" value=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
216
    let (_, sk) = client.secret_key().unwrap().unwrap();
217
    let sig = sk.sign_challenge(&key, &hex::decode(&challenge_hex).unwrap()).unwrap();
218
    let sig_hex = hex::encode(oxy_core::identity::Signature::encode_list(&[sig]));
219
    let r = post(app, "/settings/keys/verify", Some(&andy), &format!("_csrf={csrf}&challenge={challenge_id}&signature={sig_hex}")).await;
220
    assert!(r.body.contains("Key linked"), "{}", r.body);
221
    let hist = get(app, "/andy/secret/changes/main", Some(&andy)).await.body;
222
    assert!(hist.contains("href=\"/andy\">Andy McCall</a>"), "author linked to the account: {hist}");
223
    let change = get(app, &format!("/andy/secret/change/{}", c1.to_hex()), Some(&andy)).await.body;
224
    assert!(change.contains("@andy"), "{change}");
225
    // A forged signature is refused.
226
    let r = post(app, "/settings/keys/verify", Some(&andy), &format!("_csrf={csrf}&challenge=999&signature={sig_hex}")).await;
227
    assert!(r.body.contains("expired"), "{}", r.body);
228
229
    // Organisations: a private org repository is visible to members through the default role.
230
    let org_page = get(app, "/orgs/new", Some(&andy)).await;
231
    let csrf = csrf_of(&org_page.body);
232
    let r = post(app, "/orgs/new", Some(&andy), &format!("_csrf={csrf}&name=acme&display_name=Acme")).await;
233
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
234
    let new_page = get(app, "/new", Some(&andy)).await;
235
    let csrf = csrf_of(&new_page.body);
236
    assert_eq!(
237
        post(app, "/new", Some(&andy), &format!("_csrf={csrf}&owner=acme&name=plans&visibility=private")).await.status,
238
        StatusCode::SEE_OTHER
239
    );
240
    assert_eq!(get(app, "/acme/plans", Some(&bob)).await.status, StatusCode::NOT_FOUND);
241
    let org_settings = get(app, "/orgs/acme/settings", Some(&andy)).await;
242
    let csrf = csrf_of(&org_settings.body);
243
    assert_eq!(
244
        post(app, "/orgs/acme/settings/members", Some(&andy), &format!("_csrf={csrf}&username=bob&role=member")).await.status,
245
        StatusCode::OK
246
    );
247
    assert_eq!(get(app, "/acme/plans", Some(&bob)).await.status, StatusCode::OK, "members read by default");
248
    assert_eq!(get(app, "/orgs/acme/settings", Some(&bob)).await.status, StatusCode::NOT_FOUND, "members do not administer");
249
    // Bob cannot create under acme's... he can, as a member; a stranger cannot.
250
    let r = post(
251
        app,
252
        "/new",
253
        Some(&bob),
254
        &format!("_csrf={}&owner=acme&name=bobs&visibility=public", csrf_of(&get(app, "/new", Some(&bob)).await.body)),
255
    )
256
    .await;
257
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
258
259
    // Sign out everywhere invalidates the old cookie.
260
    let sec = get(app, "/settings/security", Some(&andy)).await;
261
    let csrf = csrf_of(&sec.body);
262
    let r = post(app, "/settings/security/sessions", Some(&andy), &format!("_csrf={csrf}")).await;
263
    assert_eq!(r.status, StatusCode::SEE_OTHER);
264
    assert_eq!(get(app, "/settings", Some(&andy)).await.status, StatusCode::SEE_OTHER, "old session is gone");
265
    let fresh = r.cookie.unwrap();
266
    assert_eq!(get(app, "/settings", Some(&fresh)).await.status, StatusCode::OK);
267
268
    // TOTP: enable with the current code, then sign in needs it.
269
    let sec = get(app, "/settings/security", Some(&fresh)).await;
270
    let csrf = csrf_of(&sec.body);
271
    let r = post(app, "/settings/security/totp/begin", Some(&fresh), &format!("_csrf={csrf}")).await;
272
    let secret = r.body.split("name=\"secret\" value=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
273
    let now = (db::now_ms() / 1000) as u64;
274
    let code = oxygenhub::auth::totp::current(&secret, now).unwrap();
275
    let r = post(app, "/settings/security/totp/enable", Some(&fresh), &format!("_csrf={csrf}&secret={secret}&code={code}")).await;
276
    assert!(r.body.contains("Recovery codes"), "{}", r.body);
277
    let r = post(app, "/login", None, "username=andy&password=correct-horse-battery").await;
278
    assert!(r.body.contains("authenticator"), "second step asked: {}", r.body);
279
    let code = oxygenhub::auth::totp::current(&secret, (db::now_ms() / 1000) as u64).unwrap();
280
    let r = post(app, "/login", None, &format!("username=andy&password=correct-horse-battery&code={code}")).await;
281
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
282
    assert!(r.cookie.is_some());
283
    assert!(r.location.as_deref() == Some("/"));
284
}