//! Own-origin profile onboarding with isolated SQLite and synthetic email/GitHub identities. 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, provider::GitHubProfile, store}, database, identity::Issuer, web::{self, HubState}, }; const ORIGIN: &str = "https://central.loki-code.dev"; struct Fixture { _dir: tempfile::TempDir, state: Arc, app: Router, } 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, } } async fn call( f: &Fixture, user: &str, path: &str, body: Value, origin: &str, csrf_ok: bool, ) -> (StatusCode, Value) { let (token, csrf) = store::create_session(&f.state.database, user) .await .unwrap(); let req = Request::builder() .method("POST") .uri(path) .header("origin", origin) .header("content-type", "application/json") .header("cookie", format!("__Host-vnox_session={token}")) .header("x-csrf-token", if csrf_ok { csrf } else { "bad".into() }) .body(Body::from(body.to_string())) .unwrap(); let r = f.app.clone().oneshot(req).await.unwrap(); let status = r.status(); let bytes = to_bytes(r.into_body(), 2048).await.unwrap(); (status, serde_json::from_slice(&bytes).unwrap()) } fn generated(name: &str) { let (word, digits) = name.rsplit_once('_').unwrap(); assert!(word.chars().all(|c| ('а'..='я').contains(&c) || c == 'ё')); assert_eq!(digits.len(), 4); assert!(digits.bytes().all(|c| c.is_ascii_digit())); } #[tokio::test] async fn names_are_generated_once_for_both_providers_and_user_names_survive_login() { let f = fixture().await; let mail = store::upsert_email_identity(&f.state.database, "first@example.org") .await .unwrap(); generated(&mail.display_name); let profile = GitHubProfile { id: 1234, login: "provider_private_login".into(), name: Some("Provider Name".into()), avatar_url: None, }; let github = store::upsert_identity(&f.state.database, &profile) .await .unwrap(); generated(&github.display_name); assert_ne!(github.display_name, "Provider Name"); assert!( store::onboarding_pending(&f.state.database, &github.user_id) .await .unwrap() ); for (user, provider) in [(&mail, "email"), (&github, "github")] { let before = user.handle.clone(); let (status, body) = call( &f, &user.user_id, "/v1/account/display-name", json!({"display_name":" Моё имя "}), ORIGIN, true, ) .await; assert_eq!(status, StatusCode::OK); assert_eq!(body["display_name"], "Моё имя"); assert!( !store::onboarding_pending(&f.state.database, &user.user_id) .await .unwrap() ); let again = if provider == "email" { store::upsert_email_identity(&f.state.database, "first@example.org") .await .unwrap() } else { store::upsert_identity(&f.state.database, &profile) .await .unwrap() }; assert_eq!(again.display_name, "Моё имя"); assert_eq!(again.handle, before); } } #[tokio::test] async fn decision_is_persisted_idempotently_and_not_created_for_existing_accounts() { let f = fixture().await; let user = store::upsert_email_identity(&f.state.database, "new@example.org") .await .unwrap(); assert!( store::onboarding_pending(&f.state.database, &user.user_id) .await .unwrap() ); for decision in ["later", "rename"] { assert_eq!( call( &f, &user.user_id, "/v1/account/onboarding", json!({"decision":decision}), ORIGIN, true ) .await .0, StatusCode::OK ); } let saved: String = sqlx::query_scalar("SELECT decision FROM account_onboarding WHERE user_id=?") .bind(&user.user_id) .fetch_one(&f.state.database) .await .unwrap(); assert_eq!(saved, "later"); assert!( !store::onboarding_pending(&f.state.database, &user.user_id) .await .unwrap() ); sqlx::query("DELETE FROM account_onboarding WHERE user_id=?") .bind(&user.user_id) .execute(&f.state.database) .await .unwrap(); let again = store::upsert_email_identity(&f.state.database, "new@example.org") .await .unwrap(); assert_eq!(again.display_name, user.display_name); assert!( !store::onboarding_pending(&f.state.database, &user.user_id) .await .unwrap() ); } #[tokio::test] async fn session_exposes_pending_and_actions_require_origin_csrf_and_valid_name() { let f = fixture().await; let user = store::upsert_email_identity(&f.state.database, "secure@example.org") .await .unwrap(); let (token, _) = store::create_session(&f.state.database, &user.user_id) .await .unwrap(); let r = f .app .clone() .oneshot( Request::builder() .uri("/v1/auth/session") .header("cookie", format!("__Host-vnox_session={token}")) .body(Body::empty()) .unwrap(), ) .await .unwrap(); let body: Value = serde_json::from_slice(&to_bytes(r.into_body(), 4096).await.unwrap()).unwrap(); assert_eq!(body["onboarding_pending"], true); for path in ["/v1/account/onboarding", "/v1/account/display-name"] { for (origin, csrf) in [("https://evil.example", true), (ORIGIN, false)] { assert_eq!( call( &f, &user.user_id, path, json!({"decision":"later"}), origin, csrf ) .await .0, StatusCode::FORBIDDEN ); } } for name in ["", "bad\nname", "\u{202e}evil"] { assert_eq!( call( &f, &user.user_id, "/v1/account/display-name", json!({"display_name":name}), ORIGIN, true ) .await .0, StatusCode::UNPROCESSABLE_ENTITY ); } assert_eq!( call( &f, &user.user_id, "/v1/account/display-name", json!({"display_name":"Name","handle":"override"}), ORIGIN, true ) .await .0, StatusCode::BAD_REQUEST ); assert_eq!( call( &f, &user.user_id, "/v1/account/onboarding", json!({"decision":"bad"}), ORIGIN, true ) .await .0, StatusCode::BAD_REQUEST ); }