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