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