Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232use std::{sync::Arc, time::Duration};
use axum::Router;use axum::body::Body;use axum::extract::{DefaultBodyLimit, Path, Request, State};use axum::http::StatusCode;use axum::middleware::{self, Next};use axum::response::{IntoResponse, Json, Response};use axum::routing::{delete, get, post};use serde_json::Value;use tokio::time::timeout;use uuid::Uuid;
pub mod jwt;pub mod model;pub mod mojang;pub mod rate_limit;
use crate::AppState;use crate::db;use crate::error::AppError;use crate::identifier::{ENTITLEMENTS_KEY, Identifier};use jwt::AuthUser;use model::{AuthRequest, ChallengeRequest, ChallengeResponse, Entitlements, SessionResponse};use mojang::{CHALLENGE_TTL_SECS, MojangAuth};
pub fn setup_routes(state: Arc<AppState>) -> Router { let admin_routes = Router::new() .route("/entitlements/{uuid}", post(post_entitlements_admin)) .route("/data/{uuid}", delete(delete_data)) .route_layer(middleware::from_fn_with_state(state.clone(), admin_layer));
let auth_routes = Router::new() .route("/api/auth/mojang/challenge", post(post_challenge)) .route("/api/auth/mojang", post(post_auth)) .route_layer(middleware::from_fn_with_state( state.auth_limiter.clone(), rate_limit::layer, ));
let data_routes = Router::new() .route( "/api/v0/data/{uuid}/{namespace}/{path}", get(get_data).post(post_data), ) .route_layer(middleware::from_fn_with_state( state.data_limiter.clone(), rate_limit::layer, ));
Router::new() .merge(auth_routes) .merge(data_routes) .nest("/api/admin", admin_routes) .layer(middleware::from_fn(timeout_middleware)) .layer(DefaultBodyLimit::max(1024)) .with_state(state)}
async fn get_data( Path((uuid, namespace, path)): Path<(Uuid, String, String)>, State(state): State<Arc<AppState>>,) -> Result<Json<Value>, AppError> { let id = Identifier::new(&namespace, &path)?;
let value = db::get_value(&state.db_pool, &uuid, &id) .await? .ok_or(AppError::NotFound)?;
Ok(Json(value))}
async fn post_challenge( State(state): State<Arc<AppState>>, Json(payload): Json<ChallengeRequest>,) -> Result<Json<ChallengeResponse>, AppError> { if payload.id.is_empty() { return Err(AppError::BadRequest("id is required".to_string())); }
let challenge = MojangAuth::generate_challenge(); state.mojang.store_challenge(&payload.id, challenge.clone());
Ok(Json(ChallengeResponse { token: challenge, expires_in: CHALLENGE_TTL_SECS, }))}
async fn post_auth( State(state): State<Arc<AppState>>, Json(payload): Json<AuthRequest>,) -> Result<Json<SessionResponse>, AppError> { if payload.id.is_empty() || payload.username.is_empty() || payload.token.is_empty() { return Err(AppError::BadRequest( "id, username and token are required".to_string(), )); }
let stored = state .mojang .consume_challenge(&payload.id) .ok_or_else(|| AppError::Unauthorized("challenge not found or expired".to_string()))?;
if stored != payload.token { return Err(AppError::Unauthorized( "challenge token mismatch".to_string(), )); }
let profile = state .mojang .verify_with_mojang(&payload.username, &stored) .await? .ok_or_else(|| AppError::Unauthorized("Mojang verification failed".to_string()))?;
let mojang_id = profile.id.replace('-', ""); let claimed_id = payload.id.replace('-', ""); if mojang_id != claimed_id { return Err(AppError::Unauthorized("UUID mismatch".to_string())); }
let user_id = Uuid::try_parse(&profile.id)?;
let session = jwt::mint(&state.config.jwt_secret, user_id)?;
Ok(Json(SessionResponse { user_id: session.user_id, token: session.token, expires_at: session.expires_at, }))}
async fn post_data( Path((uuid, namespace, path)): Path<(Uuid, String, String)>, State(state): State<Arc<AppState>>, auth: AuthUser, Json(body): Json<Value>,) -> Result<impl IntoResponse, AppError> { let data_id = Identifier::new(&namespace, &path)?;
if data_id == ENTITLEMENTS_KEY { return Err(AppError::Unauthorized( "entitlements are managed server-side only".to_string(), )); }
if auth.user_id != uuid { return Err(AppError::Unauthorized( "cannot write data for another player".to_string(), )); }
let entitlements = db::fetch_entitlements(&state.db_pool, &uuid).await?; if !entitlements.contains(&data_id) { return Err(AppError::Unauthorized(format!( "missing entitlement: {data_id}" ))); }
db::upsert_value(&state.db_pool, &uuid, &data_id, &body).await?;
Ok(StatusCode::NO_CONTENT)}
async fn post_entitlements_admin( Path(uuid): Path<Uuid>, State(state): State<Arc<AppState>>, Json(payload): Json<Entitlements>,) -> Result<(), AppError> { payload.validate()?; let json = serde_json::json!(&payload);
db::upsert_value(&state.db_pool, &uuid, &ENTITLEMENTS_KEY, &json).await?;
Ok(())}
async fn delete_data( Path(uuid): Path<Uuid>, State(state): State<Arc<AppState>>,) -> Result<(), AppError> { db::delete_all_for_player(&state.db_pool, &uuid).await?;
Ok(())}
async fn admin_layer( State(state): State<Arc<AppState>>, req: Request<axum::body::Body>, next: Next,) -> Result<Response, AppError> { let provided = req .headers() .get("X-Admin-Secret") .and_then(|v| v.to_str().ok());
if !provided.is_some_and(|p| constant_time_eq(p, &state.config.admin_secret)) { return Err(AppError::Unauthorized("not authorized".to_string())); }
Ok(next.run(req).await)}
fn constant_time_eq(provided: &str, expected: &str) -> bool { let (a, b) = (provided.as_bytes(), expected.as_bytes()); let mut diff = a.len() ^ b.len(); for (x, y) in a.iter().zip(b) { diff |= usize::from(x ^ y); } diff == 0}
async fn timeout_middleware(req: Request<Body>, next: Next) -> Result<Response, AppError> { Ok(timeout(Duration::from_secs(30), next.run(req)).await?)}
#[cfg(test)]mod tests { use super::*;
#[test] fn constant_time_eq_matches_only_equal_strings() { assert!(constant_time_eq("secret", "secret")); assert!(!constant_time_eq("secret", "secreT")); assert!(!constant_time_eq("secret", "secrett")); assert!(!constant_time_eq("secret", "secre")); assert!(!constant_time_eq("", "x")); assert!(constant_time_eq("", "")); }}