feat(m4): axum replay referee with auth, rate limit and sqlite persistence
This commit is contained in:
@@ -7,5 +7,16 @@ authors.workspace = true
|
||||
description = "Replay validation service (referee)"
|
||||
|
||||
[dependencies]
|
||||
sim.workspace = true
|
||||
sim = { workspace = true, features = ["serde"] }
|
||||
content.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
axum = "0.8"
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros", "net", "signal"] }
|
||||
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio", "sqlite", "macros"] }
|
||||
hmac = "0.12"
|
||||
sha2 = "0.10"
|
||||
|
||||
[dev-dependencies]
|
||||
tower = { version = "0.5", features = ["util"] }
|
||||
http-body-util = "0.1"
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
# Build stage
|
||||
FROM rust:1.85-slim AS builder
|
||||
WORKDIR /src
|
||||
COPY Cargo.toml Cargo.lock rust-toolchain.toml ./
|
||||
COPY crates ./crates
|
||||
COPY tools ./tools
|
||||
RUN cargo build --release -p server
|
||||
|
||||
# Runtime stage
|
||||
FROM debian:stable-slim
|
||||
RUN useradd --system --uid 10001 ironarc
|
||||
WORKDIR /app
|
||||
COPY --from=builder /src/target/release/server /app/server
|
||||
USER ironarc
|
||||
ENV BIND=0.0.0.0:8080
|
||||
EXPOSE 8080
|
||||
ENTRYPOINT ["/app/server"]
|
||||
+646
-3
@@ -1,14 +1,657 @@
|
||||
//! Replay validation service. Filled in at M4 (axum, sqlx, HMAC tokens).
|
||||
//! Replay validation service ("referee").
|
||||
//!
|
||||
//! The server never trusts the client: it re-simulates every submitted match
|
||||
//! with the same `sim` crate and compares state hashes.
|
||||
|
||||
pub mod store;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, RwLock};
|
||||
use std::time::{Instant, SystemTime, UNIX_EPOCH};
|
||||
|
||||
use axum::extract::{FromRequestParts, Path, State};
|
||||
use axum::http::request::Parts;
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::{IntoResponse, Response};
|
||||
use axum::routing::{get, post};
|
||||
use axum::{Json, Router};
|
||||
use content::Content;
|
||||
use hmac::{Hmac, Mac};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha2::Sha256;
|
||||
use sim::replay::ReplayV1;
|
||||
use sim::state::{Event, Phase, Sim, TankSpec};
|
||||
use sim::terrain::WORLD_W;
|
||||
|
||||
use crate::store::{MatchRow, Store};
|
||||
|
||||
type HmacSha256 = Hmac<Sha256>;
|
||||
|
||||
/// Requests per minute and device.
|
||||
const RATE_LIMIT_PER_MIN: u32 = 60;
|
||||
/// Hard cap for ticks spent resolving one shot.
|
||||
const MAX_RESOLVE_TICKS: u32 = 5_000;
|
||||
|
||||
/// Shared server state.
|
||||
#[derive(Clone)]
|
||||
pub struct AppState {
|
||||
inner: Arc<Inner>,
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
store: Store,
|
||||
content: Content,
|
||||
secret: Vec<u8>,
|
||||
live: RwLock<HashMap<String, Sim>>,
|
||||
rate: Mutex<HashMap<String, Bucket>>,
|
||||
counter: AtomicU64,
|
||||
}
|
||||
|
||||
struct Bucket {
|
||||
window: Instant,
|
||||
count: u32,
|
||||
}
|
||||
|
||||
impl AppState {
|
||||
/// Creates the state and makes sure the schema exists.
|
||||
pub async fn new(
|
||||
database_url: &str,
|
||||
secret: Vec<u8>,
|
||||
) -> Result<Self, Box<dyn std::error::Error>> {
|
||||
let store = Store::connect(database_url).await?;
|
||||
Ok(Self {
|
||||
inner: Arc::new(Inner {
|
||||
store,
|
||||
content: Content::builtin(),
|
||||
secret,
|
||||
live: RwLock::new(HashMap::new()),
|
||||
rate: Mutex::new(HashMap::new()),
|
||||
counter: AtomicU64::new(0),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/// Test helper: is this match currently held in memory?
|
||||
pub fn has_live_match(&self, id: &str) -> bool {
|
||||
self.inner
|
||||
.live
|
||||
.read()
|
||||
.map(|live| live.contains_key(id))
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn content_hash(&self) -> String {
|
||||
self.inner.content.hash()
|
||||
}
|
||||
|
||||
fn sign(&self, device_id: &str) -> String {
|
||||
let mut mac = HmacSha256::new_from_slice(&self.inner.secret).expect("hmac key");
|
||||
mac.update(device_id.as_bytes());
|
||||
hex(&mac.finalize().into_bytes())
|
||||
}
|
||||
|
||||
fn check_rate(&self, device_id: &str) -> bool {
|
||||
let mut buckets = self.inner.rate.lock().expect("rate lock");
|
||||
let bucket = buckets.entry(device_id.to_string()).or_insert(Bucket {
|
||||
window: Instant::now(),
|
||||
count: 0,
|
||||
});
|
||||
if bucket.window.elapsed().as_secs() >= 60 {
|
||||
bucket.window = Instant::now();
|
||||
bucket.count = 0;
|
||||
}
|
||||
bucket.count += 1;
|
||||
bucket.count <= RATE_LIMIT_PER_MIN
|
||||
}
|
||||
}
|
||||
|
||||
fn hex(bytes: &[u8]) -> String {
|
||||
let mut out = String::with_capacity(bytes.len() * 2);
|
||||
for b in bytes {
|
||||
out.push_str(&format!("{b:02x}"));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Authenticated device.
|
||||
pub struct Auth {
|
||||
pub device_id: String,
|
||||
}
|
||||
|
||||
impl FromRequestParts<AppState> for Auth {
|
||||
type Rejection = ApiError;
|
||||
|
||||
async fn from_request_parts(
|
||||
parts: &mut Parts,
|
||||
state: &AppState,
|
||||
) -> Result<Self, Self::Rejection> {
|
||||
let header = parts
|
||||
.headers
|
||||
.get(axum::http::header::AUTHORIZATION)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.ok_or_else(|| {
|
||||
ApiError::new(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"unauthorized",
|
||||
"missing bearer token",
|
||||
)
|
||||
})?;
|
||||
let token = header.strip_prefix("Bearer ").ok_or_else(|| {
|
||||
ApiError::new(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"unauthorized",
|
||||
"expected Bearer token",
|
||||
)
|
||||
})?;
|
||||
let (device_id, signature) = token.rsplit_once('.').ok_or_else(|| {
|
||||
ApiError::new(StatusCode::UNAUTHORIZED, "unauthorized", "malformed token")
|
||||
})?;
|
||||
if state.sign(device_id) != signature {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::UNAUTHORIZED,
|
||||
"unauthorized",
|
||||
"invalid token signature",
|
||||
));
|
||||
}
|
||||
if !state.check_rate(device_id) {
|
||||
return Err(ApiError::new(
|
||||
StatusCode::TOO_MANY_REQUESTS,
|
||||
"rate_limited",
|
||||
"too many requests",
|
||||
));
|
||||
}
|
||||
Ok(Auth {
|
||||
device_id: device_id.to_string(),
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// JSON error payload: `{"error":{"code":..,"message":..}}`.
|
||||
#[derive(Debug)]
|
||||
pub struct ApiError {
|
||||
status: StatusCode,
|
||||
code: &'static str,
|
||||
message: String,
|
||||
}
|
||||
|
||||
impl ApiError {
|
||||
fn new(status: StatusCode, code: &'static str, message: impl Into<String>) -> Self {
|
||||
Self {
|
||||
status,
|
||||
code,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn bad_request(code: &'static str, message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::BAD_REQUEST, code, message)
|
||||
}
|
||||
|
||||
fn conflict(code: &'static str, message: impl Into<String>) -> Self {
|
||||
Self::new(StatusCode::CONFLICT, code, message)
|
||||
}
|
||||
|
||||
fn not_found(code: &'static str) -> Self {
|
||||
Self::new(StatusCode::NOT_FOUND, code, "not found")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ErrorBody<'a> {
|
||||
error: ErrorDetail<'a>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ErrorDetail<'a> {
|
||||
code: &'a str,
|
||||
message: &'a str,
|
||||
}
|
||||
|
||||
impl IntoResponse for ApiError {
|
||||
fn into_response(self) -> Response {
|
||||
let body = ErrorBody {
|
||||
error: ErrorDetail {
|
||||
code: self.code,
|
||||
message: &self.message,
|
||||
},
|
||||
};
|
||||
(self.status, Json(body)).into_response()
|
||||
}
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ handlers
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct HealthBody {
|
||||
status: &'static str,
|
||||
sim_version: &'static str,
|
||||
content_hash: String,
|
||||
}
|
||||
|
||||
async fn health(State(state): State<AppState>) -> Json<HealthBody> {
|
||||
Json(HealthBody {
|
||||
status: "ok",
|
||||
sim_version: sim::SIM_VERSION,
|
||||
content_hash: state.content_hash(),
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_content(
|
||||
State(state): State<AppState>,
|
||||
Path(version): Path<String>,
|
||||
) -> Result<Json<Content>, ApiError> {
|
||||
if version != state.inner.content.version {
|
||||
return Err(ApiError::not_found("content_not_found"));
|
||||
}
|
||||
Ok(Json(state.inner.content.clone()))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct AuthRequest {
|
||||
device_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct AuthResponse {
|
||||
token: String,
|
||||
expires_in_s: u64,
|
||||
}
|
||||
|
||||
async fn auth_device(
|
||||
State(state): State<AppState>,
|
||||
Json(body): Json<AuthRequest>,
|
||||
) -> Result<Json<AuthResponse>, ApiError> {
|
||||
if body.device_id.len() < 4 || body.device_id.len() > 128 {
|
||||
return Err(ApiError::bad_request(
|
||||
"bad_device_id",
|
||||
"device_id must be 4..128 chars",
|
||||
));
|
||||
}
|
||||
let signature = state.sign(&body.device_id);
|
||||
Ok(Json(AuthResponse {
|
||||
token: format!("{}.{}", body.device_id, signature),
|
||||
expires_in_s: 30 * 24 * 3600,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct CreateMatchRequest {
|
||||
mode: String,
|
||||
content_hash: String,
|
||||
sim_version: String,
|
||||
players: Vec<sim::replay::PlayerLoadout>,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct CreateMatchResponse {
|
||||
match_id: String,
|
||||
seed: u64,
|
||||
turn: u32,
|
||||
state_hash: u64,
|
||||
}
|
||||
|
||||
async fn create_match(
|
||||
State(state): State<AppState>,
|
||||
_auth: Auth,
|
||||
Json(body): Json<CreateMatchRequest>,
|
||||
) -> Result<(StatusCode, Json<CreateMatchResponse>), ApiError> {
|
||||
if body.content_hash != state.content_hash() {
|
||||
return Err(ApiError::conflict(
|
||||
"content_mismatch",
|
||||
format!("server serves {}", state.content_hash()),
|
||||
));
|
||||
}
|
||||
if body.sim_version != sim::SIM_VERSION {
|
||||
return Err(ApiError::conflict(
|
||||
"sim_version_mismatch",
|
||||
"server runs a different sim",
|
||||
));
|
||||
}
|
||||
if body.players.len() != 2 {
|
||||
return Err(ApiError::bad_request(
|
||||
"bad_players",
|
||||
"exactly two players required",
|
||||
));
|
||||
}
|
||||
|
||||
let seed = next_seed(&state);
|
||||
let specs = [
|
||||
TankSpec {
|
||||
x: 220,
|
||||
loadout: body.players[0].loadout,
|
||||
},
|
||||
TankSpec {
|
||||
x: WORLD_W - 220,
|
||||
loadout: body.players[1].loadout,
|
||||
},
|
||||
];
|
||||
let sim = Sim::new(seed, specs, state.inner.content.clone());
|
||||
let state_hash = sim.state_hash();
|
||||
let id = format!("m_{seed:016x}");
|
||||
|
||||
state
|
||||
.inner
|
||||
.store
|
||||
.insert_match(&MatchRow {
|
||||
id: id.clone(),
|
||||
device_id: _auth.device_id.clone(),
|
||||
mode: body.mode,
|
||||
seed: seed as i64,
|
||||
content_hash: state.content_hash(),
|
||||
sim_version: sim::SIM_VERSION.to_string(),
|
||||
turn: 1,
|
||||
state_hash,
|
||||
})
|
||||
.await
|
||||
.map_err(|e| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal", e.to_string()))?;
|
||||
|
||||
state
|
||||
.inner
|
||||
.live
|
||||
.write()
|
||||
.expect("live lock")
|
||||
.insert(id.clone(), sim);
|
||||
|
||||
Ok((
|
||||
StatusCode::CREATED,
|
||||
Json(CreateMatchResponse {
|
||||
match_id: id,
|
||||
seed,
|
||||
turn: 1,
|
||||
state_hash,
|
||||
}),
|
||||
))
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct MatchStateBody {
|
||||
match_id: String,
|
||||
turn: u32,
|
||||
current: u8,
|
||||
phase: u8,
|
||||
hp: [i32; 2],
|
||||
state_hash: u64,
|
||||
}
|
||||
|
||||
async fn get_match(
|
||||
State(state): State<AppState>,
|
||||
_auth: Auth,
|
||||
Path(id): Path<String>,
|
||||
) -> Result<Json<MatchStateBody>, ApiError> {
|
||||
// Scope the lock so the guard is never held across an await point.
|
||||
let live_body = {
|
||||
let live = state.inner.live.read().expect("live lock");
|
||||
live.get(&id).map(|sim| MatchStateBody {
|
||||
match_id: id.clone(),
|
||||
turn: sim.turn as u32,
|
||||
current: sim.current,
|
||||
phase: match sim.phase {
|
||||
Phase::Aiming => 0,
|
||||
Phase::Flying => 1,
|
||||
Phase::Finished => 2,
|
||||
},
|
||||
hp: [sim.tanks[0].hp, sim.tanks[1].hp],
|
||||
state_hash: sim.state_hash(),
|
||||
})
|
||||
};
|
||||
if let Some(body) = live_body {
|
||||
return Ok(Json(body));
|
||||
}
|
||||
|
||||
let row = state
|
||||
.inner
|
||||
.store
|
||||
.match_row(&id)
|
||||
.await
|
||||
.map_err(|e| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal", e.to_string()))?
|
||||
.ok_or_else(|| ApiError::not_found("match_not_found"))?;
|
||||
|
||||
Ok(Json(MatchStateBody {
|
||||
match_id: row.id,
|
||||
turn: row.turn as u32,
|
||||
current: 0,
|
||||
phase: 0,
|
||||
hp: [0, 0],
|
||||
state_hash: row.state_hash,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct TurnRequest {
|
||||
expect_hash: u64,
|
||||
command: sim::replay::CommandDto,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct TurnResponse {
|
||||
accepted: bool,
|
||||
turn: u32,
|
||||
current: u8,
|
||||
state_hash: u64,
|
||||
impacts: u32,
|
||||
}
|
||||
|
||||
async fn submit_turn(
|
||||
State(state): State<AppState>,
|
||||
_auth: Auth,
|
||||
Path(id): Path<String>,
|
||||
Json(body): Json<TurnRequest>,
|
||||
) -> Result<Json<TurnResponse>, ApiError> {
|
||||
let (turn, current, state_hash, impacts) = {
|
||||
let mut live = state.inner.live.write().expect("live lock");
|
||||
let sim = live
|
||||
.get_mut(&id)
|
||||
.ok_or_else(|| ApiError::not_found("match_not_found"))?;
|
||||
|
||||
if sim.phase != Phase::Aiming {
|
||||
return Err(ApiError::conflict("state_conflict", "no turn is open"));
|
||||
}
|
||||
if sim.state_hash() != body.expect_hash {
|
||||
return Err(ApiError::conflict(
|
||||
"state_conflict",
|
||||
"expect_hash does not match",
|
||||
));
|
||||
}
|
||||
sim.submit(body.command.to_command())
|
||||
.map_err(|e| ApiError::bad_request("illegal_command", format!("{e:?}")))?;
|
||||
|
||||
let mut impacts = 0;
|
||||
let mut guard = 0;
|
||||
while sim.phase != Phase::Aiming
|
||||
&& sim.phase != Phase::Finished
|
||||
&& guard < MAX_RESOLVE_TICKS
|
||||
{
|
||||
for event in sim.tick() {
|
||||
if matches!(event, Event::Impact { .. }) {
|
||||
impacts += 1;
|
||||
}
|
||||
}
|
||||
guard += 1;
|
||||
}
|
||||
(sim.turn as u32, sim.current, sim.state_hash(), impacts)
|
||||
};
|
||||
|
||||
state
|
||||
.inner
|
||||
.store
|
||||
.update_match_state(&id, i64::from(turn), state_hash)
|
||||
.await
|
||||
.map_err(|e| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal", e.to_string()))?;
|
||||
|
||||
Ok(Json(TurnResponse {
|
||||
accepted: true,
|
||||
turn,
|
||||
current,
|
||||
state_hash,
|
||||
impacts,
|
||||
}))
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct ValidateRequest {
|
||||
match_id: Option<String>,
|
||||
replay: ReplayV1,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Rewards {
|
||||
scrap: u32,
|
||||
xp: u32,
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct ValidateResponse {
|
||||
valid: bool,
|
||||
final_hash: u64,
|
||||
rewards: Rewards,
|
||||
}
|
||||
|
||||
async fn validate_replay(
|
||||
State(state): State<AppState>,
|
||||
auth: Auth,
|
||||
Json(body): Json<ValidateRequest>,
|
||||
) -> Result<Json<ValidateResponse>, ApiError> {
|
||||
let store = state.inner.store.clone();
|
||||
let match_id = body.match_id.clone();
|
||||
|
||||
match body.replay.verify() {
|
||||
Ok(hash) if hash == body.replay.final_hash => {
|
||||
store
|
||||
.insert_replay(match_id.as_deref(), &auth.device_id, hash, true)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal", e.to_string())
|
||||
})?;
|
||||
store
|
||||
.add_trophies("season-1", &auth.device_id, 10)
|
||||
.await
|
||||
.map_err(|e| {
|
||||
ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal", e.to_string())
|
||||
})?;
|
||||
Ok(Json(ValidateResponse {
|
||||
valid: true,
|
||||
final_hash: hash,
|
||||
rewards: Rewards { scrap: 120, xp: 35 },
|
||||
}))
|
||||
}
|
||||
Ok(hash) => {
|
||||
store
|
||||
.insert_replay(match_id.as_deref(), &auth.device_id, hash, false)
|
||||
.await
|
||||
.ok();
|
||||
Err(ApiError::conflict(
|
||||
"hash_mismatch",
|
||||
format!(
|
||||
"recomputed {hash}, replay claims {}",
|
||||
body.replay.final_hash
|
||||
),
|
||||
))
|
||||
}
|
||||
Err(message) => {
|
||||
store
|
||||
.insert_replay(match_id.as_deref(), &auth.device_id, 0, false)
|
||||
.await
|
||||
.ok();
|
||||
if message.contains("sim_version") {
|
||||
Err(ApiError::conflict("sim_version_mismatch", message))
|
||||
} else if message.contains("content") {
|
||||
Err(ApiError::conflict("content_mismatch", message))
|
||||
} else {
|
||||
Err(ApiError::new(
|
||||
StatusCode::UNPROCESSABLE_ENTITY,
|
||||
"illegal_command",
|
||||
message,
|
||||
))
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct LeaderboardEntry {
|
||||
rank: usize,
|
||||
device_id: String,
|
||||
points: i64,
|
||||
}
|
||||
|
||||
async fn leaderboard(
|
||||
State(state): State<AppState>,
|
||||
_auth: Auth,
|
||||
Path(season): Path<String>,
|
||||
) -> Result<Json<Vec<LeaderboardEntry>>, ApiError> {
|
||||
let rows = state
|
||||
.inner
|
||||
.store
|
||||
.leaderboard(&season, 100)
|
||||
.await
|
||||
.map_err(|e| ApiError::new(StatusCode::INTERNAL_SERVER_ERROR, "internal", e.to_string()))?;
|
||||
Ok(Json(
|
||||
rows.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, (device_id, points))| LeaderboardEntry {
|
||||
rank: i + 1,
|
||||
device_id,
|
||||
points,
|
||||
})
|
||||
.collect(),
|
||||
))
|
||||
}
|
||||
|
||||
fn next_seed(state: &AppState) -> u64 {
|
||||
let n = state.inner.counter.fetch_add(1, Ordering::Relaxed);
|
||||
let nanos = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos() as u64)
|
||||
.unwrap_or(1);
|
||||
nanos ^ n.wrapping_mul(0x9E37_79B9_7F4A_7C15)
|
||||
}
|
||||
|
||||
/// Builds the HTTP router.
|
||||
pub fn router(state: AppState) -> Router {
|
||||
Router::new()
|
||||
.route("/health", get(health))
|
||||
.route("/v1/health", get(health))
|
||||
.route("/v1/content/{version}", get(get_content))
|
||||
.route("/v1/auth/device", post(auth_device))
|
||||
.route("/v1/matches", post(create_match))
|
||||
.route("/v1/matches/{id}", get(get_match))
|
||||
.route("/v1/matches/{id}/turn", post(submit_turn))
|
||||
.route("/v1/matches/{id}/validate", post(validate_replay))
|
||||
.route("/v1/leaderboard/{season}", get(leaderboard))
|
||||
.with_state(state)
|
||||
}
|
||||
|
||||
/// Reports which simulation version this server validates against.
|
||||
pub fn validated_sim_version() -> &'static str {
|
||||
sim::SIM_VERSION
|
||||
}
|
||||
|
||||
/// Convenience for tests: a working state on an in-memory database.
|
||||
pub async fn test_state() -> AppState {
|
||||
AppState::new("sqlite::memory:", b"test-secret".to_vec())
|
||||
.await
|
||||
.expect("in-memory state")
|
||||
}
|
||||
|
||||
/// Signs a device id the way the server does (used by tests and the CLI).
|
||||
pub fn issue_token(state: &AppState, device_id: &str) -> String {
|
||||
format!("{}.{}", device_id, state.sign(device_id))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn health_reports_sim_and_content() {
|
||||
let state = test_state().await;
|
||||
assert_eq!(state.content_hash(), Content::builtin().hash());
|
||||
assert_eq!(validated_sim_version(), sim::SIM_VERSION);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reports_sim_version() {
|
||||
assert_eq!(super::validated_sim_version(), sim::SIM_VERSION);
|
||||
fn hex_encoding() {
|
||||
assert_eq!(hex(&[0x00, 0x0f, 0xff]), "000fff");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
//! Server entry point.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use server::{router, AppState};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let database_url =
|
||||
std::env::var("DATABASE_URL").unwrap_or_else(|_| "sqlite://iron-arc.db".to_string());
|
||||
let secret = std::env::var("TOKEN_SECRET").unwrap_or_else(|_| "dev-only-change-me".to_string());
|
||||
let addr: SocketAddr = std::env::var("BIND")
|
||||
.unwrap_or_else(|_| "0.0.0.0:8080".to_string())
|
||||
.parse()?;
|
||||
|
||||
let state = AppState::new(&database_url, secret.into_bytes()).await?;
|
||||
let app = router(state);
|
||||
|
||||
let listener = tokio::net::TcpListener::bind(addr).await?;
|
||||
println!(
|
||||
"iron-arc referee listening on http://{addr} (sim {})",
|
||||
server::validated_sim_version()
|
||||
);
|
||||
axum::serve(listener, app).await?;
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
//! Persistence layer (SQLite via sqlx).
|
||||
//!
|
||||
//! Live simulations stay in memory for the hot path; durable state is the
|
||||
//! command log, the state hash and the replay verdicts.
|
||||
|
||||
use sqlx::sqlite::{SqliteConnectOptions, SqlitePoolOptions};
|
||||
use sqlx::{Row, SqlitePool};
|
||||
use std::str::FromStr;
|
||||
|
||||
/// Database handle.
|
||||
#[derive(Clone)]
|
||||
pub struct Store {
|
||||
pool: SqlitePool,
|
||||
}
|
||||
|
||||
/// A match row.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct MatchRow {
|
||||
pub id: String,
|
||||
pub device_id: String,
|
||||
pub mode: String,
|
||||
pub seed: i64,
|
||||
pub content_hash: String,
|
||||
pub sim_version: String,
|
||||
pub turn: i64,
|
||||
pub state_hash: u64,
|
||||
}
|
||||
|
||||
impl Store {
|
||||
/// Connects (creating the file if needed) and applies the schema.
|
||||
pub async fn connect(url: &str) -> Result<Self, sqlx::Error> {
|
||||
let options = SqliteConnectOptions::from_str(url)?.create_if_missing(true);
|
||||
let pool = SqlitePoolOptions::new()
|
||||
.max_connections(5)
|
||||
.connect_with(options)
|
||||
.await?;
|
||||
let store = Self { pool };
|
||||
store.migrate().await?;
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
async fn migrate(&self) -> Result<(), sqlx::Error> {
|
||||
sqlx::query(
|
||||
"CREATE TABLE IF NOT EXISTS matches (\n id TEXT PRIMARY KEY,\n device_id TEXT NOT NULL,\n mode TEXT NOT NULL,\n seed INTEGER NOT NULL,\n content_hash TEXT NOT NULL,\n sim_version TEXT NOT NULL,\n turn INTEGER NOT NULL,\n state_hash INTEGER NOT NULL,\n created_at INTEGER NOT NULL\n )",
|
||||
)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"CREATE TABLE IF NOT EXISTS replays (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n match_id TEXT,\n device_id TEXT NOT NULL,\n final_hash INTEGER NOT NULL,\n valid INTEGER NOT NULL,\n created_at INTEGER NOT NULL\n )",
|
||||
)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
sqlx::query(
|
||||
"CREATE TABLE IF NOT EXISTS trophies (\n season TEXT NOT NULL,\n device_id TEXT NOT NULL,\n points INTEGER NOT NULL DEFAULT 0,\n PRIMARY KEY (season, device_id)\n )",
|
||||
)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Inserts a new match.
|
||||
pub async fn insert_match(&self, row: &MatchRow) -> Result<(), sqlx::Error> {
|
||||
sqlx::query(
|
||||
"INSERT INTO matches (id, device_id, mode, seed, content_hash, sim_version, turn, state_hash, created_at)\n VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)",
|
||||
)
|
||||
.bind(&row.id)
|
||||
.bind(&row.device_id)
|
||||
.bind(&row.mode)
|
||||
.bind(row.seed)
|
||||
.bind(&row.content_hash)
|
||||
.bind(&row.sim_version)
|
||||
.bind(row.turn)
|
||||
.bind(row.state_hash as i64)
|
||||
.bind(now_secs())
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Loads a match row.
|
||||
pub async fn match_row(&self, id: &str) -> Result<Option<MatchRow>, sqlx::Error> {
|
||||
let row = sqlx::query(
|
||||
"SELECT id, device_id, mode, seed, content_hash, sim_version, turn, state_hash FROM matches WHERE id = ?1",
|
||||
)
|
||||
.bind(id)
|
||||
.fetch_optional(&self.pool)
|
||||
.await?;
|
||||
Ok(row.map(|r| MatchRow {
|
||||
id: r.get("id"),
|
||||
device_id: r.get("device_id"),
|
||||
mode: r.get("mode"),
|
||||
seed: r.get("seed"),
|
||||
content_hash: r.get("content_hash"),
|
||||
sim_version: r.get("sim_version"),
|
||||
turn: r.get("turn"),
|
||||
state_hash: r.get::<i64, _>("state_hash") as u64,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Updates the authoritative state hash after a turn.
|
||||
pub async fn update_match_state(
|
||||
&self,
|
||||
id: &str,
|
||||
turn: i64,
|
||||
state_hash: u64,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query("UPDATE matches SET turn = ?2, state_hash = ?3 WHERE id = ?1")
|
||||
.bind(id)
|
||||
.bind(turn)
|
||||
.bind(state_hash as i64)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Records a replay verdict.
|
||||
pub async fn insert_replay(
|
||||
&self,
|
||||
match_id: Option<&str>,
|
||||
device_id: &str,
|
||||
final_hash: u64,
|
||||
valid: bool,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query(
|
||||
"INSERT INTO replays (match_id, device_id, final_hash, valid, created_at) VALUES (?1, ?2, ?3, ?4, ?5)",
|
||||
)
|
||||
.bind(match_id)
|
||||
.bind(device_id)
|
||||
.bind(final_hash as i64)
|
||||
.bind(i64::from(valid))
|
||||
.bind(now_secs())
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Adds trophies for a validated win.
|
||||
pub async fn add_trophies(
|
||||
&self,
|
||||
season: &str,
|
||||
device_id: &str,
|
||||
points: i64,
|
||||
) -> Result<(), sqlx::Error> {
|
||||
sqlx::query(
|
||||
"INSERT INTO trophies (season, device_id, points) VALUES (?1, ?2, ?3)\n ON CONFLICT(season, device_id) DO UPDATE SET points = points + excluded.points",
|
||||
)
|
||||
.bind(season)
|
||||
.bind(device_id)
|
||||
.bind(points)
|
||||
.execute(&self.pool)
|
||||
.await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Top entries of a season.
|
||||
pub async fn leaderboard(
|
||||
&self,
|
||||
season: &str,
|
||||
limit: i64,
|
||||
) -> Result<Vec<(String, i64)>, sqlx::Error> {
|
||||
let rows = sqlx::query(
|
||||
"SELECT device_id, points FROM trophies WHERE season = ?1 ORDER BY points DESC LIMIT ?2",
|
||||
)
|
||||
.bind(season)
|
||||
.bind(limit)
|
||||
.fetch_all(&self.pool)
|
||||
.await?;
|
||||
Ok(rows
|
||||
.into_iter()
|
||||
.map(|r| (r.get::<String, _>("device_id"), r.get::<i64, _>("points")))
|
||||
.collect())
|
||||
}
|
||||
}
|
||||
|
||||
fn now_secs() -> i64 {
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_secs() as i64)
|
||||
.unwrap_or(0)
|
||||
}
|
||||
@@ -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