OXYGENHUB
# c4c87f481d05 oxygenhub / crates / hub / tests / accounts.rs
25.1 KiB · Rust · last changed Organisation webhooks under the organisation's settings, sharing the repository webhook code; an admin storage page with sizes, loose objects and packs, and maintenance (oxy gc) per repository or for all 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
}
285
286
/// A multipart picture form.
287
fn picture_form(csrf: &str, action: &str, file: &[u8]) -> (String, Vec<u8>) {
288
    let boundary = "picture-boundary-1234";
289
    let mut body = Vec::new();
290
    body.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"_csrf\"\r\n\r\n{csrf}\r\n").as_bytes());
291
    body.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"action\"\r\n\r\n{action}\r\n").as_bytes());
292
    body.extend_from_slice(
293
        format!("--{boundary}\r\nContent-Disposition: form-data; name=\"picture\"; filename=\"me.png\"\r\nContent-Type: image/png\r\n\r\n")
294
            .as_bytes(),
295
    );
296
    body.extend_from_slice(file);
297
    body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
298
    (format!("multipart/form-data; boundary={boundary}"), body)
299
}
300
301
async fn upload(app: &Shared, path: &str, cookie: &str, csrf: &str, action: &str, file: &[u8]) -> Res {
302
    let (ct, body) = picture_form(csrf, action, file);
303
    let req = Request::post(path)
304
        .header(header::COOKIE, format!("oxyhub={cookie}"))
305
        .header(header::CONTENT_TYPE, ct)
306
        .body(Body::from(body))
307
        .unwrap();
308
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
309
    let status = res.status();
310
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
311
    Res { status, body: String::from_utf8_lossy(&bytes).into_owned(), cookie: None, location: None }
312
}
313
314
/// Status, content type and bytes of a picture.
315
async fn picture(app: &Shared, name: &str) -> (StatusCode, String, Vec<u8>) {
316
    let res = oxygenhub::router(app.clone()).oneshot(Request::get(format!("/avatar/{name}")).body(Body::empty()).unwrap()).await.unwrap();
317
    let ct = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("").to_string();
318
    let status = res.status();
319
    (status, ct, res.into_body().collect().await.unwrap().to_bytes().to_vec())
320
}
321
322
fn png(w: u32, h: u32, alpha: bool) -> Vec<u8> {
323
    let img = if alpha {
324
        image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(w, h, |x, _| {
325
            image::Rgba([0, 114, 255, if x % 2 == 0 { 0 } else { 255 }])
326
        }))
327
    } else {
328
        image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(w, h, |x, y| image::Rgb([x as u8, y as u8, 128])))
329
    };
330
    let mut out = Vec::new();
331
    img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
332
    out
333
}
334
335
#[tokio::test(flavor = "multi_thread")]
336
async fn profile_pictures_and_logos() {
337
    let h = hub().await;
338
    let app = &h.app;
339
    let andy = register(app, "andy", "").await;
340
    assert_eq!(picture(app, "andy").await.1, "image/svg+xml", "the identicon first");
341
    let csrf = csrf_of(&get(app, "/settings", Some(&andy)).await.body);
342
    assert!(get(app, "/settings", Some(&andy)).await.body.contains("id=\"picture\""));
343
344
    // A photo: cropped, scaled and re-encoded as JPEG.
345
    let r = upload(app, "/settings/avatar", &andy, &csrf, "upload", &png(640, 480, false)).await;
346
    assert!(r.body.contains("Picture saved"), "{}", r.body);
347
    let (st, ct, bytes) = picture(app, "andy").await;
348
    assert_eq!((st, ct.as_str()), (StatusCode::OK, "image/jpeg"));
349
    let img = image::load_from_memory(&bytes).unwrap();
350
    assert_eq!((img.width(), img.height()), (400, 400));
351
    let stored = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap().avatar;
352
    assert!(stored.starts_with("jpeg:"), "{stored}");
353
354
    // Not an image, or no CSRF: refused, and the picture stays.
355
    let r = upload(
356
        app,
357
        "/settings/avatar",
358
        &andy,
359
        &csrf,
360
        "upload",
361
        b"<svg xmlns=\"http://www.w3.org/2000/svg\"><script>alert(1)</script></svg>",
362
    )
363
    .await;
364
    assert!(r.body.contains("not a PNG, JPEG or WebP"), "{}", r.body);
365
    let r = upload(app, "/settings/avatar", &andy, "wrong", "upload", &png(10, 10, false)).await;
366
    assert_ne!(r.status, StatusCode::OK);
367
    assert_eq!(picture(app, "andy").await.1, "image/jpeg");
368
    // Removing brings the identicon back.
369
    let r = upload(app, "/settings/avatar", &andy, &csrf, "remove", b"").await;
370
    assert!(r.body.contains("Picture removed"));
371
    assert_eq!(picture(app, "andy").await.1, "image/svg+xml");
372
373
    // An organisation's logo keeps its transparency; only owners may set it.
374
    let me = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
375
    db::accounts::create_org(&app.db, "acme", "Acme", me.id).await.unwrap();
376
    let org_csrf = csrf_of(&get(app, "/orgs/acme/settings", Some(&andy)).await.body);
377
    let r = upload(app, "/orgs/acme/settings/avatar", &andy, &org_csrf, "upload", &png(120, 120, true)).await;
378
    assert!(r.body.contains("Picture saved"), "{}", r.body);
379
    let (_, ct, bytes) = picture(app, "acme").await;
380
    assert_eq!(ct, "image/png");
381
    assert!(image::load_from_memory(&bytes).unwrap().color().has_alpha());
382
    let invite = {
383
        let admin = get(app, "/admin", Some(&andy)).await;
384
        let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={}", csrf_of(&admin.body))).await;
385
        let i = r.body.find("invite=").map(|i| i + 7).expect("an invitation");
386
        r.body[i..].chars().take_while(|c| c.is_ascii_alphanumeric()).collect::<String>()
387
    };
388
    let bob = register(app, "bob", &invite).await;
389
    let bob_csrf = csrf_of(&get(app, "/settings", Some(&bob)).await.body);
390
    let r = upload(app, "/orgs/acme/settings/avatar", &bob, &bob_csrf, "remove", b"").await;
391
    assert_eq!(r.status, StatusCode::NOT_FOUND, "not an owner");
392
    assert_eq!(picture(app, "acme").await.1, "image/png");
393
}
394
395
#[tokio::test(flavor = "multi_thread")]
396
async fn organisation_webhooks_and_storage() {
397
    let h = hub().await;
398
    let app = &h.app;
399
    let andy = register(app, "andy", "").await;
400
    let me = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
401
    let org = db::accounts::create_org(&app.db, "acme", "Acme", me.id).await.unwrap();
402
403
    // Organisation webhooks: add, ping, deliveries; only for this organisation.
404
    let page = get(app, "/orgs/acme/settings", Some(&andy)).await;
405
    assert!(page.body.contains("id=\"webhooks\"") && page.body.contains("href=\"#webhooks\""));
406
    let csrf = csrf_of(&page.body);
407
    let r = post(app, "/orgs/acme/settings/hooks", Some(&andy), &format!("_csrf={csrf}&url=ftp%3A%2F%2Fx&events=*")).await;
408
    assert!(r.body.contains("starts with http"), "{}", r.body);
409
    let r = post(
410
        app,
411
        "/orgs/acme/settings/hooks",
412
        Some(&andy),
413
        &format!("_csrf={csrf}&url=https%3A%2F%2Fhooks.invalid%2Facme&secret=s&events=push"),
414
    )
415
    .await;
416
    assert!(r.body.contains("Webhook added"));
417
    let hooks = db::hooks::hooks_for_org(&app.db, org.id).await.unwrap();
418
    assert_eq!(hooks.len(), 1);
419
    let id = hooks[0].id;
420
    assert!(post(app, "/orgs/acme/settings/hooks", Some(&andy), &format!("_csrf={csrf}&id={id}&action=ping"))
421
        .await
422
        .body
423
        .contains("Ping queued"));
424
    let deliveries = get(app, &format!("/orgs/acme/settings/hooks/{id}/deliveries"), Some(&andy)).await;
425
    assert_eq!(deliveries.status, StatusCode::OK);
426
    assert!(deliveries.body.contains(">ping<") && deliveries.body.contains("/orgs/acme/settings#webhooks"));
427
    // A repository's hook cannot be touched through the organisation's form.
428
    let repo = oxygenhub::repos::RepoName::parse("andy/demo").unwrap();
429
    app.repos.create(&repo, None).unwrap();
430
    let row = db::repos::create(&app.db, "andy", "demo", "", hub_api::Visibility::Public).await.unwrap();
431
    let repo_hook = db::hooks::create_hook(&app.db, Some(row.id), None, "https://hooks.invalid/repo", "", "*").await.unwrap().id;
432
    post(app, "/orgs/acme/settings/hooks", Some(&andy), &format!("_csrf={csrf}&id={repo_hook}&action=delete")).await;
433
    assert!(db::hooks::hook(&app.db, repo_hook).await.unwrap().is_some(), "not the organisation's");
434
    assert_eq!(get(app, &format!("/orgs/acme/settings/hooks/{repo_hook}/deliveries"), Some(&andy)).await.status, StatusCode::NOT_FOUND);
435
    // The repository's own settings still manage its hooks (shared code).
436
    let rs = get(app, "/andy/demo/settings", Some(&andy)).await;
437
    assert!(rs.body.contains("https://hooks.invalid/repo") && rs.body.contains("action=\"/andy/demo/settings/hooks\""));
438
439
    // Storage: sizes and loose objects, and maintenance packs them.
440
    let work = tempfile::tempdir().unwrap();
441
    let mut client = Repo::init(work.path()).unwrap();
442
    client.config.set("remote.origin.url", &format!("{}/andy/demo", h.base)).unwrap();
443
    let (token, hash) = oxygenhub::auth::new_token();
444
    db::accounts::create_token(&app.db, me.id, "push", &hash, "repo:write", "", None).await.unwrap();
445
    client.config.set("remote.origin.token", &token).unwrap();
446
    client.save_config().unwrap();
447
    write(work.path(), "a.txt", b"a\n");
448
    client.snapshot("t").unwrap();
449
    client.commit("one", &[]).unwrap();
450
    assert!(client.push("origin", false).unwrap().iter().all(|r| r.ok));
451
    let storage = get(app, "/admin/storage", Some(&andy)).await;
452
    assert_eq!(storage.status, StatusCode::OK);
453
    assert!(storage.body.contains("href=\"/andy/demo\""));
454
    let loose_before = std::fs::read_dir(app.repos.dir(&repo).join(".oxy/objects/loose")).map(|d| d.count()).unwrap_or(0);
455
    assert!(loose_before > 0, "the push left loose objects");
456
    let r = post(app, "/admin/storage", Some(&andy), &format!("_csrf={}&repo=andy%2Fdemo", csrf_of(&storage.body))).await;
457
    assert!(r.body.contains("Maintained 1 repository") && r.body.contains("loose objects packed"), "{}", r.body);
458
    let loose_after: usize = walk_files(&app.repos.dir(&repo).join(".oxy/objects/loose"));
459
    assert_eq!(loose_after, 0, "packed");
460
    let audit = db::accounts::audit_rows(&app.db, 20).await.unwrap();
461
    assert!(audit.iter().any(|a| a.action == "admin.gc" && a.target == "andy/demo"));
462
    let r = post(app, "/admin/storage", Some(&andy), &format!("_csrf={}&repo=nobody%2Fnone", csrf_of(&storage.body))).await;
463
    assert!(r.body.contains("No repository nobody/none"));
464
}
465
466
fn walk_files(dir: &Path) -> usize {
467
    let Ok(rd) = std::fs::read_dir(dir) else { return 0 };
468
    rd.flatten().map(|e| if e.path().is_dir() { walk_files(&e.path()) } else { 1 }).sum()
469
}