OXYGENHUB
◆ v0.2.0 oxygenhub / crates / hub / tests / accounts.rs
27.5 KiB · Rust · last changed oh signs in through oxy's credential store; pin oxygen with oxy auth and remote bookmarks (refs andymccall/oxygen#47, #48) 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
    // oxygen#47: signed in once (oxy auth login), a private repository
192
    // clones with no OXY_TOKEN, and the clone keeps no token of its own.
193
    let store = oxy_core::credentials::Credentials::user();
194
    let hub = oxy_core::credentials::hub_of(&h.base).unwrap();
195
    store.save(&hub, &rw, Some("andy"), None).unwrap();
196
    let signed_in = Repo::clone(&format!("{}/andy/secret", h.base), &work.path().join("signedin"));
197
    store.remove(&hub).unwrap();
198
    let signed_in = signed_in.unwrap();
199
    assert!(signed_in.config.remote_tokens.is_empty());
200
    assert_eq!(signed_in.bookmark_heads().unwrap(), vec![c1]);
201
202
    // Linking a key: upload the identity, sign the challenge, see attribution.
203
    let (key, identity) = {
204
        let k = client.config.author_key.unwrap();
205
        (k, client.identity(&k).unwrap())
206
    };
207
    let keys_page = get(app, "/settings/keys", Some(&andy)).await;
208
    let csrf = csrf_of(&keys_page.body);
209
    let boundary = "XYZ";
210
    let mut multipart = Vec::new();
211
    multipart.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"_csrf\"\r\n\r\n{csrf}\r\n").as_bytes());
212
    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());
213
    multipart.extend_from_slice(&identity.encode());
214
    multipart.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
215
    let req = Request::builder()
216
        .method("POST")
217
        .uri("/settings/keys/upload")
218
        .header(header::COOKIE, format!("oxyhub={andy}"))
219
        .header(header::CONTENT_TYPE, format!("multipart/form-data; boundary={boundary}"))
220
        .body(Body::from(multipart))
221
        .unwrap();
222
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
223
    assert_eq!(res.status(), StatusCode::OK);
224
    let body = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
225
    let challenge_hex = body.split("sign-challenge ").nth(1).unwrap().split('<').next().unwrap().trim().to_string();
226
    let challenge_id = body.split("name=\"challenge\" value=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
227
    let (_, sk) = client.secret_key().unwrap().unwrap();
228
    let sig = sk.sign_challenge(&key, &hex::decode(&challenge_hex).unwrap()).unwrap();
229
    let sig_hex = hex::encode(oxy_core::identity::Signature::encode_list(&[sig]));
230
    let r = post(app, "/settings/keys/verify", Some(&andy), &format!("_csrf={csrf}&challenge={challenge_id}&signature={sig_hex}")).await;
231
    assert!(r.body.contains("Key linked"), "{}", r.body);
232
    let hist = get(app, "/andy/secret/changes/main", Some(&andy)).await.body;
233
    assert!(hist.contains("href=\"/andy\">Andy McCall</a>"), "author linked to the account: {hist}");
234
    let change = get(app, &format!("/andy/secret/change/{}", c1.to_hex()), Some(&andy)).await.body;
235
    assert!(change.contains("@andy"), "{change}");
236
    // A forged signature is refused.
237
    let r = post(app, "/settings/keys/verify", Some(&andy), &format!("_csrf={csrf}&challenge=999&signature={sig_hex}")).await;
238
    assert!(r.body.contains("expired"), "{}", r.body);
239
240
    // Organisations: a private org repository is visible to members through the default role.
241
    let org_page = get(app, "/orgs/new", Some(&andy)).await;
242
    let csrf = csrf_of(&org_page.body);
243
    let r = post(app, "/orgs/new", Some(&andy), &format!("_csrf={csrf}&name=acme&display_name=Acme")).await;
244
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
245
    let new_page = get(app, "/new", Some(&andy)).await;
246
    let csrf = csrf_of(&new_page.body);
247
    assert_eq!(
248
        post(app, "/new", Some(&andy), &format!("_csrf={csrf}&owner=acme&name=plans&visibility=private")).await.status,
249
        StatusCode::SEE_OTHER
250
    );
251
    assert_eq!(get(app, "/acme/plans", Some(&bob)).await.status, StatusCode::NOT_FOUND);
252
    let org_settings = get(app, "/orgs/acme/settings", Some(&andy)).await;
253
    let csrf = csrf_of(&org_settings.body);
254
    assert_eq!(
255
        post(app, "/orgs/acme/settings/members", Some(&andy), &format!("_csrf={csrf}&username=bob&role=member")).await.status,
256
        StatusCode::OK
257
    );
258
    assert_eq!(get(app, "/acme/plans", Some(&bob)).await.status, StatusCode::OK, "members read by default");
259
    assert_eq!(get(app, "/orgs/acme/settings", Some(&bob)).await.status, StatusCode::NOT_FOUND, "members do not administer");
260
    // Bob cannot create under acme's... he can, as a member; a stranger cannot.
261
    let r = post(
262
        app,
263
        "/new",
264
        Some(&bob),
265
        &format!("_csrf={}&owner=acme&name=bobs&visibility=public", csrf_of(&get(app, "/new", Some(&bob)).await.body)),
266
    )
267
    .await;
268
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
269
270
    // Sign out everywhere invalidates the old cookie.
271
    let sec = get(app, "/settings/security", Some(&andy)).await;
272
    let csrf = csrf_of(&sec.body);
273
    let r = post(app, "/settings/security/sessions", Some(&andy), &format!("_csrf={csrf}")).await;
274
    assert_eq!(r.status, StatusCode::SEE_OTHER);
275
    assert_eq!(get(app, "/settings", Some(&andy)).await.status, StatusCode::SEE_OTHER, "old session is gone");
276
    let fresh = r.cookie.unwrap();
277
    assert_eq!(get(app, "/settings", Some(&fresh)).await.status, StatusCode::OK);
278
279
    // TOTP: enable with the current code, then sign in needs it.
280
    let sec = get(app, "/settings/security", Some(&fresh)).await;
281
    let csrf = csrf_of(&sec.body);
282
    let r = post(app, "/settings/security/totp/begin", Some(&fresh), &format!("_csrf={csrf}")).await;
283
    let secret = r.body.split("name=\"secret\" value=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
284
    let now = (db::now_ms() / 1000) as u64;
285
    let code = oxygenhub::auth::totp::current(&secret, now).unwrap();
286
    let r = post(app, "/settings/security/totp/enable", Some(&fresh), &format!("_csrf={csrf}&secret={secret}&code={code}")).await;
287
    assert!(r.body.contains("Recovery codes"), "{}", r.body);
288
    let r = post(app, "/login", None, "username=andy&password=correct-horse-battery").await;
289
    assert!(r.body.contains("authenticator"), "second step asked: {}", r.body);
290
    // Submit the second step as a browser would: every field of the
291
    // rendered form, each name once (a repeated name is refused).
292
    let form = &r.body[r.body.find("<form class=\"card\" method=\"post\" action=\"/login\">").unwrap()..];
293
    let form = &form[..form.find("</form>").unwrap()];
294
    let names: Vec<&str> = form.split("name=\"").skip(1).map(|t| t.split('"').next().unwrap()).collect();
295
    let mut unique = names.clone();
296
    unique.sort();
297
    unique.dedup();
298
    assert_eq!(unique.len(), names.len(), "a field named twice: {names:?}");
299
    let code = oxygenhub::auth::totp::current(&secret, (db::now_ms() / 1000) as u64).unwrap();
300
    let body: Vec<String> = names
301
        .iter()
302
        .map(|n| match *n {
303
            "username" => "username=andy".to_string(),
304
            "password" => "password=correct-horse-battery".to_string(),
305
            "code" => format!("code={code}"),
306
            other => format!("{other}="),
307
        })
308
        .collect();
309
    let r = post(app, "/login", None, &body.join("&")).await;
310
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
311
    assert!(r.cookie.is_some());
312
    assert!(r.location.as_deref() == Some("/"));
313
}
314
315
/// A multipart picture form.
316
fn picture_form(csrf: &str, action: &str, file: &[u8]) -> (String, Vec<u8>) {
317
    let boundary = "picture-boundary-1234";
318
    let mut body = Vec::new();
319
    body.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"_csrf\"\r\n\r\n{csrf}\r\n").as_bytes());
320
    body.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"action\"\r\n\r\n{action}\r\n").as_bytes());
321
    body.extend_from_slice(
322
        format!("--{boundary}\r\nContent-Disposition: form-data; name=\"picture\"; filename=\"me.png\"\r\nContent-Type: image/png\r\n\r\n")
323
            .as_bytes(),
324
    );
325
    body.extend_from_slice(file);
326
    body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
327
    (format!("multipart/form-data; boundary={boundary}"), body)
328
}
329
330
async fn upload(app: &Shared, path: &str, cookie: &str, csrf: &str, action: &str, file: &[u8]) -> Res {
331
    let (ct, body) = picture_form(csrf, action, file);
332
    let req = Request::post(path)
333
        .header(header::COOKIE, format!("oxyhub={cookie}"))
334
        .header(header::CONTENT_TYPE, ct)
335
        .body(Body::from(body))
336
        .unwrap();
337
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
338
    let status = res.status();
339
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
340
    Res { status, body: String::from_utf8_lossy(&bytes).into_owned(), cookie: None, location: None }
341
}
342
343
/// Status, content type and bytes of a picture.
344
async fn picture(app: &Shared, name: &str) -> (StatusCode, String, Vec<u8>) {
345
    let res = oxygenhub::router(app.clone()).oneshot(Request::get(format!("/avatar/{name}")).body(Body::empty()).unwrap()).await.unwrap();
346
    let ct = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("").to_string();
347
    let status = res.status();
348
    (status, ct, res.into_body().collect().await.unwrap().to_bytes().to_vec())
349
}
350
351
fn png(w: u32, h: u32, alpha: bool) -> Vec<u8> {
352
    let img = if alpha {
353
        image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(w, h, |x, _| {
354
            image::Rgba([0, 114, 255, if x % 2 == 0 { 0 } else { 255 }])
355
        }))
356
    } else {
357
        image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(w, h, |x, y| image::Rgb([x as u8, y as u8, 128])))
358
    };
359
    let mut out = Vec::new();
360
    img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
361
    out
362
}
363
364
#[tokio::test(flavor = "multi_thread")]
365
async fn profile_pictures_and_logos() {
366
    let h = hub().await;
367
    let app = &h.app;
368
    let andy = register(app, "andy", "").await;
369
    assert_eq!(picture(app, "andy").await.1, "image/svg+xml", "the identicon first");
370
    let csrf = csrf_of(&get(app, "/settings", Some(&andy)).await.body);
371
    assert!(get(app, "/settings", Some(&andy)).await.body.contains("id=\"picture\""));
372
373
    // A photo: cropped, scaled and re-encoded as JPEG.
374
    let r = upload(app, "/settings/avatar", &andy, &csrf, "upload", &png(640, 480, false)).await;
375
    assert!(r.body.contains("Picture saved"), "{}", r.body);
376
    let (st, ct, bytes) = picture(app, "andy").await;
377
    assert_eq!((st, ct.as_str()), (StatusCode::OK, "image/jpeg"));
378
    let img = image::load_from_memory(&bytes).unwrap();
379
    assert_eq!((img.width(), img.height()), (400, 400));
380
    let stored = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap().avatar;
381
    assert!(stored.starts_with("jpeg:"), "{stored}");
382
383
    // Not an image, or no CSRF: refused, and the picture stays.
384
    let r = upload(
385
        app,
386
        "/settings/avatar",
387
        &andy,
388
        &csrf,
389
        "upload",
390
        b"<svg xmlns=\"http://www.w3.org/2000/svg\"><script>alert(1)</script></svg>",
391
    )
392
    .await;
393
    assert!(r.body.contains("not a PNG, JPEG or WebP"), "{}", r.body);
394
    let r = upload(app, "/settings/avatar", &andy, "wrong", "upload", &png(10, 10, false)).await;
395
    assert_ne!(r.status, StatusCode::OK);
396
    assert_eq!(picture(app, "andy").await.1, "image/jpeg");
397
    // Removing brings the identicon back.
398
    let r = upload(app, "/settings/avatar", &andy, &csrf, "remove", b"").await;
399
    assert!(r.body.contains("Picture removed"));
400
    assert_eq!(picture(app, "andy").await.1, "image/svg+xml");
401
402
    // An organisation's logo keeps its transparency; only owners may set it.
403
    let me = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
404
    db::accounts::create_org(&app.db, "acme", "Acme", me.id).await.unwrap();
405
    let org_csrf = csrf_of(&get(app, "/orgs/acme/settings", Some(&andy)).await.body);
406
    let r = upload(app, "/orgs/acme/settings/avatar", &andy, &org_csrf, "upload", &png(120, 120, true)).await;
407
    assert!(r.body.contains("Picture saved"), "{}", r.body);
408
    let (_, ct, bytes) = picture(app, "acme").await;
409
    assert_eq!(ct, "image/png");
410
    assert!(image::load_from_memory(&bytes).unwrap().color().has_alpha());
411
    let invite = {
412
        let admin = get(app, "/admin", Some(&andy)).await;
413
        let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={}", csrf_of(&admin.body))).await;
414
        let i = r.body.find("invite=").map(|i| i + 7).expect("an invitation");
415
        r.body[i..].chars().take_while(|c| c.is_ascii_alphanumeric()).collect::<String>()
416
    };
417
    let bob = register(app, "bob", &invite).await;
418
    let bob_csrf = csrf_of(&get(app, "/settings", Some(&bob)).await.body);
419
    let r = upload(app, "/orgs/acme/settings/avatar", &bob, &bob_csrf, "remove", b"").await;
420
    assert_eq!(r.status, StatusCode::NOT_FOUND, "not an owner");
421
    assert_eq!(picture(app, "acme").await.1, "image/png");
422
}
423
424
#[tokio::test(flavor = "multi_thread")]
425
async fn organisation_webhooks_and_storage() {
426
    let h = hub().await;
427
    let app = &h.app;
428
    let andy = register(app, "andy", "").await;
429
    let me = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
430
    let org = db::accounts::create_org(&app.db, "acme", "Acme", me.id).await.unwrap();
431
432
    // A repository requires one sealed approval by default only where
433
    // someone else can give it: an organisation of two or more members
434
    // (oxygenhub#64). Acme has one member so far, like a personal account.
435
    let alone = db::repos::create(&app.db, "acme", "alone", "", hub_api::Visibility::Public).await.unwrap();
436
    let solo = db::repos::create(&app.db, "andy", "solo", "", hub_api::Visibility::Public).await.unwrap();
437
    assert_eq!(db::proposals::requirements(&app.db, alone.id).await.unwrap().required_approvals, 0);
438
    assert_eq!(db::proposals::requirements(&app.db, solo.id).await.unwrap().required_approvals, 0);
439
    let bobby = db::accounts::create_account(&app.db, "bobby", "[email protected]", "x", "salt", false).await.unwrap();
440
    db::accounts::set_org_member(&app.db, org.id, bobby.id, "member").await.unwrap();
441
    let tools = db::repos::create(&app.db, "acme", "tools", "", hub_api::Visibility::Public).await.unwrap();
442
    assert_eq!(db::proposals::requirements(&app.db, tools.id).await.unwrap().required_approvals, 1);
443
444
    // Organisation webhooks: add, ping, deliveries; only for this organisation.
445
    let page = get(app, "/orgs/acme/settings", Some(&andy)).await;
446
    assert!(page.body.contains("id=\"webhooks\"") && page.body.contains("href=\"#webhooks\""));
447
    let csrf = csrf_of(&page.body);
448
    let r = post(app, "/orgs/acme/settings/hooks", Some(&andy), &format!("_csrf={csrf}&url=ftp%3A%2F%2Fx&events=*")).await;
449
    assert!(r.body.contains("starts with http"), "{}", r.body);
450
    let r = post(
451
        app,
452
        "/orgs/acme/settings/hooks",
453
        Some(&andy),
454
        &format!("_csrf={csrf}&url=https%3A%2F%2Fhooks.invalid%2Facme&secret=s&events=push"),
455
    )
456
    .await;
457
    assert!(r.body.contains("Webhook added"));
458
    let hooks = db::hooks::hooks_for_org(&app.db, org.id).await.unwrap();
459
    assert_eq!(hooks.len(), 1);
460
    let id = hooks[0].id;
461
    assert!(post(app, "/orgs/acme/settings/hooks", Some(&andy), &format!("_csrf={csrf}&id={id}&action=ping"))
462
        .await
463
        .body
464
        .contains("Ping queued"));
465
    let deliveries = get(app, &format!("/orgs/acme/settings/hooks/{id}/deliveries"), Some(&andy)).await;
466
    assert_eq!(deliveries.status, StatusCode::OK);
467
    assert!(deliveries.body.contains(">ping<") && deliveries.body.contains("/orgs/acme/settings#webhooks"));
468
    // A repository's hook cannot be touched through the organisation's form.
469
    let repo = oxygenhub::repos::RepoName::parse("andy/demo").unwrap();
470
    app.repos.create(&repo, None).unwrap();
471
    let row = db::repos::create(&app.db, "andy", "demo", "", hub_api::Visibility::Public).await.unwrap();
472
    let repo_hook = db::hooks::create_hook(&app.db, Some(row.id), None, "https://hooks.invalid/repo", "", "*").await.unwrap().id;
473
    post(app, "/orgs/acme/settings/hooks", Some(&andy), &format!("_csrf={csrf}&id={repo_hook}&action=delete")).await;
474
    assert!(db::hooks::hook(&app.db, repo_hook).await.unwrap().is_some(), "not the organisation's");
475
    assert_eq!(get(app, &format!("/orgs/acme/settings/hooks/{repo_hook}/deliveries"), Some(&andy)).await.status, StatusCode::NOT_FOUND);
476
    // The repository's own settings still manage its hooks (shared code).
477
    let rs = get(app, "/andy/demo/settings", Some(&andy)).await;
478
    assert!(rs.body.contains("https://hooks.invalid/repo") && rs.body.contains("action=\"/andy/demo/settings/hooks\""));
479
480
    // Storage: sizes and loose objects, and maintenance packs them.
481
    let work = tempfile::tempdir().unwrap();
482
    let mut client = Repo::init(work.path()).unwrap();
483
    client.config.set("remote.origin.url", &format!("{}/andy/demo", h.base)).unwrap();
484
    let (token, hash) = oxygenhub::auth::new_token();
485
    db::accounts::create_token(&app.db, me.id, "push", &hash, "repo:write", "", None).await.unwrap();
486
    client.config.set("remote.origin.token", &token).unwrap();
487
    client.save_config().unwrap();
488
    write(work.path(), "a.txt", b"a\n");
489
    client.snapshot("t").unwrap();
490
    client.commit("one", &[]).unwrap();
491
    assert!(client.push("origin", false).unwrap().iter().all(|r| r.ok));
492
    let storage = get(app, "/admin/storage", Some(&andy)).await;
493
    assert_eq!(storage.status, StatusCode::OK);
494
    assert!(storage.body.contains("href=\"/andy/demo\""));
495
    let loose_before = std::fs::read_dir(app.repos.dir(&repo).join(".oxy/objects/loose")).map(|d| d.count()).unwrap_or(0);
496
    assert!(loose_before > 0, "the push left loose objects");
497
    let r = post(app, "/admin/storage", Some(&andy), &format!("_csrf={}&repo=andy%2Fdemo", csrf_of(&storage.body))).await;
498
    assert!(r.body.contains("Maintained 1 repository") && r.body.contains("loose objects packed"), "{}", r.body);
499
    let loose_after: usize = walk_files(&app.repos.dir(&repo).join(".oxy/objects/loose"));
500
    assert_eq!(loose_after, 0, "packed");
501
    let audit = db::accounts::audit_rows(&app.db, 20).await.unwrap();
502
    assert!(audit.iter().any(|a| a.action == "admin.gc" && a.target == "andy/demo"));
503
    let r = post(app, "/admin/storage", Some(&andy), &format!("_csrf={}&repo=nobody%2Fnone", csrf_of(&storage.body))).await;
504
    assert!(r.body.contains("No repository nobody/none"));
505
}
506
507
fn walk_files(dir: &Path) -> usize {
508
    let Ok(rd) = std::fs::read_dir(dir) else { return 0 };
509
    rd.flatten().map(|e| if e.path().is_dir() { walk_files(&e.path()) } else { 1 }).sum()
510
}