//! Milestone 0.2 end to end: registration, sessions, tokens, roles and //! visibility, linked identities with attribution, organisations. use axum::body::Body; use axum::http::{header, Request, StatusCode}; use http_body_util::BodyExt; use oxy_core::repo::Repo; use oxygenhub::config::Config; use oxygenhub::db; use oxygenhub::Shared; use std::path::Path; use tower::ServiceExt; fn hermetic() { static ONCE: std::sync::Once = std::sync::Once::new(); static DIR: std::sync::OnceLock = std::sync::OnceLock::new(); ONCE.call_once(|| { let d = tempfile::tempdir().unwrap(); std::env::set_var("OXY_HOME", d.path()); DIR.set(d).ok(); }); } fn write(root: &Path, rel: &str, content: &[u8]) { let p = root.join(rel); std::fs::create_dir_all(p.parent().unwrap()).unwrap(); std::fs::write(p, content).unwrap(); } struct Hub { app: Shared, base: String, _dir: tempfile::TempDir, } async fn hub() -> Hub { hermetic(); let dir = tempfile::tempdir().unwrap(); let mut config = Config::load(dir.path()).unwrap(); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = listener.local_addr().unwrap().port(); config.server.base_url = format!("http://127.0.0.1:{port}"); // The stand-in webhook and assistant servers listen on 127.0.0.1 (#219). config.outbound.allow = vec!["http://127.0.0.1".into()]; config.registration.mode = "invite".into(); let app = oxygenhub::build(config).await.unwrap(); let router = oxygenhub::router(app.clone()); tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); Hub { app, base: format!("http://127.0.0.1:{port}"), _dir: dir } } struct Res { status: StatusCode, body: String, /// The session cookie's value, when the response set one. cookie: Option, location: Option, /// Every Set-Cookie header, whole. raw_cookies: Vec, } async fn send(app: &Shared, method: &str, path: &str, cookie: Option<&str>, form: Option<&str>) -> Res { let header_value = cookie.map(|c| format!("oxyhub={c}")); send_with(app, method, path, header_value.as_deref(), form).await } /// As `send`, with the whole Cookie header given. async fn send_with(app: &Shared, method: &str, path: &str, cookie_header: Option<&str>, form: Option<&str>) -> Res { let mut req = Request::builder().method(method).uri(path); if let Some(c) = cookie_header { req = req.header(header::COOKIE, c.to_string()); } let body = match form { Some(f) => { req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); Body::from(f.to_string()) } None => Body::empty(), }; let res = oxygenhub::router(app.clone()).oneshot(req.body(body).unwrap()).await.unwrap(); let status = res.status(); let raw_cookies: Vec = res.headers().get_all(header::SET_COOKIE).iter().filter_map(|v| v.to_str().ok()).map(String::from).collect(); let cookie = raw_cookies.iter().filter_map(|c| c.split(';').next()).filter_map(|kv| kv.strip_prefix("oxyhub=")).map(String::from).next(); let location = res.headers().get(header::LOCATION).and_then(|v| v.to_str().ok()).map(String::from); let bytes = res.into_body().collect().await.unwrap().to_bytes(); Res { status, body: String::from_utf8_lossy(&bytes).into_owned(), cookie, location, raw_cookies } } async fn get(app: &Shared, path: &str, cookie: Option<&str>) -> Res { send(app, "GET", path, cookie, None).await } async fn post(app: &Shared, path: &str, cookie: Option<&str>, form: &str) -> Res { send(app, "POST", path, cookie, Some(form)).await } /// Register (or sign in) and return the session cookie value. async fn register(app: &Shared, user: &str, invite: &str) -> String { let r = post(app, "/register", None, &format!("username={user}&email={user}%40example.com&password=correct-horse-battery&invite={invite}")) .await; assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); r.cookie.expect("session cookie") } fn csrf_of(page: &str) -> String { let i = page.find("name=\"_csrf\" value=\"").expect("csrf field") + "name=\"_csrf\" value=\"".len(); page[i..].split('"').next().unwrap().to_string() } #[tokio::test(flavor = "multi_thread")] async fn accounts_roles_tokens_and_attribution() { let h = hub().await; let app = &h.app; // The first account registers without an invitation and is the administrator. let andy = register(app, "andy", "").await; let me = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap(); assert!(me.is_admin); // A second registration needs an invitation. let r = post(app, "/register", None, "username=mallory&email=m%40example.com&password=correct-horse-battery&invite=").await; assert_eq!(r.status, StatusCode::OK); assert!(r.body.contains("invitation"), "{}", r.body); let admin_page = get(app, "/admin", Some(&andy)).await; assert_eq!(admin_page.status, StatusCode::OK); let csrf = csrf_of(&admin_page.body); let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={csrf}")).await; let code = r.body.split("register?invite=").nth(1).unwrap().split('<').next().unwrap().trim().to_string(); let bob = register(app, "bob", &code).await; assert!(!db::accounts::account_by_name(&app.db, "bob").await.unwrap().unwrap().is_admin); // Wrong password, banned users and CSRF-less posts are refused. assert_eq!(post(app, "/login", None, "username=andy&password=nope").await.status, StatusCode::OK); assert_eq!(post(app, "/settings", Some(&andy), "_csrf=bogus&display_name=x&email=y").await.status, StatusCode::BAD_REQUEST); assert_eq!(get(app, "/settings", None).await.status, StatusCode::SEE_OTHER, "anonymous settings redirects to sign in"); // Andy creates a private repository through the form; Bob cannot see it. let new_page = get(app, "/new", Some(&andy)).await; let csrf = csrf_of(&new_page.body); let r = post(app, "/new", Some(&andy), &format!("_csrf={csrf}&owner=andy&name=secret&description=hush&visibility=private")).await; assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); assert_eq!(get(app, "/andy/secret", Some(&andy)).await.status, StatusCode::OK); assert_eq!(get(app, "/andy/secret", Some(&bob)).await.status, StatusCode::NOT_FOUND); assert_eq!(get(app, "/andy/secret", None).await.status, StatusCode::NOT_FOUND); assert!(!get(app, "/", Some(&bob)).await.body.contains("secret")); assert!(get(app, "/", Some(&andy)).await.body.contains("secret")); // Tokens: a read-only token cannot push; a write token can. Anonymous cannot read a private repository. let tokens_page = get(app, "/settings/tokens", Some(&andy)).await; let csrf = csrf_of(&tokens_page.body); let r = post(app, "/settings/tokens", Some(&andy), &format!("_csrf={csrf}&name=ro&scopes=repo%3Aread")).await; let ro = r.body.split("oxyhub_").nth(1).map(|s| format!("oxyhub_{}", s.split('<').next().unwrap().trim())).unwrap(); let r = post(app, "/settings/tokens", Some(&andy), &format!("_csrf={csrf}&name=rw&scopes=repo%3Aread&scopes=repo%3Awrite")).await; let rw = r.body.split("oxyhub_").nth(1).map(|s| format!("oxyhub_{}", s.split('<').next().unwrap().trim())).unwrap(); let work = tempfile::tempdir().unwrap(); let mut client = Repo::init(work.path()).unwrap(); client.create_identity("Andy McCall", "andy@example.com", oxy_core::repo::IdentityScope::User).unwrap(); client.config.set("remote.origin.url", &format!("{}/andy/secret", h.base)).unwrap(); client.config.set("core.sign", "change").unwrap(); client.save_config().unwrap(); write(work.path(), "a.txt", b"a\n"); client.snapshot("t").unwrap(); let c1 = client.commit("first", &[]).unwrap(); let err = client.push("origin", false).err().unwrap().to_string(); assert!(err.contains("404"), "anonymous cannot even see it: {err}"); client.config.set("remote.origin.token", &ro).unwrap(); let err = client.push("origin", false).err().unwrap().to_string(); assert!(err.contains("403"), "read-only token cannot push: {err}"); client.config.set("remote.origin.token", &rw).unwrap(); assert!(client.push("origin", false).unwrap().iter().all(|r| r.ok)); // Bob's token cannot read it either. let bob_tokens = get(app, "/settings/tokens", Some(&bob)).await; let csrf_b = csrf_of(&bob_tokens.body); let r = post(app, "/settings/tokens", Some(&bob), &format!("_csrf={csrf_b}&name=b&scopes=repo%3Aread&scopes=repo%3Awrite")).await; let bob_tok = r.body.split("oxyhub_").nth(1).map(|s| format!("oxyhub_{}", s.split('<').next().unwrap().trim())).unwrap(); std::env::set_var("OXY_TOKEN", &bob_tok); let err = Repo::clone(&format!("{}/andy/secret", h.base), &work.path().join("bobclone")).err().unwrap().to_string(); std::env::remove_var("OXY_TOKEN"); assert!(err.contains("404"), "{err}"); // The push log names the pusher. tokio::time::sleep(std::time::Duration::from_millis(150)).await; let pushes = get(app, "/andy/secret/pushes", Some(&andy)).await.body; assert!(pushes.contains("andy"), "{pushes}"); // Bob becomes a collaborator with write, and can then see and push. let settings = get(app, "/andy/secret/settings", Some(&andy)).await; assert_eq!(settings.status, StatusCode::OK); let csrf = csrf_of(&settings.body); let r = post(app, "/andy/secret/settings/collaborators", Some(&andy), &format!("_csrf={csrf}&username=bob&role=write")).await; assert_eq!(r.status, StatusCode::OK, "{}", r.body); assert_eq!(get(app, "/andy/secret", Some(&bob)).await.status, StatusCode::OK); assert_eq!(get(app, "/andy/secret/settings", Some(&bob)).await.status, StatusCode::NOT_FOUND, "write is not maintain"); std::env::set_var("OXY_TOKEN", &bob_tok); let ok = Repo::clone(&format!("{}/andy/secret", h.base), &work.path().join("bobclone2")).is_ok(); std::env::remove_var("OXY_TOKEN"); assert!(ok); // oxygen#47: signed in once (oxy auth login), a private repository // clones with no OXY_TOKEN, and the clone keeps no token of its own. let store = oxy_core::credentials::Credentials::user(); let hub = oxy_core::credentials::hub_of(&h.base).unwrap(); store.save(&hub, &rw, Some("andy"), None).unwrap(); let signed_in = Repo::clone(&format!("{}/andy/secret", h.base), &work.path().join("signedin")); store.remove(&hub).unwrap(); let signed_in = signed_in.unwrap(); assert!(signed_in.config.remote_tokens.is_empty()); assert_eq!(signed_in.bookmark_heads().unwrap(), vec![c1]); // Linking a key: upload the identity, sign the challenge, see attribution. let (key, identity) = { let k = client.config.author_key.unwrap(); (k, client.identity(&k).unwrap()) }; let keys_page = get(app, "/settings/keys", Some(&andy)).await; let csrf = csrf_of(&keys_page.body); let boundary = "XYZ"; let mut multipart = Vec::new(); multipart.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"_csrf\"\r\n\r\n{csrf}\r\n").as_bytes()); 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()); multipart.extend_from_slice(&identity.encode()); multipart.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes()); let req = Request::builder() .method("POST") .uri("/settings/keys/upload") .header(header::COOKIE, format!("oxyhub={andy}")) .header(header::CONTENT_TYPE, format!("multipart/form-data; boundary={boundary}")) .body(Body::from(multipart)) .unwrap(); let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap(); assert_eq!(res.status(), StatusCode::OK); let body = String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned(); let challenge_hex = body.split("sign-challenge ").nth(1).unwrap().split('<').next().unwrap().trim().to_string(); let challenge_id = body.split("name=\"challenge\" value=\"").nth(1).unwrap().split('"').next().unwrap().to_string(); let (_, sk) = client.secret_key().unwrap().unwrap(); let sig = sk.sign_challenge(&key, &hex::decode(&challenge_hex).unwrap()).unwrap(); let sig_hex = hex::encode(oxy_core::identity::Signature::encode_list(&[sig])); let r = post(app, "/settings/keys/verify", Some(&andy), &format!("_csrf={csrf}&challenge={challenge_id}&signature={sig_hex}")).await; assert!(r.body.contains("Key linked"), "{}", r.body); let hist = get(app, "/andy/secret/changes/main", Some(&andy)).await.body; assert!(hist.contains("href=\"/andy\">Andy McCall"), "author linked to the account: {hist}"); let change = get(app, &format!("/andy/secret/change/{}", c1.to_hex()), Some(&andy)).await.body; assert!(change.contains("@andy"), "{change}"); // A forged signature is refused. let r = post(app, "/settings/keys/verify", Some(&andy), &format!("_csrf={csrf}&challenge=999&signature={sig_hex}")).await; assert!(r.body.contains("expired"), "{}", r.body); // Organisations: a private org repository is visible to members through the default role. let org_page = get(app, "/orgs/new", Some(&andy)).await; let csrf = csrf_of(&org_page.body); let r = post(app, "/orgs/new", Some(&andy), &format!("_csrf={csrf}&name=acme&display_name=Acme")).await; assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); let new_page = get(app, "/new", Some(&andy)).await; let csrf = csrf_of(&new_page.body); assert_eq!( post(app, "/new", Some(&andy), &format!("_csrf={csrf}&owner=acme&name=plans&visibility=private")).await.status, StatusCode::SEE_OTHER ); assert_eq!(get(app, "/acme/plans", Some(&bob)).await.status, StatusCode::NOT_FOUND); let org_settings = get(app, "/orgs/acme/settings", Some(&andy)).await; let csrf = csrf_of(&org_settings.body); assert_eq!( post(app, "/orgs/acme/settings/members", Some(&andy), &format!("_csrf={csrf}&username=bob&role=member")).await.status, StatusCode::OK ); assert_eq!(get(app, "/acme/plans", Some(&bob)).await.status, StatusCode::OK, "members read by default"); assert_eq!(get(app, "/orgs/acme/settings", Some(&bob)).await.status, StatusCode::NOT_FOUND, "members do not administer"); // Bob cannot create under acme's... he can, as a member; a stranger cannot. let r = post( app, "/new", Some(&bob), &format!("_csrf={}&owner=acme&name=bobs&visibility=public", csrf_of(&get(app, "/new", Some(&bob)).await.body)), ) .await; assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); // Sign out everywhere invalidates the old cookie. let sec = get(app, "/settings/security", Some(&andy)).await; let csrf = csrf_of(&sec.body); let r = post(app, "/settings/security/sessions", Some(&andy), &format!("_csrf={csrf}")).await; assert_eq!(r.status, StatusCode::SEE_OTHER); assert_eq!(get(app, "/settings", Some(&andy)).await.status, StatusCode::SEE_OTHER, "old session is gone"); let fresh = r.cookie.unwrap(); assert_eq!(get(app, "/settings", Some(&fresh)).await.status, StatusCode::OK); // TOTP: enable with the current code, then sign in needs it. let sec = get(app, "/settings/security", Some(&fresh)).await; let csrf = csrf_of(&sec.body); let r = post(app, "/settings/security/totp/begin", Some(&fresh), &format!("_csrf={csrf}")).await; let secret = r.body.split("name=\"secret\" value=\"").nth(1).unwrap().split('"').next().unwrap().to_string(); let now = (db::now_ms() / 1000) as u64; let code = oxygenhub::auth::totp::current(&secret, now).unwrap(); let r = post(app, "/settings/security/totp/enable", Some(&fresh), &format!("_csrf={csrf}&secret={secret}&code={code}")).await; assert!(r.body.contains("Recovery codes"), "{}", r.body); let r = post(app, "/login", None, "username=andy&password=correct-horse-battery").await; assert!(r.body.contains("authenticator"), "second step asked: {}", r.body); // Submit the second step as a browser would: every field of the // rendered form, each name once (a repeated name is refused). let form = &r.body[r.body.find("
").unwrap()..]; let form = &form[..form.find("
").unwrap()]; let names: Vec<&str> = form.split("name=\"").skip(1).map(|t| t.split('"').next().unwrap()).collect(); let mut unique = names.clone(); unique.sort(); unique.dedup(); assert_eq!(unique.len(), names.len(), "a field named twice: {names:?}"); // The code step asks for the code alone: the password is not typed // again, the step carries proof of it instead. assert!(!names.contains(&"password"), "{names:?}"); let pending = form.split("name=\"pending\" value=\"").nth(1).unwrap().split('"').next().unwrap().to_string(); let code = oxygenhub::auth::totp::current(&secret, (db::now_ms() / 1000) as u64).unwrap(); let fill = |pending: &str| -> String { names .iter() .map(|n| match *n { "username" => "username=andy".to_string(), "pending" => format!("pending={pending}"), "code" => format!("code={code}"), other => format!("{other}="), }) .collect::>() .join("&") }; // A forged or stale proof starts again. let r = post(app, "/login", None, &fill("1.forged")).await; assert!(r.body.contains("sign in again") && r.cookie.is_none(), "{}", r.body); let r = post(app, "/login", None, &fill(&pending)).await; assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); assert!(r.cookie.is_some()); assert!(r.location.as_deref() == Some("/")); } /// A multipart picture form. fn picture_form(csrf: &str, action: &str, file: &[u8]) -> (String, Vec) { let boundary = "picture-boundary-1234"; let mut body = Vec::new(); body.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"_csrf\"\r\n\r\n{csrf}\r\n").as_bytes()); body.extend_from_slice(format!("--{boundary}\r\nContent-Disposition: form-data; name=\"action\"\r\n\r\n{action}\r\n").as_bytes()); body.extend_from_slice( format!("--{boundary}\r\nContent-Disposition: form-data; name=\"picture\"; filename=\"me.png\"\r\nContent-Type: image/png\r\n\r\n") .as_bytes(), ); body.extend_from_slice(file); body.extend_from_slice(format!("\r\n--{boundary}--\r\n").as_bytes()); (format!("multipart/form-data; boundary={boundary}"), body) } async fn upload(app: &Shared, path: &str, cookie: &str, csrf: &str, action: &str, file: &[u8]) -> Res { let (ct, body) = picture_form(csrf, action, file); let req = Request::post(path) .header(header::COOKIE, format!("oxyhub={cookie}")) .header(header::CONTENT_TYPE, ct) .body(Body::from(body)) .unwrap(); let res = oxygenhub::router(app.clone()).oneshot(req).await.unwrap(); let status = res.status(); let bytes = res.into_body().collect().await.unwrap().to_bytes(); Res { status, body: String::from_utf8_lossy(&bytes).into_owned(), cookie: None, location: None, raw_cookies: vec![] } } /// Status, content type and bytes of a picture. async fn picture(app: &Shared, name: &str) -> (StatusCode, String, Vec) { let res = oxygenhub::router(app.clone()).oneshot(Request::get(format!("/avatar/{name}")).body(Body::empty()).unwrap()).await.unwrap(); let ct = res.headers().get(header::CONTENT_TYPE).and_then(|v| v.to_str().ok()).unwrap_or("").to_string(); let status = res.status(); (status, ct, res.into_body().collect().await.unwrap().to_bytes().to_vec()) } fn png(w: u32, h: u32, alpha: bool) -> Vec { let img = if alpha { image::DynamicImage::ImageRgba8(image::RgbaImage::from_fn(w, h, |x, _| { image::Rgba([0, 114, 255, if x % 2 == 0 { 0 } else { 255 }]) })) } else { image::DynamicImage::ImageRgb8(image::RgbImage::from_fn(w, h, |x, y| image::Rgb([x as u8, y as u8, 128]))) }; let mut out = Vec::new(); img.write_to(&mut std::io::Cursor::new(&mut out), image::ImageFormat::Png).unwrap(); out } #[tokio::test(flavor = "multi_thread")] async fn profile_pictures_and_logos() { let h = hub().await; let app = &h.app; let andy = register(app, "andy", "").await; assert_eq!(picture(app, "andy").await.1, "image/svg+xml", "the identicon first"); let csrf = csrf_of(&get(app, "/settings", Some(&andy)).await.body); assert!(get(app, "/settings", Some(&andy)).await.body.contains("id=\"picture\"")); // A photo: cropped, scaled and re-encoded as JPEG. let r = upload(app, "/settings/avatar", &andy, &csrf, "upload", &png(640, 480, false)).await; assert!(r.body.contains("Picture saved"), "{}", r.body); let (st, ct, bytes) = picture(app, "andy").await; assert_eq!((st, ct.as_str()), (StatusCode::OK, "image/jpeg")); let img = image::load_from_memory(&bytes).unwrap(); assert_eq!((img.width(), img.height()), (400, 400)); let stored = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap().avatar; assert!(stored.starts_with("jpeg:"), "{stored}"); // Not an image, or no CSRF: refused, and the picture stays. let r = upload( app, "/settings/avatar", &andy, &csrf, "upload", b"", ) .await; assert!(r.body.contains("not a PNG, JPEG or WebP"), "{}", r.body); let r = upload(app, "/settings/avatar", &andy, "wrong", "upload", &png(10, 10, false)).await; assert_ne!(r.status, StatusCode::OK); assert_eq!(picture(app, "andy").await.1, "image/jpeg"); // Removing brings the identicon back. let r = upload(app, "/settings/avatar", &andy, &csrf, "remove", b"").await; assert!(r.body.contains("Picture removed")); assert_eq!(picture(app, "andy").await.1, "image/svg+xml"); // An organisation's logo keeps its transparency; only owners may set it. let me = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap(); db::accounts::create_org(&app.db, "acme", "Acme", me.id).await.unwrap(); let org_csrf = csrf_of(&get(app, "/orgs/acme/settings", Some(&andy)).await.body); let r = upload(app, "/orgs/acme/settings/avatar", &andy, &org_csrf, "upload", &png(120, 120, true)).await; assert!(r.body.contains("Picture saved"), "{}", r.body); let (_, ct, bytes) = picture(app, "acme").await; assert_eq!(ct, "image/png"); assert!(image::load_from_memory(&bytes).unwrap().color().has_alpha()); let invite = { let admin = get(app, "/admin", Some(&andy)).await; let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={}", csrf_of(&admin.body))).await; let i = r.body.find("invite=").map(|i| i + 7).expect("an invitation"); r.body[i..].chars().take_while(|c| c.is_ascii_alphanumeric()).collect::() }; let bob = register(app, "bob", &invite).await; let bob_csrf = csrf_of(&get(app, "/settings", Some(&bob)).await.body); let r = upload(app, "/orgs/acme/settings/avatar", &bob, &bob_csrf, "remove", b"").await; assert_eq!(r.status, StatusCode::NOT_FOUND, "not an owner"); assert_eq!(picture(app, "acme").await.1, "image/png"); } #[tokio::test(flavor = "multi_thread")] async fn organisation_webhooks_and_storage() { let h = hub().await; let app = &h.app; let andy = register(app, "andy", "").await; let me = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap(); let org = db::accounts::create_org(&app.db, "acme", "Acme", me.id).await.unwrap(); // A repository requires one sealed approval by default only where // someone else can give it: an organisation of two or more members // (oxygenhub#64). Acme has one member so far, like a personal account. let alone = db::repos::create(&app.db, "acme", "alone", "", hub_api::Visibility::Public).await.unwrap(); let solo = db::repos::create(&app.db, "andy", "solo", "", hub_api::Visibility::Public).await.unwrap(); assert_eq!(db::proposals::requirements(&app.db, alone.id).await.unwrap().required_approvals, 0); assert_eq!(db::proposals::requirements(&app.db, solo.id).await.unwrap().required_approvals, 0); let bobby = db::accounts::create_account(&app.db, "bobby", "b@example.com", "x", "salt", false).await.unwrap(); db::accounts::set_org_member(&app.db, org.id, bobby.id, "member").await.unwrap(); let tools = db::repos::create(&app.db, "acme", "tools", "", hub_api::Visibility::Public).await.unwrap(); assert_eq!(db::proposals::requirements(&app.db, tools.id).await.unwrap().required_approvals, 1); // Organisation webhooks: add, ping, deliveries; only for this organisation. let page = get(app, "/orgs/acme/settings", Some(&andy)).await; assert!(page.body.contains("id=\"webhooks\"") && page.body.contains("href=\"#webhooks\"")); let csrf = csrf_of(&page.body); let r = post(app, "/orgs/acme/settings/hooks", Some(&andy), &format!("_csrf={csrf}&url=ftp%3A%2F%2Fx&events=*")).await; assert!(r.body.contains("starts with http"), "{}", r.body); let r = post( app, "/orgs/acme/settings/hooks", Some(&andy), &format!("_csrf={csrf}&url=https%3A%2F%2Fhooks.invalid%2Facme&secret=s&events=push"), ) .await; assert!(r.body.contains("Webhook added")); let hooks = db::hooks::hooks_for_org(&app.db, org.id).await.unwrap(); assert_eq!(hooks.len(), 1); let id = hooks[0].id; assert!(post(app, "/orgs/acme/settings/hooks", Some(&andy), &format!("_csrf={csrf}&id={id}&action=ping")) .await .body .contains("Ping queued")); let deliveries = get(app, &format!("/orgs/acme/settings/hooks/{id}/deliveries"), Some(&andy)).await; assert_eq!(deliveries.status, StatusCode::OK); assert!(deliveries.body.contains(">ping<") && deliveries.body.contains("/orgs/acme/settings#webhooks")); // A repository's hook cannot be touched through the organisation's form. let repo = oxygenhub::repos::RepoName::parse("andy/demo").unwrap(); app.repos.create(&repo, None).unwrap(); let row = db::repos::create(&app.db, "andy", "demo", "", hub_api::Visibility::Public).await.unwrap(); let repo_hook = db::hooks::create_hook(&app.db, Some(row.id), None, "https://hooks.invalid/repo", "", "*").await.unwrap().id; post(app, "/orgs/acme/settings/hooks", Some(&andy), &format!("_csrf={csrf}&id={repo_hook}&action=delete")).await; assert!(db::hooks::hook(&app.db, repo_hook).await.unwrap().is_some(), "not the organisation's"); assert_eq!(get(app, &format!("/orgs/acme/settings/hooks/{repo_hook}/deliveries"), Some(&andy)).await.status, StatusCode::NOT_FOUND); // The repository's own settings still manage its hooks (shared code). let rs = get(app, "/andy/demo/settings", Some(&andy)).await; assert!(rs.body.contains("https://hooks.invalid/repo") && rs.body.contains("action=\"/andy/demo/settings/hooks\"")); // Storage: sizes and loose objects, and maintenance packs them. let work = tempfile::tempdir().unwrap(); let mut client = Repo::init(work.path()).unwrap(); client.config.set("remote.origin.url", &format!("{}/andy/demo", h.base)).unwrap(); let (token, hash) = oxygenhub::auth::new_token(); db::accounts::create_token(&app.db, me.id, "push", &hash, "repo:write", "", None).await.unwrap(); client.config.set("remote.origin.token", &token).unwrap(); client.save_config().unwrap(); write(work.path(), "a.txt", b"a\n"); client.snapshot("t").unwrap(); client.commit("one", &[]).unwrap(); assert!(client.push("origin", false).unwrap().iter().all(|r| r.ok)); let storage = get(app, "/admin/storage", Some(&andy)).await; assert_eq!(storage.status, StatusCode::OK); assert!(storage.body.contains("href=\"/andy/demo\"")); let loose_before = std::fs::read_dir(app.repos.dir(&repo).join(".oxy/objects/loose")).map(|d| d.count()).unwrap_or(0); assert!(loose_before > 0, "the push left loose objects"); let r = post(app, "/admin/storage", Some(&andy), &format!("_csrf={}&repo=andy%2Fdemo", csrf_of(&storage.body))).await; assert!(r.body.contains("Maintained 1 repository") && r.body.contains("loose objects packed"), "{}", r.body); let loose_after: usize = walk_files(&app.repos.dir(&repo).join(".oxy/objects/loose")); assert_eq!(loose_after, 0, "packed"); let audit = db::accounts::audit_rows(&app.db, 20).await.unwrap(); assert!(audit.iter().any(|a| a.action == "admin.gc" && a.target == "andy/demo")); let r = post(app, "/admin/storage", Some(&andy), &format!("_csrf={}&repo=nobody%2Fnone", csrf_of(&storage.body))).await; assert!(r.body.contains("No repository nobody/none")); } fn walk_files(dir: &Path) -> usize { let Ok(rd) = std::fs::read_dir(dir) else { return 0 }; rd.flatten().map(|e| if e.path().is_dir() { walk_files(&e.path()) } else { 1 }).sum() } /// oxygenhub#81: an admin disables an account (sign-in says so, its session /// and pushes stop) and enables it again; deletes one, refused while it /// owns a repository, after which its name stays retired. #[tokio::test(flavor = "multi_thread")] async fn admins_disable_enable_and_delete_accounts() { let h = hub().await; let app = &h.app; let andy = register(app, "andy", "").await; let invite = |app: Shared, andy: String| async move { let csrf = csrf_of(&get(&app, "/admin", Some(&andy)).await.body); let r = post(&app, "/admin/invite", Some(&andy), &format!("_csrf={csrf}")).await; r.body.split("register?invite=").nth(1).unwrap().split('<').next().unwrap().trim().to_string() }; let bob = register(app, "bob", &invite(app.clone(), andy.clone()).await).await; let act = |who: &'static str, action: &'static str, confirm: &'static str| { let (app, andy) = (app.clone(), andy.clone()); async move { let csrf = csrf_of(&get(&app, "/admin", Some(&andy)).await.body); post(&app, "/admin/account", Some(&andy), &format!("_csrf={csrf}&username={who}&action={action}&confirm={confirm}")).await.body } }; let login = |user: &'static str| { let app = app.clone(); async move { post(&app, "/login", None, &format!("username={user}&password=correct-horse-battery")).await } }; // Disabled: sign-in says so, the old session no longer counts. act("bob", "disable", "").await; assert!(db::accounts::account_by_name(&app.db, "bob").await.unwrap().unwrap().disabled); let r = login("bob").await; assert!(r.body.contains("Your account has been disabled"), "{}", r.body); assert!(r.cookie.is_none()); assert_eq!(get(app, "/settings", Some(&bob)).await.status, StatusCode::SEE_OTHER, "the session is refused"); assert!(act("andy", "disable", "").await.contains("Not on yourself")); // Enabled again: sign-in works. act("bob", "enable", "").await; assert_eq!(login("bob").await.status, StatusCode::SEE_OTHER); // Delete: confirmed by name, refused while Bob owns a repository. let bob = login("bob").await.cookie.unwrap(); let csrf = csrf_of(&get(app, "/new", Some(&bob)).await.body); assert_eq!( post(app, "/new", Some(&bob), &format!("_csrf={csrf}&owner=bob&name=keep&visibility=public")).await.status, StatusCode::SEE_OTHER ); assert!(act("bob", "delete", "bo").await.contains("type bob to confirm")); let page = act("bob", "delete", "bob").await; assert!(page.contains("still owns bob/keep"), "{page}"); assert!(db::accounts::account_by_name(&app.db, "bob").await.unwrap().is_some()); let row = db::repos::get(&app.db, "bob", "keep").await.unwrap().unwrap(); db::repos::delete(&app.db, row.id).await.unwrap(); let page = act("bob", "delete", "bob").await; assert!(page.contains("bob deleted"), "{page}"); assert!(db::accounts::account_by_name(&app.db, "bob").await.unwrap().is_none()); assert_eq!(get(app, "/settings", Some(&bob)).await.status, StatusCode::SEE_OTHER); // Its name stays retired. let code = invite(app.clone(), andy.clone()).await; let r = post(app, "/register", None, &format!("username=bob&email=b%40example.com&password=correct-horse-battery&invite={code}")).await; assert!(r.body.contains("That name is taken"), "{}", r.body); // The last admin can be neither disabled nor deleted. assert!(act("andy", "delete", "andy").await.contains("Not on yourself")); } /// oxygenhub#89: an admin sets the site's job time limits on Admin → /// Runners → Settings; nobody else can. #[tokio::test(flavor = "multi_thread")] async fn admins_set_the_job_time_limits() { let h = hub().await; let app = &h.app; let andy = register(app, "andy", "").await; let page = get(app, "/admin/runners/settings", Some(&andy)).await; assert_eq!(page.status, StatusCode::OK); assert!(page.body.contains("Job time limits") && page.body.contains("value=\"60\""), "the hub.toml default shows"); let csrf = csrf_of(&page.body); let r = post(app, "/admin/runners/settings", Some(&andy), &format!("_csrf={csrf}&default_minutes=200&max_minutes=120&grace_minutes=5")) .await; assert!(r.body.contains("cannot be longer than the maximum"), "{}", r.body); let r = post(app, "/admin/runners/settings", Some(&andy), &format!("_csrf={csrf}&default_minutes=90&max_minutes=240&grace_minutes=10")) .await; assert!(r.body.contains("Saved."), "{}", r.body); let l = oxygenhub::flow::limits(app).await; assert_eq!((l.default_s, l.max_s, l.grace_ms), (5400, 14400, 600_000)); assert!(get(app, "/admin/runners", Some(&andy)).await.body.contains("href=\"/admin/runners/settings\"")); let code = { let csrf = csrf_of(&get(app, "/admin", Some(&andy)).await.body); let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={csrf}")).await; r.body.split("register?invite=").nth(1).unwrap().split('<').next().unwrap().trim().to_string() }; let bob = register(app, "bob", &code).await; assert_ne!(get(app, "/admin/runners/settings", Some(&bob)).await.status, StatusCode::OK, "not for others"); } /// Mail settings from the admin page (#101): saved over hub.toml, shown /// with the password masked, a test message sent to the administrator. #[tokio::test(flavor = "multi_thread")] async fn mail_settings_are_saved_masked_and_tested_from_the_admin_page() { let h = hub().await; let app = &h.app; let andy = register(app, "andy", "").await; let page = get(app, "/admin", Some(&andy)).await.body; assert!(page.contains("Mail is off"), "{page}"); let csrf = csrf_of(&page); // A directory store for messages, as hub.toml's file:// would be. let outbox = tempfile::tempdir().unwrap(); let r = post( app, "/admin/mail", Some(&andy), &format!("_csrf={csrf}&smtp=file%3A%2F%2F{}&from=Hub+%3Chub%40example.org%3E", outbox.path().display()), ) .await; assert!(r.body.contains("Mail settings saved") && r.body.contains("Mail is on"), "{}", r.body); assert!(oxygenhub::mail::enabled(app)); let r = post(app, "/admin/mail/test", Some(&andy), &format!("_csrf={csrf}")).await; assert!(r.body.contains("Sent a test message to"), "{}", r.body); let sent: Vec<_> = std::fs::read_dir(outbox.path()).unwrap().flatten().collect(); assert_eq!(sent.len(), 1); let text = std::fs::read_to_string(sent[0].path()).unwrap(); assert!(text.contains("Subject: [") && text.contains("Test message") && text.contains("From: Hub "), "{text}"); // An SMTP URL comes back masked, and a masked value left alone keeps the password. let r = post( app, "/admin/mail", Some(&andy), &format!("_csrf={csrf}&smtp=smtps%3A%2F%2Fhub%3Asecret%40mail.example.org%3A465&from=Hub+%3Chub%40example.org%3E"), ) .await; assert!(r.body.contains("smtps://hub:***@mail.example.org:465") && !r.body.contains("hub:secret"), "{}", r.body); let r = post( app, "/admin/mail", Some(&andy), &format!("_csrf={csrf}&smtp=smtps%3A%2F%2Fhub%3A***%40mail.example.org%3A465&from=Hub+%3Chub%40example.org%3E"), ) .await; assert!(r.body.contains("Mail settings saved"), "{}", r.body); assert_eq!(oxygenhub::mail::settings(app).smtp, "smtps://hub:secret@mail.example.org:465"); // A bad URL is refused; an empty one turns mail off. let r = post(app, "/admin/mail", Some(&andy), &format!("_csrf={csrf}&smtp=mail.example.org&from=x")).await; assert!(r.body.contains("starts with smtp://"), "{}", r.body); let r = post(app, "/admin/mail", Some(&andy), &format!("_csrf={csrf}&smtp=&from=")).await; assert!(r.body.contains("Mail is off"), "{}", r.body); assert!(!oxygenhub::mail::enabled(app)); // Not for everyone. let r = post(app, "/admin/mail", None, &format!("_csrf={csrf}&smtp=&from=")).await; assert_ne!(r.status, StatusCode::OK); } /// A stand-in chat-completions endpoint: answers "OK from mock" and keeps /// the Authorization header and body of each call. async fn mock_assistant() -> (String, std::sync::Arc>>) { use std::sync::{Arc, Mutex}; let seen: Arc>> = Arc::new(Mutex::new(vec![])); let s2 = seen.clone(); let router = axum::Router::new().route( "/v1/chat/completions", axum::routing::post(move |headers: axum::http::HeaderMap, body: String| { let s2 = s2.clone(); async move { let auth = headers.get("authorization").and_then(|v| v.to_str().ok()).unwrap_or("").to_string(); s2.lock().unwrap().push(format!("{auth} {body}")); axum::Json(serde_json::json!({ "choices": [{ "message": { "role": "assistant", "content": "OK from mock" } }] })) } }), ); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = listener.local_addr().unwrap().port(); tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); (format!("http://127.0.0.1:{port}/v1/chat/completions"), seen) } fn enc(s: &str) -> String { s.replace('%', "%25").replace(':', "%3A").replace('/', "%2F").replace(' ', "+").replace('\n', "%0A").replace('&', "%26") } #[tokio::test(flavor = "multi_thread")] async fn ai_assistants_are_kept_per_level_with_sealed_tokens_and_combined_downwards() { use oxygenhub::assistants::{self, Scope}; let h = hub().await; let app = &h.app; let andy = register(app, "andy", "").await; let (endpoint, seen) = mock_assistant().await; // The site level: an administrator adds Claude with a token. let page = get(app, "/admin", Some(&andy)).await.body; assert!(page.contains("AI assistants") && page.contains("Add an assistant"), "{page}"); let csrf = csrf_of(&page); let add = |name: &str, extra: &str| { format!( "_csrf={csrf}&action=add&name={name}&endpoint={}&api=chat-completions&model=claude-opus-5-5&token=sk-test-secret&enabled=1&budget=50000{extra}", enc(&endpoint) ) }; let r = post(app, "/admin/assistants", Some(&andy), &add("Claude", "")).await; assert!(r.body.contains("Claude added and answered: OK from mock") && r.body.contains("token set"), "{}", r.body); assert!(!r.body.contains("sk-test-secret"), "the token never comes back"); let site = assistants::list(&app.db, Scope::Site).await.unwrap(); assert_eq!(site.len(), 1); let claude = &site[0]; assert!(!String::from_utf8_lossy(&claude.token).contains("sk-test"), "sealed at rest"); assert_eq!(app.assistant_key.open(&claude.token).as_deref(), Some("sk-test-secret")); // A second of the same name is refused; a bad endpoint is explained. let r = post(app, "/admin/assistants", Some(&andy), &add("claude", "")).await; assert!(r.body.contains("already an assistant called"), "{}", r.body); let r = post( app, "/admin/assistants", Some(&andy), &format!("_csrf={csrf}&action=add&name=Bad&endpoint=ftp%3A%2F%2Fx&api=chat-completions&model=m"), ) .await; assert!(r.body.contains("starting with https://"), "{}", r.body); // TEST calls the endpoint with the bearer token and shows the answer. let r = post(app, "/admin/assistants", Some(&andy), &format!("_csrf={csrf}&action=test&id={}", claude.id)).await; assert!(r.body.contains("Claude answered: OK from mock"), "{}", r.body); { let calls = seen.lock().unwrap(); assert_eq!(calls.len(), 2, "once on add, once on test"); assert!(calls[0].starts_with("Bearer sk-test-secret "), "{}", calls[0]); assert!(calls[0].contains("\"model\":\"claude-opus-5-5\"") && calls[0].contains("Reply with the single word OK"), "{}", calls[0]); } // An update with the token field empty keeps the stored token. let r = post( app, "/admin/assistants", Some(&andy), &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)), ) .await; assert!(r.body.contains("Claude updated.") && r.body.contains("context 60000 characters"), "{}", r.body); assert_eq!( app.assistant_key.open(&assistants::get(&app.db, claude.id).await.unwrap().unwrap().token).as_deref(), Some("sk-test-secret") ); // The site prompt. let r = post(app, "/admin/assistants", Some(&andy), &format!("_csrf={csrf}&action=prompt&prompt={}", enc("Review for correctness first."))) .await; assert!(r.body.contains("Prompt saved.") && r.body.contains("Review for correctness first."), "{}", r.body); // An organisation and its repository see the site's assistant and prompt. let r = post(app, "/orgs/new", Some(&andy), &format!("_csrf={csrf}&name=acme&display_name=Acme")).await; assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); let r = post(app, "/new", Some(&andy), &format!("_csrf={csrf}&owner=acme&name=plans&visibility=public")).await; assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); let org_page = get(app, "/orgs/acme/settings", Some(&andy)).await.body; assert!(org_page.contains("Inherited") && org_page.contains("from the site") && org_page.contains("None of its own"), "{org_page}"); assert!(org_page.contains("From the site") && org_page.contains("Review for correctness first."), "{org_page}"); let repo = db::repos::get(&app.db, "acme", "plans").await.unwrap().unwrap(); let on = assistants::enabled_for_repo(&app.db, &repo).await.unwrap(); assert_eq!(on.iter().map(|a| a.name.as_str()).collect::>(), ["Claude"]); // The organisation adds a prompt and its own DeepSeek; the repository // sees both levels' prompts under headings, outermost first. let r = post( app, "/orgs/acme/settings/assistants", Some(&andy), &format!("_csrf={csrf}&action=prompt&prompt={}", enc("We write 6502 assembly.")), ) .await; assert!(r.body.contains("Prompt saved."), "{}", r.body); let r = post(app, "/orgs/acme/settings/assistants", Some(&andy), &add("DeepSeek", "")).await; assert!(r.body.contains("DeepSeek added and answered"), "{}", r.body); let prompt = assistants::prompt_for_repo(&app.db, &repo).await.unwrap(); 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}"); let repo_page = get(app, "/acme/plans/settings", Some(&andy)).await.body; assert!(repo_page.contains("from the acme organisation") && repo_page.contains("From the acme organisation"), "{repo_page}"); let on = assistants::enabled_for_repo(&app.db, &repo).await.unwrap(); assert_eq!(on.iter().map(|a| a.name.as_str()).collect::>(), ["Claude", "DeepSeek"]); // Turning Claude off at the site turns it off below, even where a // repository defines its own Claude; turning it back on lets the // repository's own definition win. let r = post(app, "/admin/assistants", Some(&andy), &format!("_csrf={csrf}&action=toggle&id={}", claude.id)).await; assert!(r.body.contains("Claude is off."), "{}", r.body); let r = post(app, "/acme/plans/settings/assistants", Some(&andy), &add("Claude", "")).await; assert!(r.body.contains("Claude added and answered"), "{}", r.body); let on = assistants::enabled_for_repo(&app.db, &repo).await.unwrap(); assert_eq!(on.iter().map(|a| a.name.as_str()).collect::>(), ["DeepSeek"]); let repo_page = get(app, "/acme/plans/settings", Some(&andy)).await.body; assert!(repo_page.contains("off above"), "{repo_page}"); post(app, "/admin/assistants", Some(&andy), &format!("_csrf={csrf}&action=toggle&id={}", claude.id)).await; let on = assistants::enabled_for_repo(&app.db, &repo).await.unwrap(); assert_eq!(on.iter().map(|a| (a.name.as_str(), a.scope.as_str())).collect::>(), [("DeepSeek", "org"), ("Claude", "repo")]); // Only administrators and owners reach the panels. let invite = { let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={csrf}")).await; let i = r.body.find("invite=").map(|i| i + 7).expect("an invitation"); r.body[i..].chars().take_while(|c| c.is_ascii_alphanumeric()).collect::() }; let bob = register(app, "bob", &invite).await; assert_eq!( post(app, "/admin/assistants", Some(&bob), &format!("_csrf={csrf}&action=prompt&prompt=x")).await.status, StatusCode::NOT_FOUND ); assert_eq!( post(app, "/orgs/acme/settings/assistants", Some(&bob), &format!("_csrf={csrf}&action=prompt&prompt=x")).await.status, StatusCode::NOT_FOUND ); assert_eq!( post(app, "/acme/plans/settings/assistants", Some(&bob), &format!("_csrf={csrf}&action=prompt&prompt=x")).await.status, StatusCode::NOT_FOUND ); // Deleting the repository forgets its assistants and prompt. let r = post(app, "/acme/plans/settings/delete", Some(&andy), &format!("_csrf={csrf}&confirm=acme%2Fplans")).await; assert!(r.status == StatusCode::SEE_OTHER || r.status == StatusCode::OK, "{} {}", r.status, r.body); assert!(assistants::list(&app.db, Scope::Repo(repo.id)).await.unwrap().is_empty()); } #[tokio::test(flavor = "multi_thread")] async fn accounts_elsewhere_are_checked_and_shown_on_the_profile() { let h = hub().await; let app = &h.app; let andy = register(app, "andy", "").await; let page = get(app, "/settings", Some(&andy)).await.body; let csrf = csrf_of(&page); let base = format!("_csrf={csrf}&display_name=Andy&email=andy%40example.com&bio=&website=&location="); 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; assert!( r.body.contains("value=\"andy.bsky.social\"") && r.body.contains("value=\"@andy@fosstodon.org\"") && r.body.contains("value=\"andymccall\""), "{}", r.body ); let profile = get(app, "/andy", None).await.body; assert!(profile.contains("href=\"https://bsky.app/profile/andy.bsky.social\"") && profile.contains("@andy.bsky.social"), "{profile}"); assert!(profile.contains("href=\"https://fosstodon.org/@andy\"") && profile.contains("rel=\"nofollow noopener me\""), "{profile}"); assert!(profile.contains("href=\"https://github.com/andymccall\"") && profile.contains("title=\"GitHub\""), "{profile}"); // A bad one is refused and nothing changes. let r = post(app, "/settings", Some(&andy), &format!("{base}&bluesky=not+a+handle&mastodon=&github=")).await; assert!(r.body.contains("not a Bluesky handle"), "{}", r.body); assert!(get(app, "/andy", None).await.body.contains("andy.bsky.social")); // Cleared. post(app, "/settings", Some(&andy), &format!("{base}&bluesky=&mastodon=&github=")).await; assert!(!get(app, "/andy", None).await.body.contains("class=\"social\"")); } /// A stand-in GitHub and Google: token exchanges and who the token is. async fn mock_provider() -> (String, std::sync::Arc>>) { use std::sync::{Arc, Mutex}; let seen: Arc>> = Arc::new(Mutex::new(vec![])); let s1 = seen.clone(); let s2 = seen.clone(); let router = axum::Router::new() .route( "/github/token", axum::routing::post(move |body: String| { let s1 = s1.clone(); async move { s1.lock().unwrap().push(format!("github token {body}")); axum::Json(serde_json::json!({ "access_token": "gh-token", "token_type": "bearer" })) } }), ) .route( "/github/userinfo", axum::routing::get(|headers: axum::http::HeaderMap| async move { assert_eq!(headers.get("authorization").and_then(|v| v.to_str().ok()), Some("Bearer gh-token")); axum::Json(serde_json::json!({ "id": 583231, "login": "octocat", "name": "The Octocat", "email": null })) }), ) .route( "/github/userinfo/emails", axum::routing::get(|| async { axum::Json(serde_json::json!([ { "email": "old@example.com", "primary": false, "verified": false }, { "email": "octo@example.com", "primary": true, "verified": true } ])) }), ) .route( "/google/token", axum::routing::post(move |body: String| { let s2 = s2.clone(); async move { s2.lock().unwrap().push(format!("google token {body}")); axum::Json(serde_json::json!({ "access_token": "g-token", "id_token": "x" })) } }), ) .route( "/gitlab/token", axum::routing::post(|| async { axum::Json(serde_json::json!({ "access_token": "gl-token", "token_type": "Bearer" })) }), ) .route( "/gitlab/userinfo", axum::routing::get(|headers: axum::http::HeaderMap| async move { assert_eq!(headers.get("authorization").and_then(|v| v.to_str().ok()), Some("Bearer gl-token")); axum::Json(serde_json::json!({ "sub": "1234567", "nickname": "tanuki", "name": "The Tanuki", "email": "tanuki@example.com", "email_verified": true })) }), ) .route( "/google/userinfo", axum::routing::get(|| async { axum::Json(serde_json::json!({ "sub": "1076915035000615071", "email": "andy@example.com", "email_verified": true, "name": "Andy McCall" })) }), ); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = listener.local_addr().unwrap().port(); tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); (format!("http://127.0.0.1:{port}"), seen) } fn state_of(res: &Res) -> (String, String) { let cookie = res.raw_cookies.iter().find(|c| c.starts_with("oxyhub_signin=")).expect("state cookie").clone(); let value = cookie.trim_start_matches("oxyhub_signin=").split(';').next().unwrap().to_string(); (cookie, value) } #[tokio::test(flavor = "multi_thread")] async fn people_sign_in_with_github_or_google_once_an_admin_sets_it_up() { hermetic(); let (mock, seen) = mock_provider().await; let dir = tempfile::tempdir().unwrap(); let mut config = Config::load(dir.path()).unwrap(); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = listener.local_addr().unwrap().port(); config.server.base_url = format!("http://127.0.0.1:{port}"); config.registration.mode = "open".into(); config.auth.signin_mock = Some(mock.clone()); let app = oxygenhub::build(config).await.unwrap(); let router = oxygenhub::router(app.clone()); tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); let app = &app; let andy = register(app, "andy", "").await; let andy_row = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap(); db::accounts::set_email_verified(&app.db, andy_row.id, true).await.unwrap(); // Nothing to sign in with until an administrator sets a provider up. assert!(!get(app, "/login", None).await.body.contains("/login/github")); let admin = get(app, "/admin", Some(&andy)).await.body; assert!(admin.contains("Sign in with") && admin.contains(&format!("http://127.0.0.1:{port}/login/github/callback")), "{admin}"); let csrf = csrf_of(&admin); let r = post(app, "/admin/signin", Some(&andy), &format!("_csrf={csrf}&provider=github&client_id=gh-cid&secret=gh-sek&enabled=1")).await; assert!(r.body.contains("Signing in with GitHub is on.") && !r.body.contains("gh-sek"), "{}", r.body); let r = post(app, "/admin/signin", Some(&andy), &format!("_csrf={csrf}&provider=google&client_id=g-cid&secret=g-sek&enabled=1")).await; assert!(r.body.contains("Signing in with Google is on."), "{}", r.body); let login = get(app, "/login", None).await.body; assert!(login.contains("href=\"/login/github\"") && login.contains("href=\"/login/google\""), "{login}"); // GitHub: off to the provider with a state, back with a code: a new account. let r = get(app, "/login/github", None).await; assert_eq!(r.status, StatusCode::SEE_OTHER); let to = r.location.clone().unwrap(); assert!(to.starts_with(&format!("{mock}/github/authorize?client_id=gh-cid&redirect_uri=")) && to.contains("&state="), "{to}"); let (cookie, state) = state_of(&r); let bad = send_with(app, "GET", "/login/github/callback?code=c1&state=wrong", Some(&cookie), None).await; assert!(bad.location.as_deref().unwrap_or("").starts_with("/login?error="), "{:?}", bad.location); let ok = send_with(app, "GET", &format!("/login/github/callback?code=c1&state={state}"), Some(&cookie), None).await; assert_eq!(ok.status, StatusCode::SEE_OTHER, "{}", ok.body); assert_eq!(ok.location.as_deref(), Some("/")); let octo_cookie = ok.cookie.clone().expect("signed in"); let octo = db::accounts::account_by_name(&app.db, "octocat").await.unwrap().expect("account made from the GitHub login"); assert!( (octo.email.as_str(), octo.email_verified, octo.display_name.as_str()) == ("octo@example.com", true, "The Octocat"), "{octo:?}" ); assert!(seen.lock().unwrap().iter().any(|s| s.contains("github token") && s.contains("code=c1") && s.contains("client_secret=gh-sek"))); assert!(get(app, "/settings", Some(&octo_cookie)).await.body.contains("octocat")); // Again: the same account, no new one. let r = get(app, "/login/github", None).await; let (cookie, state) = state_of(&r); let ok = send_with(app, "GET", &format!("/login/github/callback?code=c2&state={state}"), Some(&cookie), None).await; assert_eq!(ok.location.as_deref(), Some("/")); assert_eq!(db::accounts::account_count(&app.db).await.unwrap(), 2); // GitLab (#213): a self-managed address is checked, then sign-in makes // an account from the GitLab username. let r = post( app, "/admin/signin", Some(&andy), &format!("_csrf={csrf}&provider=gitlab&client_id=gl-cid&secret=gl-sek&enabled=1&base=http%3A%2F%2Fgitlab.example.org"), ) .await; assert!(r.body.contains("is an https:// address"), "{}", r.body); let r = post( app, "/admin/signin", Some(&andy), &format!("_csrf={csrf}&provider=gitlab&client_id=gl-cid&secret=gl-sek&enabled=1&base=https%3A%2F%2Fgitlab.example.org%2F"), ) .await; assert!(r.body.contains("Signing in with GitLab is on.") && r.body.contains("value=\"https://gitlab.example.org\""), "{}", r.body); let r = post( app, "/admin/signin", Some(&andy), &format!("_csrf={csrf}&provider=github&client_id=gh-cid&enabled=1&base=https%3A%2F%2Fx.org"), ) .await; assert!(r.body.contains("GitHub has no address to set."), "{}", r.body); let login = get(app, "/login", None).await.body; assert!(login.contains("signin-btn gitlab") && login.contains("Sign in with GitLab"), "{login}"); let r = get(app, "/login/gitlab", None).await; assert!(r.location.clone().unwrap().contains("scope=openid%20profile%20email"), "{:?}", r.location); let (cookie, state) = state_of(&r); let ok = send_with(app, "GET", &format!("/login/gitlab/callback?code=c9&state={state}"), Some(&cookie), None).await; assert_eq!(ok.location.as_deref(), Some("/"), "{}", ok.body); let tanuki = db::accounts::account_by_name(&app.db, "tanuki").await.unwrap().expect("account made from the GitLab username"); assert!((tanuki.email.as_str(), tanuki.email_verified) == ("tanuki@example.com", true), "{tanuki:?}"); assert_eq!(db::accounts::account_count(&app.db).await.unwrap(), 3); // Google, for an address Andy has verified: linked to Andy, signed in as Andy. let r = get(app, "/login/google", None).await; assert!(r.location.clone().unwrap().contains("prompt=select_account")); let (cookie, state) = state_of(&r); let ok = send_with(app, "GET", &format!("/login/google/callback?code=c3&state={state}"), Some(&cookie), None).await; assert_eq!(ok.location.as_deref(), Some("/"), "{}", ok.body); let as_andy = ok.cookie.clone().unwrap(); let sec = get(app, "/settings/security", Some(&as_andy)).await.body; assert!( sec.contains("Connected accounts") && sec.contains("Google: andy") && sec.contains("GitHub: connect"), "{sec}" ); assert_eq!(db::accounts::account_count(&app.db).await.unwrap(), 3, "no fourth account"); // Disconnect, then connect again from Settings › Security. let csrf_s = csrf_of(&sec); let r = post(app, "/settings/security/disconnect/google", Some(&as_andy), &format!("_csrf={csrf_s}")).await; assert!(r.location.as_deref().unwrap_or("").contains("notice=Google%20disconnected"), "{:?}", r.location); assert!(!get(app, "/settings/security", Some(&as_andy)).await.body.contains("Google: andy")); let r = get(app, "/settings/security/connect/google", Some(&as_andy)).await; assert_eq!(r.status, StatusCode::SEE_OTHER); let (cookie, state) = state_of(&r); let both = format!("{cookie}; oxyhub={as_andy}"); let ok = send_with(app, "GET", &format!("/login/google/callback?code=c4&state={state}"), Some(&both), None).await; assert!(ok.location.as_deref().unwrap_or("").contains("notice=Google%20connected%20as%20andy"), "{:?} {}", ok.location, ok.body); // With registration closed, an unknown GitHub account is turned away. db::accounts::set_setting(&app.db, "registration_mode", "closed").await.unwrap(); sqlx::query("DELETE FROM account_logins WHERE provider = 'github'").execute(&app.db).await.unwrap(); sqlx::query("UPDATE accounts SET email_verified = FALSE WHERE username = 'octocat'").execute(&app.db).await.unwrap(); let r = get(app, "/login/github", None).await; let (cookie, state) = state_of(&r); let no = send_with(app, "GET", &format!("/login/github/callback?code=c5&state={state}"), Some(&cookie), None).await; assert!(no.location.as_deref().unwrap_or("").contains("registration%20is%20closed"), "{:?}", no.location); assert!(no.cookie.is_none()); } #[tokio::test(flavor = "multi_thread")] async fn administration_is_sectioned_and_its_audit_log_pages() { let h = hub().await; let app = &h.app; let andy = register(app, "andy", "").await; let andy_row = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap(); for i in 0..60 { db::accounts::audit(&app.db, Some(&andy_row), "test.event", &format!("t{i}"), "").await.unwrap(); } let page = get(app, "/admin", Some(&andy)).await.body; for id in ["accounts", "registration", "organisations", "signin", "mail", "variables", "secrets", "assistants", "audit"] { assert!(page.contains(&format!("href=\"#{id}\"")) && page.contains(&format!("id=\"{id}\"")), "section {id}: {page}"); } assert!(page.contains("class=\"section-nav\"")); assert!(page.contains(">t59<") && !page.contains(">t5<"), "the newest page only"); let i = page.find("audit_before=").expect("an older link") + "audit_before=".len(); let before: String = page[i..].chars().take_while(|c| c.is_ascii_digit()).collect(); let older = get(app, &format!("/admin?audit_before={before}"), Some(&andy)).await.body; assert!(older.contains(">t5<") && !older.contains(">t59<"), "the next page: {older}"); } #[tokio::test(flavor = "multi_thread")] async fn adding_an_assistant_offers_providers_and_only_models_the_endpoint_lists() { let h = hub().await; let app = &h.app; let andy = register(app, "andy", "").await; let router = axum::Router::new() .route( "/v1/models", axum::routing::get(|headers: axum::http::HeaderMap| async move { assert_eq!(headers.get("authorization").and_then(|v| v.to_str().ok()), Some("Bearer sk-m")); axum::Json(serde_json::json!({ "data": [ { "id": "models/gemini-3-pro" }, { "id": "gemini-3-flash" }, { "id": "text-embedding-004" } ] })) }), ) .route( "/v1/chat/completions", axum::routing::post(|| async { axum::Json(serde_json::json!({ "choices": [{ "message": { "content": "OK" } }] })) }), ); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = listener.local_addr().unwrap().port(); tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); let ep = format!("http%3A%2F%2F127.0.0.1%3A{port}%2Fv1%2Fchat%2Fcompletions"); let page = get(app, "/admin", Some(&andy)).await.body; assert!(page.contains("data-preset-select") && page.contains("Google Gemini") && page.contains("Other (enter the endpoint)"), "{page}"); assert!(page.contains("LIST MODELS")); let csrf = csrf_of(&page); // The model list, as the button asks for it: chat models only, prefixes gone. let r = post(app, "/admin/assistants/models", Some(&andy), &format!("_csrf={csrf}&endpoint={ep}&api=chat-completions&token=sk-m")).await; let v: serde_json::Value = serde_json::from_str(&r.body).unwrap(); assert_eq!(v["models"], serde_json::json!(["gemini-3-flash", "gemini-3-pro"]), "{}", r.body); // A model the endpoint does not list is refused, with what it offers. let r = post( app, "/admin/assistants", Some(&andy), &format!("_csrf={csrf}&action=add&preset=gemini&endpoint={ep}&model=gemini-2.5-pro&token=sk-m&enabled=1"), ) .await; assert!(r.body.contains("gemini-2.5-pro is not a model this endpoint offers") && r.body.contains("gemini-3-pro"), "{}", r.body); // One it lists is added, named after the provider when no name is given. let r = post( app, "/admin/assistants", Some(&andy), &format!("_csrf={csrf}&action=add&preset=gemini&endpoint={ep}&model=gemini-3-pro&token=sk-m&enabled=1"), ) .await; assert!(r.body.contains("Gemini added and answered: OK"), "{}", r.body); let a = &oxygenhub::assistants::list(&app.db, oxygenhub::levels::Scope::Site).await.unwrap()[0]; assert_eq!((a.name.as_str(), a.api.as_str(), a.model.as_str()), ("Gemini", "chat-completions", "gemini-3-pro")); // The stored token serves the edit form's button. let r = post(app, "/admin/assistants/models", Some(&andy), &format!("_csrf={csrf}&id={}&endpoint={ep}&api=chat-completions", a.id)).await; assert!(r.body.contains("gemini-3-flash"), "{}", r.body); } /// #217: a profile shows the year's pulse: changes pushed per day in /// repositories the viewer may see, the share via agent tokens, releases on /// the peaks; landings and private repositories the viewer cannot see are /// left out. #[tokio::test(flavor = "multi_thread")] async fn a_profile_shows_the_year_as_a_signal() { let h = hub().await; let app = &h.app; register(app, "andy", "").await; let andy = db::accounts::account_by_name(&app.db, "andy").await.unwrap().unwrap(); // The account is over a year old, but the span follows its first push. sqlx::query("UPDATE accounts SET created_ms = $1 WHERE id = $2") .bind(db::now_ms() - 400 * 86_400_000) .bind(andy.id) .execute(&app.db) .await .unwrap(); let game = db::repos::create(&app.db, "andy", "game", "", hub_api::Visibility::Public).await.unwrap(); let secret = db::repos::create(&app.db, "andy", "secret", "", hub_api::Visibility::Private).await.unwrap(); let now = db::now_ms(); for (repo, ago_days, changes, reason, via) in [ (game.id, 3, 5, "", ""), (game.id, 3, 2, "", "Claude"), (game.id, 40, 4, "", ""), (game.id, 2, 9, "landed #1 (web)", ""), (secret.id, 1, 50, "", ""), ] { 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)") .bind(repo) .bind(now - ago_days * 86_400_000) .bind(reason) .bind(changes) .bind(andy.id) .bind(via) .execute(&app.db) .await .unwrap(); } sqlx::query("INSERT INTO releases (repo_id, tag, title, author_id, author, created_ms) VALUES ($1, 'v1.0', 'One', $2, 'andy', $3)") .bind(game.id) .bind(andy.id) .bind(now - 3 * 86_400_000) .execute(&app.db) .await .unwrap(); // A stranger sees the public repository only, and no landing counts. let page = get(app, "/andy", None).await.body; let start = page.find("id=\"pulse-data\">").expect("the pulse is on the profile") + "id=\"pulse-data\">".len(); let json: serde_json::Value = serde_json::from_str(&page[start..start + page[start..].find("").unwrap()]).unwrap(); assert_eq!(json["repos"], serde_json::json!(["andy/game"])); let days = json["days"].as_array().unwrap(); // The first push was 40 days ago: three months are drawn, not a year. assert_eq!((days.len(), json["months"].as_i64()), (91, Some(3))); let total: i64 = days.iter().map(|d| d[0].as_i64().unwrap()).sum(); let via: i64 = days.iter().map(|d| d[1].as_i64().unwrap()).sum(); assert_eq!((total, via), (11, 2), "5 + 2 + 4 changes, 2 via an agent; the landing and the private push left out"); assert_eq!(days[87], serde_json::json!([7, 2, [[0, 7]]]), "three days ago"); assert_eq!(json["peaks"][0], serde_json::json!([87, "game v1.0"])); db::accounts::create_account(&app.db, "bea", "bea@example.com", "x", "salt", false).await.unwrap(); assert!(get(app, "/bea", None).await.body.contains("No changes pushed"), "a new account with no pushes says so"); assert!( page.contains("data-total=\"11\"") && page.find("pulse-box").unwrap() < page.find("

Repositories

").unwrap(), "above the repositories" ); } /// #218: on an https site, what a proxy reports as plain http is sent to /// https (pages) or refused (forms), so a password is never taken over /// http; requests made to the hub directly are untouched; cookies are /// Secure. #[tokio::test(flavor = "multi_thread")] async fn an_https_site_takes_nothing_over_http() { hermetic(); let dir = tempfile::tempdir().unwrap(); let mut config = Config::load(dir.path()).unwrap(); config.server.base_url = "https://hub.example.org".into(); config.registration.mode = "open".into(); let app = oxygenhub::build(config).await.unwrap(); let call = |method: &'static str, path: &'static str, header: Option<(&'static str, &'static str)>, body: Option<&'static str>| { let app = app.clone(); async move { let mut req = Request::builder().method(method).uri(path); if let Some((k, v)) = header { req = req.header(k, v); } if body.is_some() { req = req.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); } oxygenhub::router(app).oneshot(req.body(body.map(Body::from).unwrap_or_else(Body::empty)).unwrap()).await.unwrap() } }; // A page asked for over http (as the tunnel reports it) goes to https, path and query kept. let r = call("GET", "/login?next=%2Fx", Some(("x-forwarded-proto", "http")), None).await; assert!(r.status().is_redirection(), "{}", r.status()); assert_eq!(r.headers().get(header::LOCATION).unwrap(), "https://hub.example.org/login?next=%2Fx"); // A form over http is refused, whichever header says so. let r = call("POST", "/login", Some(("cf-visitor", r#"{"scheme":"http"}"#)), Some("username=a&password=b")).await; assert_eq!(r.status(), StatusCode::BAD_REQUEST); // Over https, and asked of the hub directly (its runners), it answers. assert_eq!(call("GET", "/login", Some(("x-forwarded-proto", "https")), None).await.status(), StatusCode::OK); assert_eq!(call("GET", "/login", None, None).await.status(), StatusCode::OK); // The session cookie is Secure. let r = call( "POST", "/register", Some(("x-forwarded-proto", "https")), Some("username=andy&email=a%40example.org&password=correct-horse-battery"), ) .await; let cookie = r.headers().get(header::SET_COOKIE).expect("signed in").to_str().unwrap(); assert!(cookie.contains("; Secure") && cookie.contains("HttpOnly"), "{cookie}"); } #[tokio::test] async fn guessing_passwords_is_slowed_per_account_and_per_address() { hermetic(); let dir = tempfile::tempdir().unwrap(); let mut config = Config::load(dir.path()).unwrap(); config.server.behind_proxy = true; config.registration.mode = "open".into(); let app = oxygenhub::build(config).await.unwrap(); let from = |addr: &'static str, form: String| { let app = app.clone(); async move { let req = Request::builder() .method("POST") .uri("/login") .header("x-forwarded-for", addr) .header(header::CONTENT_TYPE, "application/x-www-form-urlencoded"); let res = oxygenhub::router(app).oneshot(req.body(Body::from(form)).unwrap()).await.unwrap(); let status = res.status(); (status, String::from_utf8_lossy(&res.into_body().collect().await.unwrap().to_bytes()).into_owned()) } }; register(&app, "andy", "").await; let right = || "username=andy&password=correct-horse-battery".to_string(); // An account: five wrong passwords cost nothing, the sixth starts a // wait, and then even the right password waits (told when to retry). for i in 0..6 { let (_, body) = from("198.51.100.1", "username=andy&password=wrong".into()).await; assert!(body.contains("Wrong username or password."), "try {i}"); } let (status, body) = from("198.51.100.2", right()).await; assert_eq!(status, StatusCode::OK, "not signed in"); assert!(body.contains("Too many tries: try again in"), "{body}"); let audit = db::accounts::audit_rows(&app.db, 50).await.unwrap(); assert!(audit.iter().any(|r| r.action == "login.throttled" && r.target == "andy" && r.detail.contains("198.51.100.1"))); app.throttle.lock().unwrap().cleared(&oxygenhub::throttle::Key::account("login", "andy")); // An address: twenty misses on any names, then it waits whoever it // names; another address does not. for i in 0..21 { let (_, body) = from("203.0.113.7", format!("username=nobody{i}&password=wrong")).await; assert!(body.contains("Wrong username or password."), "try {i}"); } let (_, body) = from("203.0.113.7", right()).await; assert!(body.contains("Too many tries"), "{body}"); let (status, _) = from("198.51.100.3", right()).await; assert_eq!(status, StatusCode::SEE_OTHER, "another address signs in"); } #[tokio::test] async fn every_page_carries_the_security_headers_and_violations_are_reported() { let h = hub().await; let res = oxygenhub::router(h.app.clone()).oneshot(Request::get("/login").body(Body::empty()).unwrap()).await.unwrap(); let hd = res.headers(); assert_eq!(hd[header::X_CONTENT_TYPE_OPTIONS], "nosniff"); assert_eq!(hd[header::REFERRER_POLICY], "strict-origin-when-cross-origin"); assert_eq!(hd[header::X_FRAME_OPTIONS], "DENY"); assert!(hd["permissions-policy"].to_str().unwrap().contains("camera=()")); // Reported, not yet enforced; and no HSTS until the site owner says. let csp = hd[header::CONTENT_SECURITY_POLICY_REPORT_ONLY].to_str().unwrap(); for part in [ "default-src 'self'", "object-src 'none'", "frame-ancestors 'none'", "form-action 'self'", "'wasm-unsafe-eval'", "report-uri /csp-report", ] { assert!(csp.contains(part), "{part} in {csp}"); } assert!(hd.get(header::CONTENT_SECURITY_POLICY).is_none() && hd.get(header::STRICT_TRANSPORT_SECURITY).is_none()); // Static files and errors carry them too. let res = oxygenhub::router(h.app.clone()).oneshot(Request::get("/no/such/page").body(Body::empty()).unwrap()).await.unwrap(); assert_eq!(res.headers()[header::X_CONTENT_TYPE_OPTIONS], "nosniff"); let report = r#"{"csp-report":{"document-uri":"http://127.0.0.1/login","violated-directive":"script-src-elem","blocked-uri":"inline"}}"#; let req = Request::post("/csp-report").header(header::CONTENT_TYPE, "application/csp-report").body(Body::from(report)).unwrap(); assert_eq!(oxygenhub::router(h.app.clone()).oneshot(req).await.unwrap().status(), StatusCode::NO_CONTENT); let big = Request::post("/csp-report").body(Body::from(vec![b' '; 64 * 1024])).unwrap(); assert_eq!(oxygenhub::router(h.app.clone()).oneshot(big).await.unwrap().status(), StatusCode::PAYLOAD_TOO_LARGE); } #[tokio::test] async fn security_txt_names_the_contact_an_administrator_sets() { let h = hub().await; let app = &h.app; assert_eq!(get(app, "/.well-known/security.txt", None).await.status, StatusCode::NOT_FOUND, "no contact, no file"); let andy = register(app, "andy", "").await; let page = get(app, "/admin", Some(&andy)).await.body; assert!(page.contains("No contact yet"), "the panel"); let csrf = csrf_of(&page); let set = |contact: &'static str, policy: &'static str| { let (andy, csrf) = (andy.clone(), csrf.clone()); async move { post(app, "/admin/security", Some(&andy), &format!("_csrf={csrf}&contact={contact}&policy={policy}")).await } }; assert_eq!(set("javascript%3Aalert(1)", "").await.status, StatusCode::BAD_REQUEST); assert_eq!(set("sec%40example.org", "http%3A%2F%2Fexample.org").await.status, StatusCode::BAD_REQUEST, "policy over https only"); let r = set("sec%40example.org", "https%3A%2F%2Fexample.org%2Fpolicy").await; assert!(r.body.contains("Security contact saved"), "{}", r.body); for path in ["/.well-known/security.txt", "/security.txt"] { let r = get(app, path, None).await; assert_eq!(r.status, StatusCode::OK); assert!(r.body.starts_with("Contact: mailto:sec@example.org\nExpires: 20"), "{}", r.body); assert!(r.body.contains("Policy: https://example.org/policy\n") && r.body.contains("/.well-known/security.txt\n"), "{}", r.body); } // Someone not an administrator cannot change it. let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={csrf}")).await; let code = r.body.split("register?invite=").nth(1).unwrap().split('<').next().unwrap().trim().to_string(); let bob = register(app, "bob", &code).await; let r = post(app, "/admin/security", Some(&bob), &format!("_csrf={csrf}&contact=x%40evil.example")).await; assert_ne!(r.status, StatusCode::OK); // An empty contact takes the file down. set("", "").await; assert_eq!(get(app, "/security.txt", None).await.status, StatusCode::NOT_FOUND); } #[tokio::test] async fn sessions_are_records_that_can_be_listed_ended_and_expire() { let h = hub().await; let app = &h.app; let a = register(app, "andy", "").await; assert_eq!(a.len(), 64, "a random id, not the account's name"); let b = post(app, "/login", None, "username=andy&password=correct-horse-battery").await.cookie.expect("signed in again"); assert_ne!(a, b, "each sign-in is a new session"); let page = get(app, "/settings/security", Some(&a)).await.body; assert_eq!(page.matches("/end\"").count(), 2, "both browsers listed"); // Each entry is an
  • ; the other browser's is the one without the tag. let entries: Vec<&str> = page.split("
  • ").skip(1).filter(|e| e.contains("/end\"")).collect(); assert_eq!(entries.iter().filter(|e| e.contains("this browser")).count(), 1); let other = entries.iter().find(|e| !e.contains("class=\"tag\">this browser")).unwrap(); let other: i64 = other.split("/settings/security/sessions/").nth(1).unwrap().split('/').next().unwrap().parse().unwrap(); let csrf = csrf_of(&page); let r = post(app, &format!("/settings/security/sessions/{other}/end"), Some(&a), &format!("_csrf={csrf}")).await; assert_eq!(r.status, StatusCode::SEE_OTHER); let signed_in = |c: String| async move { get(app, "/settings/security", Some(&c)).await.body.contains("SIGN OUT EVERYWHERE") }; assert!(signed_in(a.clone()).await, "this browser stays"); assert!(!signed_in(b.clone()).await, "that browser is signed out"); // Unused for 14 days, it ends. sqlx::query("UPDATE sessions SET seen_ms = seen_ms - 15 * 86400000").execute(&app.db).await.unwrap(); assert!(!signed_in(a.clone()).await, "idle too long"); // Signing out ends the record itself, not just the cookie. let c = post(app, "/login", None, "username=andy&password=correct-horse-battery").await.cookie.unwrap(); let csrf = csrf_of(&get(app, "/settings/security", Some(&c)).await.body); post(app, "/logout", Some(&c), &format!("_csrf={csrf}")).await; assert!(!signed_in(c).await, "the old cookie no longer works"); // A cookie of the old form (name.mac) is nobody. assert!(!signed_in("andy.0123456789abcdef".into()).await); } #[tokio::test] async fn an_invitation_signs_up_through_a_provider_once() { hermetic(); let (mock, _) = mock_provider().await; let dir = tempfile::tempdir().unwrap(); let mut config = Config::load(dir.path()).unwrap(); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); let port = listener.local_addr().unwrap().port(); config.server.base_url = format!("http://127.0.0.1:{port}"); config.registration.mode = "invite".into(); config.auth.signin_mock = Some(mock.clone()); let app = oxygenhub::build(config).await.unwrap(); let router = oxygenhub::router(app.clone()); tokio::spawn(async move { axum::serve(listener, router).await.unwrap() }); let app = &app; let andy = register(app, "andy", "").await; let admin = get(app, "/admin", Some(&andy)).await.body; let csrf = csrf_of(&admin); post(app, "/admin/signin", Some(&andy), &format!("_csrf={csrf}&provider=github&client_id=gh-cid&secret=gh-sek&enabled=1")).await; // Without an invitation: no buttons, and the provider alone makes no account. assert!(!get(app, "/register", None).await.body.contains("/login/github")); let r = get(app, "/login/github", None).await; let (cookie, state) = state_of(&r); let no = send_with(app, "GET", &format!("/login/github/callback?code=c1&state={state}"), Some(&cookie), None).await; assert!(no.location.as_deref().unwrap_or("").contains("by%20invitation"), "{:?}", no.location); assert_eq!(db::accounts::account_count(&app.db).await.unwrap(), 1); // With one: the branded buttons carry it, it rides the round trip, and // the new account uses it up. let r = post(app, "/admin/invite", Some(&andy), &format!("_csrf={csrf}")).await; let code = r.body.split("register?invite=").nth(1).unwrap().split('<').next().unwrap().trim().to_string(); let page = get(app, &format!("/register?invite={code}"), None).await.body; assert!(page.contains(&format!("href=\"/login/github?invite={code}\"")) && page.contains("Sign up with GitHub"), "{page}"); let r = get(app, &format!("/login/github?invite={code}"), None).await; assert_eq!(r.status, StatusCode::SEE_OTHER); let (cookie, state) = state_of(&r); let ok = send_with(app, "GET", &format!("/login/github/callback?code=c2&state={state}"), Some(&cookie), None).await; assert_eq!(ok.location.as_deref(), Some("/"), "{}", ok.body); let octo = db::accounts::account_by_name(&app.db, "octocat").await.unwrap().expect("signed up through the invitation"); assert!(!db::accounts::invitation_unused(&app.db, &code).await.unwrap(), "the invitation is spent"); let used_by: Option = sqlx::query_scalar("SELECT used_by FROM invitations WHERE code = $1").bind(&code).fetch_one(&app.db).await.unwrap(); assert_eq!(used_by, Some(octo.id)); // Spent: no buttons, and starting with it is refused plainly. assert!(!get(app, &format!("/register?invite={code}"), None).await.body.contains("/login/github")); let r = get(app, &format!("/login/github?invite={code}"), None).await; assert_eq!(r.status, StatusCode::BAD_REQUEST); assert!(r.body.contains("That invitation has been used or does not exist."), "{}", r.body); assert_eq!(get(app, "/login/github?invite=not-a.code", None).await.status, StatusCode::BAD_REQUEST); }