use axum::{ Router, body::{Body, to_bytes}, http::{Request, StatusCode}, }; use serde_json::{Value, json}; use std::sync::Arc; use tower::ServiceExt; use vnox_hub::{ auth::{self, store}, database, identity::Issuer, web::{self, HubState}, }; const ORIGIN: &str = "https://central.loki-code.dev"; struct Fixture { _dir: tempfile::TempDir, state: Arc, app: Router, } struct Session { user: store::User, token: String, csrf: String, } async fn fixture() -> Fixture { let dir = tempfile::tempdir().unwrap(); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); } let issuer = Issuer::load_or_create(dir.path()).unwrap(); let pool = database::open(dir.path(), &issuer).await.unwrap(); let auth = auth::AuthService::with_provider(pool.clone(), ORIGIN.parse().unwrap(), None); let state = Arc::new(HubState { database: pool, auth: Arc::new(auth), issuer, smtp_configured: false, started: std::time::Instant::now(), }); Fixture { _dir: dir, app: web::router(state.clone()), state, } } impl Fixture { async fn login(&self, email: &str) -> Session { let user = store::upsert_email_identity(&self.state.database, email) .await .unwrap(); let (token, csrf) = store::create_session(&self.state.database, &user.user_id) .await .unwrap(); Session { user, token, csrf } } fn request(&self, s: &Session, body: String) -> Request { Request::builder() .method("PUT") .uri("/v1/account/profile") .header("origin", ORIGIN) .header("content-type", "application/json") .header("cookie", format!("__Host-vnox_session={}", s.token)) .header("x-csrf-token", &s.csrf) .body(Body::from(body)) .unwrap() } async fn send(&self, r: Request) -> (StatusCode, Value) { let r = self.app.clone().oneshot(r).await.unwrap(); assert_eq!(r.headers()["cache-control"], "no-store"); let status = r.status(); ( status, serde_json::from_slice(&to_bytes(r.into_body(), 8192).await.unwrap()).unwrap(), ) } async fn update(&self, s: &Session, handle: &str, name: &str) -> (StatusCode, Value) { self.send(self.request(s, json!({"handle":handle,"display_name":name}).to_string())) .await } } #[tokio::test] async fn selection_is_normalized_persisted_and_preserved_by_login() { let f = fixture().await; let s = f.login("person@example.org").await; assert!(!s.user.profile_complete); let (status, body) = f.update(&s, " Alice_123 ", " Алиса ").await; assert_eq!(status, StatusCode::OK); assert_eq!(body["user"]["handle"], "alice_123"); assert_eq!(body["user"]["display_name"], "Алиса"); assert_eq!(body["user"]["profile_complete"], true); assert_eq!(body["user"]["user_id"], s.user.user_id); let again = f.login("person@example.org").await; assert_eq!(again.user.handle, "alice_123"); assert_eq!(again.user.display_name, "Алиса"); assert!(again.user.profile_complete); let session = f .send( Request::builder() .uri("/v1/auth/session") .header("cookie", format!("__Host-vnox_session={}", s.token)) .body(Body::empty()) .unwrap(), ) .await; assert_eq!(session.1["user"], body["user"]); assert_eq!( f.update(&s, "ALICE_123", "New name").await.0, StatusCode::OK ); assert_eq!( f.update(&again, "other_handle", "Changed").await.1["error"], "handle_locked" ); } #[tokio::test] async fn case_insensitive_claims_are_atomic_and_leave_loser_unchanged() { let f = fixture().await; let a = f.login("a@example.org").await; let b = f.login("b@example.org").await; let (left, right) = tokio::join!( f.update(&a, "Same_Name", "A"), f.update(&b, "same_name", "B") ); assert_eq!( [left.0, right.0] .iter() .filter(|s| **s == StatusCode::OK) .count(), 1 ); let (loser, conflict) = if left.0 == StatusCode::OK { (&b, right) } else { (&a, left) }; assert_eq!(conflict.0, StatusCode::CONFLICT); assert_eq!(conflict.1["error"], "handle_taken"); let (user, _) = store::get_session(&f.state.database, &loser.token) .await .unwrap() .unwrap(); assert_eq!(user.handle, loser.user.handle); assert_eq!(user.display_name, loser.user.display_name); assert!(!user.profile_complete); } #[tokio::test] async fn concurrent_sessions_cannot_choose_two_handles() { let f = fixture().await; let a = f.login("a@example.org").await; let b = f.login("a@example.org").await; let (left, right) = tokio::join!( f.update(&a, "first_name", "A"), f.update(&b, "second_name", "B") ); assert_eq!( [left.0, right.0] .iter() .filter(|s| **s == StatusCode::OK) .count(), 1 ); assert_eq!( if left.0 == StatusCode::OK { right.1 } else { left.1 }["error"], "handle_locked" ); } #[tokio::test] async fn authorization_and_expiry_precede_body_parsing() { let f = fixture().await; let s = f.login("a@example.org").await; for (header, error) in [ ("origin", "invalid_origin"), ("cookie", "not_authenticated"), ("x-csrf-token", "invalid_csrf"), ] { let mut r = f.request(&s, "invalid JSON".into()); r.headers_mut().remove(header); assert_eq!(f.send(r).await.1["error"], error); } let mut r = f.request(&s, "x".repeat(2048)); r.headers_mut() .insert("origin", "https://wrong.example".parse().unwrap()); assert_eq!(f.send(r).await.1["error"], "invalid_origin"); sqlx::query("UPDATE web_sessions SET expires_at=0") .execute(&f.state.database) .await .unwrap(); assert_eq!( f.update(&s, "valid_name", "Name").await.0, StatusCode::UNAUTHORIZED ); } #[tokio::test] async fn validation_and_body_limits_leave_account_unchanged() { let f = fixture().await; for handle in [ "ab", "1alice", "алиса", "with-dash", "with space", "u_placeholder", "ADMIN", "root", "everyone", "abcdefghijklmnopqrstuvwxyz", ] { let s = f .login(&format!("{}@example.org", uuid::Uuid::new_v4())) .await; assert_eq!( f.update(&s, handle, "Name").await.1["error"], "invalid_handle" ); assert!( !store::get_session(&f.state.database, &s.token) .await .unwrap() .unwrap() .0 .profile_complete ); } let s = f.login("names@example.org").await; for name in [ "".to_owned(), " ".into(), "n\n".into(), "x\u{202e}y".into(), "x\u{2066}y".into(), "я".repeat(65), ] { assert_eq!( f.update(&s, "valid_name", &name).await.1["error"], "invalid_display_name" ); } for body in [ "{}", "{", r#"{"handle":"valid_name","display_name":"Name","user_id":"other"}"#, ] { assert_eq!( f.send(f.request(&s, body.into())).await.0, StatusCode::BAD_REQUEST ); } let s = f.login("large@example.org").await; assert_eq!( f.send(f.request(&s, "x".repeat(1025))).await.0, StatusCode::PAYLOAD_TOO_LARGE ); assert_eq!( f.update(&s, "valid_name", &"я".repeat(64)).await.0, StatusCode::OK ); } #[tokio::test] async fn budgets_limit_accounts_and_sources_independently() { let f = fixture().await; let s = f.login("person@example.org").await; for _ in 0..10 { assert_eq!(f.update(&s, "person", "Person").await.0, StatusCode::OK); } assert_eq!( f.update(&s, "person", "Person").await.0, StatusCode::TOO_MANY_REQUESTS ); for i in 0..2 { let s = f.login(&format!("p{i}@example.org")).await; for _ in 0..10 { assert_eq!( f.update(&s, &format!("person{i}"), "Name").await.0, StatusCode::OK ); } } let s = f.login("last@example.org").await; assert_eq!( f.update(&s, "last_person", "Name").await.0, StatusCode::TOO_MANY_REQUESTS ); let mut r = f.request( &s, json!({"handle":"last_person","display_name":"Name"}).to_string(), ); r.headers_mut() .insert("x-forwarded-for", "192.0.2.1".parse().unwrap()); assert_eq!(f.send(r).await.0, StatusCode::OK); } #[tokio::test] async fn github_relogin_preserves_selected_profile_and_own_avatar() { use vnox_hub::auth::provider::GitHubProfile; let f = fixture().await; let mut provider = GitHubProfile { id: 123, login: "original".into(), name: Some("Provider name".into()), avatar_url: Some("https://avatars.githubusercontent.com/u/123".into()), }; let user = store::upsert_identity(&f.state.database, &provider) .await .unwrap(); let (token, csrf) = store::create_session(&f.state.database, &user.user_id) .await .unwrap(); let s = Session { user, token, csrf }; let png = image::RgbImage::new(256, 256); let mut bytes = std::io::Cursor::new(Vec::new()); png.write_to(&mut bytes, image::ImageFormat::Png).unwrap(); let avatar = vnox_hub::avatar::replace(&f.state.database, &s.user.user_id, bytes.get_ref()) .await .unwrap(); let (status, body) = f.update(&s, "my_handle", "My name").await; assert_eq!(status, StatusCode::OK); assert_eq!(body["user"]["avatar_url"], avatar); provider.login = "renamed".into(); provider.name = Some("New provider name".into()); let user = store::upsert_identity(&f.state.database, &provider) .await .unwrap(); assert_eq!(user.user_id, s.user.user_id); assert_eq!(user.handle, "my_handle"); assert_eq!(user.display_name, "My name"); assert_eq!(user.avatar_url.as_deref(), Some(avatar.as_str())); assert!(user.profile_complete); } #[tokio::test] async fn upgrading_legacy_database_preserves_accounts_bindings_sessions_and_avatars() { let dir = tempfile::tempdir().unwrap(); #[cfg(unix)] { use std::os::unix::fs::PermissionsExt; std::fs::set_permissions(dir.path(), std::fs::Permissions::from_mode(0o700)).unwrap(); } let issuer = Issuer::load_or_create(dir.path()).unwrap(); let migrations = tempfile::tempdir().unwrap(); let source = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("migrations"); for name in [ "0001_foundation.sql", "0002_github_auth.sql", "0003_email_auth.sql", "0004_email_resend_chain.sql", "0005_avatars.sql", ] { std::fs::copy(source.join(name), migrations.path().join(name)).unwrap(); } let options = sqlx::sqlite::SqliteConnectOptions::new() .filename(dir.path().join("hub.sqlite3")) .create_if_missing(true) .foreign_keys(true); let pool = sqlx::sqlite::SqlitePoolOptions::new() .max_connections(1) .connect_with(options) .await .unwrap(); sqlx::migrate::Migrator::new(migrations.path()) .await .unwrap() .run(&pool) .await .unwrap(); sqlx::query("INSERT INTO accounts(user_id,handle,created_at,display_name) VALUES('legacy-id','u_legacy',1,'Legacy')").execute(&pool).await.unwrap(); sqlx::query("INSERT INTO external_identities(provider,subject,user_id,linked_at) VALUES('email','legacy@example.org','legacy-id',1)").execute(&pool).await.unwrap(); let (token, csrf) = store::create_session(&pool, "legacy-id").await.unwrap(); let avatar = vnox_hub::avatar::replace(&pool, "legacy-id", b"stored legacy avatar") .await .unwrap(); pool.close().await; let upgraded = database::open(dir.path(), &issuer).await.unwrap(); let (user, stored_csrf) = store::get_session(&upgraded, &token) .await .unwrap() .unwrap(); assert_eq!(stored_csrf, csrf); assert_eq!(user.user_id, "legacy-id"); assert_eq!(user.handle, "u_legacy"); assert_eq!(user.display_name, "Legacy"); assert!(!user.profile_complete); assert_eq!(user.avatar_url.as_deref(), Some(avatar.as_str())); assert_eq!( store::upsert_email_identity(&upgraded, "legacy@example.org") .await .unwrap() .user_id, "legacy-id" ); // The new index also protects writes outside the HTTP handler. assert!( sqlx::query("INSERT INTO accounts(user_id,handle,created_at) VALUES('other','U_LEGACY',1)") .execute(&upgraded) .await .is_err() ); upgraded.close().await; let reopened = database::open(dir.path(), &issuer).await.unwrap(); assert!( store::get_session(&reopened, &token) .await .unwrap() .is_some() ); }