//! 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}"); 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, cookie: Option, location: Option, } async fn send(app: &Shared, method: &str, path: &str, cookie: Option<&str>, form: Option<&str>) -> Res { let mut req = Request::builder().method(method).uri(path); if let Some(c) = cookie { req = req.header(header::COOKIE, format!("oxyhub={c}")); } 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 cookie = res .headers() .get(header::SET_COOKIE) .and_then(|v| v.to_str().ok()) .and_then(|v| v.split(';').next()) .and_then(|kv| kv.split_once('=')) .map(|(_, v)| v.to_string()); 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 } } 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); // 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); let code = oxygenhub::auth::totp::current(&secret, (db::now_ms() / 1000) as u64).unwrap(); let r = post(app, "/login", None, &format!("username=andy&password=correct-horse-battery&code={code}")).await; assert_eq!(r.status, StatusCode::SEE_OTHER, "{}", r.body); assert!(r.cookie.is_some()); assert!(r.location.as_deref() == Some("/")); }