chore(server): checkpoint deployed services and unfinished forums
User requested a checkpoint and stopped all agents. Deployed artifacts remain the last verified releases; unfinished settings/categories/forums are preserved as WIP. See TODO/roadmap for verification and remaining release/updater work.
This commit is contained in:
parent
d6d406bbf5
commit
c18ccadf99
96 changed files with 8665 additions and 276 deletions
|
|
@ -129,6 +129,23 @@ async fn login_browser_binding_replay_session_and_csrf() {
|
|||
response.headers()["location"],
|
||||
"https://central.loki-code.dev/account"
|
||||
);
|
||||
let persisted_cookie = response
|
||||
.headers()
|
||||
.get_all("set-cookie")
|
||||
.iter()
|
||||
.find(|v| v.to_str().unwrap().starts_with("__Host-vnox_session="))
|
||||
.unwrap()
|
||||
.to_str()
|
||||
.unwrap();
|
||||
for property in [
|
||||
"Secure",
|
||||
"HttpOnly",
|
||||
"SameSite=Lax",
|
||||
"Path=/",
|
||||
"Max-Age=604800",
|
||||
] {
|
||||
assert!(persisted_cookie.contains(property), "{property}");
|
||||
}
|
||||
let session = response
|
||||
.headers()
|
||||
.get_all("set-cookie")
|
||||
|
|
|
|||
|
|
@ -276,7 +276,10 @@ async fn assert_error(response: Response<Body>, status: StatusCode, code: &str)
|
|||
async fn upload_reencodes_to_a_square_png_and_serves_it_with_safe_headers() {
|
||||
let fx = fixture().await;
|
||||
let alice = fx.email_user("alice@example.com").await;
|
||||
assert_eq!(fx.session_avatar(&alice).await, serde_json::Value::Null);
|
||||
assert_eq!(
|
||||
fx.session_avatar(&alice).await,
|
||||
vnox_hub::avatar::default_url(&alice.user.user_id)
|
||||
);
|
||||
|
||||
let response = fx.upload(&alice, "image/png", png(600, 300)).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
|
|
@ -325,7 +328,9 @@ async fn jpeg_and_webp_are_accepted_and_exif_and_png_text_chunks_are_removed() {
|
|||
.as_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let body = bytes(fx.get(&url).await).await;
|
||||
let body = to_bytes(fx.get(&url).await.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!contains(&body, b"SECRET"));
|
||||
assert!(!contains(&body, b"Exif"));
|
||||
assert_eq!(chunk_names(&body), ["IHDR", "IDAT", "IEND"]);
|
||||
|
|
@ -339,7 +344,9 @@ async fn jpeg_and_webp_are_accepted_and_exif_and_png_text_chunks_are_removed() {
|
|||
.as_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
let body = bytes(fx.get(&url).await).await;
|
||||
let body = to_bytes(fx.get(&url).await.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
assert!(!contains(&body, b"SECRET"));
|
||||
assert_eq!(chunk_names(&body), ["IHDR", "IDAT", "IEND"]);
|
||||
|
||||
|
|
@ -453,7 +460,10 @@ async fn another_account_cannot_change_or_remove_my_avatar() {
|
|||
assert_eq!(response.status(), StatusCode::FORBIDDEN);
|
||||
}
|
||||
assert_eq!(fx.session_avatar(&alice).await, alice_url);
|
||||
assert_eq!(fx.session_avatar(&bob).await, serde_json::Value::Null);
|
||||
assert_eq!(
|
||||
fx.session_avatar(&bob).await,
|
||||
vnox_hub::avatar::default_url(&bob.user.user_id)
|
||||
);
|
||||
|
||||
// Bob acting as himself only affects Bob.
|
||||
assert_eq!(
|
||||
|
|
@ -622,32 +632,42 @@ async fn a_new_upload_replaces_the_old_one() {
|
|||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn delete_returns_the_provider_avatar_or_the_default() {
|
||||
async fn delete_restores_vnox_default_and_legacy_provider_images_are_never_exposed() {
|
||||
let fx = fixture().await;
|
||||
let github = fx.github_user().await;
|
||||
assert_eq!(fx.session_avatar(&github).await, GITHUB_AVATAR);
|
||||
let default = vnox_hub::avatar::default_url(&github.user.user_id);
|
||||
assert_eq!(fx.session_avatar(&github).await, default);
|
||||
|
||||
let url = json(fx.upload(&github, "image/png", png(64, 64)).await).await["avatar_url"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.to_owned();
|
||||
assert_ne!(fx.session_avatar(&github).await, GITHUB_AVATAR);
|
||||
assert_eq!(fx.session_avatar(&github).await, url);
|
||||
|
||||
let response = fx.remove(&github).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()["cache-control"], "no-store");
|
||||
assert_eq!(json(response).await["avatar_url"], GITHUB_AVATAR);
|
||||
assert_eq!(fx.session_avatar(&github).await, GITHUB_AVATAR);
|
||||
assert_eq!(json(response).await["avatar_url"], default);
|
||||
assert_eq!(fx.session_avatar(&github).await, default);
|
||||
assert_eq!(fx.get(&url).await.status(), StatusCode::NOT_FOUND);
|
||||
assert_eq!(fx.avatar_rows().await, 0);
|
||||
|
||||
// Removing again is harmless, and an email account falls back to the default (null).
|
||||
// Removing again is harmless; email accounts also get a stable VNOX default.
|
||||
assert_eq!(fx.remove(&github).await.status(), StatusCode::OK);
|
||||
let alice = fx.email_user("alice@example.com").await;
|
||||
fx.upload(&alice, "image/png", png(64, 64)).await;
|
||||
let response = fx.remove(&alice).await;
|
||||
assert_eq!(json(response).await["avatar_url"], serde_json::Value::Null);
|
||||
assert_eq!(fx.session_avatar(&alice).await, serde_json::Value::Null);
|
||||
let alice_default = vnox_hub::avatar::default_url(&alice.user.user_id);
|
||||
assert_eq!(json(response).await["avatar_url"], alice_default);
|
||||
assert_eq!(fx.session_avatar(&alice).await, alice_default);
|
||||
// Simulate an old row that still carries a GitHub provider URL.
|
||||
sqlx::query("UPDATE accounts SET avatar_url=? WHERE user_id=?")
|
||||
.bind(GITHUB_AVATAR)
|
||||
.bind(&github.user.user_id)
|
||||
.execute(&fx.state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(fx.session_avatar(&github).await, default);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
|
@ -740,3 +760,37 @@ async fn deleting_an_account_removes_its_avatar() {
|
|||
.unwrap();
|
||||
assert_eq!(fx.avatar_rows().await, 0);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn generated_defaults_are_stable_pngs_without_account_enumeration() {
|
||||
let fx = fixture().await;
|
||||
let id = uuid::Uuid::new_v4().to_string();
|
||||
let url = vnox_hub::avatar::default_url(&id);
|
||||
let response = fx.get(&url).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
assert_eq!(response.headers()["content-type"], "image/png");
|
||||
assert_eq!(
|
||||
response.headers()["cache-control"],
|
||||
"public, max-age=31536000, immutable"
|
||||
);
|
||||
let first = to_bytes(response.into_body(), usize::MAX).await.unwrap();
|
||||
assert_eq!(image::load_from_memory(&first).unwrap().width(), 256);
|
||||
assert_eq!(
|
||||
first,
|
||||
to_bytes(fx.get(&url).await.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
let other = vnox_hub::avatar::default_url(&uuid::Uuid::new_v4().to_string());
|
||||
assert_ne!(
|
||||
first,
|
||||
to_bytes(fx.get(&other).await.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
fx.get("/v1/avatars/default/not-a-uuid").await.status(),
|
||||
StatusCode::NOT_FOUND
|
||||
);
|
||||
assert_eq!(fx.avatar_rows().await, 0);
|
||||
}
|
||||
|
|
|
|||
614
hub/tests/desktop_auth.rs
Normal file
614
hub/tests/desktop_auth.rs
Normal file
|
|
@ -0,0 +1,614 @@
|
|||
use axum::{
|
||||
Router,
|
||||
body::{Body, to_bytes},
|
||||
http::{Request, StatusCode},
|
||||
};
|
||||
use ed25519_dalek::{Signature, VerifyingKey};
|
||||
use serde_json::{Value, json};
|
||||
use std::sync::Arc;
|
||||
use tower::ServiceExt;
|
||||
use vnox_hub::{
|
||||
auth::{self, store},
|
||||
database,
|
||||
identity::Issuer,
|
||||
web::{self, HubState},
|
||||
};
|
||||
async fn setup() -> (tempfile::TempDir, Arc<HubState>, Router, String, String) {
|
||||
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(),
|
||||
url::Url::parse("https://central.loki-code.dev").unwrap(),
|
||||
None,
|
||||
);
|
||||
let user = store::upsert_email_identity(&pool, "test@example.org")
|
||||
.await
|
||||
.unwrap();
|
||||
let (session, csrf) = store::create_session(&pool, &user.user_id).await.unwrap();
|
||||
let state = Arc::new(HubState {
|
||||
database: pool,
|
||||
auth: Arc::new(auth),
|
||||
issuer,
|
||||
smtp_configured: false,
|
||||
started: std::time::Instant::now(),
|
||||
});
|
||||
let app = web::router(state.clone());
|
||||
(dir, state, app, session, csrf)
|
||||
}
|
||||
async fn call(
|
||||
app: &Router,
|
||||
path: &str,
|
||||
body: Value,
|
||||
session: Option<(&str, &str)>,
|
||||
) -> (StatusCode, Value) {
|
||||
let mut b = Request::builder()
|
||||
.method("POST")
|
||||
.uri(path)
|
||||
.header("content-type", "application/json");
|
||||
if let Some((session, csrf)) = session {
|
||||
b = b
|
||||
.header("origin", "https://central.loki-code.dev")
|
||||
.header("cookie", format!("__Host-vnox_session={session}"))
|
||||
.header("x-csrf-token", csrf);
|
||||
}
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(b.body(Body::from(body.to_string())).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let status = response.status();
|
||||
let bytes = to_bytes(response.into_body(), 65536).await.unwrap();
|
||||
(
|
||||
status,
|
||||
serde_json::from_slice(&bytes).unwrap_or(Value::Null),
|
||||
)
|
||||
}
|
||||
async fn start(app: &Router) -> (String, Value) {
|
||||
let key = ed25519_dalek::SigningKey::generate(&mut rand::rng());
|
||||
let public = hex::encode(key.verifying_key().to_bytes());
|
||||
let (status, request) = call(
|
||||
app,
|
||||
"/v1/auth/desktop/start",
|
||||
json!({"public_key":public}),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
(public, request)
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn browser_approval_proof_binding_single_use_and_revocation() {
|
||||
let (_dir, state, app, session, csrf) = setup().await;
|
||||
let (public, request) = start(&app).await;
|
||||
let code = request["user_code"].as_str().unwrap();
|
||||
let secret = request["device_secret"].as_str().unwrap();
|
||||
assert!(
|
||||
!request["verification_uri"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains(secret)
|
||||
);
|
||||
assert_eq!(
|
||||
call(
|
||||
&app,
|
||||
"/v1/auth/desktop/poll",
|
||||
json!({"device_secret":secret}),
|
||||
None
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::ACCEPTED
|
||||
);
|
||||
assert_eq!(
|
||||
call(&app, "/v1/auth/desktop/approve", json!({"code":code}), None)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::FORBIDDEN
|
||||
);
|
||||
assert_eq!(
|
||||
call(
|
||||
&app,
|
||||
"/v1/auth/desktop/approve",
|
||||
json!({"code":code}),
|
||||
Some((&session, "wrong"))
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::FORBIDDEN
|
||||
);
|
||||
assert_eq!(
|
||||
call(
|
||||
&app,
|
||||
"/v1/auth/desktop/approve",
|
||||
json!({"code":code}),
|
||||
Some((&session, &csrf))
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::OK
|
||||
);
|
||||
let (status, approved) = call(
|
||||
&app,
|
||||
"/v1/auth/desktop/poll",
|
||||
json!({"device_secret":secret}),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
let claims = hex::decode(approved["account_proof"]["claims"].as_str().unwrap()).unwrap();
|
||||
let claim: Value = serde_json::from_slice(&claims).unwrap();
|
||||
assert_eq!(claim["public_key"], public);
|
||||
assert_eq!(claim["subject"], approved["user"]["user_id"]);
|
||||
assert_eq!(
|
||||
claim["expires_at"].as_i64().unwrap() - claim["issued_at"].as_i64().unwrap(),
|
||||
600
|
||||
);
|
||||
let key = VerifyingKey::from_bytes(
|
||||
&hex::decode(&state.issuer.public_key)
|
||||
.unwrap()
|
||||
.try_into()
|
||||
.unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let sig = Signature::from_slice(
|
||||
&hex::decode(approved["account_proof"]["signature"].as_str().unwrap()).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
let mut transcript = b"VNOX-CENTRAL-ACCOUNT-v1\0".to_vec();
|
||||
transcript.extend_from_slice(&claims);
|
||||
key.verify_strict(&transcript, &sig).unwrap();
|
||||
assert_eq!(
|
||||
call(
|
||||
&app,
|
||||
"/v1/auth/desktop/poll",
|
||||
json!({"device_secret":secret}),
|
||||
None
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::GONE
|
||||
);
|
||||
let refresh = approved["refresh_secret"].as_str().unwrap();
|
||||
let body = json!({"refresh_secret":refresh});
|
||||
assert_eq!(
|
||||
call(&app, "/v1/auth/desktop/refresh", body.clone(), None)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::OK
|
||||
);
|
||||
let stored: String = sqlx::query_scalar("SELECT refresh_hash FROM desktop_devices")
|
||||
.fetch_one(&state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(stored, store::hash(refresh));
|
||||
assert_ne!(stored, refresh);
|
||||
assert_eq!(
|
||||
call(&app, "/v1/auth/desktop/revoke", body.clone(), None)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
assert_eq!(
|
||||
call(&app, "/v1/auth/desktop/refresh", body, None).await.0,
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn canceled_expired_and_invalid_requests_fail_closed() {
|
||||
let (_dir, state, app, session, csrf) = setup().await;
|
||||
for expire in [false, true] {
|
||||
let (_, request) = start(&app).await;
|
||||
let secret = request["device_secret"].as_str().unwrap();
|
||||
let code = request["user_code"].as_str().unwrap();
|
||||
if expire {
|
||||
sqlx::query("UPDATE desktop_authorizations SET expires_at=0")
|
||||
.execute(&state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
} else {
|
||||
assert_eq!(
|
||||
call(
|
||||
&app,
|
||||
"/v1/auth/desktop/cancel",
|
||||
json!({"device_secret":secret}),
|
||||
None
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
call(
|
||||
&app,
|
||||
"/v1/auth/desktop/approve",
|
||||
json!({"code":code}),
|
||||
Some((&session, &csrf))
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::GONE
|
||||
);
|
||||
assert_eq!(
|
||||
call(
|
||||
&app,
|
||||
"/v1/auth/desktop/poll",
|
||||
json!({"device_secret":secret}),
|
||||
None
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::GONE
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
call(
|
||||
&app,
|
||||
"/v1/auth/desktop/start",
|
||||
json!({"public_key":"bad"}),
|
||||
None
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cancel_also_revokes_an_enrollment_whose_poll_response_was_lost() {
|
||||
let (_dir, _state, app, session, csrf) = setup().await;
|
||||
let (_, request) = start(&app).await;
|
||||
let code = request["user_code"].as_str().unwrap();
|
||||
let device = json!({"device_secret":request["device_secret"]});
|
||||
assert_eq!(
|
||||
call(
|
||||
&app,
|
||||
"/v1/auth/desktop/approve",
|
||||
json!({"code":code}),
|
||||
Some((&session, &csrf))
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::OK
|
||||
);
|
||||
let (status, approved) = call(&app, "/v1/auth/desktop/poll", device.clone(), None).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(
|
||||
call(&app, "/v1/auth/desktop/cancel", device, None).await.0,
|
||||
StatusCode::NO_CONTENT
|
||||
);
|
||||
let refresh = json!({"refresh_secret":approved["refresh_secret"]});
|
||||
assert_eq!(
|
||||
call(&app, "/v1/auth/desktop/refresh", refresh, None)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
}
|
||||
|
||||
async fn enroll(
|
||||
app: &Router,
|
||||
session: &str,
|
||||
csrf: &str,
|
||||
) -> (ed25519_dalek::SigningKey, String, Value) {
|
||||
let key = ed25519_dalek::SigningKey::generate(&mut rand::rng());
|
||||
let (_, request) = call(
|
||||
app,
|
||||
"/v1/auth/desktop/start",
|
||||
json!({"public_key":hex::encode(key.verifying_key().to_bytes())}),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(
|
||||
call(
|
||||
app,
|
||||
"/v1/auth/desktop/approve",
|
||||
json!({"code":request["user_code"]}),
|
||||
Some((session, csrf))
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::OK
|
||||
);
|
||||
let (status, approved) = call(
|
||||
app,
|
||||
"/v1/auth/desktop/poll",
|
||||
json!({"device_secret":request["device_secret"]}),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
(
|
||||
key,
|
||||
approved["refresh_secret"].as_str().unwrap().to_owned(),
|
||||
approved["user"].clone(),
|
||||
)
|
||||
}
|
||||
fn test_png() -> Vec<u8> {
|
||||
let picture = image::DynamicImage::ImageRgba8(image::RgbaImage::from_pixel(
|
||||
64,
|
||||
64,
|
||||
image::Rgba([20, 100, 220, 255]),
|
||||
));
|
||||
let mut bytes = std::io::Cursor::new(Vec::new());
|
||||
picture
|
||||
.write_to(&mut bytes, image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
bytes.into_inner()
|
||||
}
|
||||
async fn mutate(
|
||||
app: &Router,
|
||||
method: &str,
|
||||
path: &str,
|
||||
key: &ed25519_dalek::SigningKey,
|
||||
secret: &str,
|
||||
bytes: Vec<u8>,
|
||||
timestamp: i64,
|
||||
) -> (StatusCode, Value) {
|
||||
use ed25519_dalek::Signer;
|
||||
use sha2::{Digest, Sha256};
|
||||
let timestamp = timestamp.to_string();
|
||||
let mut signed = b"VNOX-CENTRAL-PROFILE-v1\0".to_vec();
|
||||
signed.extend_from_slice(method.as_bytes());
|
||||
signed.push(0);
|
||||
signed.extend_from_slice(path.as_bytes());
|
||||
signed.push(0);
|
||||
signed.extend_from_slice(timestamp.as_bytes());
|
||||
signed.push(0);
|
||||
signed.extend_from_slice(&Sha256::digest(&bytes));
|
||||
let request = Request::builder()
|
||||
.method(method)
|
||||
.uri(path)
|
||||
.header("authorization", format!("Bearer {secret}"))
|
||||
.header(
|
||||
"x-vnox-public-key",
|
||||
hex::encode(key.verifying_key().to_bytes()),
|
||||
)
|
||||
.header("x-vnox-timestamp", timestamp)
|
||||
.header(
|
||||
"x-vnox-signature",
|
||||
hex::encode(key.sign(&signed).to_bytes()),
|
||||
)
|
||||
.header(
|
||||
"content-type",
|
||||
if path.ends_with("profile") {
|
||||
"application/json"
|
||||
} else {
|
||||
"image/png"
|
||||
},
|
||||
)
|
||||
.body(Body::from(bytes))
|
||||
.unwrap();
|
||||
let response = app.clone().oneshot(request).await.unwrap();
|
||||
let status = response.status();
|
||||
let bytes = to_bytes(response.into_body(), 65536).await.unwrap();
|
||||
(
|
||||
status,
|
||||
serde_json::from_slice(&bytes).unwrap_or(Value::Null),
|
||||
)
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn desktop_avatar_upload_delete_and_website_refresh_share_one_account() {
|
||||
let (_dir, state, app, session, csrf) = setup().await;
|
||||
let (key, secret, user) = enroll(&app, &session, &csrf).await;
|
||||
let user_id = user["user_id"].as_str().unwrap();
|
||||
let website_url = vnox_hub::avatar::replace(&state.database, user_id, &test_png())
|
||||
.await
|
||||
.unwrap();
|
||||
let (status, fresh) = call(
|
||||
&app,
|
||||
"/v1/auth/desktop/refresh",
|
||||
json!({"refresh_secret":secret}),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(fresh["user"]["avatar_url"], website_url);
|
||||
let claims: Value = serde_json::from_slice(
|
||||
&hex::decode(fresh["account_proof"]["claims"].as_str().unwrap()).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(claims["avatar_url"], website_url);
|
||||
let (status, uploaded) = mutate(
|
||||
&app,
|
||||
"POST",
|
||||
"/v1/auth/desktop/avatar",
|
||||
&key,
|
||||
&secret,
|
||||
test_png(),
|
||||
store::now(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(uploaded["user"]["user_id"], user_id);
|
||||
let url = uploaded["user"]["avatar_url"].as_str().unwrap();
|
||||
assert_ne!(
|
||||
url, website_url,
|
||||
"desktop normalizes source to a fresh stored 256px PNG"
|
||||
);
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(Request::builder().uri(url).body(Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let bytes = to_bytes(response.into_body(), 1024 * 1024).await.unwrap();
|
||||
let image = image::load_from_memory(&bytes).unwrap();
|
||||
assert_eq!((image.width(), image.height()), (256, 256));
|
||||
let (status, deleted) = mutate(
|
||||
&app,
|
||||
"DELETE",
|
||||
"/v1/auth/desktop/avatar",
|
||||
&key,
|
||||
&secret,
|
||||
Vec::new(),
|
||||
store::now(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(
|
||||
deleted["user"]["avatar_url"],
|
||||
format!("/v1/avatars/default-v2/{user_id}")
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn desktop_profile_name_changes_without_handle_or_identity_reassignment() {
|
||||
let (_dir, _state, app, session, csrf) = setup().await;
|
||||
let (key, secret, user) = enroll(&app, &session, &csrf).await;
|
||||
let (status, updated) = mutate(
|
||||
&app,
|
||||
"POST",
|
||||
"/v1/auth/desktop/profile",
|
||||
&key,
|
||||
&secret,
|
||||
br#"{"display_name":" New Name "}"#.to_vec(),
|
||||
store::now(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(updated["user"]["display_name"], "New Name");
|
||||
assert_eq!(updated["user"]["handle"], user["handle"]);
|
||||
assert_eq!(updated["user"]["user_id"], user["user_id"]);
|
||||
let (_, fresh) = call(
|
||||
&app,
|
||||
"/v1/auth/desktop/refresh",
|
||||
json!({"refresh_secret":secret}),
|
||||
None,
|
||||
)
|
||||
.await;
|
||||
let claim: Value = serde_json::from_slice(
|
||||
&hex::decode(fresh["account_proof"]["claims"].as_str().unwrap()).unwrap(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(claim["display_name"], "New Name");
|
||||
for name in ["", "\nBad", "Bad\u{202e}Name"] {
|
||||
assert_eq!(
|
||||
mutate(
|
||||
&app,
|
||||
"POST",
|
||||
"/v1/auth/desktop/profile",
|
||||
&key,
|
||||
&secret,
|
||||
serde_json::to_vec(&json!({"display_name":name})).unwrap(),
|
||||
store::now()
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::UNPROCESSABLE_ENTITY
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
mutate(
|
||||
&app,
|
||||
"POST",
|
||||
"/v1/auth/desktop/profile",
|
||||
&key,
|
||||
&secret,
|
||||
serde_json::to_vec(&json!({"display_name":"x".repeat(65)})).unwrap(),
|
||||
store::now()
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::UNPROCESSABLE_ENTITY
|
||||
);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn desktop_avatar_requires_live_secret_device_signature_and_bounded_valid_png() {
|
||||
let (_dir, state, app, session, csrf) = setup().await;
|
||||
let (key, secret, _) = enroll(&app, &session, &csrf).await;
|
||||
let other = ed25519_dalek::SigningKey::generate(&mut rand::rng());
|
||||
for (signer, secret, time) in [
|
||||
(&other, secret.as_str(), store::now()),
|
||||
(
|
||||
&key,
|
||||
"0000000000000000000000000000000000000000000000000000000000000000",
|
||||
store::now(),
|
||||
),
|
||||
(&key, secret.as_str(), store::now() - 61),
|
||||
] {
|
||||
assert_eq!(
|
||||
mutate(
|
||||
&app,
|
||||
"POST",
|
||||
"/v1/auth/desktop/avatar",
|
||||
signer,
|
||||
secret,
|
||||
test_png(),
|
||||
time
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
mutate(
|
||||
&app,
|
||||
"POST",
|
||||
"/v1/auth/desktop/avatar",
|
||||
&key,
|
||||
&secret,
|
||||
b"not png".to_vec(),
|
||||
store::now()
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::UNSUPPORTED_MEDIA_TYPE
|
||||
);
|
||||
assert_eq!(
|
||||
mutate(
|
||||
&app,
|
||||
"POST",
|
||||
"/v1/auth/desktop/avatar",
|
||||
&key,
|
||||
&secret,
|
||||
vec![0; 2 * 1024 * 1024 + 1],
|
||||
store::now()
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::PAYLOAD_TOO_LARGE
|
||||
);
|
||||
sqlx::query("UPDATE desktop_devices SET expires_at=0")
|
||||
.execute(&state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
mutate(
|
||||
&app,
|
||||
"DELETE",
|
||||
"/v1/auth/desktop/avatar",
|
||||
&key,
|
||||
&secret,
|
||||
Vec::new(),
|
||||
store::now()
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
sqlx::query("DELETE FROM desktop_devices")
|
||||
.execute(&state.database)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
mutate(
|
||||
&app,
|
||||
"POST",
|
||||
"/v1/auth/desktop/profile",
|
||||
&key,
|
||||
&secret,
|
||||
br#"{"display_name":"Changed"}"#.to_vec(),
|
||||
store::now()
|
||||
)
|
||||
.await
|
||||
.0,
|
||||
StatusCode::UNAUTHORIZED
|
||||
);
|
||||
}
|
||||
230
hub/tests/directory.rs
Normal file
230
hub/tests/directory.rs
Normal file
|
|
@ -0,0 +1,230 @@
|
|||
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<HubState>,
|
||||
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<Body> {
|
||||
Request::builder()
|
||||
.method("POST")
|
||||
.uri("/v1/servers")
|
||||
.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<Body>) -> (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(), 1048576).await.unwrap()).unwrap(),
|
||||
)
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn directory_auth_ownership_normalization_and_persistence() {
|
||||
let f = fixture().await;
|
||||
let owner = f.login("owner@example.org").await;
|
||||
let other = f.login("other@example.org").await;
|
||||
let body =
|
||||
json!({"name":" Voice ","address":"Voice.Example.COM.:07600","description":" public "})
|
||||
.to_string();
|
||||
let mut unauth = f.request(&owner, body.clone());
|
||||
unauth.headers_mut().remove("cookie");
|
||||
assert_eq!(f.send(unauth).await.0, StatusCode::UNAUTHORIZED);
|
||||
for header in ["origin", "x-csrf-token"] {
|
||||
let mut req = f.request(&owner, body.clone());
|
||||
req.headers_mut().remove(header);
|
||||
assert_eq!(f.send(req).await.0, StatusCode::FORBIDDEN);
|
||||
}
|
||||
let (status, result) = f.send(f.request(&owner, body.clone())).await;
|
||||
assert_eq!(status, StatusCode::CREATED);
|
||||
assert_eq!(result["server"]["address"], "voice.example.com:7600");
|
||||
assert_eq!(result["server"]["owner_id"], owner.user.user_id);
|
||||
assert_eq!(
|
||||
f.send(f.request(&owner, body)).await.0,
|
||||
StatusCode::CONFLICT
|
||||
);
|
||||
let id = result["server"]["id"].as_str().unwrap();
|
||||
let mut remove = f.request(&other, String::new());
|
||||
*remove.method_mut() = axum::http::Method::DELETE;
|
||||
*remove.uri_mut() = format!("/v1/servers/{id}").parse().unwrap();
|
||||
assert_eq!(f.send(remove).await.0, StatusCode::NOT_FOUND);
|
||||
let pool = database::open(f._dir.path(), &f.state.issuer)
|
||||
.await
|
||||
.unwrap();
|
||||
let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM community_servers")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count, 1);
|
||||
let (_, page) = f
|
||||
.send(
|
||||
Request::builder()
|
||||
.uri("/v1/servers")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(page["servers"].as_array().unwrap().len(), 1);
|
||||
sqlx::query("DELETE FROM accounts WHERE user_id=?")
|
||||
.bind(owner.user.user_id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
let count: i64 = sqlx::query_scalar("SELECT COUNT(*) FROM community_servers")
|
||||
.fetch_one(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(count, 0);
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn directory_rejects_bad_json_oversize_and_bounds() {
|
||||
let f = fixture().await;
|
||||
let s = f.login("bounds@example.org").await;
|
||||
assert_eq!(
|
||||
f.send(f.request(&s, "{".into())).await.0,
|
||||
StatusCode::BAD_REQUEST
|
||||
);
|
||||
assert_eq!(
|
||||
f.send(f.request(&s, "x".repeat(4097))).await.0,
|
||||
StatusCode::PAYLOAD_TOO_LARGE
|
||||
);
|
||||
for body in [
|
||||
json!({"name":"","address":"voice.example.com:7600","description":""}),
|
||||
json!({"name":"voice","address":"127.0.0.1:7600","description":""}),
|
||||
json!({"name":"voice","address":"voice.example.com:7600","description":"x".repeat(501)}),
|
||||
] {
|
||||
assert_eq!(
|
||||
f.send(f.request(&s, body.to_string())).await.0,
|
||||
StatusCode::UNPROCESSABLE_ENTITY
|
||||
);
|
||||
}
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn directory_owner_can_remove_and_rate_budget_is_independent() {
|
||||
let f = fixture().await;
|
||||
let s = f.login("delete@example.org").await;
|
||||
let (_, result) = f
|
||||
.send(f.request(
|
||||
&s,
|
||||
json!({"name":"Voice","address":"voice.example.org:7600","description":""}).to_string(),
|
||||
))
|
||||
.await;
|
||||
let mut req = f.request(&s, String::new());
|
||||
*req.method_mut() = axum::http::Method::DELETE;
|
||||
*req.uri_mut() = format!("/v1/servers/{}", result["server"]["id"].as_str().unwrap())
|
||||
.parse()
|
||||
.unwrap();
|
||||
let response = f.app.clone().oneshot(req).await.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::NO_CONTENT);
|
||||
for _ in 0..8 {
|
||||
assert!(f.state.auth.allow_directory(&s.user.user_id, "local"));
|
||||
}
|
||||
assert!(!f.state.auth.allow_directory(&s.user.user_id, "local"));
|
||||
assert!(f.state.auth.allow_avatar(&s.user.user_id, "local"));
|
||||
}
|
||||
#[tokio::test]
|
||||
async fn directory_account_cap_and_pagination_are_bounded() {
|
||||
let f = fixture().await;
|
||||
let s = f.login("cap@example.org").await;
|
||||
for i in 0..105 {
|
||||
sqlx::query("INSERT INTO community_servers(id,name,address,description,owner_id,created_at) VALUES (?,?,?,?,?,?)")
|
||||
.bind(format!("00000000-0000-4000-8000-{i:012}" )).bind("voice").bind(format!("voice{i}.example.org:7600")).bind("").bind(&s.user.user_id).bind(1_i64).execute(&f.state.database).await.unwrap();
|
||||
}
|
||||
let (status, page) = f
|
||||
.send(
|
||||
Request::builder()
|
||||
.uri("/v1/servers")
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(page["servers"].as_array().unwrap().len(), 100);
|
||||
let last = page["servers"][99]["id"].as_str().unwrap();
|
||||
let (_, next) = f
|
||||
.send(
|
||||
Request::builder()
|
||||
.uri(format!("/v1/servers?after={last}"))
|
||||
.body(Body::empty())
|
||||
.unwrap(),
|
||||
)
|
||||
.await;
|
||||
assert_eq!(next["servers"].as_array().unwrap().len(), 5);
|
||||
assert_eq!(
|
||||
f.send(f.request(
|
||||
&s,
|
||||
json!({"name":"voice","address":"new.example.org:7600","description":""}).to_string()
|
||||
))
|
||||
.await
|
||||
.1["error"],
|
||||
"listing_limit"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn directory_reads_do_not_consume_login_budget() {
|
||||
let f = fixture().await;
|
||||
for _ in 0..20 {
|
||||
assert!(f.state.auth.allow_directory_read("source"));
|
||||
}
|
||||
assert!(!f.state.auth.allow_directory_read("source"));
|
||||
assert!(f.state.auth.allow("source"));
|
||||
}
|
||||
|
|
@ -288,7 +288,12 @@ async fn full_flow_creates_neutral_account_and_session() {
|
|||
}
|
||||
let json: Value = serde_json::from_str(&body).unwrap();
|
||||
assert_eq!(json["authenticated"], true);
|
||||
assert_eq!(json["user"]["display_name"], "Vnox user");
|
||||
let initial_name = json["user"]["display_name"].as_str().unwrap();
|
||||
let (word, digits) = initial_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()));
|
||||
assert_eq!(json["onboarding_pending"], true);
|
||||
let handle = json["user"]["handle"].as_str().unwrap();
|
||||
assert!(handle.starts_with("u_") && !handle.contains("alice"));
|
||||
assert!(!body.to_lowercase().contains("alice"));
|
||||
|
|
|
|||
|
|
@ -184,6 +184,7 @@ async fn capabilities_and_routes_do_not_pretend_authentication_is_ready() {
|
|||
"marketplace",
|
||||
] {
|
||||
assert_eq!(value["capabilities"][capability], "not_enabled");
|
||||
assert_eq!(value["capabilities"]["account_profile"], "enabled");
|
||||
}
|
||||
assert_eq!(value["smtp"]["public_send_endpoint"], false);
|
||||
assert!(value.get("secret_key").is_none());
|
||||
|
|
@ -203,7 +204,10 @@ async fn capabilities_and_routes_do_not_pretend_authentication_is_ready() {
|
|||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::SERVICE_UNAVAILABLE);
|
||||
}
|
||||
for path in ["/v1/servers/register", "/v1/mail/send"] {
|
||||
for (path, expected) in [
|
||||
("/v1/servers/register", StatusCode::METHOD_NOT_ALLOWED),
|
||||
("/v1/mail/send", StatusCode::NOT_FOUND),
|
||||
] {
|
||||
let response = app
|
||||
.clone()
|
||||
.oneshot(
|
||||
|
|
@ -215,7 +219,7 @@ async fn capabilities_and_routes_do_not_pretend_authentication_is_ready() {
|
|||
)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::NOT_FOUND);
|
||||
assert_eq!(response.status(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
265
hub/tests/onboarding.rs
Normal file
265
hub/tests/onboarding.rs
Normal file
|
|
@ -0,0 +1,265 @@
|
|||
//! 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<HubState>,
|
||||
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
|
||||
);
|
||||
}
|
||||
412
hub/tests/profile.rs
Normal file
412
hub/tests/profile.rs
Normal file
|
|
@ -0,0 +1,412 @@
|
|||
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<HubState>,
|
||||
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<Body> {
|
||||
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<Body>) -> (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()
|
||||
);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue