feat(m4): axum replay referee with auth, rate limit and sqlite persistence
This commit is contained in:
@@ -0,0 +1,213 @@
|
||||
//! End-to-end tests against the HTTP router (no sockets involved).
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::{Request, StatusCode};
|
||||
use http_body_util::BodyExt;
|
||||
use serde_json::{json, Value};
|
||||
use tower::ServiceExt;
|
||||
|
||||
use content::Content;
|
||||
use server::{issue_token, router, test_state, AppState};
|
||||
use sim::fixed::from_int;
|
||||
use sim::replay::ReplayV1;
|
||||
use sim::state::{Command, Sim, TankSpec};
|
||||
use sim::terrain::WORLD_W;
|
||||
|
||||
async fn app() -> (axum::Router, AppState, String) {
|
||||
let state = test_state().await;
|
||||
let token = issue_token(&state, "device-1234");
|
||||
(router(state.clone()), state, token)
|
||||
}
|
||||
|
||||
async fn call(app: &axum::Router, req: Request<Body>) -> (StatusCode, Value) {
|
||||
let resp = app.clone().oneshot(req).await.expect("request");
|
||||
let status = resp.status();
|
||||
let bytes = resp.into_body().collect().await.expect("body").to_bytes();
|
||||
let value: Value = if bytes.is_empty() {
|
||||
Value::Null
|
||||
} else {
|
||||
serde_json::from_slice(&bytes).expect("json body")
|
||||
};
|
||||
(status, value)
|
||||
}
|
||||
|
||||
fn bearer(token: &str) -> String {
|
||||
format!("Bearer {token}")
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn health_is_public() {
|
||||
let (app, _state, _token) = app().await;
|
||||
let req = Request::builder()
|
||||
.uri("/v1/health")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let (status, body) = call(&app, req).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body["status"], "ok");
|
||||
assert_eq!(body["sim_version"], sim::SIM_VERSION);
|
||||
assert!(body["content_hash"].as_str().unwrap().starts_with("fnv1a:"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn auth_issues_verifiable_tokens() {
|
||||
let (app, _state, token) = app().await;
|
||||
let req = Request::builder()
|
||||
.method("POST")
|
||||
.uri("/v1/auth/device")
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(r#"{"device_id":"device-1234"}"#))
|
||||
.unwrap();
|
||||
let (status, body) = call(&app, req).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body["token"], token);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn protected_routes_reject_missing_token() {
|
||||
let (app, _state, _token) = app().await;
|
||||
let req = Request::builder()
|
||||
.uri("/v1/leaderboard/season-1")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let (status, body) = call(&app, req).await;
|
||||
assert_eq!(status, StatusCode::UNAUTHORIZED);
|
||||
assert_eq!(body["error"]["code"], "unauthorized");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn create_match_and_play_a_turn() {
|
||||
let (app, state, token) = app().await;
|
||||
let content = Content::builtin();
|
||||
|
||||
let create = json!({
|
||||
"mode": "ranked",
|
||||
"content_hash": content.hash(),
|
||||
"sim_version": sim::SIM_VERSION,
|
||||
"players": [
|
||||
{"tank": "vanguard", "loadout": [1, 2, 5]},
|
||||
{"tank": "longshot", "loadout": [1, 3, 4]}
|
||||
]
|
||||
});
|
||||
let req = Request::builder()
|
||||
.method("POST")
|
||||
.uri("/v1/matches")
|
||||
.header("authorization", bearer(&token))
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(create.to_string()))
|
||||
.unwrap();
|
||||
let (status, body) = call(&app, req).await;
|
||||
assert_eq!(status, StatusCode::CREATED, "body: {body}");
|
||||
let match_id = body["match_id"].as_str().unwrap().to_string();
|
||||
let state_hash = body["state_hash"].as_u64().unwrap();
|
||||
assert!(state.has_live_match(&match_id));
|
||||
|
||||
// Wrong expect_hash must be rejected.
|
||||
let turn = json!({
|
||||
"expect_hash": state_hash ^ 0xFF,
|
||||
"command": {"kind": "fire", "angle": 45000, "power": 65536, "w": 1}
|
||||
});
|
||||
let req = Request::builder()
|
||||
.method("POST")
|
||||
.uri(format!("/v1/matches/{match_id}/turn"))
|
||||
.header("authorization", bearer(&token))
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(turn.to_string()))
|
||||
.unwrap();
|
||||
let (status, body) = call(&app, req).await;
|
||||
assert_eq!(status, StatusCode::CONFLICT, "body: {body}");
|
||||
assert_eq!(body["error"]["code"], "state_conflict");
|
||||
|
||||
// Correct hash is accepted and the shot is resolved server side.
|
||||
let turn = json!({
|
||||
"expect_hash": state_hash,
|
||||
"command": {"kind": "fire", "angle": 45000, "power": 65536, "w": 1}
|
||||
});
|
||||
let req = Request::builder()
|
||||
.method("POST")
|
||||
.uri(format!("/v1/matches/{match_id}/turn"))
|
||||
.header("authorization", bearer(&token))
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(turn.to_string()))
|
||||
.unwrap();
|
||||
let (status, body) = call(&app, req).await;
|
||||
assert_eq!(status, StatusCode::OK, "body: {body}");
|
||||
assert_eq!(body["accepted"], true);
|
||||
assert_eq!(body["turn"], 2);
|
||||
assert!(body["state_hash"].as_u64().unwrap() != state_hash);
|
||||
}
|
||||
|
||||
fn build_replay(seed: u64) -> ReplayV1 {
|
||||
let specs = [
|
||||
TankSpec {
|
||||
x: 220,
|
||||
loadout: [1, 2, 5],
|
||||
},
|
||||
TankSpec {
|
||||
x: WORLD_W - 220,
|
||||
loadout: [1, 3, 4],
|
||||
},
|
||||
];
|
||||
let mut sim = Sim::new(seed, specs, Content::builtin());
|
||||
sim.submit(Command::Fire {
|
||||
angle_mdeg: 45_000,
|
||||
power: from_int(1),
|
||||
weapon: 1,
|
||||
})
|
||||
.expect("valid command");
|
||||
for _ in 0..400 {
|
||||
sim.tick();
|
||||
}
|
||||
ReplayV1::capture(&sim, "hotseat", sim.tick)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn valid_replay_is_accepted() {
|
||||
let (app, _state, token) = app().await;
|
||||
let replay = build_replay(4242);
|
||||
let req = Request::builder()
|
||||
.method("POST")
|
||||
.uri("/v1/matches/m_test/validate")
|
||||
.header("authorization", bearer(&token))
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(json!({ "replay": replay }).to_string()))
|
||||
.unwrap();
|
||||
let (status, body) = call(&app, req).await;
|
||||
assert_eq!(status, StatusCode::OK, "body: {body}");
|
||||
assert_eq!(body["valid"], true);
|
||||
assert_eq!(body["final_hash"].as_u64().unwrap(), replay.final_hash);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tampered_replay_is_rejected() {
|
||||
let (app, _state, token) = app().await;
|
||||
let mut replay = build_replay(4242);
|
||||
replay.final_hash ^= 1; // claim a different result
|
||||
let req = Request::builder()
|
||||
.method("POST")
|
||||
.uri("/v1/matches/m_test/validate")
|
||||
.header("authorization", bearer(&token))
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(json!({ "replay": replay }).to_string()))
|
||||
.unwrap();
|
||||
let (status, body) = call(&app, req).await;
|
||||
assert_eq!(status, StatusCode::CONFLICT, "body: {body}");
|
||||
assert_eq!(body["error"]["code"], "hash_mismatch");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tampered_seed_is_rejected() {
|
||||
let (app, _state, token) = app().await;
|
||||
let mut replay = build_replay(4242);
|
||||
replay.seed = replay.seed.wrapping_add(99);
|
||||
let req = Request::builder()
|
||||
.method("POST")
|
||||
.uri("/v1/matches/m_test/validate")
|
||||
.header("authorization", bearer(&token))
|
||||
.header("content-type", "application/json")
|
||||
.body(Body::from(json!({ "replay": replay }).to_string()))
|
||||
.unwrap();
|
||||
let (status, body) = call(&app, req).await;
|
||||
assert_eq!(status, StatusCode::CONFLICT, "body: {body}");
|
||||
assert_eq!(body["error"]["code"], "hash_mismatch");
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
//! Throughput of the request pipeline (in-process, no sockets).
|
||||
//!
|
||||
//! Authenticated routes are intentionally rate limited to 60 req/min per
|
||||
//! device, so throughput is measured on the public health endpoint.
|
||||
//! Run with: cargo test -p server --release --test load -- --ignored --nocapture
|
||||
|
||||
use std::time::Instant;
|
||||
|
||||
use axum::body::Body;
|
||||
use axum::http::Request;
|
||||
use http_body_util::BodyExt;
|
||||
use tower::ServiceExt;
|
||||
|
||||
use server::{router, test_state};
|
||||
|
||||
#[tokio::test]
|
||||
#[ignore = "throughput measurement, run manually"]
|
||||
async fn health_throughput() {
|
||||
let state = test_state().await;
|
||||
let app = router(state);
|
||||
let requests = 5_000;
|
||||
|
||||
let started = Instant::now();
|
||||
for _ in 0..requests {
|
||||
let req = Request::builder()
|
||||
.uri("/v1/health")
|
||||
.body(Body::empty())
|
||||
.unwrap();
|
||||
let resp = app.clone().oneshot(req).await.expect("request");
|
||||
assert_eq!(resp.status(), axum::http::StatusCode::OK);
|
||||
let _ = resp.into_body().collect().await.expect("body");
|
||||
}
|
||||
let elapsed = started.elapsed().as_secs_f64();
|
||||
println!(
|
||||
"requests={requests} elapsed={elapsed:.2}s throughput={:.0} req/s (single task, in-process)",
|
||||
requests as f64 / elapsed
|
||||
);
|
||||
assert!(
|
||||
requests as f64 / elapsed > 200.0,
|
||||
"expected more than 200 req/s"
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user