OXYGENHUB
◆ v0.6.1 oxygenhub / crates / hub / tests / accounts.rs
96.1 KiB · Rust · last changed Repository settings: one page per setting under a grouped sidebar (#278) 15 days 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
    // The first account's setup code (oxygenhub#245).
41
    config.registration.setup_code = "test-setup".into();
42
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
43
    let port = listener.local_addr().unwrap().port();
44
    config.server.base_url = format!("http://127.0.0.1:{port}");
45
    // The stand-in webhook and assistant servers listen on 127.0.0.1 (#219).
46
    config.outbound.allow = vec!["http://127.0.0.1".into()];
47
    config.registration.mode = "invite".into();
48
    let app = oxygenhub::build(config).await.unwrap();
49
    let router = oxygenhub::router(app.clone());
50
    tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
51
    Hub { app, base: format!("http://127.0.0.1:{port}"), _dir: dir }
52
}
53
54
struct Res {
55
    status: StatusCode,
56
    body: String,
57
    /// The session cookie's value, when the response set one.
58
    cookie: Option<String>,
59
    location: Option<String>,
60
    /// Every Set-Cookie header, whole.
61
    raw_cookies: Vec<String>,
62
}
63
64
async fn send(app: &Shared, method: &str, path: &str, cookie: Option<&str>, form: Option<&str>) -> Res {
65
    let header_value = cookie.map(|c| format!("oxyhub={c}"));
66
    send_with(app, method, path, header_value.as_deref(), form).await
67
}
68
69
/// As `send`, with the whole Cookie header given.
70
async fn send_with(app: &Shared, method: &str, path: &str, cookie_header: Option<&str>, form: Option<&str>) -> Res {
71
    let mut req = Request::builder().method(method).uri(path);
72
    if let Some(c) = cookie_header {
73
        req = req.header(header::COOKIE, c.to_string());
74
    }
75
    let body = match form {
76
        Some(f) => {
77
            req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
78
            Body::from(f.to_string())
79
        }
80
        None => Body::empty(),
81
    };
82
    let res = oxygenhub::router(app.clone()).oneshot(req.body(body).unwrap()).await.unwrap();
83
    let status = res.status();
84
    let raw_cookies: Vec<String> =
85
        res.headers().get_all(header::SET_COOKIE).iter().filter_map(|v| v.to_str().ok()).map(String::from).collect();
86
    let cookie =
87
        raw_cookies.iter().filter_map(|c| c.split(';').next()).filter_map(|kv| kv.strip_prefix("oxyhub=")).map(String::from).next();
88
    let location = res.headers().get(header::LOCATION).and_then(|v| v.to_str().ok()).map(String::from);
89
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
90
    Res { status, body: String::from_utf8_lossy(&bytes).into_owned(), cookie, location, raw_cookies }
91
}
92
93
async fn get(app: &Shared, path: &str, cookie: Option<&str>) -> Res {
94
    send(app, "GET", path, cookie, None).await
95
}
96
97
async fn post(app: &Shared, path: &str, cookie: Option<&str>, form: &str) -> Res {
98
    send(app, "POST", path, cookie, Some(form)).await
99
}
100
101
/// A repository settings form's answer (#278): a redirect to the page that
102
/// holds the form, followed.
103
async fn settled(app: &Shared, r: Res, cookie: Option<&str>, page: &str) -> Res {
104
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
105
    let to = r.location.expect("a redirect");
106
    assert!(to.starts_with(&format!("{page}?")), "{to} is not {page}");
107
    get(app, &to, cookie).await
108
}
109
110
/// Register (or sign in) and return the session cookie value.
111
async fn register(app: &Shared, user: &str, invite: &str) -> String {
112
    let r = post(
113
        app,
114
        "/register",
115
        None,
116
        &format!("username={user}&email={user}%40example.com&password=correct-horse-battery&setup=test-setup&invite={invite}"),
117
    )
118
    .await;
119
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
120
    r.cookie.expect("session cookie")
121
}
122
123
fn csrf_of(page: &str) -> String {
124
    let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len();
125
    page[i..].split('"').next().unwrap().to_string()
126
}
127
128
#[tokio::test(flavor = "multi_thread")]
129
async fn accounts_roles_tokens_and_attribution() {
130
    let h = hub().await;
131
    let app = &h.app;
132
133
    // The first account registers without an invitation and is the administrator.
134
    let andy = register(app, "andy", "").await;
135
    let me = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
136
    assert!(me.is_admin);
137
    // A second registration needs an invitation.
138
    let r = post(app, "/register", None, "username=mallory&email=m%40example.com&password=correct-horse-battery&setup=test-setup&invite=")
139
        .await;
140
    assert_eq!(r.status, StatusCode::OK);
141
    assert!(r.body.contains("invitation"), "{}", r.body);
142
    let admin_page = get(app, "/admin", Some(&andy)).await;
143
    assert_eq!(admin_page.status, StatusCode::OK);
144
    let csrf = csrf_of(&admin_page.body);
145
    let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={csrf}")).await;
146
    let code = r.body.split("register?invite=").nth(1).unwrap().split('<').next().unwrap().trim().to_string();
147
    let bob = register(app, "bob", &code).await;
148
    assert!(!db::accounts::account_by_name(&app.db, "bob").await.unwrap().unwrap().is_admin);
149
    // Wrong password, banned users and CSRF-less posts are refused.
150
    assert_eq!(post(app, "/login", None, "username=andy&password=nope").await.status, StatusCode::OK);
151
    assert_eq!(post(app, "/settings", Some(&andy), "_csrf=bogus&display_name=x&email=y").await.status, StatusCode::BAD_REQUEST);
152
    assert_eq!(get(app, "/settings", None).await.status, StatusCode::SEE_OTHER, "anonymous settings redirects to sign in");
153
154
    // Andy creates a private repository through the form; Bob cannot see it.
155
    let new_page = get(app, "/new", Some(&andy)).await;
156
    let csrf = csrf_of(&new_page.body);
157
    let r = post(app, "/new", Some(&andy), &format!("_csrf={csrf}&owner=andy&name=secret&description=hush&visibility=private")).await;
158
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
159
    assert_eq!(get(app, "/andy/secret", Some(&andy)).await.status, StatusCode::OK);
160
    assert_eq!(get(app, "/andy/secret", Some(&bob)).await.status, StatusCode::NOT_FOUND);
161
    assert_eq!(get(app, "/andy/secret", None).await.status, StatusCode::NOT_FOUND);
162
    assert!(!get(app, "/", Some(&bob)).await.body.contains("secret"));
163
    assert!(get(app, "/", Some(&andy)).await.body.contains("secret"));
164
165
    // Tokens: a read-only token cannot push; a write token can. Anonymous cannot read a private repository.
166
    let tokens_page = get(app, "/settings/tokens", Some(&andy)).await;
167
    let csrf = csrf_of(&tokens_page.body);
168
    let r = post(app, "/settings/tokens", Some(&andy), &format!("_csrf={csrf}&name=ro&scopes=repo%3Aread")).await;
169
    let ro = r.body.split("oxyhub_").nth(1).map(|s| format!("oxyhub_{}", s.split('<').next().unwrap().trim())).unwrap();
170
    let r = post(app, "/settings/tokens", Some(&andy), &format!("_csrf={csrf}&name=rw&scopes=repo%3Aread&scopes=repo%3Awrite")).await;
171
    let rw = r.body.split("oxyhub_").nth(1).map(|s| format!("oxyhub_{}", s.split('<').next().unwrap().trim())).unwrap();
172
    let work = tempfile::tempdir().unwrap();
173
    let mut client = Repo::init(work.path()).unwrap();
174
    client.create_identity("Andy McCall", "[email protected]", oxy_core::repo::IdentityScope::User).unwrap();
175
    client.config.set("remote.origin.url", &format!("{}/andy/secret", h.base)).unwrap();
176
    client.config.set("core.sign", "change").unwrap();
177
    client.save_config().unwrap();
178
    write(work.path(), "a.txt", b"a\n");
179
    client.snapshot("t").unwrap();
180
    let c1 = client.commit("first", &[]).unwrap();
181
    let err = client.push("origin", false).err().unwrap().to_string();
182
    assert!(err.contains("404"), "anonymous cannot even see it: {err}");
183
    client.config.set("remote.origin.token", &ro).unwrap();
184
    let err = client.push("origin", false).err().unwrap().to_string();
185
    assert!(err.contains("403"), "read-only token cannot push: {err}");
186
    client.config.set("remote.origin.token", &rw).unwrap();
187
    assert!(client.push("origin", false).unwrap().iter().all(|r| r.ok));
188
    // Bob's token cannot read it either.
189
    let bob_tokens = get(app, "/settings/tokens", Some(&bob)).await;
190
    let csrf_b = csrf_of(&bob_tokens.body);
191
    let r = post(app, "/settings/tokens", Some(&bob), &format!("_csrf={csrf_b}&name=b&scopes=repo%3Aread&scopes=repo%3Awrite")).await;
192
    let bob_tok = r.body.split("oxyhub_").nth(1).map(|s| format!("oxyhub_{}", s.split('<').next().unwrap().trim())).unwrap();
193
    std::env::set_var("OXY_TOKEN", &bob_tok);
194
    let err = Repo::clone(&format!("{}/andy/secret", h.base), &work.path().join("bobclone")).err().unwrap().to_string();
195
    std::env::remove_var("OXY_TOKEN");
196
    assert!(err.contains("404"), "{err}");
197
    // The push log names the pusher.
198
    tokio::time::sleep(std::time::Duration::from_millis(150)).await;
199
    let pushes = get(app, "/andy/secret/pushes", Some(&andy)).await.body;
200
    assert!(pushes.contains("andy"), "{pushes}");
201
202
    // Bob becomes a collaborator with write, and can then see and push.
203
    let settings = get(app, "/andy/secret/settings", Some(&andy)).await;
204
    assert_eq!(settings.status, StatusCode::OK);
205
    let csrf = csrf_of(&settings.body);
206
    let r = post(app, "/andy/secret/settings/collaborators", Some(&andy), &format!("_csrf={csrf}&username=bob&role=write")).await;
207
    let r = settled(app, r, Some(&andy), "/andy/secret/settings/collaborators").await;
208
    assert!(r.body.contains("bob now has write access."), "{}", r.body);
209
    assert_eq!(get(app, "/andy/secret", Some(&bob)).await.status, StatusCode::OK);
210
    assert_eq!(get(app, "/andy/secret/settings", Some(&bob)).await.status, StatusCode::NOT_FOUND, "write is not maintain");
211
    std::env::set_var("OXY_TOKEN", &bob_tok);
212
    let ok = Repo::clone(&format!("{}/andy/secret", h.base), &work.path().join("bobclone2")).is_ok();
213
    std::env::remove_var("OXY_TOKEN");
214
    assert!(ok);
215
216
    // oxygen#47: signed in once (oxy auth login), a private repository
217
    // clones with no OXY_TOKEN, and the clone keeps no token of its own.
218
    let store = oxy_core::credentials::Credentials::user();
219
    let hub = oxy_core::credentials::hub_of(&h.base).unwrap();
220
    store.save(&hub, &rw, Some("andy"), None).unwrap();
221
    let signed_in = Repo::clone(&format!("{}/andy/secret", h.base), &work.path().join("signedin"));
222
    store.remove(&hub).unwrap();
223
    let signed_in = signed_in.unwrap();
224
    assert!(signed_in.config.remote_tokens.is_empty());
225
    assert_eq!(signed_in.bookmark_heads().unwrap(), vec![c1]);
226
227
    // Linking a key: upload the identity, sign the challenge, see attribution.
228
    let (key, identity) = {
229
        let k = client.config.author_key.unwrap();
230
        (k, client.identity(&k).unwrap())
231
    };
232
    let keys_page = get(app, "/settings/keys", Some(&andy)).await;
233
    let csrf = csrf_of(&keys_page.body);
234
    let boundary = "XYZ";
235
    let mut multipart = Vec::new();
236
    multipart.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"_csrf\"\r\n\r\n{csrf}\r\n").as_bytes());
237
    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());
238
    multipart.extend_from_slice(&identity.encode());
239
    multipart.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
240
    let req = Request::builder()
241
        .method("POST")
242
        .uri("/settings/keys/upload")
243
        .header(header::COOKIE, format!("oxyhub={andy}"))
244
        .header(header::CONTENT_TYPE, format!("multipart/form-data; boundary={boundary}"))
245
        .body(Body::from(multipart))
246
        .unwrap();
247
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
248
    assert_eq!(res.status(), StatusCode::OK);
249
    let body = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned();
250
    let challenge_hex = body.split("sign-challenge ").nth(1).unwrap().split('<').next().unwrap().trim().to_string();
251
    let challenge_id = body.split("name=\"challenge\" value=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
252
    let (_, sk) = client.secret_key().unwrap().unwrap();
253
    let sig = sk.sign_challenge(&key, &hex::decode(&challenge_hex).unwrap()).unwrap();
254
    let sig_hex = hex::encode(oxy_core::identity::Signature::encode_list(&[sig]));
255
    let r = post(app, "/settings/keys/verify", Some(&andy), &format!("_csrf={csrf}&challenge={challenge_id}&signature={sig_hex}")).await;
256
    assert!(r.body.contains("Key linked"), "{}", r.body);
257
    let hist = get(app, "/andy/secret/changes/main", Some(&andy)).await.body;
258
    assert!(hist.contains("href=\"/andy\">Andy McCall</a>"), "author linked to the account: {hist}");
259
    let change = get(app, &format!("/andy/secret/change/{}", c1.to_hex()), Some(&andy)).await.body;
260
    assert!(change.contains("@andy"), "{change}");
261
    // A forged signature is refused.
262
    let r = post(app, "/settings/keys/verify", Some(&andy), &format!("_csrf={csrf}&challenge=999&signature={sig_hex}")).await;
263
    assert!(r.body.contains("expired"), "{}", r.body);
264
265
    // Organisations: a private org repository is visible to members through the default role.
266
    let org_page = get(app, "/orgs/new", Some(&andy)).await;
267
    let csrf = csrf_of(&org_page.body);
268
    let r = post(app, "/orgs/new", Some(&andy), &format!("_csrf={csrf}&name=acme&display_name=Acme")).await;
269
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
270
    let new_page = get(app, "/new", Some(&andy)).await;
271
    let csrf = csrf_of(&new_page.body);
272
    assert_eq!(
273
        post(app, "/new", Some(&andy), &format!("_csrf={csrf}&owner=acme&name=plans&visibility=private")).await.status,
274
        StatusCode::SEE_OTHER
275
    );
276
    assert_eq!(get(app, "/acme/plans", Some(&bob)).await.status, StatusCode::NOT_FOUND);
277
    let org_settings = get(app, "/orgs/acme/settings", Some(&andy)).await;
278
    let csrf = csrf_of(&org_settings.body);
279
    assert_eq!(
280
        post(app, "/orgs/acme/settings/members", Some(&andy), &format!("_csrf={csrf}&username=bob&role=member")).await.status,
281
        StatusCode::OK
282
    );
283
    assert_eq!(get(app, "/acme/plans", Some(&bob)).await.status, StatusCode::OK, "members read by default");
284
    assert_eq!(get(app, "/orgs/acme/settings", Some(&bob)).await.status, StatusCode::NOT_FOUND, "members do not administer");
285
    // Bob cannot create under acme's... he can, as a member; a stranger cannot.
286
    let r = post(
287
        app,
288
        "/new",
289
        Some(&bob),
290
        &format!("_csrf={}&owner=acme&name=bobs&visibility=public", csrf_of(&get(app, "/new", Some(&bob)).await.body)),
291
    )
292
    .await;
293
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
294
295
    // Sign out everywhere invalidates the old cookie.
296
    let sec = get(app, "/settings/security", Some(&andy)).await;
297
    let csrf = csrf_of(&sec.body);
298
    let r = post(app, "/settings/security/sessions", Some(&andy), &format!("_csrf={csrf}")).await;
299
    assert_eq!(r.status, StatusCode::SEE_OTHER);
300
    assert_eq!(get(app, "/settings", Some(&andy)).await.status, StatusCode::SEE_OTHER, "old session is gone");
301
    let fresh = r.cookie.unwrap();
302
    assert_eq!(get(app, "/settings", Some(&fresh)).await.status, StatusCode::OK);
303
304
    // TOTP: enable with the current code, then sign in needs it.
305
    let sec = get(app, "/settings/security", Some(&fresh)).await;
306
    let csrf = csrf_of(&sec.body);
307
    let r = post(app, "/settings/security/totp/begin", Some(&fresh), &format!("_csrf={csrf}")).await;
308
    let secret = r.body.split("name=\"secret\" value=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
309
    let now = (db::now_ms() / 1000) as u64;
310
    let code = oxygenhub::auth::totp::current(&secret, now).unwrap();
311
    let r = post(app, "/settings/security/totp/enable", Some(&fresh), &format!("_csrf={csrf}&secret={secret}&code={code}")).await;
312
    assert!(r.body.contains("Recovery codes"), "{}", r.body);
313
    let r = post(app, "/login", None, "username=andy&password=correct-horse-battery&setup=test-setup").await;
314
    assert!(r.body.contains("authenticator"), "second step asked: {}", r.body);
315
    // Submit the second step as a browser would: every field of the
316
    // rendered form, each name once (a repeated name is refused).
317
    let form = &r.body[r.body.find("<form class=\"card\" method=\"post\" action=\"/login\">").unwrap()..];
318
    let form = &form[..form.find("</form>").unwrap()];
319
    let names: Vec<&str> = form.split("name=\"").skip(1).map(|t| t.split('"').next().unwrap()).collect();
320
    let mut unique = names.clone();
321
    unique.sort();
322
    unique.dedup();
323
    assert_eq!(unique.len(), names.len(), "a field named twice: {names:?}");
324
    // The code step asks for the code alone: the password is not typed
325
    // again, the step carries proof of it instead.
326
    assert!(!names.contains(&"password"), "{names:?}");
327
    let pending = form.split("name=\"pending\" value=\"").nth(1).unwrap().split('"').next().unwrap().to_string();
328
    let code = oxygenhub::auth::totp::current(&secret, (db::now_ms() / 1000) as u64).unwrap();
329
    let fill = |pending: &str| -> String {
330
        names
331
            .iter()
332
            .map(|n| match *n {
333
                "username" => "username=andy".to_string(),
334
                "pending" => format!("pending={pending}"),
335
                "code" => format!("code={code}"),
336
                other => format!("{other}="),
337
            })
338
            .collect::<Vec<_>>()
339
            .join("&")
340
    };
341
    // A forged or stale proof starts again.
342
    let r = post(app, "/login", None, &fill("1.forged")).await;
343
    assert!(r.body.contains("sign in again") && r.cookie.is_none(), "{}", r.body);
344
    let r = post(app, "/login", None, &fill(&pending)).await;
345
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
346
    assert!(r.cookie.is_some());
347
    assert!(r.location.as_deref() == Some("/"));
348
}
349
350
/// A multipart picture form.
351
fn picture_form(csrf: &str, action: &str, file: &[u8]) -> (String, Vec<u8>) {
352
    let boundary = "picture-boundary-1234";
353
    let mut body = Vec::new();
354
    body.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"_csrf\"\r\n\r\n{csrf}\r\n").as_bytes());
355
    body.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"action\"\r\n\r\n{action}\r\n").as_bytes());
356
    body.extend_from_slice(
357
        format!("--{boundary}\r\nContent-Disposition: form-data; name=\"picture\"; filename=\"me.png\"\r\nContent-Type: image/png\r\n\r\n")
358
            .as_bytes(),
359
    );
360
    body.extend_from_slice(file);
361
    body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes());
362
    (format!("multipart/form-data; boundary={boundary}"), body)
363
}
364
365
async fn upload(app: &Shared, path: &str, cookie: &str, csrf: &str, action: &str, file: &[u8]) -> Res {
366
    let (ct, body) = picture_form(csrf, action, file);
367
    let req = Request::post(path)
368
        .header(header::COOKIE, format!("oxyhub={cookie}"))
369
        .header(header::CONTENT_TYPE, ct)
370
        .body(Body::from(body))
371
        .unwrap();
372
    let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap();
373
    let status = res.status();
374
    let bytes = res.into_body().collect().await.unwrap().to_bytes();
375
    Res { status, body: String::from_utf8_lossy(&bytes).into_owned(), cookie: None, location: None, raw_cookies: vec![] }
376
}
377
378
/// Status, content type and bytes of a picture.
379
async fn picture(app: &Shared, name: &str) -> (StatusCode, String, Vec<u8>) {
380
    let res = oxygenhub::router(app.clone()).oneshot(Request::get(format!("/avatar/{name}")).body(Body::empty()).unwrap()).await.unwrap();
381
    let ct = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("").to_string();
382
    let status = res.status();
383
    (status, ct, res.into_body().collect().await.unwrap().to_bytes().to_vec())
384
}
385
386
fn png(w: u32, h: u32, alpha: bool) -> Vec<u8> {
387
    let img = if alpha {
388
        image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(w, h, |x, _| {
389
            image::Rgba([0, 114, 255, if x % 2 == 0 { 0 } else { 255 }])
390
        }))
391
    } else {
392
        image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(w, h, |x, y| image::Rgb([x as u8, y as u8, 128])))
393
    };
394
    let mut out = Vec::new();
395
    img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap();
396
    out
397
}
398
399
/// Repository settings (oxygenhub#278): one page per setting beside a
400
/// grouped sidebar that marks the page shown; a role sees only its pages
401
/// and the others are not found; each form returns to the page holding it.
402
#[tokio::test(flavor = "multi_thread")]
403
async fn repository_settings_are_a_page_each_by_role() {
404
    let h = hub().await;
405
    let app = &h.app;
406
    let andy = register(app, "andy", "").await;
407
    let mut invited = vec![];
408
    for name in ["bob", "carol"] {
409
        let csrf = csrf_of(&get(app, "/admin", Some(&andy)).await.body);
410
        let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={csrf}")).await;
411
        let code = r.body.split("register?invite=").nth(1).unwrap().split('<').next().unwrap().trim().to_string();
412
        invited.push(register(app, name, &code).await);
413
    }
414
    let (bob, carol) = (invited[0].clone(), invited[1].clone());
415
    let csrf = csrf_of(&get(app, "/new", Some(&andy)).await.body);
416
    let r = post(app, "/new", Some(&andy), &format!("_csrf={csrf}&owner=andy&name=demo&visibility=public")).await;
417
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
418
    let csrf = csrf_of(&get(app, "/andy/demo/settings", Some(&andy)).await.body);
419
    for (who, role) in [("bob", "maintain"), ("carol", "write")] {
420
        let r = post(app, "/andy/demo/settings/collaborators", Some(&andy), &format!("_csrf={csrf}&username={who}&role={role}")).await;
421
        let page = settled(app, r, Some(&andy), "/andy/demo/settings/collaborators").await;
422
        assert!(page.body.contains(&format!("{who} now has {role} access.")), "{}", page.body);
423
    }
424
425
    let marked = |slug: &str| format!("href=\"/andy/demo/settings/{slug}\" data-slug=\"{slug}\" class=\"on\" aria-current=\"page\"");
426
    let maintainers =
427
        ["general", "landing", "checks", "push-protection", "flow", "runs", "gates", "coverage", "git-mirror", "diffusion", "backup"];
428
    let admins = ["collaborators", "runners", "variables", "secrets", "webhooks", "assistants", "advanced"];
429
    // /settings is General, marked in the sidebar, with the groups' headings.
430
    let general = get(app, "/andy/demo/settings", Some(&andy)).await;
431
    assert_eq!(general.status, StatusCode::OK);
432
    assert!(general.body.contains(&marked("general")) && general.body.contains("id=\"general\""), "{}", general.body);
433
    for group in ["General", "Code", "Flow", "Integrations", "Data", "Danger zone"] {
434
        assert!(general.body.contains(&format!("<h2>{group}</h2>")), "group {group}");
435
    }
436
    assert!(general.body.contains("data-settings-anchors"), "kept #anchor links are sent on from General");
437
    // Every page renders for an admin, marked; one page's sections only.
438
    for slug in maintainers.iter().chain(admins.iter()) {
439
        let page = get(app, &format!("/andy/demo/settings/{slug}"), Some(&andy)).await;
440
        assert_eq!(page.status, StatusCode::OK, "{slug}");
441
        assert!(page.body.contains(&marked(slug)), "{slug} is marked: {}", page.body);
442
        for other in maintainers.iter().chain(admins.iter()).filter(|o| *o != slug) {
443
            assert!(!page.body.contains(&marked(other)), "{slug} marks {other}");
444
        }
445
    }
446
    let runs = get(app, "/andy/demo/settings/runs", Some(&andy)).await.body;
447
    assert!(runs.contains("id=\"flow-priority\"") && runs.contains("id=\"flow-supersede\"") && !runs.contains("id=\"general\""));
448
    // Storage is only for a repository kept in a bucket.
449
    assert_eq!(get(app, "/andy/demo/settings/storage", Some(&andy)).await.status, StatusCode::NOT_FOUND);
450
    assert!(!general.body.contains("/andy/demo/settings/storage\""));
451
    assert_eq!(get(app, "/andy/demo/settings/nope", Some(&andy)).await.status, StatusCode::NOT_FOUND);
452
453
    // A maintainer has the maintainers' pages only; the admins' are not
454
    // listed and not found.
455
    let page = get(app, "/andy/demo/settings", Some(&bob)).await;
456
    assert_eq!(page.status, StatusCode::OK);
457
    for slug in maintainers {
458
        assert_eq!(get(app, &format!("/andy/demo/settings/{slug}"), Some(&bob)).await.status, StatusCode::OK, "{slug}");
459
        assert!(page.body.contains(&format!("data-slug=\"{slug}\"")), "{slug} listed");
460
    }
461
    for slug in admins {
462
        assert_eq!(get(app, &format!("/andy/demo/settings/{slug}"), Some(&bob)).await.status, StatusCode::NOT_FOUND, "{slug}");
463
        assert!(!page.body.contains(&format!("data-slug=\"{slug}\"")), "{slug} not listed");
464
    }
465
    assert!(!page.body.contains("<h2>Danger zone</h2>"), "an empty group is left out");
466
    let bob_csrf = csrf_of(&page.body);
467
    let r = post(app, "/andy/demo/settings/flow-priority", Some(&bob), &format!("_csrf={bob_csrf}&priority=normal")).await;
468
    let back = settled(app, r, Some(&bob), "/andy/demo/settings/runs").await;
469
    assert!(back.body.contains("Its jobs are normal priority.") && back.body.contains(&marked("runs")), "{}", back.body);
470
    // A writer has none of them.
471
    assert_eq!(get(app, "/andy/demo/settings", Some(&carol)).await.status, StatusCode::NOT_FOUND);
472
    for slug in ["general", "push-protection", "advanced"] {
473
        assert_eq!(get(app, &format!("/andy/demo/settings/{slug}"), Some(&carol)).await.status, StatusCode::NOT_FOUND, "{slug}");
474
    }
475
476
    // Each form returns to its own page, with what happened.
477
    for (path, form, page, says) in [
478
        ("", "description=Demo&default_bookmark=main&visibility=public&topics=", "general", "Saved."),
479
        ("/requirements", "required_approvals=1", "landing", "Landing requirements saved."),
480
        ("/checks", "required_checks=build", "checks", "Required checks saved."),
481
        ("/push-protection", "", "push-protection", "Push protection is off"),
482
        ("/push-protection", "protect=on", "push-protection", "Push protection is on"),
483
        ("/secret-bypass", "fingerprint=0123456789abcdef&reason=a+test+fixture", "push-protection", "is allowed here"),
484
        ("/flow", "flow=sometimes", "flow", "Pick on, own runners, off or the site default."),
485
        ("/flow-priority", "priority=low", "runs", "Its jobs are low priority."),
486
        ("/flow-supersede", "running=on", "runs", "cancels the older runs it supersedes, queued or running"),
487
        ("/agent-gates", "agents=on", "gates", "may now approve or reject"),
488
        ("/variables", "action=set&name=RUST_LOG&value=debug", "variables", "RUST_LOG set."),
489
        ("/coverage", "min=80&max_drop=", "coverage", "Coverage rules saved"),
490
        ("/hooks", "action=delete&id=999", "webhooks", "Webhook deleted."),
491
        ("/mirror", "", "git-mirror", "The Git mirror is off."),
492
        ("/diffusion", "diffusion=off&land=propose", "diffusion", "Diffusion is off"),
493
        ("/backup", "backup=off", "backup", "left out of its owner"),
494
        ("/archive", "action=neither", "advanced", "Unknown action."),
495
    ] {
496
        let r = post(app, &format!("/andy/demo/settings{path}"), Some(&andy), &format!("_csrf={csrf}&{form}")).await;
497
        let back = settled(app, r, Some(&andy), &format!("/andy/demo/settings/{page}")).await;
498
        assert_eq!(back.status, StatusCode::OK, "{path}");
499
        assert!(back.body.contains(says) && back.body.contains(&marked(page)), "{path}: {}", back.body);
500
    }
501
502
    // A kept /settings#anchor link is sent on by hub.js, never inline.
503
    let js = get(app, "/static/hub.js", None).await.body;
504
    assert!(js.contains("[data-settings-anchors]") && js.contains("\"flow-priority\": \"runs\""), "{js}");
505
}
506
507
#[tokio::test(flavor = "multi_thread")]
508
async fn profile_pictures_and_logos() {
509
    let h = hub().await;
510
    let app = &h.app;
511
    let andy = register(app, "andy", "").await;
512
    assert_eq!(picture(app, "andy").await.1, "image/svg+xml", "the identicon first");
513
    let csrf = csrf_of(&get(app, "/settings", Some(&andy)).await.body);
514
    assert!(get(app, "/settings", Some(&andy)).await.body.contains("id=\"picture\""));
515
516
    // A photo: cropped, scaled and re-encoded as JPEG.
517
    let r = upload(app, "/settings/avatar", &andy, &csrf, "upload", &png(640, 480, false)).await;
518
    assert!(r.body.contains("Picture saved"), "{}", r.body);
519
    let (st, ct, bytes) = picture(app, "andy").await;
520
    assert_eq!((st, ct.as_str()), (StatusCode::OK, "image/jpeg"));
521
    let img = image::load_from_memory(&bytes).unwrap();
522
    assert_eq!((img.width(), img.height()), (400, 400));
523
    let stored = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap().avatar;
524
    assert!(stored.starts_with("jpeg:"), "{stored}");
525
526
    // Not an image, or no CSRF: refused, and the picture stays.
527
    let r = upload(
528
        app,
529
        "/settings/avatar",
530
        &andy,
531
        &csrf,
532
        "upload",
533
        b"<svg xmlns=\"http://www.w3.org/2000/svg\"><script>alert(1)</script></svg>",
534
    )
535
    .await;
536
    assert!(r.body.contains("not a PNG, JPEG or WebP"), "{}", r.body);
537
    let r = upload(app, "/settings/avatar", &andy, "wrong", "upload", &png(10, 10, false)).await;
538
    assert_ne!(r.status, StatusCode::OK);
539
    assert_eq!(picture(app, "andy").await.1, "image/jpeg");
540
    // Removing brings the identicon back.
541
    let r = upload(app, "/settings/avatar", &andy, &csrf, "remove", b"").await;
542
    assert!(r.body.contains("Picture removed"));
543
    assert_eq!(picture(app, "andy").await.1, "image/svg+xml");
544
545
    // An organisation's logo keeps its transparency; only owners may set it.
546
    let me = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
547
    db::accounts::create_org(&app.db, "acme", "Acme", me.id).await.unwrap();
548
    let org_csrf = csrf_of(&get(app, "/orgs/acme/settings", Some(&andy)).await.body);
549
    let r = upload(app, "/orgs/acme/settings/avatar", &andy, &org_csrf, "upload", &png(120, 120, true)).await;
550
    assert!(r.body.contains("Picture saved"), "{}", r.body);
551
    let (_, ct, bytes) = picture(app, "acme").await;
552
    assert_eq!(ct, "image/png");
553
    assert!(image::load_from_memory(&bytes).unwrap().color().has_alpha());
554
    let invite = {
555
        let admin = get(app, "/admin", Some(&andy)).await;
556
        let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={}", csrf_of(&admin.body))).await;
557
        let i = r.body.find("invite=").map(|i| i + 7).expect("an invitation");
558
        r.body[i..].chars().take_while(|c| c.is_ascii_alphanumeric()).collect::<String>()
559
    };
560
    let bob = register(app, "bob", &invite).await;
561
    let bob_csrf = csrf_of(&get(app, "/settings", Some(&bob)).await.body);
562
    let r = upload(app, "/orgs/acme/settings/avatar", &bob, &bob_csrf, "remove", b"").await;
563
    assert_eq!(r.status, StatusCode::NOT_FOUND, "not an owner");
564
    assert_eq!(picture(app, "acme").await.1, "image/png");
565
}
566
567
#[tokio::test(flavor = "multi_thread")]
568
async fn organisation_webhooks_and_storage() {
569
    let h = hub().await;
570
    let app = &h.app;
571
    let andy = register(app, "andy", "").await;
572
    let me = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
573
    let org = db::accounts::create_org(&app.db, "acme", "Acme", me.id).await.unwrap();
574
575
    // A repository requires one sealed approval by default only where
576
    // someone else can give it: an organisation of two or more members
577
    // (oxygenhub#64). Acme has one member so far, like a personal account.
578
    let alone = db::repos::create(&app.db, "acme", "alone", "", hub_api::Visibility::Public).await.unwrap();
579
    let solo = db::repos::create(&app.db, "andy", "solo", "", hub_api::Visibility::Public).await.unwrap();
580
    assert_eq!(db::proposals::requirements(&app.db, alone.id).await.unwrap().required_approvals, 0);
581
    assert_eq!(db::proposals::requirements(&app.db, solo.id).await.unwrap().required_approvals, 0);
582
    let bobby = db::accounts::create_account(&app.db, "bobby", "[email protected]", "x", "salt", false).await.unwrap();
583
    db::accounts::set_org_member(&app.db, org.id, bobby.id, "member").await.unwrap();
584
    let tools = db::repos::create(&app.db, "acme", "tools", "", hub_api::Visibility::Public).await.unwrap();
585
    assert_eq!(db::proposals::requirements(&app.db, tools.id).await.unwrap().required_approvals, 1);
586
587
    // Organisation webhooks: add, ping, deliveries; only for this organisation.
588
    let page = get(app, "/orgs/acme/settings", Some(&andy)).await;
589
    assert!(page.body.contains("id=\"webhooks\"") && page.body.contains("href=\"#webhooks\""));
590
    let csrf = csrf_of(&page.body);
591
    let r = post(app, "/orgs/acme/settings/hooks", Some(&andy), &format!("_csrf={csrf}&url=ftp%3A%2F%2Fx&events=*")).await;
592
    assert!(r.body.contains("starts with http"), "{}", r.body);
593
    let r = post(
594
        app,
595
        "/orgs/acme/settings/hooks",
596
        Some(&andy),
597
        &format!("_csrf={csrf}&url=https%3A%2F%2Fhooks.invalid%2Facme&secret=s&events=push"),
598
    )
599
    .await;
600
    assert!(r.body.contains("Webhook added"));
601
    let hooks = db::hooks::hooks_for_org(&app.db, org.id).await.unwrap();
602
    assert_eq!(hooks.len(), 1);
603
    let id = hooks[0].id;
604
    assert!(post(app, "/orgs/acme/settings/hooks", Some(&andy), &format!("_csrf={csrf}&id={id}&action=ping"))
605
        .await
606
        .body
607
        .contains("Ping queued"));
608
    let deliveries = get(app, &format!("/orgs/acme/settings/hooks/{id}/deliveries"), Some(&andy)).await;
609
    assert_eq!(deliveries.status, StatusCode::OK);
610
    assert!(deliveries.body.contains(">ping<") && deliveries.body.contains("/orgs/acme/settings#webhooks"));
611
    // A repository's hook cannot be touched through the organisation's form.
612
    let repo = oxygenhub::repos::RepoName::parse("andy/demo").unwrap();
613
    app.repos.create(&repo, None).unwrap();
614
    let row = db::repos::create(&app.db, "andy", "demo", "", hub_api::Visibility::Public).await.unwrap();
615
    let repo_hook = db::hooks::create_hook(&app.db, Some(row.id), None, "https://hooks.invalid/repo", "", "*").await.unwrap().id;
616
    post(app, "/orgs/acme/settings/hooks", Some(&andy), &format!("_csrf={csrf}&id={repo_hook}&action=delete")).await;
617
    assert!(db::hooks::hook(&app.db, repo_hook).await.unwrap().is_some(), "not the organisation's");
618
    assert_eq!(get(app, &format!("/orgs/acme/settings/hooks/{repo_hook}/deliveries"), Some(&andy)).await.status, StatusCode::NOT_FOUND);
619
    // The repository's own settings still manage its hooks (shared code).
620
    let rs = get(app, "/andy/demo/settings/webhooks", Some(&andy)).await;
621
    assert!(rs.body.contains("https://hooks.invalid/repo") && rs.body.contains("action=\"/andy/demo/settings/hooks\""));
622
623
    // Storage: sizes and loose objects, and maintenance packs them.
624
    let work = tempfile::tempdir().unwrap();
625
    let mut client = Repo::init(work.path()).unwrap();
626
    client.config.set("remote.origin.url", &format!("{}/andy/demo", h.base)).unwrap();
627
    let (token, hash) = oxygenhub::auth::new_token();
628
    db::accounts::create_token(&app.db, me.id, "push", &hash, "repo:write", "", None).await.unwrap();
629
    client.config.set("remote.origin.token", &token).unwrap();
630
    client.save_config().unwrap();
631
    write(work.path(), "a.txt", b"a\n");
632
    client.snapshot("t").unwrap();
633
    client.commit("one", &[]).unwrap();
634
    assert!(client.push("origin", false).unwrap().iter().all(|r| r.ok));
635
    let storage = get(app, "/admin/storage", Some(&andy)).await;
636
    assert_eq!(storage.status, StatusCode::OK);
637
    assert!(storage.body.contains("href=\"/andy/demo\""));
638
    let loose_before = std::fs::read_dir(app.repos.dir(&repo).join(".oxy/objects/loose")).map(|d| d.count()).unwrap_or(0);
639
    assert!(loose_before > 0, "the push left loose objects");
640
    let r = post(app, "/admin/storage", Some(&andy), &format!("_csrf={}&repo=andy%2Fdemo", csrf_of(&storage.body))).await;
641
    assert!(r.body.contains("Maintained 1 repository") && r.body.contains("loose objects packed"), "{}", r.body);
642
    // Packed: the store has no loose objects; their files stay retired for
643
    // an hour, for readers that listed them before the repack (#249).
644
    let loose_after = Repo::open(&app.repos.dir(&repo)).unwrap().store().loose_count().unwrap();
645
    assert_eq!(loose_after, 0, "packed");
646
    let audit = db::accounts::audit_rows(&app.db, 20).await.unwrap();
647
    assert!(audit.iter().any(|a| a.action == "admin.gc" && a.target == "andy/demo"));
648
    let r = post(app, "/admin/storage", Some(&andy), &format!("_csrf={}&repo=nobody%2Fnone", csrf_of(&storage.body))).await;
649
    assert!(r.body.contains("No repository nobody/none"));
650
}
651
652
/// oxygenhub#81: an admin disables an account (sign-in says so, its session
653
/// and pushes stop) and enables it again; deletes one, refused while it
654
/// owns a repository, after which its name stays retired.
655
#[tokio::test(flavor = "multi_thread")]
656
async fn admins_disable_enable_and_delete_accounts() {
657
    let h = hub().await;
658
    let app = &h.app;
659
    let andy = register(app, "andy", "").await;
660
    let invite = |app: Shared, andy: String| async move {
661
        let csrf = csrf_of(&get(&app, "/admin", Some(&andy)).await.body);
662
        let r = post(&app, "/admin/invite", Some(&andy), &format!("_csrf={csrf}")).await;
663
        r.body.split("register?invite=").nth(1).unwrap().split('<').next().unwrap().trim().to_string()
664
    };
665
    let bob = register(app, "bob", &invite(app.clone(), andy.clone()).await).await;
666
    let act = |who: &'static str, action: &'static str, confirm: &'static str| {
667
        let (app, andy) = (app.clone(), andy.clone());
668
        async move {
669
            let csrf = csrf_of(&get(&app, "/admin", Some(&andy)).await.body);
670
            post(&app, "/admin/account", Some(&andy), &format!("_csrf={csrf}&username={who}&action={action}&confirm={confirm}")).await.body
671
        }
672
    };
673
    let login = |user: &'static str| {
674
        let app = app.clone();
675
        async move { post(&app, "/login", None, &format!("username={user}&password=correct-horse-battery&setup=test-setup")).await }
676
    };
677
678
    // Disabled: sign-in says so, the old session no longer counts.
679
    act("bob", "disable", "").await;
680
    assert!(db::accounts::account_by_name(&app.db, "bob").await.unwrap().unwrap().disabled);
681
    let r = login("bob").await;
682
    assert!(r.body.contains("Your account has been disabled"), "{}", r.body);
683
    assert!(r.cookie.is_none());
684
    assert_eq!(get(app, "/settings", Some(&bob)).await.status, StatusCode::SEE_OTHER, "the session is refused");
685
    assert!(act("andy", "disable", "").await.contains("Not on yourself"));
686
    // Enabled again: sign-in works.
687
    act("bob", "enable", "").await;
688
    assert_eq!(login("bob").await.status, StatusCode::SEE_OTHER);
689
690
    // Delete: confirmed by name, refused while Bob owns a repository.
691
    let bob = login("bob").await.cookie.unwrap();
692
    let csrf = csrf_of(&get(app, "/new", Some(&bob)).await.body);
693
    assert_eq!(
694
        post(app, "/new", Some(&bob), &format!("_csrf={csrf}&owner=bob&name=keep&visibility=public")).await.status,
695
        StatusCode::SEE_OTHER
696
    );
697
    assert!(act("bob", "delete", "bo").await.contains("type bob to confirm"));
698
    let page = act("bob", "delete", "bob").await;
699
    assert!(page.contains("still owns bob/keep"), "{page}");
700
    assert!(db::accounts::account_by_name(&app.db, "bob").await.unwrap().is_some());
701
    let row = db::repos::get(&app.db, "bob", "keep").await.unwrap().unwrap();
702
    db::repos::delete(&app.db, row.id).await.unwrap();
703
    let page = act("bob", "delete", "bob").await;
704
    assert!(page.contains("bob deleted"), "{page}");
705
    assert!(db::accounts::account_by_name(&app.db, "bob").await.unwrap().is_none());
706
    assert_eq!(get(app, "/settings", Some(&bob)).await.status, StatusCode::SEE_OTHER);
707
    // Its name stays retired.
708
    let code = invite(app.clone(), andy.clone()).await;
709
    let r = post(
710
        app,
711
        "/register",
712
        None,
713
        &format!("username=bob&email=b%40example.com&password=correct-horse-battery&setup=test-setup&invite={code}"),
714
    )
715
    .await;
716
    assert!(r.body.contains("That name is taken"), "{}", r.body);
717
    // The last admin can be neither disabled nor deleted.
718
    assert!(act("andy", "delete", "andy").await.contains("Not on yourself"));
719
}
720
721
/// oxygenhub#89: an admin sets the site's job time limits on Admin →
722
/// Runners → Settings; nobody else can.
723
#[tokio::test(flavor = "multi_thread")]
724
async fn admins_set_the_job_time_limits() {
725
    let h = hub().await;
726
    let app = &h.app;
727
    let andy = register(app, "andy", "").await;
728
    let page = get(app, "/admin/runners/settings", Some(&andy)).await;
729
    assert_eq!(page.status, StatusCode::OK);
730
    assert!(page.body.contains("Job time limits") && page.body.contains("value=\"60\""), "the hub.toml default shows");
731
    let csrf = csrf_of(&page.body);
732
    let r = post(app, "/admin/runners/settings", Some(&andy), &format!("_csrf={csrf}&default_minutes=200&max_minutes=120&grace_minutes=5"))
733
        .await;
734
    assert!(r.body.contains("cannot be longer than the maximum"), "{}", r.body);
735
    let r = post(app, "/admin/runners/settings", Some(&andy), &format!("_csrf={csrf}&default_minutes=90&max_minutes=240&grace_minutes=10"))
736
        .await;
737
    assert!(r.body.contains("Saved."), "{}", r.body);
738
    let l = oxygenhub::flow::limits(app).await;
739
    assert_eq!((l.default_s, l.max_s, l.grace_ms), (5400, 14400, 600_000));
740
    assert!(get(app, "/admin/runners", Some(&andy)).await.body.contains("href=\"/admin/runners/settings\""));
741
    let code = {
742
        let csrf = csrf_of(&get(app, "/admin", Some(&andy)).await.body);
743
        let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={csrf}")).await;
744
        r.body.split("register?invite=").nth(1).unwrap().split('<').next().unwrap().trim().to_string()
745
    };
746
    let bob = register(app, "bob", &code).await;
747
    assert_ne!(get(app, "/admin/runners/settings", Some(&bob)).await.status, StatusCode::OK, "not for others");
748
}
749
750
/// Mail settings from the admin page (#101): saved over hub.toml, shown
751
/// with the password masked, a test message sent to the administrator.
752
#[tokio::test(flavor = "multi_thread")]
753
async fn mail_settings_are_saved_masked_and_tested_from_the_admin_page() {
754
    let h = hub().await;
755
    let app = &h.app;
756
    let andy = register(app, "andy", "").await;
757
    let page = get(app, "/admin", Some(&andy)).await.body;
758
    assert!(page.contains("Mail is off"), "{page}");
759
    let csrf = csrf_of(&page);
760
    // A directory store for messages, as hub.toml's file:// would be.
761
    let outbox = tempfile::tempdir().unwrap();
762
    let r = post(
763
        app,
764
        "/admin/mail",
765
        Some(&andy),
766
        &format!("_csrf={csrf}&smtp=file%3A%2F%2F{}&from=Hub+%3Chub%40example.org%3E", outbox.path().display()),
767
    )
768
    .await;
769
    assert!(r.body.contains("Mail settings saved") && r.body.contains("Mail is on"), "{}", r.body);
770
    assert!(oxygenhub::mail::enabled(app));
771
    let r = post(app, "/admin/mail/test", Some(&andy), &format!("_csrf={csrf}")).await;
772
    assert!(r.body.contains("Sent a test message to"), "{}", r.body);
773
    let sent: Vec<_> = std::fs::read_dir(outbox.path()).unwrap().flatten().collect();
774
    assert_eq!(sent.len(), 1);
775
    let text = std::fs::read_to_string(sent[0].path()).unwrap();
776
    assert!(text.contains("Subject: [") && text.contains("Test message") && text.contains("From: Hub <[email protected]>"), "{text}");
777
    // An SMTP URL comes back masked, and a masked value left alone keeps the password.
778
    let r = post(
779
        app,
780
        "/admin/mail",
781
        Some(&andy),
782
        &format!("_csrf={csrf}&smtp=smtps%3A%2F%2Fhub%3Asecret%40mail.example.org%3A465&from=Hub+%3Chub%40example.org%3E"),
783
    )
784
    .await;
785
    assert!(r.body.contains("smtps://hub:***@mail.example.org:465") && !r.body.contains("hub:secret"), "{}", r.body);
786
    let r = post(
787
        app,
788
        "/admin/mail",
789
        Some(&andy),
790
        &format!("_csrf={csrf}&smtp=smtps%3A%2F%2Fhub%3A***%40mail.example.org%3A465&from=Hub+%3Chub%40example.org%3E"),
791
    )
792
    .await;
793
    assert!(r.body.contains("Mail settings saved"), "{}", r.body);
794
    assert_eq!(oxygenhub::mail::settings(app).smtp, "smtps://hub:[email protected]:465");
795
    // A bad URL is refused; an empty one turns mail off.
796
    let r = post(app, "/admin/mail", Some(&andy), &format!("_csrf={csrf}&smtp=mail.example.org&from=x")).await;
797
    assert!(r.body.contains("starts with smtp://"), "{}", r.body);
798
    let r = post(app, "/admin/mail", Some(&andy), &format!("_csrf={csrf}&smtp=&from=")).await;
799
    assert!(r.body.contains("Mail is off"), "{}", r.body);
800
    assert!(!oxygenhub::mail::enabled(app));
801
    // Not for everyone.
802
    let r = post(app, "/admin/mail", None, &format!("_csrf={csrf}&smtp=&from=")).await;
803
    assert_ne!(r.status, StatusCode::OK);
804
805
    // The service panel (oxygenhub#181): Resend asks only for its key,
806
    // which is never shown again and is kept when left empty.
807
    let from = "from=OxygenHub+%3Cnoreply%40example.org%3E";
808
    let r = post(app, "/admin/mail", Some(&andy), &format!("_csrf={csrf}&service=resend&secret=&{from}")).await;
809
    assert!(r.body.contains("Give the Resend API key"), "{}", r.body);
810
    let r = post(app, "/admin/mail", Some(&andy), &format!("_csrf={csrf}&service=resend&secret=re_test_key_1&{from}")).await;
811
    assert!(r.body.contains("Mail settings saved") && !r.body.contains("re_test_key_1"), "{}", r.body);
812
    assert!(r.body.contains(r#"<option value="resend" selected>"#) && r.body.contains("saved: leave empty to keep it"), "{}", r.body);
813
    assert_eq!(oxygenhub::mail::settings(app).smtp, "smtps://resend:[email protected]:465");
814
    let r = post(app, "/admin/mail", Some(&andy), &format!("_csrf={csrf}&service=resend&secret=&{from}")).await;
815
    assert!(r.body.contains("Mail settings saved"), "{}", r.body);
816
    assert_eq!(oxygenhub::mail::settings(app).smtp, "smtps://resend:[email protected]:465", "kept");
817
    // Amazon SES in London, then off.
818
    let r =
819
        post(app, "/admin/mail", Some(&andy), &format!("_csrf={csrf}&service=ses&region=eu-west-2&user=AKIAEXAMPLE&secret=s3cret&{from}"))
820
            .await;
821
    assert!(r.body.contains(r#"<option value="ses" selected>"#), "{}", r.body);
822
    assert_eq!(oxygenhub::mail::settings(app).smtp, "smtps://AKIAEXAMPLE:[email protected]:465");
823
    let r = post(app, "/admin/mail", Some(&andy), &format!("_csrf={csrf}&service=off&{from}")).await;
824
    assert!(r.body.contains("Mail is off"), "{}", r.body);
825
}
826
827
/// A stand-in chat-completions endpoint: answers "OK from mock" and keeps
828
/// the Authorization header and body of each call.
829
async fn mock_assistant() -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
830
    use std::sync::{Arc, Mutex};
831
    let seen: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(vec![]));
832
    let s2 = seen.clone();
833
    let router = axum::Router::new().route(
834
        "/v1/chat/completions",
835
        axum::routing::post(move |headers: axum::http::HeaderMap, body: String| {
836
            let s2 = s2.clone();
837
            async move {
838
                let auth = headers.get("authorization").and_then(|v| v.to_str().ok()).unwrap_or("").to_string();
839
                s2.lock().unwrap().push(format!("{auth} {body}"));
840
                axum::Json(serde_json::json!({ "choices": [{ "message": { "role": "assistant", "content": "OK from mock" } }] }))
841
            }
842
        }),
843
    );
844
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
845
    let port = listener.local_addr().unwrap().port();
846
    tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
847
    (format!("http://127.0.0.1:{port}/v1/chat/completions"), seen)
848
}
849
850
fn enc(s: &str) -> String {
851
    s.replace('%', "%25").replace(':', "%3A").replace('/', "%2F").replace(' ', "+").replace('\n', "%0A").replace('&', "%26")
852
}
853
854
#[tokio::test(flavor = "multi_thread")]
855
async fn ai_assistants_are_kept_per_level_with_sealed_tokens_and_combined_downwards() {
856
    use oxygenhub::assistants::{self, Scope};
857
    let h = hub().await;
858
    let app = &h.app;
859
    let andy = register(app, "andy", "").await;
860
    let (endpoint, seen) = mock_assistant().await;
861
862
    // The site level: an administrator adds Claude with a token.
863
    let page = get(app, "/admin", Some(&andy)).await.body;
864
    assert!(page.contains("AI assistants") && page.contains("Add an assistant"), "{page}");
865
    let csrf = csrf_of(&page);
866
    let add = |name: &str, extra: &str| {
867
        format!(
868
            "_csrf={csrf}&action=add&name={name}&endpoint={}&api=chat-completions&model=claude-opus-5-5&token=sk-test-secret&enabled=1&budget=50000{extra}",
869
            enc(&endpoint)
870
        )
871
    };
872
    let r = post(app, "/admin/assistants", Some(&andy), &add("Claude", "")).await;
873
    assert!(r.body.contains("Claude added and answered: OK from mock") && r.body.contains("token set"), "{}", r.body);
874
    assert!(!r.body.contains("sk-test-secret"), "the token never comes back");
875
    let site = assistants::list(&app.db, Scope::Site).await.unwrap();
876
    assert_eq!(site.len(), 1);
877
    let claude = &site[0];
878
    assert!(!String::from_utf8_lossy(&claude.token).contains("sk-test"), "sealed at rest");
879
    assert_eq!(app.assistant_key.open(&claude.token).as_deref(), Some("sk-test-secret"));
880
    // A second of the same name is refused; a bad endpoint is explained.
881
    let r = post(app, "/admin/assistants", Some(&andy), &add("claude", "")).await;
882
    assert!(r.body.contains("already an assistant called"), "{}", r.body);
883
    let r = post(
884
        app,
885
        "/admin/assistants",
886
        Some(&andy),
887
        &format!("_csrf={csrf}&action=add&name=Bad&endpoint=ftp%3A%2F%2Fx&api=chat-completions&model=m"),
888
    )
889
    .await;
890
    assert!(r.body.contains("starting with https://"), "{}", r.body);
891
892
    // TEST calls the endpoint with the bearer token and shows the answer.
893
    let r = post(app, "/admin/assistants", Some(&andy), &format!("_csrf={csrf}&action=test&id={}", claude.id)).await;
894
    assert!(r.body.contains("Claude answered: OK from mock"), "{}", r.body);
895
    {
896
        let calls = seen.lock().unwrap();
897
        assert_eq!(calls.len(), 2, "once on add, once on test");
898
        assert!(calls[0].starts_with("Bearer sk-test-secret "), "{}", calls[0]);
899
        assert!(calls[0].contains("\"model\":\"claude-opus-5-5\"") && calls[0].contains("Reply with the single word OK"), "{}", calls[0]);
900
    }
901
    // An update with the token field empty keeps the stored token.
902
    let r = post(
903
        app,
904
        "/admin/assistants",
905
        Some(&andy),
906
        &format!("_csrf={csrf}&action=update&id={}&name=Claude&endpoint={}&api=chat-completions&model=claude-opus-5-5&token=&enabled=1&budget=60000", claude.id, enc(&endpoint)),
907
    )
908
    .await;
909
    assert!(r.body.contains("Claude updated.") && r.body.contains("context 60000 characters"), "{}", r.body);
910
    assert_eq!(
911
        app.assistant_key.open(&assistants::get(&app.db, claude.id).await.unwrap().unwrap().token).as_deref(),
912
        Some("sk-test-secret")
913
    );
914
    // The site prompt.
915
    let r =
916
        post(app, "/admin/assistants", Some(&andy), &format!("_csrf={csrf}&action=prompt&prompt={}", enc("Review for correctness first.")))
917
            .await;
918
    assert!(r.body.contains("Prompt saved.") && r.body.contains("Review for correctness first."), "{}", r.body);
919
920
    // An organisation and its repository see the site's assistant and prompt.
921
    let r = post(app, "/orgs/new", Some(&andy), &format!("_csrf={csrf}&name=acme&display_name=Acme")).await;
922
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
923
    let r = post(app, "/new", Some(&andy), &format!("_csrf={csrf}&owner=acme&name=plans&visibility=public")).await;
924
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
925
    let org_page = get(app, "/orgs/acme/settings", Some(&andy)).await.body;
926
    assert!(org_page.contains("Inherited") && org_page.contains("from the site") && org_page.contains("None of its own"), "{org_page}");
927
    assert!(org_page.contains("From the site") && org_page.contains("Review for correctness first."), "{org_page}");
928
    let repo = db::repos::get(&app.db, "acme", "plans").await.unwrap().unwrap();
929
    let on = assistants::enabled_for_repo(&app.db, &repo).await.unwrap();
930
    assert_eq!(on.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["Claude"]);
931
932
    // The organisation adds a prompt and its own DeepSeek; the repository
933
    // sees both levels' prompts under headings, outermost first.
934
    let r = post(
935
        app,
936
        "/orgs/acme/settings/assistants",
937
        Some(&andy),
938
        &format!("_csrf={csrf}&action=prompt&prompt={}", enc("We write 6502 assembly.")),
939
    )
940
    .await;
941
    assert!(r.body.contains("Prompt saved."), "{}", r.body);
942
    let r = post(app, "/orgs/acme/settings/assistants", Some(&andy), &add("DeepSeek", "")).await;
943
    assert!(r.body.contains("DeepSeek added and answered"), "{}", r.body);
944
    let prompt = assistants::prompt_for_repo(&app.db, &repo).await.unwrap();
945
    assert!(prompt.starts_with("## Instructions from the site\n\nReview for correctness first.\n\n## Instructions from the acme organisation\n\nWe write 6502 assembly."), "{prompt}");
946
    let repo_page = get(app, "/acme/plans/settings/assistants", Some(&andy)).await.body;
947
    assert!(repo_page.contains("from the acme organisation") && repo_page.contains("From the acme organisation"), "{repo_page}");
948
    let on = assistants::enabled_for_repo(&app.db, &repo).await.unwrap();
949
    assert_eq!(on.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["Claude", "DeepSeek"]);
950
951
    // Turning Claude off at the site turns it off below, even where a
952
    // repository defines its own Claude; turning it back on lets the
953
    // repository's own definition win.
954
    let r = post(app, "/admin/assistants", Some(&andy), &format!("_csrf={csrf}&action=toggle&id={}", claude.id)).await;
955
    assert!(r.body.contains("Claude is off."), "{}", r.body);
956
    let r = post(app, "/acme/plans/settings/assistants", Some(&andy), &add("Claude", "")).await;
957
    let r = settled(app, r, Some(&andy), "/acme/plans/settings/assistants").await;
958
    assert!(r.body.contains("Claude added and answered"), "{}", r.body);
959
    let on = assistants::enabled_for_repo(&app.db, &repo).await.unwrap();
960
    assert_eq!(on.iter().map(|a| a.name.as_str()).collect::<Vec<_>>(), ["DeepSeek"]);
961
    let repo_page = get(app, "/acme/plans/settings/assistants", Some(&andy)).await.body;
962
    assert!(repo_page.contains("off above"), "{repo_page}");
963
    post(app, "/admin/assistants", Some(&andy), &format!("_csrf={csrf}&action=toggle&id={}", claude.id)).await;
964
    let on = assistants::enabled_for_repo(&app.db, &repo).await.unwrap();
965
    assert_eq!(on.iter().map(|a| (a.name.as_str(), a.scope.as_str())).collect::<Vec<_>>(), [("DeepSeek", "org"), ("Claude", "repo")]);
966
967
    // Only administrators and owners reach the panels.
968
    let invite = {
969
        let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={csrf}")).await;
970
        let i = r.body.find("invite=").map(|i| i + 7).expect("an invitation");
971
        r.body[i..].chars().take_while(|c| c.is_ascii_alphanumeric()).collect::<String>()
972
    };
973
    let bob = register(app, "bob", &invite).await;
974
    assert_eq!(
975
        post(app, "/admin/assistants", Some(&bob), &format!("_csrf={csrf}&action=prompt&prompt=x")).await.status,
976
        StatusCode::NOT_FOUND
977
    );
978
    assert_eq!(
979
        post(app, "/orgs/acme/settings/assistants", Some(&bob), &format!("_csrf={csrf}&action=prompt&prompt=x")).await.status,
980
        StatusCode::NOT_FOUND
981
    );
982
    assert_eq!(
983
        post(app, "/acme/plans/settings/assistants", Some(&bob), &format!("_csrf={csrf}&action=prompt&prompt=x")).await.status,
984
        StatusCode::NOT_FOUND
985
    );
986
    // Deleting the repository forgets its assistants and prompt.
987
    let r = post(app, "/acme/plans/settings/delete", Some(&andy), &format!("_csrf={csrf}&confirm=acme%2Fplans")).await;
988
    assert!(r.status == StatusCode::SEE_OTHER || r.status == StatusCode::OK, "{} {}", r.status, r.body);
989
    assert!(assistants::list(&app.db, Scope::Repo(repo.id)).await.unwrap().is_empty());
990
}
991
992
#[tokio::test(flavor = "multi_thread")]
993
async fn accounts_elsewhere_are_checked_and_shown_on_the_profile() {
994
    let h = hub().await;
995
    let app = &h.app;
996
    let andy = register(app, "andy", "").await;
997
    let page = get(app, "/settings", Some(&andy)).await.body;
998
    let csrf = csrf_of(&page);
999
    let base = format!("_csrf={csrf}&display_name=Andy&email=andy%40example.com&bio=&website=&location=");
1000
    let r = post(app, "/settings", Some(&andy), &format!("{base}&bluesky=%40Andy.bsky.social&mastodon=https%3A%2F%2FFosstodon.org%2F%40andy&github=https%3A%2F%2Fgithub.com%2Fandymccall%2F")).await;
1001
    assert!(
1002
        r.body.contains("value=\"andy.bsky.social\"")
1003
            && r.body.contains("value=\"@[email protected]\"")
1004
            && r.body.contains("value=\"andymccall\""),
1005
        "{}",
1006
        r.body
1007
    );
1008
    let profile = get(app, "/andy", None).await.body;
1009
    assert!(profile.contains("href=\"https://bsky.app/profile/andy.bsky.social\"") && profile.contains("@andy.bsky.social"), "{profile}");
1010
    assert!(profile.contains("href=\"https://fosstodon.org/@andy\"") && profile.contains("rel=\"nofollow noopener me\""), "{profile}");
1011
    assert!(profile.contains("href=\"https://github.com/andymccall\"") && profile.contains("title=\"GitHub\""), "{profile}");
1012
    // A bad one is refused and nothing changes.
1013
    let r = post(app, "/settings", Some(&andy), &format!("{base}&bluesky=not+a+handle&mastodon=&github=")).await;
1014
    assert!(r.body.contains("not a Bluesky handle"), "{}", r.body);
1015
    assert!(get(app, "/andy", None).await.body.contains("andy.bsky.social"));
1016
    // Cleared.
1017
    post(app, "/settings", Some(&andy), &format!("{base}&bluesky=&mastodon=&github=")).await;
1018
    assert!(!get(app, "/andy", None).await.body.contains("class=\"social\""));
1019
}
1020
1021
/// A stand-in GitHub and Google: token exchanges and who the token is.
1022
async fn mock_provider() -> (String, std::sync::Arc<std::sync::Mutex<Vec<String>>>) {
1023
    use std::sync::{Arc, Mutex};
1024
    let seen: Arc<Mutex<Vec<String>>> = Arc::new(Mutex::new(vec![]));
1025
    let s1 = seen.clone();
1026
    let s2 = seen.clone();
1027
    let router = axum::Router::new()
1028
        .route(
1029
            "/github/token",
1030
            axum::routing::post(move |body: String| {
1031
                let s1 = s1.clone();
1032
                async move {
1033
                    s1.lock().unwrap().push(format!("github token {body}"));
1034
                    axum::Json(serde_json::json!({ "access_token": "gh-token", "token_type": "bearer" }))
1035
                }
1036
            }),
1037
        )
1038
        .route(
1039
            "/github/userinfo",
1040
            axum::routing::get(|headers: axum::http::HeaderMap| async move {
1041
                assert_eq!(headers.get("authorization").and_then(|v| v.to_str().ok()), Some("Bearer gh-token"));
1042
                axum::Json(serde_json::json!({ "id": 583231, "login": "octocat", "name": "The Octocat", "email": null }))
1043
            }),
1044
        )
1045
        .route(
1046
            "/github/userinfo/emails",
1047
            axum::routing::get(|| async {
1048
                axum::Json(serde_json::json!([
1049
                    { "email": "[email protected]", "primary": false, "verified": false },
1050
                    { "email": "[email protected]", "primary": true, "verified": true }
1051
                ]))
1052
            }),
1053
        )
1054
        .route(
1055
            "/google/token",
1056
            axum::routing::post(move |body: String| {
1057
                let s2 = s2.clone();
1058
                async move {
1059
                    s2.lock().unwrap().push(format!("google token {body}"));
1060
                    axum::Json(serde_json::json!({ "access_token": "g-token", "id_token": "x" }))
1061
                }
1062
            }),
1063
        )
1064
        .route(
1065
            "/gitlab/token",
1066
            axum::routing::post(|| async { axum::Json(serde_json::json!({ "access_token": "gl-token", "token_type": "Bearer" })) }),
1067
        )
1068
        .route(
1069
            "/gitlab/userinfo",
1070
            axum::routing::get(|headers: axum::http::HeaderMap| async move {
1071
                assert_eq!(headers.get("authorization").and_then(|v| v.to_str().ok()), Some("Bearer gl-token"));
1072
                axum::Json(serde_json::json!({ "sub": "1234567", "nickname": "tanuki", "name": "The Tanuki", "email": "[email protected]", "email_verified": true }))
1073
            }),
1074
        )
1075
        .route(
1076
            "/google/userinfo",
1077
            axum::routing::get(|| async {
1078
                axum::Json(serde_json::json!({ "sub": "1076915035000615071", "email": "[email protected]", "email_verified": true, "name": "Andy McCall" }))
1079
            }),
1080
        );
1081
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1082
    let port = listener.local_addr().unwrap().port();
1083
    tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
1084
    (format!("http://127.0.0.1:{port}"), seen)
1085
}
1086
1087
fn state_of(res: &Res) -> (String, String) {
1088
    let cookie = res.raw_cookies.iter().find(|c| c.starts_with("oxyhub_signin=")).expect("state cookie").clone();
1089
    let value = cookie.trim_start_matches("oxyhub_signin=").split(';').next().unwrap().to_string();
1090
    (cookie, value)
1091
}
1092
1093
#[tokio::test(flavor = "multi_thread")]
1094
async fn people_sign_in_with_github_or_google_once_an_admin_sets_it_up() {
1095
    hermetic();
1096
    let (mock, seen) = mock_provider().await;
1097
    let dir = tempfile::tempdir().unwrap();
1098
    let mut config = Config::load(dir.path()).unwrap();
1099
    // The first account's setup code (oxygenhub#245).
1100
    config.registration.setup_code = "test-setup".into();
1101
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1102
    let port = listener.local_addr().unwrap().port();
1103
    config.server.base_url = format!("http://127.0.0.1:{port}");
1104
    config.registration.mode = "open".into();
1105
    config.auth.signin_mock = Some(mock.clone());
1106
    let app = oxygenhub::build(config).await.unwrap();
1107
    let router = oxygenhub::router(app.clone());
1108
    tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
1109
    let app = &app;
1110
    let andy = register(app, "andy", "").await;
1111
    let andy_row = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
1112
    db::accounts::set_email_verified(&app.db, andy_row.id, true).await.unwrap();
1113
1114
    // Nothing to sign in with until an administrator sets a provider up.
1115
    assert!(!get(app, "/login", None).await.body.contains("/login/github"));
1116
    let admin = get(app, "/admin", Some(&andy)).await.body;
1117
    assert!(admin.contains("Sign in with") && admin.contains(&format!("http://127.0.0.1:{port}/login/github/callback")), "{admin}");
1118
    let csrf = csrf_of(&admin);
1119
    let r =
1120
        post(app, "/admin/signin", Some(&andy), &format!("_csrf={csrf}&provider=github&client_id=gh-cid&secret=gh-sek&enabled=1")).await;
1121
    assert!(r.body.contains("Signing in with GitHub is on.") && !r.body.contains("gh-sek"), "{}", r.body);
1122
    let r = post(app, "/admin/signin", Some(&andy), &format!("_csrf={csrf}&provider=google&client_id=g-cid&secret=g-sek&enabled=1")).await;
1123
    assert!(r.body.contains("Signing in with Google is on."), "{}", r.body);
1124
    let login = get(app, "/login", None).await.body;
1125
    assert!(login.contains("href=\"/login/github\"") && login.contains("href=\"/login/google\""), "{login}");
1126
1127
    // GitHub: off to the provider with a state, back with a code: a new account.
1128
    let r = get(app, "/login/github", None).await;
1129
    assert_eq!(r.status, StatusCode::SEE_OTHER);
1130
    let to = r.location.clone().unwrap();
1131
    assert!(to.starts_with(&format!("{mock}/github/authorize?client_id=gh-cid&redirect_uri=")) && to.contains("&state="), "{to}");
1132
    let (cookie, state) = state_of(&r);
1133
    let bad = send_with(app, "GET", "/login/github/callback?code=c1&state=wrong", Some(&cookie), None).await;
1134
    assert!(bad.location.as_deref().unwrap_or("").starts_with("/login?error="), "{:?}", bad.location);
1135
    let ok = send_with(app, "GET", &format!("/login/github/callback?code=c1&state={state}"), Some(&cookie), None).await;
1136
    assert_eq!(ok.status, StatusCode::SEE_OTHER, "{}", ok.body);
1137
    assert_eq!(ok.location.as_deref(), Some("/"));
1138
    let octo_cookie = ok.cookie.clone().expect("signed in");
1139
    let octo = db::accounts::account_by_name(&app.db, "octocat").await.unwrap().expect("account made from the GitHub login");
1140
    assert!(
1141
        (octo.email.as_str(), octo.email_verified, octo.display_name.as_str()) == ("[email protected]", true, "The Octocat"),
1142
        "{octo:?}"
1143
    );
1144
    assert!(seen.lock().unwrap().iter().any(|s| s.contains("github token") && s.contains("code=c1") && s.contains("client_secret=gh-sek")));
1145
    assert!(get(app, "/settings", Some(&octo_cookie)).await.body.contains("octocat"));
1146
    // Again: the same account, no new one.
1147
    let r = get(app, "/login/github", None).await;
1148
    let (cookie, state) = state_of(&r);
1149
    let ok = send_with(app, "GET", &format!("/login/github/callback?code=c2&state={state}"), Some(&cookie), None).await;
1150
    assert_eq!(ok.location.as_deref(), Some("/"));
1151
    assert_eq!(db::accounts::account_count(&app.db).await.unwrap(), 2);
1152
1153
    // GitLab (#213): a self-managed address is checked, then sign-in makes
1154
    // an account from the GitLab username.
1155
    let r = post(
1156
        app,
1157
        "/admin/signin",
1158
        Some(&andy),
1159
        &format!("_csrf={csrf}&provider=gitlab&client_id=gl-cid&secret=gl-sek&enabled=1&base=http%3A%2F%2Fgitlab.example.org"),
1160
    )
1161
    .await;
1162
    assert!(r.body.contains("is an https:// address"), "{}", r.body);
1163
    let r = post(
1164
        app,
1165
        "/admin/signin",
1166
        Some(&andy),
1167
        &format!("_csrf={csrf}&provider=gitlab&client_id=gl-cid&secret=gl-sek&enabled=1&base=https%3A%2F%2Fgitlab.example.org%2F"),
1168
    )
1169
    .await;
1170
    assert!(r.body.contains("Signing in with GitLab is on.") && r.body.contains("value=\"https://gitlab.example.org\""), "{}", r.body);
1171
    let r = post(
1172
        app,
1173
        "/admin/signin",
1174
        Some(&andy),
1175
        &format!("_csrf={csrf}&provider=github&client_id=gh-cid&enabled=1&base=https%3A%2F%2Fx.org"),
1176
    )
1177
    .await;
1178
    assert!(r.body.contains("GitHub has no address to set."), "{}", r.body);
1179
    let login = get(app, "/login", None).await.body;
1180
    assert!(login.contains("signin-btn gitlab") && login.contains("Sign in with GitLab"), "{login}");
1181
    let r = get(app, "/login/gitlab", None).await;
1182
    assert!(r.location.clone().unwrap().contains("scope=openid%20profile%20email"), "{:?}", r.location);
1183
    let (cookie, state) = state_of(&r);
1184
    let ok = send_with(app, "GET", &format!("/login/gitlab/callback?code=c9&state={state}"), Some(&cookie), None).await;
1185
    assert_eq!(ok.location.as_deref(), Some("/"), "{}", ok.body);
1186
    let tanuki = db::accounts::account_by_name(&app.db, "tanuki").await.unwrap().expect("account made from the GitLab username");
1187
    assert!((tanuki.email.as_str(), tanuki.email_verified) == ("[email protected]", true), "{tanuki:?}");
1188
    assert_eq!(db::accounts::account_count(&app.db).await.unwrap(), 3);
1189
1190
    // Google, for an address Andy has verified: linked to Andy, signed in as Andy.
1191
    let r = get(app, "/login/google", None).await;
1192
    assert!(r.location.clone().unwrap().contains("prompt=select_account"));
1193
    let (cookie, state) = state_of(&r);
1194
    let ok = send_with(app, "GET", &format!("/login/google/callback?code=c3&state={state}"), Some(&cookie), None).await;
1195
    assert_eq!(ok.location.as_deref(), Some("/"), "{}", ok.body);
1196
    let as_andy = ok.cookie.clone().unwrap();
1197
    let sec = get(app, "/settings/security", Some(&as_andy)).await.body;
1198
    assert!(
1199
        sec.contains("Connected accounts")
1200
            && sec.contains("Google: <strong>andy</strong>")
1201
            && sec.contains("GitHub: <a href=\"/settings/security/connect/github\">connect</a>"),
1202
        "{sec}"
1203
    );
1204
    assert_eq!(db::accounts::account_count(&app.db).await.unwrap(), 3, "no fourth account");
1205
    // Disconnect, then connect again from Settings › Security.
1206
    let csrf_s = csrf_of(&sec);
1207
    let r = post(app, "/settings/security/disconnect/google", Some(&as_andy), &format!("_csrf={csrf_s}")).await;
1208
    assert!(r.location.as_deref().unwrap_or("").contains("notice=Google%20disconnected"), "{:?}", r.location);
1209
    assert!(!get(app, "/settings/security", Some(&as_andy)).await.body.contains("Google: <strong>andy</strong>"));
1210
    let r = get(app, "/settings/security/connect/google", Some(&as_andy)).await;
1211
    assert_eq!(r.status, StatusCode::SEE_OTHER);
1212
    let (cookie, state) = state_of(&r);
1213
    let both = format!("{cookie}; oxyhub={as_andy}");
1214
    let ok = send_with(app, "GET", &format!("/login/google/callback?code=c4&state={state}"), Some(&both), None).await;
1215
    assert!(ok.location.as_deref().unwrap_or("").contains("notice=Google%20connected%20as%20andy"), "{:?} {}", ok.location, ok.body);
1216
1217
    // With registration closed, an unknown GitHub account is turned away.
1218
    db::accounts::set_setting(&app.db, "registration_mode", "closed").await.unwrap();
1219
    sqlx::query("DELETE FROM account_logins WHERE provider = 'github'").execute(&app.db).await.unwrap();
1220
    sqlx::query("UPDATE accounts SET email_verified = FALSE WHERE username = 'octocat'").execute(&app.db).await.unwrap();
1221
    let r = get(app, "/login/github", None).await;
1222
    let (cookie, state) = state_of(&r);
1223
    let no = send_with(app, "GET", &format!("/login/github/callback?code=c5&state={state}"), Some(&cookie), None).await;
1224
    assert!(no.location.as_deref().unwrap_or("").contains("registration%20is%20closed"), "{:?}", no.location);
1225
    assert!(no.cookie.is_none());
1226
}
1227
1228
#[tokio::test(flavor = "multi_thread")]
1229
async fn administration_is_sectioned_and_its_audit_log_pages() {
1230
    let h = hub().await;
1231
    let app = &h.app;
1232
    let andy = register(app, "andy", "").await;
1233
    let andy_row = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
1234
    for i in 0..60 {
1235
        db::accounts::audit(&app.db, Some(&andy_row), "test.event", &format!("t{i}"), "").await.unwrap();
1236
    }
1237
    let page = get(app, "/admin", Some(&andy)).await.body;
1238
    for id in ["accounts", "registration", "organisations", "signin", "mail", "variables", "secrets", "assistants", "audit"] {
1239
        assert!(page.contains(&format!("href=\"#{id}\"")) && page.contains(&format!("id=\"{id}\"")), "section {id}: {page}");
1240
    }
1241
    assert!(page.contains("class=\"section-nav\""));
1242
    assert!(page.contains(">t59<") && !page.contains(">t5<"), "the newest page only");
1243
    let i = page.find("audit_before=").expect("an older link") + "audit_before=".len();
1244
    let before: String = page[i..].chars().take_while(|c| c.is_ascii_digit()).collect();
1245
    let older = get(app, &format!("/admin?audit_before={before}"), Some(&andy)).await.body;
1246
    assert!(older.contains(">t5<") && !older.contains(">t59<"), "the next page: {older}");
1247
}
1248
1249
#[tokio::test(flavor = "multi_thread")]
1250
async fn adding_an_assistant_offers_providers_and_only_models_the_endpoint_lists() {
1251
    let h = hub().await;
1252
    let app = &h.app;
1253
    let andy = register(app, "andy", "").await;
1254
    let router = axum::Router::new()
1255
        .route(
1256
            "/v1/models",
1257
            axum::routing::get(|headers: axum::http::HeaderMap| async move {
1258
                assert_eq!(headers.get("authorization").and_then(|v| v.to_str().ok()), Some("Bearer sk-m"));
1259
                axum::Json(serde_json::json!({ "data": [
1260
                    { "id": "models/gemini-3-pro" }, { "id": "gemini-3-flash" }, { "id": "text-embedding-004" }
1261
                ] }))
1262
            }),
1263
        )
1264
        .route(
1265
            "/v1/chat/completions",
1266
            axum::routing::post(|| async { axum::Json(serde_json::json!({ "choices": [{ "message": { "content": "OK" } }] })) }),
1267
        );
1268
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1269
    let port = listener.local_addr().unwrap().port();
1270
    tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
1271
    let ep = format!("http%3A%2F%2F127.0.0.1%3A{port}%2Fv1%2Fchat%2Fcompletions");
1272
1273
    let page = get(app, "/admin", Some(&andy)).await.body;
1274
    assert!(page.contains("data-preset-select") && page.contains("Google Gemini") && page.contains("Other (enter the endpoint)"), "{page}");
1275
    assert!(page.contains("LIST MODELS"));
1276
    let csrf = csrf_of(&page);
1277
    // The model list, as the button asks for it: chat models only, prefixes gone.
1278
    let r =
1279
        post(app, "/admin/assistants/models", Some(&andy), &format!("_csrf={csrf}&endpoint={ep}&api=chat-completions&token=sk-m")).await;
1280
    let v: serde_json::Value = serde_json::from_str(&r.body).unwrap();
1281
    assert_eq!(v["models"], serde_json::json!(["gemini-3-flash", "gemini-3-pro"]), "{}", r.body);
1282
    // A model the endpoint does not list is refused, with what it offers.
1283
    let r = post(
1284
        app,
1285
        "/admin/assistants",
1286
        Some(&andy),
1287
        &format!("_csrf={csrf}&action=add&preset=gemini&endpoint={ep}&model=gemini-2.5-pro&token=sk-m&enabled=1"),
1288
    )
1289
    .await;
1290
    assert!(r.body.contains("gemini-2.5-pro is not a model this endpoint offers") && r.body.contains("gemini-3-pro"), "{}", r.body);
1291
    // One it lists is added, named after the provider when no name is given.
1292
    let r = post(
1293
        app,
1294
        "/admin/assistants",
1295
        Some(&andy),
1296
        &format!("_csrf={csrf}&action=add&preset=gemini&endpoint={ep}&model=gemini-3-pro&token=sk-m&enabled=1"),
1297
    )
1298
    .await;
1299
    assert!(r.body.contains("Gemini added and answered: OK"), "{}", r.body);
1300
    let a = &oxygenhub::assistants::list(&app.db, oxygenhub::levels::Scope::Site).await.unwrap()[0];
1301
    assert_eq!((a.name.as_str(), a.api.as_str(), a.model.as_str()), ("Gemini", "chat-completions", "gemini-3-pro"));
1302
    // The stored token serves the edit form's button.
1303
    let r =
1304
        post(app, "/admin/assistants/models", Some(&andy), &format!("_csrf={csrf}&id={}&endpoint={ep}&api=chat-completions", a.id)).await;
1305
    assert!(r.body.contains("gemini-3-flash"), "{}", r.body);
1306
}
1307
1308
/// #217: a profile shows the year's pulse: changes pushed per day in
1309
/// repositories the viewer may see, the share via agent tokens, releases on
1310
/// the peaks; landings and private repositories the viewer cannot see are
1311
/// left out.
1312
#[tokio::test(flavor = "multi_thread")]
1313
async fn a_profile_shows_the_year_as_a_signal() {
1314
    let h = hub().await;
1315
    let app = &h.app;
1316
    register(app, "andy", "").await;
1317
    let andy = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap();
1318
    // The account is over a year old, but the span follows its first push.
1319
    sqlx::query("UPDATE accounts SET created_ms = $1 WHERE id = $2")
1320
        .bind(db::now_ms() - 400 * 86_400_000)
1321
        .bind(andy.id)
1322
        .execute(&app.db)
1323
        .await
1324
        .unwrap();
1325
    let game = db::repos::create(&app.db, "andy", "game", "", hub_api::Visibility::Public).await.unwrap();
1326
    let secret = db::repos::create(&app.db, "andy", "secret", "", hub_api::Visibility::Private).await.unwrap();
1327
    let now = db::now_ms();
1328
    for (repo, ago_days, changes, reason, via) in [
1329
        (game.id, 3, 5, "", ""),
1330
        (game.id, 3, 2, "", "Claude"),
1331
        (game.id, 40, 4, "", ""),
1332
        (game.id, 2, 9, "landed #1 (web)", ""),
1333
        (secret.id, 1, 50, "", ""),
1334
    ] {
1335
        sqlx::query("INSERT INTO pushes (repo_id, at_ms, reference, ok, reason, changes, account_id, pusher, via) VALUES ($1, $2, 'main', TRUE, $3, $4, $5, 'andy', $6)")
1336
            .bind(repo)
1337
            .bind(now - ago_days * 86_400_000)
1338
            .bind(reason)
1339
            .bind(changes)
1340
            .bind(andy.id)
1341
            .bind(via)
1342
            .execute(&app.db)
1343
            .await
1344
            .unwrap();
1345
    }
1346
    sqlx::query("INSERT INTO releases (repo_id, tag, title, author_id, author, created_ms) VALUES ($1, 'v1.0', 'One', $2, 'andy', $3)")
1347
        .bind(game.id)
1348
        .bind(andy.id)
1349
        .bind(now - 3 * 86_400_000)
1350
        .execute(&app.db)
1351
        .await
1352
        .unwrap();
1353
    // A stranger sees the public repository only, and no landing counts.
1354
    let page = get(app, "/andy", None).await.body;
1355
    let start = page.find("id=\"pulse-data\">").expect("the pulse is on the profile") + "id=\"pulse-data\">".len();
1356
    let json: serde_json::Value = serde_json::from_str(&page[start..start + page[start..].find("</script>").unwrap()]).unwrap();
1357
    assert_eq!(json["repos"], serde_json::json!(["andy/game"]));
1358
    let days = json["days"].as_array().unwrap();
1359
    // The first push was 40 days ago: three months are drawn, not a year.
1360
    assert_eq!((days.len(), json["months"].as_i64()), (91, Some(3)));
1361
    let total: i64 = days.iter().map(|d| d[0].as_i64().unwrap()).sum();
1362
    let via: i64 = days.iter().map(|d| d[1].as_i64().unwrap()).sum();
1363
    assert_eq!((total, via), (11, 2), "5 + 2 + 4 changes, 2 via an agent; the landing and the private push left out");
1364
    assert_eq!(days[87], serde_json::json!([7, 2, [[0, 7]]]), "three days ago");
1365
    assert_eq!(json["peaks"][0], serde_json::json!([87, "game v1.0"]));
1366
    db::accounts::create_account(&app.db, "bea", "[email protected]", "x", "salt", false).await.unwrap();
1367
    assert!(get(app, "/bea", None).await.body.contains("No changes pushed"), "a new account with no pushes says so");
1368
    assert!(
1369
        page.contains("data-total=\"11\"") && page.find("pulse-box").unwrap() < page.find("<h2>Repositories</h2>").unwrap(),
1370
        "above the repositories"
1371
    );
1372
}
1373
1374
/// #218: on an https site, what a proxy reports as plain http is sent to
1375
/// https (pages) or refused (forms), so a password is never taken over
1376
/// http; requests made to the hub directly are untouched; cookies are
1377
/// Secure.
1378
#[tokio::test(flavor = "multi_thread")]
1379
async fn an_https_site_takes_nothing_over_http() {
1380
    hermetic();
1381
    let dir = tempfile::tempdir().unwrap();
1382
    let mut config = Config::load(dir.path()).unwrap();
1383
    // The first account's setup code (oxygenhub#245).
1384
    config.registration.setup_code = "test-setup".into();
1385
    config.server.base_url = "https://hub.example.org".into();
1386
    config.registration.mode = "open".into();
1387
    let app = oxygenhub::build(config).await.unwrap();
1388
    let call = |method: &'static str, path: &'static str, header: Option<(&'static str, &'static str)>, body: Option<&'static str>| {
1389
        let app = app.clone();
1390
        async move {
1391
            let mut req = Request::builder().method(method).uri(path);
1392
            if let Some((k, v)) = header {
1393
                req = req.header(k, v);
1394
            }
1395
            if body.is_some() {
1396
                req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1397
            }
1398
            oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap()
1399
        }
1400
    };
1401
    // A page asked for over http (as the tunnel reports it) goes to https, path and query kept.
1402
    let r = call("GET", "/login?next=%2Fx", Some(("x-forwarded-proto", "http")), None).await;
1403
    assert!(r.status().is_redirection(), "{}", r.status());
1404
    assert_eq!(r.headers().get(header::LOCATION).unwrap(), "https://hub.example.org/login?next=%2Fx");
1405
    // A form over http is refused, whichever header says so.
1406
    let r = call("POST", "/login", Some(("cf-visitor", r#"{"scheme":"http"}"#)), Some("username=a&password=b")).await;
1407
    assert_eq!(r.status(), StatusCode::BAD_REQUEST);
1408
    // Over https, and asked of the hub directly (its runners), it answers.
1409
    assert_eq!(call("GET", "/login", Some(("x-forwarded-proto", "https")), None).await.status(), StatusCode::OK);
1410
    assert_eq!(call("GET", "/login", None, None).await.status(), StatusCode::OK);
1411
    // The session cookie is Secure.
1412
    let r = call(
1413
        "POST",
1414
        "/register",
1415
        Some(("x-forwarded-proto", "https")),
1416
        Some("username=andy&email=a%40example.org&password=correct-horse-battery&setup=test-setup"),
1417
    )
1418
    .await;
1419
    let cookie = r.headers().get(header::SET_COOKIE).expect("signed in").to_str().unwrap();
1420
    assert!(cookie.contains("; Secure") && cookie.contains("HttpOnly"), "{cookie}");
1421
    // No HSTS until a max-age is set (oxygenhub#231).
1422
    assert!(call("GET", "/login", Some(("x-forwarded-proto", "https")), None)
1423
        .await
1424
        .headers()
1425
        .get(header::STRICT_TRANSPORT_SECURITY)
1426
        .is_none());
1427
    assert_eq!(oxygenhub::headers::hsts("https://hub.example.org", 300).unwrap(), "max-age=300");
1428
    assert!(oxygenhub::headers::hsts("http://127.0.0.1:7300", 300).is_none(), "never over plain http");
1429
    assert!(oxygenhub::headers::hsts("https://hub.example.org", 0).is_none());
1430
}
1431
1432
#[tokio::test]
1433
async fn guessing_passwords_is_slowed_per_account_and_per_address() {
1434
    hermetic();
1435
    let dir = tempfile::tempdir().unwrap();
1436
    let mut config = Config::load(dir.path()).unwrap();
1437
    // The first account's setup code (oxygenhub#245).
1438
    config.registration.setup_code = "test-setup".into();
1439
    config.server.behind_proxy = true;
1440
    config.registration.mode = "open".into();
1441
    let app = oxygenhub::build(config).await.unwrap();
1442
    let from = |addr: &'static str, form: String| {
1443
        let app = app.clone();
1444
        async move {
1445
            let req = Request::builder()
1446
                .method("POST")
1447
                .uri("/login")
1448
                .header("x-forwarded-for", addr)
1449
                .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded");
1450
            let res = oxygenhub::router(app).oneshot(req.body(Body::from(form)).unwrap()).await.unwrap();
1451
            let status = res.status();
1452
            (status, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned())
1453
        }
1454
    };
1455
    register(&app, "andy", "").await;
1456
    let right = || "username=andy&password=correct-horse-battery&setup=test-setup".to_string();
1457
1458
    // An account: five wrong passwords cost nothing, the sixth starts a
1459
    // wait, and then even the right password waits (told when to retry).
1460
    for i in 0..6 {
1461
        let (_, body) = from("198.51.100.1", "username=andy&password=wrong".into()).await;
1462
        assert!(body.contains("Wrong username or password."), "try {i}");
1463
    }
1464
    let (status, body) = from("198.51.100.2", right()).await;
1465
    assert_eq!(status, StatusCode::OK, "not signed in");
1466
    assert!(body.contains("Too many tries: try again in"), "{body}");
1467
    let audit = db::accounts::audit_rows(&app.db, 50).await.unwrap();
1468
    assert!(audit.iter().any(|r| r.action == "login.throttled" && r.target == "andy" && r.detail.contains("198.51.100.1")));
1469
    app.throttle.lock().unwrap().cleared(&oxygenhub::throttle::Key::account("login", "andy"));
1470
1471
    // An address: twenty misses on any names, then it waits whoever it
1472
    // names; another address does not.
1473
    for i in 0..21 {
1474
        let (_, body) = from("203.0.113.7", format!("username=nobody{i}&password=wrong")).await;
1475
        assert!(body.contains("Wrong username or password."), "try {i}");
1476
    }
1477
    let (_, body) = from("203.0.113.7", right()).await;
1478
    assert!(body.contains("Too many tries"), "{body}");
1479
    let (status, _) = from("198.51.100.3", right()).await;
1480
    assert_eq!(status, StatusCode::SEE_OTHER, "another address signs in");
1481
}
1482
1483
#[tokio::test]
1484
async fn every_page_carries_the_security_headers_and_violations_are_reported() {
1485
    let h = hub().await;
1486
    let res = oxygenhub::router(h.app.clone()).oneshot(Request::get("/login").body(Body::empty()).unwrap()).await.unwrap();
1487
    let hd = res.headers();
1488
    assert_eq!(hd[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
1489
    assert_eq!(hd[header::REFERRER_POLICY], "strict-origin-when-cross-origin");
1490
    assert_eq!(hd[header::X_FRAME_OPTIONS], "DENY");
1491
    assert!(hd["permissions-policy"].to_str().unwrap().contains("camera=()"));
1492
    // Reported, not yet enforced; and no HSTS until the site owner says.
1493
    let csp = hd[header::CONTENT_SECURITY_POLICY_REPORT_ONLY].to_str().unwrap();
1494
    for part in [
1495
        "default-src 'self'",
1496
        "object-src 'none'",
1497
        "frame-ancestors 'none'",
1498
        "form-action 'self'",
1499
        "'wasm-unsafe-eval'",
1500
        "report-uri /csp-report",
1501
    ] {
1502
        assert!(csp.contains(part), "{part} in {csp}");
1503
    }
1504
    assert!(hd.get(header::CONTENT_SECURITY_POLICY).is_none() && hd.get(header::STRICT_TRANSPORT_SECURITY).is_none());
1505
    // Static files and errors carry them too.
1506
    let res = oxygenhub::router(h.app.clone()).oneshot(Request::get("/no/such/page").body(Body::empty()).unwrap()).await.unwrap();
1507
    assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff");
1508
1509
    let report =
1510
        r#"{"csp-report":{"document-uri":"http://127.0.0.1/login","violated-directive":"script-src-elem","blocked-uri":"inline"}}"#;
1511
    let req = Request::post("/csp-report").header(header::CONTENT_TYPE, "application/csp-report").body(Body::from(report)).unwrap();
1512
    assert_eq!(oxygenhub::router(h.app.clone()).oneshot(req).await.unwrap().status(), StatusCode::NO_CONTENT);
1513
    let big = Request::post("/csp-report").body(Body::from(vec![b' '; 64 * 1024])).unwrap();
1514
    assert_eq!(oxygenhub::router(h.app.clone()).oneshot(big).await.unwrap().status(), StatusCode::PAYLOAD_TOO_LARGE);
1515
}
1516
1517
#[tokio::test]
1518
async fn security_txt_names_the_contact_an_administrator_sets() {
1519
    let h = hub().await;
1520
    let app = &h.app;
1521
    assert_eq!(get(app, "/.well-known/security.txt", None).await.status, StatusCode::NOT_FOUND, "no contact, no file");
1522
    let andy = register(app, "andy", "").await;
1523
    let page = get(app, "/admin", Some(&andy)).await.body;
1524
    assert!(page.contains("No contact yet"), "the panel");
1525
    let csrf = csrf_of(&page);
1526
    let set = |contact: &'static str, policy: &'static str| {
1527
        let (andy, csrf) = (andy.clone(), csrf.clone());
1528
        async move { post(app, "/admin/security", Some(&andy), &format!("_csrf={csrf}&contact={contact}&policy={policy}")).await }
1529
    };
1530
    assert_eq!(set("javascript%3Aalert(1)", "").await.status, StatusCode::BAD_REQUEST);
1531
    assert_eq!(set("sec%40example.org", "http%3A%2F%2Fexample.org").await.status, StatusCode::BAD_REQUEST, "policy over https only");
1532
    let r = set("sec%40example.org", "https%3A%2F%2Fexample.org%2Fpolicy").await;
1533
    assert!(r.body.contains("Security contact saved"), "{}", r.body);
1534
    for path in ["/.well-known/security.txt", "/security.txt"] {
1535
        let r = get(app, path, None).await;
1536
        assert_eq!(r.status, StatusCode::OK);
1537
        assert!(r.body.starts_with("Contact: mailto:[email protected]\nExpires: 20"), "{}", r.body);
1538
        assert!(r.body.contains("Policy: https://example.org/policy\n") && r.body.contains("/.well-known/security.txt\n"), "{}", r.body);
1539
    }
1540
    // Someone not an administrator cannot change it.
1541
    let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={csrf}")).await;
1542
    let code = r.body.split("register?invite=").nth(1).unwrap().split('<').next().unwrap().trim().to_string();
1543
    let bob = register(app, "bob", &code).await;
1544
    let r = post(app, "/admin/security", Some(&bob), &format!("_csrf={csrf}&contact=x%40evil.example")).await;
1545
    assert_ne!(r.status, StatusCode::OK);
1546
    // An empty contact takes the file down.
1547
    set("", "").await;
1548
    assert_eq!(get(app, "/security.txt", None).await.status, StatusCode::NOT_FOUND);
1549
1550
    // /security-contact (oxygenhub#230): sensible text until it is written,
1551
    // then the address and the administrator's own text.
1552
    set("first%40example.org", "").await;
1553
    let page = get(app, "/security-contact", None).await;
1554
    assert_eq!(page.status, StatusCode::OK);
1555
    assert!(page.body.contains("[email protected]"), "security.txt's address until the page has its own");
1556
    assert!(page.body.contains("Report a security problem") && page.body.contains("tell us privately"), "{}", page.body);
1557
    let r = post(
1558
        app,
1559
        "/admin/security",
1560
        Some(&andy),
1561
        &format!(
1562
            "_csrf={csrf}&contact=https%3A%2F%2Fhub.example%2Fsecurity-contact&email=security%40example.org&page=Mail+us.+**Thank+you.**"
1563
        ),
1564
    )
1565
    .await;
1566
    assert!(r.body.contains("Security contact saved"), "{}", r.body);
1567
    let page = get(app, "/security-contact", None).await.body;
1568
    assert!(
1569
        page.contains("[email protected]") && page.contains("<strong>Thank you.</strong>") && !page.contains("tell us privately"),
1570
        "{page}"
1571
    );
1572
    let r = post(app, "/admin/security", Some(&andy), &format!("_csrf={csrf}&contact=sec%40example.org&email=not-an-address")).await;
1573
    assert_eq!(r.status, StatusCode::BAD_REQUEST);
1574
    assert!(!oxygenhub::repos::names::valid_owner("security-contact") && !oxygenhub::repos::names::valid_owner("live"), "reserved");
1575
}
1576
1577
#[tokio::test]
1578
async fn sessions_are_records_that_can_be_listed_ended_and_expire() {
1579
    let h = hub().await;
1580
    let app = &h.app;
1581
    let a = register(app, "andy", "").await;
1582
    assert_eq!(a.len(), 64, "a random id, not the account's name");
1583
    let b =
1584
        post(app, "/login", None, "username=andy&password=correct-horse-battery&setup=test-setup").await.cookie.expect("signed in again");
1585
    assert_ne!(a, b, "each sign-in is a new session");
1586
1587
    let page = get(app, "/settings/security", Some(&a)).await.body;
1588
    assert_eq!(page.matches("/end\"").count(), 2, "both browsers listed");
1589
    // Each entry is an <li>; the other browser's is the one without the tag.
1590
    let entries: Vec<&str> = page.split("<li><strong>").skip(1).filter(|e| e.contains("/end\"")).collect();
1591
    assert_eq!(entries.iter().filter(|e| e.contains("<span class=\"tag\">this browser</span>")).count(), 1);
1592
    let other = entries.iter().find(|e| !e.contains("class=\"tag\">this browser")).unwrap();
1593
    let other: i64 = other.split("/settings/security/sessions/").nth(1).unwrap().split('/').next().unwrap().parse().unwrap();
1594
    let csrf = csrf_of(&page);
1595
    let r = post(app, &format!("/settings/security/sessions/{other}/end"), Some(&a), &format!("_csrf={csrf}")).await;
1596
    assert_eq!(r.status, StatusCode::SEE_OTHER);
1597
    let signed_in = |c: String| async move { get(app, "/settings/security", Some(&c)).await.body.contains("SIGN OUT EVERYWHERE") };
1598
    assert!(signed_in(a.clone()).await, "this browser stays");
1599
    assert!(!signed_in(b.clone()).await, "that browser is signed out");
1600
1601
    // Unused for 14 days, it ends.
1602
    sqlx::query("UPDATE sessions SET seen_ms = seen_ms - 15 * 86400000").execute(&app.db).await.unwrap();
1603
    assert!(!signed_in(a.clone()).await, "idle too long");
1604
1605
    // Signing out ends the record itself, not just the cookie.
1606
    let c = post(app, "/login", None, "username=andy&password=correct-horse-battery&setup=test-setup").await.cookie.unwrap();
1607
    let csrf = csrf_of(&get(app, "/settings/security", Some(&c)).await.body);
1608
    post(app, "/logout", Some(&c), &format!("_csrf={csrf}")).await;
1609
    assert!(!signed_in(c).await, "the old cookie no longer works");
1610
    // A cookie of the old form (name.mac) is nobody.
1611
    assert!(!signed_in("andy.0123456789abcdef".into()).await);
1612
}
1613
1614
#[tokio::test]
1615
async fn an_invitation_signs_up_through_a_provider_once() {
1616
    hermetic();
1617
    let (mock, _) = mock_provider().await;
1618
    let dir = tempfile::tempdir().unwrap();
1619
    let mut config = Config::load(dir.path()).unwrap();
1620
    // The first account's setup code (oxygenhub#245).
1621
    config.registration.setup_code = "test-setup".into();
1622
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
1623
    let port = listener.local_addr().unwrap().port();
1624
    config.server.base_url = format!("http://127.0.0.1:{port}");
1625
    config.registration.mode = "invite".into();
1626
    config.auth.signin_mock = Some(mock.clone());
1627
    let app = oxygenhub::build(config).await.unwrap();
1628
    let router = oxygenhub::router(app.clone());
1629
    tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
1630
    let app = &app;
1631
    let andy = register(app, "andy", "").await;
1632
    let admin = get(app, "/admin", Some(&andy)).await.body;
1633
    let csrf = csrf_of(&admin);
1634
    post(app, "/admin/signin", Some(&andy), &format!("_csrf={csrf}&provider=github&client_id=gh-cid&secret=gh-sek&enabled=1")).await;
1635
1636
    // Without an invitation: no buttons, and the provider alone makes no account.
1637
    assert!(!get(app, "/register", None).await.body.contains("/login/github"));
1638
    let r = get(app, "/login/github", None).await;
1639
    let (cookie, state) = state_of(&r);
1640
    let no = send_with(app, "GET", &format!("/login/github/callback?code=c1&state={state}"), Some(&cookie), None).await;
1641
    assert!(no.location.as_deref().unwrap_or("").contains("by%20invitation"), "{:?}", no.location);
1642
    assert_eq!(db::accounts::account_count(&app.db).await.unwrap(), 1);
1643
1644
    // With one: the branded buttons carry it, it rides the round trip, and
1645
    // the new account uses it up.
1646
    let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={csrf}")).await;
1647
    let code = r.body.split("register?invite=").nth(1).unwrap().split('<').next().unwrap().trim().to_string();
1648
    let page = get(app, &format!("/register?invite={code}"), None).await.body;
1649
    assert!(page.contains(&format!("href=\"/login/github?invite={code}\"")) && page.contains("Sign up with GitHub"), "{page}");
1650
    let r = get(app, &format!("/login/github?invite={code}"), None).await;
1651
    assert_eq!(r.status, StatusCode::SEE_OTHER);
1652
    let (cookie, state) = state_of(&r);
1653
    let ok = send_with(app, "GET", &format!("/login/github/callback?code=c2&state={state}"), Some(&cookie), None).await;
1654
    assert_eq!(ok.location.as_deref(), Some("/"), "{}", ok.body);
1655
    let octo = db::accounts::account_by_name(&app.db, "octocat").await.unwrap().expect("signed up through the invitation");
1656
    assert!(!db::accounts::invitation_unused(&app.db, &code).await.unwrap(), "the invitation is spent");
1657
    let used_by: Option<i64> =
1658
        sqlx::query_scalar("SELECT used_by FROM invitations WHERE code = $1").bind(&code).fetch_one(&app.db).await.unwrap();
1659
    assert_eq!(used_by, Some(octo.id));
1660
1661
    // Spent: no buttons, and starting with it is refused plainly.
1662
    assert!(!get(app, &format!("/register?invite={code}"), None).await.body.contains("/login/github"));
1663
    let r = get(app, &format!("/login/github?invite={code}"), None).await;
1664
    assert_eq!(r.status, StatusCode::BAD_REQUEST);
1665
    assert!(r.body.contains("That invitation has been used or does not exist."), "{}", r.body);
1666
    assert_eq!(get(app, "/login/github?invite=not-a.code", None).await.status, StatusCode::BAD_REQUEST);
1667
}
1668
1669
/// A new hub hands administrator only to whoever brings its setup code
1670
/// (oxygenhub#245): the one it made, kept owner-only in its data directory,
1671
/// never on the web; once spent, the file is gone.
1672
#[tokio::test(flavor = "multi_thread")]
1673
async fn the_first_account_needs_the_setup_code_the_hub_made() {
1674
    hermetic();
1675
    let dir = tempfile::tempdir().unwrap();
1676
    let config = Config::load(dir.path()).unwrap();
1677
    let app = oxygenhub::build(config).await.unwrap();
1678
    let file = dir.path().join("setup-code");
1679
    let code = std::fs::read_to_string(&file).expect("an empty hub makes a setup code").trim().to_string();
1680
    assert_eq!(code.len(), 24);
1681
    #[cfg(unix)]
1682
    {
1683
        use std::os::unix::fs::PermissionsExt;
1684
        assert_eq!(std::fs::metadata(&file).unwrap().permissions().mode() & 0o777, 0o600);
1685
    }
1686
    let page = get(&app, "/register", None).await.body;
1687
    assert!(page.contains("name=\"setup\"") && !page.contains(&code), "asks for the code, never shows it");
1688
1689
    let form = |setup: &str| format!("username=mallory&email=m%40example.com&password=correct-horse-battery&setup={setup}");
1690
    for wrong in ["", "0123456789abcdef01234567"] {
1691
        let r = post(&app, "/register", None, &form(wrong)).await;
1692
        assert!(r.cookie.is_none() && r.body.contains("needs the setup code"), "{}", r.body);
1693
    }
1694
    assert_eq!(db::accounts::account_count(&app.db).await.unwrap(), 0);
1695
1696
    let r = post(&app, "/register", None, &form(&code).replace("mallory", "andy")).await;
1697
    assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body);
1698
    assert!(db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap().is_admin);
1699
    assert!(!file.exists(), "the code is spent");
1700
    // The next account is an ordinary one, under the registration mode.
1701
    let r = post(&app, "/register", None, &form(&code)).await;
1702
    assert!(r.body.contains("invitation"), "{}", r.body);
1703
}
1704
1705
/// Live L4 (docs/live.md, oxygenhub#206): a signed-in page's bell listens
1706
/// on the viewer's own topic, the inbox list on it too, and the dashboard's
1707
/// cards and feed on it and the viewer's repositories'; a signed-out page
1708
/// listens on nothing.
1709
#[tokio::test(flavor = "multi_thread")]
1710
async fn the_bell_inbox_and_dashboard_listen_on_the_viewer_s_topics() {
1711
    let h = hub().await;
1712
    let app = &h.app;
1713
    let andy = register(app, "andy", "").await;
1714
    let id = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap().id;
1715
    let topic = format!("user:{id}");
1716
    let page = get(app, "/explore", Some(&andy)).await.body;
1717
    assert!(page.contains(&format!("data-live=\"{topic}\" data-fragment=\"bell\"")), "the bell on every page");
1718
    let inbox = get(app, "/notifications", Some(&andy)).await.body;
1719
    assert!(inbox.contains(&format!("data-live=\"{topic}\" data-fragment=\"inbox\"")), "the inbox list");
1720
    let dash = get(app, "/", Some(&andy)).await.body;
1721
    assert!(dash.contains("data-fragment=\"cards\"") && dash.contains("data-fragment=\"feed\""), "{dash}");
1722
    assert!(dash.contains(&format!("data-live=\"{topic}")), "the dashboard listens on the viewer");
1723
    let anon = get(app, "/explore", None).await.body;
1724
    assert!(!anon.contains("data-fragment=\"bell\""), "nothing to hear signed out");
1725
}