VNOX-Server/hub/tests/directory.rs
loki5512344 c18ccadf99
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.
2026-11-01 15:31:20 +01:00

230 lines
7.9 KiB
Rust

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"));
}