manabrew-server 0.51.0

Matchmaking and lobby relay server for manabrew multiplayer
Documentation
use std::cmp::Reverse;
use std::collections::HashMap;
use std::net::SocketAddr;
use std::sync::Arc;
use std::time::{Duration, Instant};

use axum::extract::{ConnectInfo, DefaultBodyLimit, Query, Request, State};
use axum::http::header::{ACCESS_CONTROL_ALLOW_ORIGIN, AUTHORIZATION};
use axum::http::{HeaderMap, HeaderValue, StatusCode};
use axum::middleware::{self, Next};
use axum::response::{Json, Response};
use axum::routing::get;
use axum::Router;
use chrono::{SecondsFormat, Utc};
use sha2::{Digest, Sha256};

use crate::connection::forwarded_client_ip;
use crate::protocol::directory::{
    DirectoryClient, Listing, ListingAnnouncement, ListingClosed, ListingSaved, ListingStatus,
    Listings, ListingsQuery, PublishedListing, PublishedListingQuery, ROOMS_PATH,
};
use crate::state::ServerState;

const BEARER_PREFIX: &str = "Bearer ";
const LISTING_TTL: Duration = Duration::from_secs(300);
const MAX_LISTINGS: usize = 100;
const MAX_LISTINGS_PER_IP: usize = 3;
const MAX_BODY_BYTES: usize = 4096;

struct Entry {
    listing: Listing,
    listing_token_hash: [u8; 32],
    publisher_ip: String,
    expires_at: Instant,
}

#[derive(Default)]
pub struct Directory {
    entries: HashMap<String, Entry>,
}

impl Directory {
    fn remove_expired(&mut self) {
        let now = Instant::now();
        self.entries.retain(|_, entry| entry.expires_at > now);
    }

    fn published(&mut self, client: DirectoryClient) -> Vec<Listing> {
        self.remove_expired();
        let mut entries: Vec<&Entry> = self
            .entries
            .values()
            .filter(|entry| entry.listing.client == client)
            .collect();
        entries.sort_by_key(|entry| Reverse(entry.expires_at));
        entries.iter().map(|entry| entry.listing.clone()).collect()
    }

    fn owned_entry(
        &mut self,
        id: &str,
        listing_token_hash: [u8; 32],
    ) -> Result<&mut Entry, StatusCode> {
        self.remove_expired();
        self.entries
            .get_mut(id)
            .filter(|entry| entry.listing_token_hash == listing_token_hash)
            .ok_or(StatusCode::NOT_FOUND)
    }
}

pub fn router(state: Arc<ServerState>) -> Router {
    Router::new()
        .route(
            ROOMS_PATH,
            get(list_rooms)
                .post(publish_room)
                .patch(update_room)
                .put(update_room)
                .delete(close_room),
        )
        .layer(DefaultBodyLimit::max(MAX_BODY_BYTES))
        .layer(middleware::from_fn(allow_any_origin))
        .with_state(state)
}

async fn allow_any_origin(request: Request, next: Next) -> Response {
    let mut response = next.run(request).await;
    response
        .headers_mut()
        .insert(ACCESS_CONTROL_ALLOW_ORIGIN, HeaderValue::from_static("*"));
    response
}

fn timestamp_now() -> String {
    Utc::now().to_rfc3339_opts(SecondsFormat::Millis, true)
}

async fn list_rooms(
    State(state): State<Arc<ServerState>>,
    Query(query): Query<ListingsQuery>,
) -> Json<Listings> {
    let mut rooms = state.directory.lock().unwrap().published(query.client);
    if query.client == DirectoryClient::Manabrew {
        rooms.extend(
            state
                .rooms
                .iter()
                .filter(|room| room.parent_limited_room.is_none())
                .filter_map(|room| Listing::from_room(&room.to_room_info(), timestamp_now())),
        );
    }
    Json(Listings { rooms })
}

async fn publish_room(
    State(state): State<Arc<ServerState>>,
    ConnectInfo(peer): ConnectInfo<SocketAddr>,
    headers: HeaderMap,
    Json(announcement): Json<ListingAnnouncement>,
) -> Result<(StatusCode, Json<PublishedListing>), StatusCode> {
    if !announcement.public_address_accepted || !announcement.is_valid() {
        return Err(StatusCode::BAD_REQUEST);
    }
    let publisher_ip = forwarded_client_ip(&headers).unwrap_or_else(|| peer.ip().to_string());
    let id = uuid::Uuid::new_v4().to_string();
    let listing_token = format!(
        "{}{}",
        uuid::Uuid::new_v4().simple(),
        uuid::Uuid::new_v4().simple()
    );

    let mut directory = state.directory.lock().unwrap();
    directory.remove_expired();
    let listings_from_ip = directory
        .entries
        .values()
        .filter(|entry| entry.publisher_ip == publisher_ip)
        .count();
    if directory.entries.len() >= MAX_LISTINGS || listings_from_ip >= MAX_LISTINGS_PER_IP {
        return Err(StatusCode::TOO_MANY_REQUESTS);
    }
    directory.entries.insert(
        id.clone(),
        Entry {
            listing: announcement.into_listing(id.clone(), ListingStatus::Open, timestamp_now()),
            listing_token_hash: Sha256::digest(listing_token.as_bytes()).into(),
            publisher_ip,
            expires_at: Instant::now() + LISTING_TTL,
        },
    );
    Ok((
        StatusCode::CREATED,
        Json(PublishedListing {
            id,
            token: listing_token,
        }),
    ))
}

async fn update_room(
    State(state): State<Arc<ServerState>>,
    Query(query): Query<PublishedListingQuery>,
    headers: HeaderMap,
    Json(announcement): Json<ListingAnnouncement>,
) -> Result<Json<ListingSaved>, StatusCode> {
    let listing_token_hash = presented_listing_token_hash(&headers)?;
    if !announcement.is_valid() {
        return Err(StatusCode::BAD_REQUEST);
    }
    let status = announcement.status.ok_or(StatusCode::BAD_REQUEST)?;

    let mut directory = state.directory.lock().unwrap();
    let entry = directory.owned_entry(&query.id, listing_token_hash)?;
    entry.listing = announcement.into_listing(query.id, status, timestamp_now());
    entry.expires_at = Instant::now() + LISTING_TTL;
    Ok(Json(ListingSaved { saved: true }))
}

async fn close_room(
    State(state): State<Arc<ServerState>>,
    Query(query): Query<PublishedListingQuery>,
    headers: HeaderMap,
) -> Result<Json<ListingClosed>, StatusCode> {
    let listing_token_hash = presented_listing_token_hash(&headers)?;
    let mut directory = state.directory.lock().unwrap();
    directory.owned_entry(&query.id, listing_token_hash)?;
    directory.entries.remove(&query.id);
    Ok(Json(ListingClosed { closed: true }))
}

fn presented_listing_token_hash(headers: &HeaderMap) -> Result<[u8; 32], StatusCode> {
    headers
        .get(AUTHORIZATION)
        .and_then(|value| value.to_str().ok())
        .and_then(|value| value.strip_prefix(BEARER_PREFIX))
        .map(|listing_token| Sha256::digest(listing_token.as_bytes()).into())
        .ok_or(StatusCode::UNAUTHORIZED)
}