From 4a9031b29c3c5a98b2d64ddc98996066a582d928 Mon Sep 17 00:00:00 2001 From: Hadrian Burkhardt Date: Sat, 24 Oct 2026 23:10:43 +0200 Subject: [PATCH] feat(m4): axum replay referee with auth, rate limit and sqlite persistence --- Cargo.lock | 1244 ++++++++++++++++++++++++++- Cargo.toml | 4 +- crates/server/Cargo.toml | 13 +- crates/server/Dockerfile | 17 + crates/server/src/lib.rs | 649 +++++++++++++- crates/server/src/main.rs | 26 + crates/server/src/store.rs | 180 ++++ crates/server/tests/api.rs | 213 +++++ crates/server/tests/load.rs | 42 + docs/ADR/0004-server-persistence.md | 44 + 10 files changed, 2425 insertions(+), 7 deletions(-) create mode 100644 crates/server/Dockerfile create mode 100644 crates/server/src/main.rs create mode 100644 crates/server/src/store.rs create mode 100644 crates/server/tests/api.rs create mode 100644 crates/server/tests/load.rs create mode 100644 docs/ADR/0004-server-persistence.md diff --git a/Cargo.lock b/Cargo.lock index 0b48826..a0b04bb 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -2,6 +2,85 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "atoi" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528" +dependencies = [ + "num-traits", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", + "tracing", +] + [[package]] name = "balance" version = "0.1.0" @@ -11,6 +90,49 @@ dependencies = [ "sim", ] +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + [[package]] name = "content" version = "0.1.0" @@ -19,6 +141,118 @@ dependencies = [ "serde_json", ] +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853" + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", + "subtle", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" +dependencies = [ + "serde", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + [[package]] name = "ffi" version = "0.1.0" @@ -27,18 +261,503 @@ dependencies = [ "sim", ] +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flume" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da0e4dd2a88388a1f4ccc7c9ce104604dab68d9f408dc34cd45823d5a9069095" +dependencies = [ + "futures-core", + "futures-sink", + "spin", +] + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-intrusive" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f" +dependencies = [ + "futures-core", + "lock_api", + "parking_lot", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-core", + "futures-io", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "hashlink" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1" +dependencies = [ + "hashbrown 0.15.5", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "bytes", + "http", + "http-body", + "hyper", + "pin-project-lite", + "tokio", + "tower-service", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + [[package]] name = "itoa" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "cc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + [[package]] name = "memchr" version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mio" +version = "1.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1788edb87fdc09c7e26304471e2f5be8cdefb1b6930d6e3985fc02ff53bf86ee" +dependencies = [ + "libc", + "wasi", + "windows-sys", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + [[package]] name = "proc-macro2" version = "1.0.107" @@ -57,6 +776,27 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags", +] + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + [[package]] name = "serde" version = "1.0.229" @@ -84,7 +824,7 @@ checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" dependencies = [ "proc-macro2", "quote", - "syn", + "syn 3.0.9", ] [[package]] @@ -100,12 +840,71 @@ dependencies = [ "zmij", ] +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + [[package]] name = "server" version = "0.1.0" dependencies = [ + "axum", "content", + "hmac", + "http-body-util", + "serde", + "serde_json", + "sha2", "sim", + "sqlx", + "tokio", + "tower", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", ] [[package]] @@ -117,6 +916,164 @@ dependencies = [ "serde_json", ] +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" +dependencies = [ + "lock_api", +] + +[[package]] +name = "sqlx" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc" +dependencies = [ + "sqlx-core", + "sqlx-macros", + "sqlx-sqlite", +] + +[[package]] +name = "sqlx-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" +dependencies = [ + "base64", + "bytes", + "crc", + "crossbeam-queue", + "either", + "event-listener", + "futures-core", + "futures-intrusive", + "futures-io", + "futures-util", + "hashbrown 0.15.5", + "hashlink", + "indexmap", + "log", + "memchr", + "once_cell", + "percent-encoding", + "serde", + "sha2", + "smallvec", + "thiserror", + "tokio", + "tokio-stream", + "tracing", + "url", +] + +[[package]] +name = "sqlx-macros" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d" +dependencies = [ + "proc-macro2", + "quote", + "sqlx-core", + "sqlx-macros-core", + "syn 2.0.119", +] + +[[package]] +name = "sqlx-macros-core" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b" +dependencies = [ + "dotenvy", + "either", + "heck", + "hex", + "once_cell", + "proc-macro2", + "quote", + "serde", + "serde_json", + "sha2", + "sqlx-core", + "sqlx-sqlite", + "syn 2.0.119", + "tokio", + "url", +] + +[[package]] +name = "sqlx-sqlite" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2d12fe70b2c1b4401038055f90f151b78208de1f9f89a7dbfd41587a10c3eea" +dependencies = [ + "atoi", + "flume", + "futures-channel", + "futures-core", + "futures-executor", + "futures-intrusive", + "futures-util", + "libsqlite3-sys", + "log", + "percent-encoding", + "serde", + "serde_urlencoded", + "sqlx-core", + "thiserror", + "tracing", + "url", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + [[package]] name = "syn" version = "3.0.9" @@ -128,12 +1085,297 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tokio-stream" +version = "0.1.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3d06f0b082ba57c26b79407372e57cf2a1e28124f78e9479fe80322cf53420b" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + [[package]] name = "zmij" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 8319e3c..9d1f84d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,8 +16,8 @@ authors = ["Hadrian Burkhardt "] repository = "https://example.invalid/iron-arc" [workspace.dependencies] -serde = { version = "1", features = ["derive"] } -serde_json = "1" +serde = { version = "1", default-features = false, features = ["derive", "alloc"] } +serde_json = { version = "1", default-features = false, features = ["alloc"] } sim = { path = "crates/sim" } content = { path = "crates/content" } diff --git a/crates/server/Cargo.toml b/crates/server/Cargo.toml index 72816e4..94e1708 100644 --- a/crates/server/Cargo.toml +++ b/crates/server/Cargo.toml @@ -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" diff --git a/crates/server/Dockerfile b/crates/server/Dockerfile new file mode 100644 index 0000000..fe61af8 --- /dev/null +++ b/crates/server/Dockerfile @@ -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"] diff --git a/crates/server/src/lib.rs b/crates/server/src/lib.rs index 8c68679..f643d63 100644 --- a/crates/server/src/lib.rs +++ b/crates/server/src/lib.rs @@ -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; + +/// 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, +} + +struct Inner { + store: Store, + content: Content, + secret: Vec, + live: RwLock>, + rate: Mutex>, + 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, + ) -> Result> { + 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 for Auth { + type Rejection = ApiError; + + async fn from_request_parts( + parts: &mut Parts, + state: &AppState, + ) -> Result { + 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) -> Self { + Self { + status, + code, + message: message.into(), + } + } + + fn bad_request(code: &'static str, message: impl Into) -> Self { + Self::new(StatusCode::BAD_REQUEST, code, message) + } + + fn conflict(code: &'static str, message: impl Into) -> 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) -> Json { + Json(HealthBody { + status: "ok", + sim_version: sim::SIM_VERSION, + content_hash: state.content_hash(), + }) +} + +async fn get_content( + State(state): State, + Path(version): Path, +) -> Result, 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, + Json(body): Json, +) -> Result, 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, +} + +#[derive(Serialize)] +struct CreateMatchResponse { + match_id: String, + seed: u64, + turn: u32, + state_hash: u64, +} + +async fn create_match( + State(state): State, + _auth: Auth, + Json(body): Json, +) -> Result<(StatusCode, Json), 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, + _auth: Auth, + Path(id): Path, +) -> Result, 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, + _auth: Auth, + Path(id): Path, + Json(body): Json, +) -> Result, 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, + 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, + auth: Auth, + Json(body): Json, +) -> Result, 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, + _auth: Auth, + Path(season): Path, +) -> Result>, 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"); } } diff --git a/crates/server/src/main.rs b/crates/server/src/main.rs new file mode 100644 index 0000000..57f4413 --- /dev/null +++ b/crates/server/src/main.rs @@ -0,0 +1,26 @@ +//! Server entry point. + +use std::net::SocketAddr; + +use server::{router, AppState}; + +#[tokio::main] +async fn main() -> Result<(), Box> { + 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(()) +} diff --git a/crates/server/src/store.rs b/crates/server/src/store.rs new file mode 100644 index 0000000..02c443e --- /dev/null +++ b/crates/server/src/store.rs @@ -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 { + 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, 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::("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, 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::("device_id"), r.get::("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) +} diff --git a/crates/server/tests/api.rs b/crates/server/tests/api.rs new file mode 100644 index 0000000..274c9c2 --- /dev/null +++ b/crates/server/tests/api.rs @@ -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) -> (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"); +} diff --git a/crates/server/tests/load.rs b/crates/server/tests/load.rs new file mode 100644 index 0000000..63bfedf --- /dev/null +++ b/crates/server/tests/load.rs @@ -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" + ); +} diff --git a/docs/ADR/0004-server-persistence.md b/docs/ADR/0004-server-persistence.md new file mode 100644 index 0000000..7d02af8 --- /dev/null +++ b/docs/ADR/0004-server-persistence.md @@ -0,0 +1,44 @@ +# ADR 0004 — Server-Persistenz: SQLite + Live-Sims im Speicher + +| Feld | Wert | +|---|---| +| Status | **Accepted** | +| Datum | 2026-10-24 | +| Verwandt | [protocol.md](../protocol.md) · [ADR 0001](0001-tech-stack-r1-r3.md) | + +--- + +## 1. Kontext + +Der Referee (M4) muss Züge autoritativ prüfen und Replays validieren. Zwei Dinge brauchen +Persistenz: der Match-Zustand (für `expect_hash`/Zugfolge) und die Replay-Verdicts (Anti-Cheat, +Leaderboard). + +## 2. Entscheidung + +| Aspekt | Umsetzung | +|---|---| +| Hot Path | Laufende `Sim`-Instanzen liegen als `HashMap` im Prozessspeicher | +| Durable | SQLite (via `sqlx`, gebündelt) für `matches`, `replays`, `trophies` | +| Schema | Beim Start idempotent angelegt (`CREATE TABLE IF NOT EXISTS`) | +| Autorität | Der Server rechnet jeden Zug **selbst** nach (Ticks bis zum Zugende) und speichert den neuen Hash | +| Tests | `sqlite::memory:` – keine Datei, keine externen Dienste | + +Begründung: Die Sim ist CPU-günstig (100k Matches in 19 s), also kann der Server sie im +Speicher halten und muss keine serialisierte Zustandsform erfinden. Persistiert wird nur, was +für Beweise und Ranking nötig ist. + +## 3. Konsequenzen + +**Positiv** +- Kein Serialisieren des `Sim`-Zustands (der Replay **ist** die Wahrheit). +- SQLite genügt für MVP und Testbetrieb, `sqlx` erlaubt später Postgres ohne API-Bruch. +- Ein Prozess, kein Cache-Cluster, keine Konsistenzprobleme. + +**Negativ / offen** +- Nach einem Neustart sind laufende Matches nur über ihren Command-Log rekonstruierbar; + dieser Rebuild ist **noch nicht implementiert** (M5). Aktuell antworten solche Matches + eingeschränkt (DB-Fallback ohne HP-Details). +- Ein einzelner Prozess skaliert nur vertikal; für mehrere Instanzen braucht es Sticky Sessions + oder einen externen Zustand (Redis/Postgres) – frühestens ab Soft Launch relevant. +- SQLite-Schreiblast ist für Ranked unkritisch (< 1 Write pro Zug).