From 2a325faad6701301725909eee8be8a6f59d1fd6d Mon Sep 17 00:00:00 2001 From: FedericoGambassi Date: Tue, 20 Jan 2026 15:46:36 +0100 Subject: [PATCH 01/17] [Sprint 1][Task 1] fix: added correct dockerhub username to compose.yml --- compose.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/compose.yml b/compose.yml index a54c69c4f..9742a1ca0 100644 --- a/compose.yml +++ b/compose.yml @@ -1,7 +1,7 @@ services: app-service: # TODO: change "letsgetrusty" to your Docker Hub username - image: letsgetrusty/app-service # specify name of image on Docker Hub + image: fedecomprido/app-service # specify name of image on Docker Hub restart: "always" # automatically restart container when server crashes environment: # set up environment variables AUTH_SERVICE_IP: ${AUTH_SERVICE_IP:-localhost} # Use localhost as the default value @@ -12,7 +12,7 @@ services: condition: service_started auth-service: # TODO: change "letsgetrusty" to your Docker Hub username - image: letsgetrusty/auth-service + image: fedecomprido/auth-service restart: "always" # automatically restart container when server crashes ports: - "3000:3000" # expose port 3000 so that applications outside the container can connect to it \ No newline at end of file From 6eae1f6dc24f9a39642e1b05f326a581a776ff76 Mon Sep 17 00:00:00 2001 From: FedericoGambassi Date: Tue, 20 Jan 2026 15:47:18 +0100 Subject: [PATCH 02/17] [Sprint 1][Task 3] refactor: moved app building into lib.rs ; created tests module --- auth-service/src/lib.rs | 32 +++++++++++++++++++++++++++++++ auth-service/src/main.rs | 23 ++++------------------ auth-service/tests/api/helpers.rs | 0 auth-service/tests/api/main.rs | 2 ++ auth-service/tests/api/routes.rs | 0 5 files changed, 38 insertions(+), 19 deletions(-) create mode 100644 auth-service/src/lib.rs create mode 100644 auth-service/tests/api/helpers.rs create mode 100644 auth-service/tests/api/main.rs create mode 100644 auth-service/tests/api/routes.rs diff --git a/auth-service/src/lib.rs b/auth-service/src/lib.rs new file mode 100644 index 000000000..954ecb601 --- /dev/null +++ b/auth-service/src/lib.rs @@ -0,0 +1,32 @@ +use tokio::net::TcpListener; +use axum::{routing::get, Router, serve::Serve}; +use tower_http::services::ServeDir; + + +type Result = std::result::Result>; + + +pub struct Application { + server: Serve, + pub address: String, +} + +impl Application { + pub async fn build(address: &str) -> Result { + let assets_dir = ServeDir::new("assets"); + let router = Router::new() + .fallback_service(assets_dir); + // .route("/hello", get(hello_handler)); + let listener = TcpListener::bind(address).await?; + let address = listener.local_addr()?.to_string(); + let server = axum::serve(listener, router); + + Ok(Application { server, address }) + } + + pub async fn run(self) -> Result<()> { + println!("Listening on {}", self.address); + self.server.await?; + Ok(()) + } +} diff --git a/auth-service/src/main.rs b/auth-service/src/main.rs index 1f243bd26..7bd4f17b0 100644 --- a/auth-service/src/main.rs +++ b/auth-service/src/main.rs @@ -1,23 +1,8 @@ -use axum::{response::Html, routing::get, serve, Router}; -use tower_http::services::ServeDir; +use auth_service::Application; + #[tokio::main] async fn main() { - let assets_dir = ServeDir::new("assets"); - let app = Router::new() - .fallback_service(assets_dir) - .route("/hello", get(hello_handler)); - - // Here we are using ip 0.0.0.0 so the service is listening on all the configured network interfaces. - // This is needed for Docker to work, which we will add later on. - // See: https://stackoverflow.com/questions/39525820/docker-port-forwarding-not-working - let listener = tokio::net::TcpListener::bind("0.0.0.0:3000").await.unwrap(); - println!("listening on {}", listener.local_addr().unwrap()); - - axum::serve(listener, app).await.unwrap(); -} - -async fn hello_handler() -> Html<&'static str> { - // TODO: Update this to a custom message! - Html("

Hello, World!

") + let app = Application::build("0.0.0.0:3000").await.expect("Failed to build app"); + app.run().await.expect("Failed to run app"); } diff --git a/auth-service/tests/api/helpers.rs b/auth-service/tests/api/helpers.rs new file mode 100644 index 000000000..e69de29bb diff --git a/auth-service/tests/api/main.rs b/auth-service/tests/api/main.rs new file mode 100644 index 000000000..397a81441 --- /dev/null +++ b/auth-service/tests/api/main.rs @@ -0,0 +1,2 @@ +mod helpers; +mod routes; diff --git a/auth-service/tests/api/routes.rs b/auth-service/tests/api/routes.rs new file mode 100644 index 000000000..e69de29bb From 3c4383487db65fd44eb39d97e6299abe2f3e776e Mon Sep 17 00:00:00 2001 From: FedericoGambassi Date: Thu, 22 Jan 2026 14:31:07 +0100 Subject: [PATCH 03/17] [Sprint 1][Task 4] implement routes using TDD --- auth-service/Cargo.lock | 443 +++++++++++++++++++++++++++++- auth-service/Cargo.toml | 6 +- auth-service/src/lib.rs | 41 ++- auth-service/tests/api/helpers.rs | 73 +++++ auth-service/tests/api/routes.rs | 69 +++++ 5 files changed, 624 insertions(+), 8 deletions(-) diff --git a/auth-service/Cargo.lock b/auth-service/Cargo.lock index cd9bd4144..3d6ec6650 100644 --- a/auth-service/Cargo.lock +++ b/auth-service/Cargo.lock @@ -13,6 +13,8 @@ name = "auth-service" version = "0.1.0" dependencies = [ "axum", + "reqwest", + "serde_json", "tokio", "tower-http", ] @@ -69,12 +71,24 @@ dependencies = [ "tracing", ] +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "bitflags" version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" +[[package]] +name = "bumpalo" +version = "3.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510" + [[package]] name = "bytes" version = "1.10.1" @@ -87,6 +101,17 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "displaydoc" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "fnv" version = "1.0.7" @@ -139,6 +164,7 @@ dependencies = [ "futures-task", "pin-project-lite", "pin-utils", + "slab", ] [[package]] @@ -212,6 +238,7 @@ dependencies = [ "pin-utils", "smallvec", "tokio", + "want", ] [[package]] @@ -220,14 +247,140 @@ version = "0.1.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c6995591a8f1380fcb4ba966a252a4b29188d51d2b89e3a252f5305be65aea8" dependencies = [ + "base64", "bytes", + "futures-channel", "futures-core", + "futures-util", "http", "http-body", "hyper", + "ipnet", + "libc", + "percent-encoding", "pin-project-lite", + "socket2", "tokio", "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c6b649701667bbe825c3b7e6388cb521c23d88644678e83c0c4d0a621a34b43" +dependencies = [ + "displaydoc", + "potential_utf", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edba7861004dd3714265b4db54a3c390e880ab658fec5f7db895fae2046b5bb6" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f6c8828b67bf8908d82127b2054ea1b4427ff0230ee9141c54251934ab1b599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7aedcccd01fc5fe81e6b489c15b247b8b0690feb23304303a9e560f37efc560a" + +[[package]] +name = "icu_properties" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "020bfc02fe870ec3a66d93e677ccca0562506e5872c650f893269e08615d74ec" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "616c294cf8d725c6afcd8f55abc17c56464ef6211f9ed59cccffe534129c77af" + +[[package]] +name = "icu_provider" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85962cf0ce02e1e0a629cc34e7ca3e373ce20dda4c4d7294bbd0bf1fdb59e614" +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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3acae9609540aa318d1bc588455225fb2085b9ed0c4f6bd0d9d5bcd86f1a0344" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "ipnet" +version = "2.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "469fb0b9cefa57e3ef31275ee7cacb78f2fdca44e4765491884a2b119d4eb130" + +[[package]] +name = "iri-string" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c91338f0783edbd6195decb37bae672fd3b165faffb89bf7b9e6942f8b1a731a" +dependencies = [ + "memchr", + "serde", ] [[package]] @@ -236,12 +389,28 @@ version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" +[[package]] +name = "js-sys" +version = "0.3.85" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c942ebf8e95485ca0d52d97da7c5a2c387d0e7f0ba4c35e93bfcaee045955b3" +dependencies = [ + "once_cell", + "wasm-bindgen", +] + [[package]] name = "libc" version = "0.2.177" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" +[[package]] +name = "litemap" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" + [[package]] name = "lock_api" version = "0.4.14" @@ -343,6 +512,15 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[package]] +name = "potential_utf" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b73949432f5e2a09657003c25bca5e19a0e9c84f8058ca374f49e0ebe605af77" +dependencies = [ + "zerovec", +] + [[package]] name = "proc-macro2" version = "1.0.103" @@ -370,6 +548,43 @@ dependencies = [ "bitflags", ] +[[package]] +name = "reqwest" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04e9018c9d814e5f30cc16a0f03271aeab3571e609612d9fe78c1aa8d11c2f62" +dependencies = [ + "base64", + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "serde", + "serde_json", + "sync_wrapper", + "tokio", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + [[package]] name = "ryu" version = "1.0.20" @@ -389,6 +604,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" dependencies = [ "serde_core", + "serde_derive", ] [[package]] @@ -456,6 +672,12 @@ dependencies = [ "libc", ] +[[package]] +name = "slab" +version = "0.4.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a2ae44ef20feb57a68b23d846850f861394c2e02dc425a50098ae8c90267589" + [[package]] name = "smallvec" version = "1.15.1" @@ -472,6 +694,12 @@ dependencies = [ "windows-sys 0.60.2", ] +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + [[package]] name = "syn" version = "2.0.108" @@ -488,6 +716,30 @@ name = "sync_wrapper" version = "1.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42d3e9c45c09de15d06dd8acf5f4e0e399e85927b7f00711024eb7ae10fa4869" +dependencies = [ + "displaydoc", + "zerovec", +] [[package]] name = "tokio" @@ -548,9 +800,9 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.6.6" +version = "0.6.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adc82fd73de2a9722ac5da747f12383d2bfdb93591ee6c58486e0097890f05f2" +checksum = "d4e6559d53cc268e5031cd8429d05415bc4cb4aefc4aa5d6cc35fbf5b924a1f8" dependencies = [ "bitflags", "bytes", @@ -561,12 +813,14 @@ dependencies = [ "http-body-util", "http-range-header", "httpdate", + "iri-string", "mime", "mime_guess", "percent-encoding", "pin-project-lite", "tokio", "tokio-util", + "tower", "tower-layer", "tower-service", "tracing", @@ -604,6 +858,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + [[package]] name = "unicase" version = "2.8.1" @@ -616,12 +876,108 @@ version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" +[[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 = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + [[package]] name = "wasi" version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasm-bindgen" +version = "0.2.108" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64024a30ec1e37399cf85a7ffefebdb72205ca1c972291c51512360d90bd8566" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.58" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70a6e77fd0ae8029c9ea0063f87c46fde723e7d887703d74ad2616d792e51e6f" +dependencies = [ + "cfg-if", + "futures-util", + "js-sys", + "once_cell", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.108" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "008b239d9c740232e71bd39e8ef6429d27097518b6b30bdf9086833bd5b6d608" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.108" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5256bae2d58f54820e6490f9839c49780dff84c65aeab9e772f15d5f0e913a55" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.108" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f01b580c9ac74c8d8f0c0e4afb04eeef2acf145458e52c03845ee9cd23e3d12" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "web-sys" +version = "0.3.85" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "312e32e551d92129218ea9a2452120f4aabc03529ef03e4d0d82fb2780608598" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + [[package]] name = "windows-link" version = "0.2.1" @@ -710,3 +1066,86 @@ name = "windows_x86_64_msvc" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "writeable" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9edde0db4769d2dc68579893f2306b26c6ecfbe0ef499b013d731b7b9247e0b9" + +[[package]] +name = "yoke" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72d6e5c6afb84d73944e5cedb052c4680d5657337201555f9f2a16b7406d4954" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b659052874eb698efe5b9e8cf382204678a0086ebf46982b79d6ca3182927e5d" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerofrom" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50cc42e0333e05660c3587f3bf9d0478688e15d870fab3346451ce7f8c9fbea5" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d71e5d6e06ab090c67b5e44993ec16b72dcbaabc526db883a360057678b48502" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a59c17a5562d507e4b54960e8569ebee33bee890c70aa3fe7b97e85a9fd7851" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c28719294829477f525be0186d13efa9a3c602f7ec202ca9e353d310fb9a002" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eadce39539ca5cb3985590102671f2567e659fca9666581ad3411d59207951f3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] diff --git a/auth-service/Cargo.toml b/auth-service/Cargo.toml index dbf7bee78..1f9c314e1 100644 --- a/auth-service/Cargo.toml +++ b/auth-service/Cargo.toml @@ -8,4 +8,8 @@ edition = "2021" [dependencies] axum = "0.8.6" tokio = { version = "1.48.0", features = ["full"] } -tower-http = { version = "0.6.6", features = ["fs"] } \ No newline at end of file +tower-http = { version = "0.6.6", features = ["fs"] } + +[dev-dependencies] +reqwest = { version = "0.13.1", default-features = false, features = ["json"] } +serde_json = { version = "1.0.145", default-features = false } diff --git a/auth-service/src/lib.rs b/auth-service/src/lib.rs index 954ecb601..8ce477692 100644 --- a/auth-service/src/lib.rs +++ b/auth-service/src/lib.rs @@ -1,6 +1,6 @@ use tokio::net::TcpListener; -use axum::{routing::get, Router, serve::Serve}; -use tower_http::services::ServeDir; +use axum::{Router, response::IntoResponse, routing::{get, post}, serve::Serve, http::StatusCode}; +use tower_http::{services::{ServeDir, ServeFile}}; type Result = std::result::Result>; @@ -13,10 +13,16 @@ pub struct Application { impl Application { pub async fn build(address: &str) -> Result { - let assets_dir = ServeDir::new("assets"); + let assets_dir = ServeDir::new("assets") + .not_found_service(ServeFile::new("assets/index.html")); + let router = Router::new() - .fallback_service(assets_dir); - // .route("/hello", get(hello_handler)); + .fallback_service(assets_dir) + .route("/signup", post(signup)) + .route("/login", post(login)) + .route("/verify-2fa", post(verify_2fa)) + .route("/logout", post(logout)) + .route("/verify-token", post(verify_token)); let listener = TcpListener::bind(address).await?; let address = listener.local_addr()?.to_string(); let server = axum::serve(listener, router); @@ -30,3 +36,28 @@ impl Application { Ok(()) } } + + +async fn signup() -> impl IntoResponse { + StatusCode::OK.into_response() +} + + +async fn login() -> impl IntoResponse { + StatusCode::OK.into_response() +} + + +async fn verify_2fa() -> impl IntoResponse { + StatusCode::OK.into_response() +} + + +async fn logout() -> impl IntoResponse { + StatusCode::OK.into_response() +} + + +async fn verify_token() -> impl IntoResponse { + StatusCode::OK.into_response() +} diff --git a/auth-service/tests/api/helpers.rs b/auth-service/tests/api/helpers.rs index e69de29bb..eaaaf9abf 100644 --- a/auth-service/tests/api/helpers.rs +++ b/auth-service/tests/api/helpers.rs @@ -0,0 +1,73 @@ +use auth_service::Application; +use reqwest; + + + +pub struct TestApp { + pub address: String, + pub client: reqwest::Client, +} + +impl TestApp { + pub async fn run() -> Self { + let app = Application::build("127.0.0.1:0").await.expect("Failed to build application"); + let address = format!("http://{}", app.address.clone()); + + #[allow(clippy::let_underscore_future)] + let _ = tokio::spawn(app.run()); + Self { address, client: reqwest::Client::new() } + } + + pub async fn get_root(&self) -> reqwest::Response { + self.client + .get(format!("{}/", &self.address)) + .send() + .await + .expect("Failed to execute request.") + } + + pub async fn post_signup(&self, body: &serde_json::Value) -> reqwest::Response { + self.client + .post(format!("{}/signup", &self.address)) + .json(body) + .send() + .await + .expect("Failed to execute request.") + } + + pub async fn post_login(&self, body: &serde_json::Value) -> reqwest::Response { + self.client + .post(format!("{}/login", &self.address)) + .json(body) + .send() + .await + .expect("Failed to execute request.") + } + + pub async fn post_logout(&self,) -> reqwest::Response { + self.client + .post(format!("{}/logout", &self.address)) + // token is in header in real use, but for testing we can skip it + .send() + .await + .expect("Failed to execute request.") + } + + pub async fn verify_2fa(&self, body: &serde_json::Value) -> reqwest::Response { + self.client + .post(format!("{}/verify-2fa", &self.address)) + .json(body) + .send() + .await + .expect("Failed to execute request.") + } + + pub async fn verify_token(&self, body: &serde_json::Value) -> reqwest::Response { + self.client + .post(format!("{}/verify-token", &self.address)) + .json(body) + .send() + .await + .expect("Failed to execute request.") + } +} diff --git a/auth-service/tests/api/routes.rs b/auth-service/tests/api/routes.rs index e69de29bb..cabdbddbd 100644 --- a/auth-service/tests/api/routes.rs +++ b/auth-service/tests/api/routes.rs @@ -0,0 +1,69 @@ +use crate::helpers::TestApp; + + +mod tests { + use axum::body; + + use super::*; + + #[tokio::test] + async fn root_returns_auth_ui() { + let app = TestApp::run().await; + let response = app.get_root().await; + assert_eq!(response.status().as_u16(), 200); + assert_eq!(response.headers().get("content-Type").unwrap(), "text/html"); + } + + #[tokio::test] + async fn test_signup() { + let app = TestApp::run().await; + + let body = serde_json::json!({ + "email": "user@example.com", + "password": "password", + "requires2FA": true + }); + let response = app.post_signup(&body).await; + assert_eq!(response.status().as_u16(), 200); + } + + #[tokio::test] + async fn test_login() { + let app = TestApp::run().await; + let body = serde_json::json!({ + "email": "user@example.com", + "password": "password" + }); + let response = app.post_login(&body).await; + assert_eq!(response.status().as_u16(), 200); + } + + #[tokio::test] + async fn test_verify_2fa() { + let app = TestApp::run().await; + let body = serde_json::json!({ + "email": "user@example.com", + "loginAttemptId": "1", + "2FACode": "123456" + }); + let response = app.verify_2fa(&body).await; + assert_eq!(response.status().as_u16(), 200); + } + + #[tokio::test] + async fn test_logout() { + let app = TestApp::run().await; + let response = app.post_logout().await; + assert_eq!(response.status().as_u16(), 200); + } + + #[tokio::test] + async fn test_verify_token() { + let app = TestApp::run().await; + let body = serde_json::json!({ + "token": "some_valid_token" + }); + let response = app.verify_token(&body).await; + assert_eq!(response.status().as_u16(), 200); + } +} From f609264da1a6c527056cbf161f6b7748a5d66fdf Mon Sep 17 00:00:00 2001 From: FedericoGambassi Date: Thu, 22 Jan 2026 14:54:52 +0100 Subject: [PATCH 04/17] [Sprint 1][Task 5] refactor auth service --- auth-service/tests/api/login.rs | 18 +++++++ auth-service/tests/api/logout.rs | 14 ++++++ auth-service/tests/api/main.rs | 7 ++- auth-service/tests/api/root.rs | 15 ++++++ auth-service/tests/api/routes.rs | 69 -------------------------- auth-service/tests/api/signup.rs | 20 ++++++++ auth-service/tests/api/verify_2fa.rs | 19 +++++++ auth-service/tests/api/verify_token.rs | 17 +++++++ 8 files changed, 109 insertions(+), 70 deletions(-) create mode 100644 auth-service/tests/api/login.rs create mode 100644 auth-service/tests/api/logout.rs create mode 100644 auth-service/tests/api/root.rs delete mode 100644 auth-service/tests/api/routes.rs create mode 100644 auth-service/tests/api/signup.rs create mode 100644 auth-service/tests/api/verify_2fa.rs create mode 100644 auth-service/tests/api/verify_token.rs diff --git a/auth-service/tests/api/login.rs b/auth-service/tests/api/login.rs new file mode 100644 index 000000000..05a02f8ad --- /dev/null +++ b/auth-service/tests/api/login.rs @@ -0,0 +1,18 @@ +use crate::helpers::TestApp; +use axum::body; + + +mod tests { + use super::*; + + #[tokio::test] + async fn test_login() { + let app = TestApp::run().await; + let body = serde_json::json!({ + "email": "user@example.com", + "password": "password" + }); + let response = app.post_login(&body).await; + assert_eq!(response.status().as_u16(), 200); + } +} diff --git a/auth-service/tests/api/logout.rs b/auth-service/tests/api/logout.rs new file mode 100644 index 000000000..7a95b753d --- /dev/null +++ b/auth-service/tests/api/logout.rs @@ -0,0 +1,14 @@ +use crate::helpers::TestApp; +use axum::body; + + +mod tests { + use super::*; + + #[tokio::test] + async fn test_logout() { + let app = TestApp::run().await; + let response = app.post_logout().await; + assert_eq!(response.status().as_u16(), 200); + } +} diff --git a/auth-service/tests/api/main.rs b/auth-service/tests/api/main.rs index 397a81441..2c69f3b08 100644 --- a/auth-service/tests/api/main.rs +++ b/auth-service/tests/api/main.rs @@ -1,2 +1,7 @@ mod helpers; -mod routes; +mod root; +mod login; +mod logout; +mod verify_2fa; +mod verify_token; +mod signup; diff --git a/auth-service/tests/api/root.rs b/auth-service/tests/api/root.rs new file mode 100644 index 000000000..f240b4cc9 --- /dev/null +++ b/auth-service/tests/api/root.rs @@ -0,0 +1,15 @@ +use crate::helpers::TestApp; +use axum::body; + + +mod tests { + use super::*; + + #[tokio::test] + async fn root_returns_auth_ui() { + let app = TestApp::run().await; + let response = app.get_root().await; + assert_eq!(response.status().as_u16(), 200); + assert_eq!(response.headers().get("content-Type").unwrap(), "text/html"); + } +} diff --git a/auth-service/tests/api/routes.rs b/auth-service/tests/api/routes.rs deleted file mode 100644 index cabdbddbd..000000000 --- a/auth-service/tests/api/routes.rs +++ /dev/null @@ -1,69 +0,0 @@ -use crate::helpers::TestApp; - - -mod tests { - use axum::body; - - use super::*; - - #[tokio::test] - async fn root_returns_auth_ui() { - let app = TestApp::run().await; - let response = app.get_root().await; - assert_eq!(response.status().as_u16(), 200); - assert_eq!(response.headers().get("content-Type").unwrap(), "text/html"); - } - - #[tokio::test] - async fn test_signup() { - let app = TestApp::run().await; - - let body = serde_json::json!({ - "email": "user@example.com", - "password": "password", - "requires2FA": true - }); - let response = app.post_signup(&body).await; - assert_eq!(response.status().as_u16(), 200); - } - - #[tokio::test] - async fn test_login() { - let app = TestApp::run().await; - let body = serde_json::json!({ - "email": "user@example.com", - "password": "password" - }); - let response = app.post_login(&body).await; - assert_eq!(response.status().as_u16(), 200); - } - - #[tokio::test] - async fn test_verify_2fa() { - let app = TestApp::run().await; - let body = serde_json::json!({ - "email": "user@example.com", - "loginAttemptId": "1", - "2FACode": "123456" - }); - let response = app.verify_2fa(&body).await; - assert_eq!(response.status().as_u16(), 200); - } - - #[tokio::test] - async fn test_logout() { - let app = TestApp::run().await; - let response = app.post_logout().await; - assert_eq!(response.status().as_u16(), 200); - } - - #[tokio::test] - async fn test_verify_token() { - let app = TestApp::run().await; - let body = serde_json::json!({ - "token": "some_valid_token" - }); - let response = app.verify_token(&body).await; - assert_eq!(response.status().as_u16(), 200); - } -} diff --git a/auth-service/tests/api/signup.rs b/auth-service/tests/api/signup.rs new file mode 100644 index 000000000..857c94a54 --- /dev/null +++ b/auth-service/tests/api/signup.rs @@ -0,0 +1,20 @@ +use crate::helpers::TestApp; +use axum::body; + + +mod tests { + use super::*; + + #[tokio::test] + async fn test_signup() { + let app = TestApp::run().await; + + let body = serde_json::json!({ + "email": "user@example.com", + "password": "password", + "requires2FA": true + }); + let response = app.post_signup(&body).await; + assert_eq!(response.status().as_u16(), 200); + } +} diff --git a/auth-service/tests/api/verify_2fa.rs b/auth-service/tests/api/verify_2fa.rs new file mode 100644 index 000000000..161efeab0 --- /dev/null +++ b/auth-service/tests/api/verify_2fa.rs @@ -0,0 +1,19 @@ +use crate::helpers::TestApp; +use axum::body; + + +mod tests { + use super::*; + + #[tokio::test] + async fn test_verify_2fa() { + let app = TestApp::run().await; + let body = serde_json::json!({ + "email": "user@example.com", + "loginAttemptId": "1", + "2FACode": "123456" + }); + let response = app.verify_2fa(&body).await; + assert_eq!(response.status().as_u16(), 200); + } +} diff --git a/auth-service/tests/api/verify_token.rs b/auth-service/tests/api/verify_token.rs new file mode 100644 index 000000000..f79d62232 --- /dev/null +++ b/auth-service/tests/api/verify_token.rs @@ -0,0 +1,17 @@ +use crate::helpers::TestApp; +use axum::body; + + +mod tests { + use super::*; + + #[tokio::test] + async fn test_verify_token() { + let app = TestApp::run().await; + let body = serde_json::json!({ + "token": "some_valid_token" + }); + let response = app.verify_token(&body).await; + assert_eq!(response.status().as_u16(), 200); + } +} From 6ce2c027babe8d8743d359ec48949b85b378ca6e Mon Sep 17 00:00:00 2001 From: FedericoGambassi Date: Thu, 22 Jan 2026 15:25:48 +0100 Subject: [PATCH 05/17] [Sprint 1][Task 6] implement signup route interface --- auth-service/Cargo.lock | 45 +++++++++++++++++++++++++ auth-service/Cargo.toml | 4 ++- auth-service/src/lib.rs | 27 +++------------ auth-service/src/routes/login.rs | 6 ++++ auth-service/src/routes/logout.rs | 6 ++++ auth-service/src/routes/mod.rs | 11 ++++++ auth-service/src/routes/signup.rs | 16 +++++++++ auth-service/src/routes/verify_2fa.rs | 6 ++++ auth-service/src/routes/verify_token.rs | 6 ++++ auth-service/tests/api/helpers.rs | 10 +++++- auth-service/tests/api/signup.rs | 26 +++++++++----- 11 files changed, 130 insertions(+), 33 deletions(-) create mode 100644 auth-service/src/routes/login.rs create mode 100644 auth-service/src/routes/logout.rs create mode 100644 auth-service/src/routes/mod.rs create mode 100644 auth-service/src/routes/signup.rs create mode 100644 auth-service/src/routes/verify_2fa.rs create mode 100644 auth-service/src/routes/verify_token.rs diff --git a/auth-service/Cargo.lock b/auth-service/Cargo.lock index 3d6ec6650..91dad88a1 100644 --- a/auth-service/Cargo.lock +++ b/auth-service/Cargo.lock @@ -14,9 +14,11 @@ version = "0.1.0" dependencies = [ "axum", "reqwest", + "serde", "serde_json", "tokio", "tower-http", + "uuid", ] [[package]] @@ -167,6 +169,18 @@ dependencies = [ "slab", ] +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi", + "wasip2", +] + [[package]] name = "http" version = "1.3.1" @@ -539,6 +553,12 @@ dependencies = [ "proc-macro2", ] +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + [[package]] name = "redox_syscall" version = "0.5.18" @@ -894,6 +914,16 @@ version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" +[[package]] +name = "uuid" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2e054861b4bd027cd373e18e8d8d8e6548085000e41290d95ce0c373a654b4a" +dependencies = [ + "getrandom", + "serde_core", +] + [[package]] name = "want" version = "0.3.1" @@ -909,6 +939,15 @@ version = "0.11.1+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" +[[package]] +name = "wasip2" +version = "1.0.2+wasi-0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5" +dependencies = [ + "wit-bindgen", +] + [[package]] name = "wasm-bindgen" version = "0.2.108" @@ -1067,6 +1106,12 @@ version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" + [[package]] name = "writeable" version = "0.6.2" diff --git a/auth-service/Cargo.toml b/auth-service/Cargo.toml index 1f9c314e1..1322d8c64 100644 --- a/auth-service/Cargo.toml +++ b/auth-service/Cargo.toml @@ -7,9 +7,11 @@ edition = "2021" [dependencies] axum = "0.8.6" +serde = { version = "1.0.228", features = ["derive"] } +serde_json = "1.0.145" +uuid = { version = "1.18.1", default-features = false, features = ["v4", "serde"] } tokio = { version = "1.48.0", features = ["full"] } tower-http = { version = "0.6.6", features = ["fs"] } [dev-dependencies] reqwest = { version = "0.13.1", default-features = false, features = ["json"] } -serde_json = { version = "1.0.145", default-features = false } diff --git a/auth-service/src/lib.rs b/auth-service/src/lib.rs index 8ce477692..7f8cdb634 100644 --- a/auth-service/src/lib.rs +++ b/auth-service/src/lib.rs @@ -1,7 +1,10 @@ use tokio::net::TcpListener; -use axum::{Router, response::IntoResponse, routing::{get, post}, serve::Serve, http::StatusCode}; +use axum::{Router, routing::post, serve::Serve}; use tower_http::{services::{ServeDir, ServeFile}}; +pub mod routes; +use routes::*; + type Result = std::result::Result>; @@ -38,26 +41,4 @@ impl Application { } -async fn signup() -> impl IntoResponse { - StatusCode::OK.into_response() -} - -async fn login() -> impl IntoResponse { - StatusCode::OK.into_response() -} - - -async fn verify_2fa() -> impl IntoResponse { - StatusCode::OK.into_response() -} - - -async fn logout() -> impl IntoResponse { - StatusCode::OK.into_response() -} - - -async fn verify_token() -> impl IntoResponse { - StatusCode::OK.into_response() -} diff --git a/auth-service/src/routes/login.rs b/auth-service/src/routes/login.rs new file mode 100644 index 000000000..0dbb10060 --- /dev/null +++ b/auth-service/src/routes/login.rs @@ -0,0 +1,6 @@ +use axum::{response::IntoResponse, http::StatusCode}; + + +pub async fn login() -> impl IntoResponse { + StatusCode::OK.into_response() +} diff --git a/auth-service/src/routes/logout.rs b/auth-service/src/routes/logout.rs new file mode 100644 index 000000000..200e65d2b --- /dev/null +++ b/auth-service/src/routes/logout.rs @@ -0,0 +1,6 @@ +use axum::{response::IntoResponse, http::StatusCode}; + + +pub async fn logout() -> impl IntoResponse { + StatusCode::OK.into_response() +} diff --git a/auth-service/src/routes/mod.rs b/auth-service/src/routes/mod.rs new file mode 100644 index 000000000..cf21ea2be --- /dev/null +++ b/auth-service/src/routes/mod.rs @@ -0,0 +1,11 @@ +mod login; +mod signup; +mod verify_2fa; +mod logout; +mod verify_token; + +pub use login::*; +pub use signup::*; +pub use verify_2fa::*; +pub use logout::*; +pub use verify_token::*; diff --git a/auth-service/src/routes/signup.rs b/auth-service/src/routes/signup.rs new file mode 100644 index 000000000..52a768399 --- /dev/null +++ b/auth-service/src/routes/signup.rs @@ -0,0 +1,16 @@ +use axum::{Json, http::StatusCode, response::IntoResponse}; +use serde::Deserialize; + + +pub async fn signup(Json(request): Json) -> impl IntoResponse { + StatusCode::OK.into_response() +} + + +#[derive(Deserialize)] +pub struct SignupRequest { + email: String, + password: String, + #[serde(rename = "requires2FA")] + requires_2fa: bool, +} diff --git a/auth-service/src/routes/verify_2fa.rs b/auth-service/src/routes/verify_2fa.rs new file mode 100644 index 000000000..2acd21c60 --- /dev/null +++ b/auth-service/src/routes/verify_2fa.rs @@ -0,0 +1,6 @@ +use axum::{response::IntoResponse, http::StatusCode}; + + +pub async fn verify_2fa() -> impl IntoResponse { + StatusCode::OK.into_response() +} diff --git a/auth-service/src/routes/verify_token.rs b/auth-service/src/routes/verify_token.rs new file mode 100644 index 000000000..8c7ee5a3e --- /dev/null +++ b/auth-service/src/routes/verify_token.rs @@ -0,0 +1,6 @@ +use axum::{response::IntoResponse, http::StatusCode}; + + +pub async fn verify_token() -> impl IntoResponse { + StatusCode::OK.into_response() +} diff --git a/auth-service/tests/api/helpers.rs b/auth-service/tests/api/helpers.rs index eaaaf9abf..ac9178aad 100644 --- a/auth-service/tests/api/helpers.rs +++ b/auth-service/tests/api/helpers.rs @@ -26,7 +26,9 @@ impl TestApp { .expect("Failed to execute request.") } - pub async fn post_signup(&self, body: &serde_json::Value) -> reqwest::Response { + pub async fn post_signup(&self, body: &Body) -> reqwest::Response + where Body: serde::Serialize + { self.client .post(format!("{}/signup", &self.address)) .json(body) @@ -71,3 +73,9 @@ impl TestApp { .expect("Failed to execute request.") } } + + +pub fn get_random_email() -> String { + let uuid = uuid::Uuid::new_v4(); + format!("{}@example.com", uuid) +} diff --git a/auth-service/tests/api/signup.rs b/auth-service/tests/api/signup.rs index 857c94a54..2fece46af 100644 --- a/auth-service/tests/api/signup.rs +++ b/auth-service/tests/api/signup.rs @@ -3,18 +3,28 @@ use axum::body; mod tests { + use serde_json::json; + + use crate::helpers::get_random_email; + use super::*; #[tokio::test] - async fn test_signup() { + async fn should_return_422_if_malformed_input() { let app = TestApp::run().await; - let body = serde_json::json!({ - "email": "user@example.com", - "password": "password", - "requires2FA": true - }); - let response = app.post_signup(&body).await; - assert_eq!(response.status().as_u16(), 200); + let email = get_random_email(); + + let test_cases = [ + json!({ + "password": "password", + "requires2FA": true + } ), + ]; + + for body in test_cases { + let response = app.post_signup(&body).await; + assert_eq!(response.status().as_u16(), 422, "Failed for body: {}", body); + } } } From f8bf369082411f4d9dd56e6ff5938ccee782e73d Mon Sep 17 00:00:00 2001 From: FedericoGambassi Date: Fri, 23 Jan 2026 11:13:39 +0100 Subject: [PATCH 06/17] [Sprint 2][Task 1] implement signup route success case --- auth-service/src/app_state.rs | 18 +++++ auth-service/src/domain/mod.rs | 1 + auth-service/src/domain/user.rs | 15 ++++ auth-service/src/lib.rs | 12 +++- auth-service/src/main.rs | 5 +- auth-service/src/routes/signup.rs | 27 ++++++-- .../src/services/hashmap_user_store.rs | 69 +++++++++++++++++++ auth-service/src/services/mod.rs | 1 + auth-service/tests/api/helpers.rs | 7 +- auth-service/tests/api/signup.rs | 30 ++++++++ 10 files changed, 176 insertions(+), 9 deletions(-) create mode 100644 auth-service/src/app_state.rs create mode 100644 auth-service/src/domain/mod.rs create mode 100644 auth-service/src/domain/user.rs create mode 100644 auth-service/src/services/hashmap_user_store.rs create mode 100644 auth-service/src/services/mod.rs diff --git a/auth-service/src/app_state.rs b/auth-service/src/app_state.rs new file mode 100644 index 000000000..a5ffa1afc --- /dev/null +++ b/auth-service/src/app_state.rs @@ -0,0 +1,18 @@ +use std::sync::Arc; +use tokio::sync::RwLock; +use crate::services::hashmap_user_store::HashmapUserStore; + + +pub type UserStoreType = Arc>; + + +#[derive(Clone)] +pub struct AppState { + pub user_store: UserStoreType, +} + +impl AppState { + pub fn new(user_store: UserStoreType) -> Self { + Self { user_store } + } +} diff --git a/auth-service/src/domain/mod.rs b/auth-service/src/domain/mod.rs new file mode 100644 index 000000000..22d12a382 --- /dev/null +++ b/auth-service/src/domain/mod.rs @@ -0,0 +1 @@ +pub mod user; diff --git a/auth-service/src/domain/user.rs b/auth-service/src/domain/user.rs new file mode 100644 index 000000000..8cf4bb75e --- /dev/null +++ b/auth-service/src/domain/user.rs @@ -0,0 +1,15 @@ +pub struct User { + pub requires_2fa: bool, + pub password: String, + pub email: String, +} + +impl User { + pub fn new(email: String, password: String, requires_2fa: bool) -> Self { + Self { + email, + password, + requires_2fa, + } + } +} diff --git a/auth-service/src/lib.rs b/auth-service/src/lib.rs index 7f8cdb634..7175daa21 100644 --- a/auth-service/src/lib.rs +++ b/auth-service/src/lib.rs @@ -3,7 +3,14 @@ use axum::{Router, routing::post, serve::Serve}; use tower_http::{services::{ServeDir, ServeFile}}; pub mod routes; +pub mod domain; +pub mod services; +pub mod app_state; + use routes::*; +use domain::*; +use services::*; +use app_state::AppState; type Result = std::result::Result>; @@ -15,7 +22,7 @@ pub struct Application { } impl Application { - pub async fn build(address: &str) -> Result { + pub async fn build(app_state: AppState, address: &str) -> Result { let assets_dir = ServeDir::new("assets") .not_found_service(ServeFile::new("assets/index.html")); @@ -25,7 +32,8 @@ impl Application { .route("/login", post(login)) .route("/verify-2fa", post(verify_2fa)) .route("/logout", post(logout)) - .route("/verify-token", post(verify_token)); + .route("/verify-token", post(verify_token)) + .with_state(app_state); let listener = TcpListener::bind(address).await?; let address = listener.local_addr()?.to_string(); let server = axum::serve(listener, router); diff --git a/auth-service/src/main.rs b/auth-service/src/main.rs index 7bd4f17b0..8bcce7de9 100644 --- a/auth-service/src/main.rs +++ b/auth-service/src/main.rs @@ -3,6 +3,9 @@ use auth_service::Application; #[tokio::main] async fn main() { - let app = Application::build("0.0.0.0:3000").await.expect("Failed to build app"); + let user_store = auth_service::app_state::UserStoreType::default(); + let app_state = auth_service::app_state::AppState::new(user_store); + + let app = Application::build(app_state, "0.0.0.0:3000").await.expect("Failed to build app"); app.run().await.expect("Failed to run app"); } diff --git a/auth-service/src/routes/signup.rs b/auth-service/src/routes/signup.rs index 52a768399..33f021980 100644 --- a/auth-service/src/routes/signup.rs +++ b/auth-service/src/routes/signup.rs @@ -1,9 +1,22 @@ -use axum::{Json, http::StatusCode, response::IntoResponse}; -use serde::Deserialize; +use axum::{Json, extract::State, http::StatusCode, response::IntoResponse}; +use serde::{Deserialize, Serialize}; +use crate::{app_state::AppState, domain::user::User}; -pub async fn signup(Json(request): Json) -> impl IntoResponse { - StatusCode::OK.into_response() +pub async fn signup( + State(_state): State, + Json(request): Json, +) -> impl IntoResponse { + let user = User::new(request.email, request.password, request.requires_2fa); + + let mut user_store = _state.user_store.write().await; + user_store.add_user(user).unwrap(); + + let response = Json(SignupResponse { + message: "User created successfully!".to_string(), + }); + + (StatusCode::CREATED, response) } @@ -14,3 +27,9 @@ pub struct SignupRequest { #[serde(rename = "requires2FA")] requires_2fa: bool, } + + +#[derive(Serialize, PartialEq, Debug, Deserialize)] +pub struct SignupResponse { + pub message: String, +} diff --git a/auth-service/src/services/hashmap_user_store.rs b/auth-service/src/services/hashmap_user_store.rs new file mode 100644 index 000000000..f3c4c35e3 --- /dev/null +++ b/auth-service/src/services/hashmap_user_store.rs @@ -0,0 +1,69 @@ +use std::collections::HashMap; +use crate::domain::user::User; + + +#[derive(Debug, PartialEq,)] +pub enum UserStoreError { + UserNotFound, + UserAlreadyExists, + InvalidCredentials, + UnexpectedError, +} + + +#[derive(Default)] +pub struct HashmapUserStore { + pub users: HashMap, +} + + +impl HashmapUserStore { + pub fn add_user(&mut self, user: User) -> Result<(), UserStoreError> { + if self.users.contains_key(&user.email) { + return Err(UserStoreError::UserAlreadyExists); + } + self.users.insert(user.email.clone(), user); + Ok(()) + } + + pub fn get_user(&self, email: &str) -> Result<&User, UserStoreError> { + self.users.get(email).ok_or(UserStoreError::UserNotFound) + } + + pub fn validate_user(&self, email: &str, password: &str) -> Result<(), UserStoreError> { + let user = self.get_user(email)?; + if user.password != password { + return Err(UserStoreError::InvalidCredentials); + } + Ok(()) + } +} + + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_add_user() { + let mut store = HashmapUserStore::default(); + let user = User::new("test@example.com".to_string(), "password".to_string(), true); + assert!(store.add_user(user).is_ok()); + } + + #[test] + fn test_get_user() { + let mut store = HashmapUserStore::default(); + let user = User::new("test@example.com".to_string(), "password".to_string(), true); + store.add_user(user).unwrap(); + assert!(store.get_user("test@example.com").is_ok()); + } + + #[test] + fn test_validate_user() { + let mut store = HashmapUserStore::default(); + let user = User::new("test@example.com".to_string(), "password".to_string(), true); + store.add_user(user).unwrap(); + assert!(store.validate_user("test@example.com", "password").is_ok()); + } +} diff --git a/auth-service/src/services/mod.rs b/auth-service/src/services/mod.rs new file mode 100644 index 000000000..567ac6550 --- /dev/null +++ b/auth-service/src/services/mod.rs @@ -0,0 +1 @@ +pub mod hashmap_user_store; diff --git a/auth-service/tests/api/helpers.rs b/auth-service/tests/api/helpers.rs index ac9178aad..8ee7ec32d 100644 --- a/auth-service/tests/api/helpers.rs +++ b/auth-service/tests/api/helpers.rs @@ -1,4 +1,4 @@ -use auth_service::Application; +use auth_service::{Application, domain::user}; use reqwest; @@ -10,7 +10,10 @@ pub struct TestApp { impl TestApp { pub async fn run() -> Self { - let app = Application::build("127.0.0.1:0").await.expect("Failed to build application"); + let user_store = auth_service::app_state::UserStoreType::default(); + let app_state = auth_service::app_state::AppState::new(user_store); + + let app = Application::build(app_state, "127.0.0.1:0").await.expect("Failed to build application"); let address = format!("http://{}", app.address.clone()); #[allow(clippy::let_underscore_future)] diff --git a/auth-service/tests/api/signup.rs b/auth-service/tests/api/signup.rs index 2fece46af..974707a0c 100644 --- a/auth-service/tests/api/signup.rs +++ b/auth-service/tests/api/signup.rs @@ -3,6 +3,8 @@ use axum::body; mod tests { + use auth_service::routes::SignupResponse; + use axum::Json; use serde_json::json; use crate::helpers::get_random_email; @@ -27,4 +29,32 @@ mod tests { assert_eq!(response.status().as_u16(), 422, "Failed for body: {}", body); } } + + #[tokio::test] + async fn should_return_201_if_valid_input() { + let app = TestApp::run().await; + + let email = get_random_email(); + + let body = json!({ + "email": email, + "password": "securepassword", + "requires2FA": true + }); + + let response = app.post_signup(&body).await; + assert_eq!(response.status().as_u16(), 201); + + let expected_response = Json(SignupResponse { + message: "User created successfully!".to_owned(), + }); + + assert_eq!( + response + .json::() + .await + .expect("Could not deserialize response body to UserBody"), + expected_response.0 + ); + } } From ac7ae2a87fc424b0fe1595b34c2154081965f75a Mon Sep 17 00:00:00 2001 From: FedericoGambassi Date: Sat, 24 Jan 2026 15:11:20 +0100 Subject: [PATCH 07/17] [Sprint 2][Task 2] implement signup route error cases --- auth-service/src/domain/error.rs | 5 ++ auth-service/src/domain/mod.rs | 1 + auth-service/src/lib.rs | 27 +++++++++- auth-service/src/routes/signup.rs | 21 ++++++-- auth-service/tests/api/signup.rs | 88 ++++++++++++++++++++++++++++++- 5 files changed, 133 insertions(+), 9 deletions(-) create mode 100644 auth-service/src/domain/error.rs diff --git a/auth-service/src/domain/error.rs b/auth-service/src/domain/error.rs new file mode 100644 index 000000000..0465c5d67 --- /dev/null +++ b/auth-service/src/domain/error.rs @@ -0,0 +1,5 @@ +pub enum AuthAPIError { + InvalidCredentials, + UserAlreadyExists, + UnexpectedError, +} \ No newline at end of file diff --git a/auth-service/src/domain/mod.rs b/auth-service/src/domain/mod.rs index 22d12a382..66748a85a 100644 --- a/auth-service/src/domain/mod.rs +++ b/auth-service/src/domain/mod.rs @@ -1 +1,2 @@ pub mod user; +pub mod error; diff --git a/auth-service/src/lib.rs b/auth-service/src/lib.rs index 7175daa21..8f3a41fe8 100644 --- a/auth-service/src/lib.rs +++ b/auth-service/src/lib.rs @@ -1,5 +1,5 @@ use tokio::net::TcpListener; -use axum::{Router, routing::post, serve::Serve}; +use axum::{Json, Router, http::StatusCode, response::IntoResponse, routing::post, serve::Serve}; use tower_http::{services::{ServeDir, ServeFile}}; pub mod routes; @@ -8,7 +8,7 @@ pub mod services; pub mod app_state; use routes::*; -use domain::*; +use domain::{error::AuthAPIError}; use services::*; use app_state::AppState; @@ -16,6 +16,29 @@ use app_state::AppState; type Result = std::result::Result>; +#[derive(serde::Serialize, serde::Deserialize)] +pub struct ErrorResponse { + pub error: String, +} + + +impl IntoResponse for AuthAPIError { + fn into_response(self) -> axum::response::Response { + let (status, error_message) = match self { + AuthAPIError::InvalidCredentials => (StatusCode::BAD_REQUEST, "Invalid credentials"), + AuthAPIError::UserAlreadyExists => (StatusCode::CONFLICT, "User already exists"), + AuthAPIError::UnexpectedError => (StatusCode::INTERNAL_SERVER_ERROR, "Unexpected error"), + }; + + let body = Json(ErrorResponse { + error: error_message.to_string(), + }); + + (status, body).into_response() + } +} + + pub struct Application { server: Serve, pub address: String, diff --git a/auth-service/src/routes/signup.rs b/auth-service/src/routes/signup.rs index 33f021980..c154c5c9e 100644 --- a/auth-service/src/routes/signup.rs +++ b/auth-service/src/routes/signup.rs @@ -1,22 +1,33 @@ use axum::{Json, extract::State, http::StatusCode, response::IntoResponse}; use serde::{Deserialize, Serialize}; -use crate::{app_state::AppState, domain::user::User}; +use crate::{app_state::AppState, domain::{error::AuthAPIError, user::User}}; pub async fn signup( State(_state): State, Json(request): Json, -) -> impl IntoResponse { - let user = User::new(request.email, request.password, request.requires_2fa); +) -> Result { + let email = request.email; + let password = request.password; + + // early return AuthAPIError::InvalidCredentials if email is empty or does not contain "@" symbol or password is less than 8 characters long + if email.is_empty() || !email.contains('@') || password.len() < 8 { + return Err(AuthAPIError::InvalidCredentials); + } + + let user = User::new(email, password, request.requires_2fa); let mut user_store = _state.user_store.write().await; - user_store.add_user(user).unwrap(); + if user_store.get_user(&user.email).is_ok() { + return Err(AuthAPIError::UserAlreadyExists); + } + user_store.add_user(user).map_err(|_| AuthAPIError::UnexpectedError)?; let response = Json(SignupResponse { message: "User created successfully!".to_string(), }); - (StatusCode::CREATED, response) + Ok((StatusCode::CREATED, response)) } diff --git a/auth-service/tests/api/signup.rs b/auth-service/tests/api/signup.rs index 974707a0c..b0c6a0538 100644 --- a/auth-service/tests/api/signup.rs +++ b/auth-service/tests/api/signup.rs @@ -3,7 +3,7 @@ use axum::body; mod tests { - use auth_service::routes::SignupResponse; + use auth_service::{ErrorResponse, routes::SignupResponse}; use axum::Json; use serde_json::json; @@ -57,4 +57,88 @@ mod tests { expected_response.0 ); } -} + + #[tokio::test] + async fn should_return_400_if_invalid_input() { + // the input is considered invalid if: + // - the email is empty or does not contain an "@" symbol + // - the password is less than 8 characters long + + // create an array of invalid inputs, then iterate over them and assert that the response status is 400 + let app = TestApp::run().await; + let test_cases = [ + json!({ + "email": "", + "password": "securepassword", + "requires2FA": true + }), + json!({ + "email": "invalidemail.com", + "password": "securepassword", + "requires2FA": true + }), + json!({ + "email": get_random_email(), + "password": "short", + "requires2FA": true + }), + ]; + + for body in test_cases { + let response = app.post_signup(&body).await; + assert_eq!(response.status().as_u16(), 400, "Failed for body: {}", body); + + assert_eq!( + response + .json::() + .await + .expect("Could not deserialize response body to Value") + .error, + "Invalid credentials".to_string(), + ); + } + + } + + #[tokio::test] + async fn should_return_409_if_email_already_exists() { + let app = TestApp::run().await; + + let email = get_random_email(); + + let body = json!({ + "email": email, + "password": "securepassword", + "requires2FA": true + }); + + // first signup attempt should succeed + let response = app.post_signup(&body).await; + assert_eq!(response.status().as_u16(), 201); + + let expected_response = Json(SignupResponse { + message: "User created successfully!".to_owned(), + }); + + assert_eq!( + response + .json::() + .await + .expect("Could not deserialize response body to UserBody"), + expected_response.0 + ); + + // second signup attempt with the same email should fail + let response = app.post_signup(&body).await; + assert_eq!(response.status().as_u16(), 409); + + assert_eq!( + response + .json::() + .await + .expect("Could not deserialize response body to Value") + .error, + "User already exists".to_string(), + ); + } +} \ No newline at end of file From f61ed49c1683ac83303228a5f3ec57dd663fe907 Mon Sep 17 00:00:00 2001 From: FedericoGambassi Date: Sat, 24 Jan 2026 21:45:08 +0100 Subject: [PATCH 08/17] [Sprint 2][Task 3] implement SOLID design --- auth-service/Cargo.lock | 12 +++++ auth-service/Cargo.toml | 2 + auth-service/src/app_state.rs | 30 ++++++++++-- auth-service/src/domain/error.rs | 2 +- auth-service/src/domain/user.rs | 1 + auth-service/src/lib.rs | 4 -- auth-service/src/main.rs | 6 +-- auth-service/src/routes/signup.rs | 4 +- auth-service/src/services/data_store.rs | 18 +++++++ .../src/services/hashmap_user_store.rs | 48 ++++++++----------- auth-service/src/services/mod.rs | 1 + auth-service/tests/api/helpers.rs | 7 ++- auth-service/tests/api/login.rs | 1 - auth-service/tests/api/logout.rs | 1 - auth-service/tests/api/root.rs | 1 - auth-service/tests/api/signup.rs | 3 -- auth-service/tests/api/verify_2fa.rs | 1 - auth-service/tests/api/verify_token.rs | 1 - 18 files changed, 90 insertions(+), 53 deletions(-) create mode 100644 auth-service/src/services/data_store.rs diff --git a/auth-service/Cargo.lock b/auth-service/Cargo.lock index 91dad88a1..d85a56334 100644 --- a/auth-service/Cargo.lock +++ b/auth-service/Cargo.lock @@ -2,6 +2,17 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "async-trait" +version = "0.1.89" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "atomic-waker" version = "1.1.2" @@ -12,6 +23,7 @@ checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" name = "auth-service" version = "0.1.0" dependencies = [ + "async-trait", "axum", "reqwest", "serde", diff --git a/auth-service/Cargo.toml b/auth-service/Cargo.toml index 1322d8c64..49b6d70aa 100644 --- a/auth-service/Cargo.toml +++ b/auth-service/Cargo.toml @@ -12,6 +12,8 @@ serde_json = "1.0.145" uuid = { version = "1.18.1", default-features = false, features = ["v4", "serde"] } tokio = { version = "1.48.0", features = ["full"] } tower-http = { version = "0.6.6", features = ["fs"] } +async-trait = "0.1.89" + [dev-dependencies] reqwest = { version = "0.13.1", default-features = false, features = ["json"] } diff --git a/auth-service/src/app_state.rs b/auth-service/src/app_state.rs index a5ffa1afc..c19ec2d72 100644 --- a/auth-service/src/app_state.rs +++ b/auth-service/src/app_state.rs @@ -1,9 +1,25 @@ -use std::sync::Arc; +use std::{ops::Deref, sync::Arc}; use tokio::sync::RwLock; -use crate::services::hashmap_user_store::HashmapUserStore; +use crate::services::{data_store::UserStore, hashmap_user_store::HashmapUserStore}; -pub type UserStoreType = Arc>; +#[derive(Clone)] +pub struct UserStoreType(pub Arc>>); + +impl Deref for UserStoreType { + type Target = Arc>>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Default for UserStoreType { + fn default() -> Self { + let store: Box = Box::new(HashmapUserStore::default()); + Self(Arc::new(RwLock::new(store))) + } +} #[derive(Clone)] @@ -15,4 +31,12 @@ impl AppState { pub fn new(user_store: UserStoreType) -> Self { Self { user_store } } + + // // Optional ergonomic constructor (useful for DI/tests) + // pub fn with_store(store: impl UserStore + 'static) -> Self { + // let store: Box = Box::new(store); + // Self { + // user_store: UserStoreType(Arc::new(RwLock::new(store))), + // } + // } } diff --git a/auth-service/src/domain/error.rs b/auth-service/src/domain/error.rs index 0465c5d67..1d7e49a9b 100644 --- a/auth-service/src/domain/error.rs +++ b/auth-service/src/domain/error.rs @@ -2,4 +2,4 @@ pub enum AuthAPIError { InvalidCredentials, UserAlreadyExists, UnexpectedError, -} \ No newline at end of file +} diff --git a/auth-service/src/domain/user.rs b/auth-service/src/domain/user.rs index 8cf4bb75e..8f97489c9 100644 --- a/auth-service/src/domain/user.rs +++ b/auth-service/src/domain/user.rs @@ -1,3 +1,4 @@ +#[derive(Clone)] pub struct User { pub requires_2fa: bool, pub password: String, diff --git a/auth-service/src/lib.rs b/auth-service/src/lib.rs index 8f3a41fe8..428720f76 100644 --- a/auth-service/src/lib.rs +++ b/auth-service/src/lib.rs @@ -9,7 +9,6 @@ pub mod app_state; use routes::*; use domain::{error::AuthAPIError}; -use services::*; use app_state::AppState; @@ -70,6 +69,3 @@ impl Application { Ok(()) } } - - - diff --git a/auth-service/src/main.rs b/auth-service/src/main.rs index 8bcce7de9..7754ce998 100644 --- a/auth-service/src/main.rs +++ b/auth-service/src/main.rs @@ -1,10 +1,10 @@ -use auth_service::Application; +use auth_service::{Application, app_state::{AppState, UserStoreType}}; #[tokio::main] async fn main() { - let user_store = auth_service::app_state::UserStoreType::default(); - let app_state = auth_service::app_state::AppState::new(user_store); + let user_store = UserStoreType::default(); + let app_state = AppState::new(user_store); // optionally, if builder pattern enabled: AppState::with_store(hashmap_store).build(); let app = Application::build(app_state, "0.0.0.0:3000").await.expect("Failed to build app"); app.run().await.expect("Failed to run app"); diff --git a/auth-service/src/routes/signup.rs b/auth-service/src/routes/signup.rs index c154c5c9e..39f450356 100644 --- a/auth-service/src/routes/signup.rs +++ b/auth-service/src/routes/signup.rs @@ -18,10 +18,10 @@ pub async fn signup( let user = User::new(email, password, request.requires_2fa); let mut user_store = _state.user_store.write().await; - if user_store.get_user(&user.email).is_ok() { + if user_store.get_user(&user.email).await.is_ok() { return Err(AuthAPIError::UserAlreadyExists); } - user_store.add_user(user).map_err(|_| AuthAPIError::UnexpectedError)?; + user_store.add_user(user).await.map_err(|_| AuthAPIError::UnexpectedError)?; let response = Json(SignupResponse { message: "User created successfully!".to_string(), diff --git a/auth-service/src/services/data_store.rs b/auth-service/src/services/data_store.rs new file mode 100644 index 000000000..4930debf4 --- /dev/null +++ b/auth-service/src/services/data_store.rs @@ -0,0 +1,18 @@ +use crate::domain::user::User; + + +#[derive(Debug, PartialEq,)] +pub enum UserStoreError { + UserNotFound, + UserAlreadyExists, + InvalidCredentials, + UnexpectedError, +} + + +#[async_trait::async_trait] +pub trait UserStore: Send + Sync { + async fn add_user(&mut self, user: User) -> Result<(), UserStoreError>; + async fn get_user(&self, email: &str) -> Result; + async fn validate_user(&self, email: &str, password: &str) -> Result<(), UserStoreError>; +} diff --git a/auth-service/src/services/hashmap_user_store.rs b/auth-service/src/services/hashmap_user_store.rs index f3c4c35e3..c8c9afc8f 100644 --- a/auth-service/src/services/hashmap_user_store.rs +++ b/auth-service/src/services/hashmap_user_store.rs @@ -1,24 +1,16 @@ use std::collections::HashMap; use crate::domain::user::User; - - -#[derive(Debug, PartialEq,)] -pub enum UserStoreError { - UserNotFound, - UserAlreadyExists, - InvalidCredentials, - UnexpectedError, -} +use super::data_store::{UserStore, UserStoreError}; #[derive(Default)] pub struct HashmapUserStore { - pub users: HashMap, + users: HashMap, } - -impl HashmapUserStore { - pub fn add_user(&mut self, user: User) -> Result<(), UserStoreError> { +#[async_trait::async_trait] +impl UserStore for HashmapUserStore { + async fn add_user(&mut self, user: User) -> Result<(), UserStoreError> { if self.users.contains_key(&user.email) { return Err(UserStoreError::UserAlreadyExists); } @@ -26,12 +18,12 @@ impl HashmapUserStore { Ok(()) } - pub fn get_user(&self, email: &str) -> Result<&User, UserStoreError> { - self.users.get(email).ok_or(UserStoreError::UserNotFound) + async fn get_user(&self, email: &str) -> Result { + self.users.get(email).cloned().ok_or(UserStoreError::UserNotFound) } - pub fn validate_user(&self, email: &str, password: &str) -> Result<(), UserStoreError> { - let user = self.get_user(email)?; + async fn validate_user(&self, email: &str, password: &str) -> Result<(), UserStoreError> { + let user = self.get_user(email).await?; if user.password != password { return Err(UserStoreError::InvalidCredentials); } @@ -44,26 +36,26 @@ impl HashmapUserStore { mod tests { use super::*; - #[test] - fn test_add_user() { + #[tokio::test] + async fn test_add_user() { let mut store = HashmapUserStore::default(); let user = User::new("test@example.com".to_string(), "password".to_string(), true); - assert!(store.add_user(user).is_ok()); + assert!(store.add_user(user).await.is_ok()); } - #[test] - fn test_get_user() { + #[tokio::test] + async fn test_get_user() { let mut store = HashmapUserStore::default(); let user = User::new("test@example.com".to_string(), "password".to_string(), true); - store.add_user(user).unwrap(); - assert!(store.get_user("test@example.com").is_ok()); + store.add_user(user).await.unwrap(); + assert!(store.get_user("test@example.com").await.is_ok()); } - #[test] - fn test_validate_user() { + #[tokio::test] + async fn test_validate_user() { let mut store = HashmapUserStore::default(); let user = User::new("test@example.com".to_string(), "password".to_string(), true); - store.add_user(user).unwrap(); - assert!(store.validate_user("test@example.com", "password").is_ok()); + store.add_user(user).await.unwrap(); + assert!(store.validate_user("test@example.com", "password").await.is_ok()); } } diff --git a/auth-service/src/services/mod.rs b/auth-service/src/services/mod.rs index 567ac6550..3545381c9 100644 --- a/auth-service/src/services/mod.rs +++ b/auth-service/src/services/mod.rs @@ -1 +1,2 @@ pub mod hashmap_user_store; +pub mod data_store; diff --git a/auth-service/tests/api/helpers.rs b/auth-service/tests/api/helpers.rs index 8ee7ec32d..f04473bea 100644 --- a/auth-service/tests/api/helpers.rs +++ b/auth-service/tests/api/helpers.rs @@ -1,8 +1,7 @@ -use auth_service::{Application, domain::user}; +use auth_service::{Application, app_state::{AppState, UserStoreType}}; use reqwest; - pub struct TestApp { pub address: String, pub client: reqwest::Client, @@ -10,8 +9,8 @@ pub struct TestApp { impl TestApp { pub async fn run() -> Self { - let user_store = auth_service::app_state::UserStoreType::default(); - let app_state = auth_service::app_state::AppState::new(user_store); + let user_store = UserStoreType::default(); + let app_state = AppState::new(user_store); let app = Application::build(app_state, "127.0.0.1:0").await.expect("Failed to build application"); let address = format!("http://{}", app.address.clone()); diff --git a/auth-service/tests/api/login.rs b/auth-service/tests/api/login.rs index 05a02f8ad..15329dbeb 100644 --- a/auth-service/tests/api/login.rs +++ b/auth-service/tests/api/login.rs @@ -1,5 +1,4 @@ use crate::helpers::TestApp; -use axum::body; mod tests { diff --git a/auth-service/tests/api/logout.rs b/auth-service/tests/api/logout.rs index 7a95b753d..c3fe103cb 100644 --- a/auth-service/tests/api/logout.rs +++ b/auth-service/tests/api/logout.rs @@ -1,5 +1,4 @@ use crate::helpers::TestApp; -use axum::body; mod tests { diff --git a/auth-service/tests/api/root.rs b/auth-service/tests/api/root.rs index f240b4cc9..7bd96e9cd 100644 --- a/auth-service/tests/api/root.rs +++ b/auth-service/tests/api/root.rs @@ -1,5 +1,4 @@ use crate::helpers::TestApp; -use axum::body; mod tests { diff --git a/auth-service/tests/api/signup.rs b/auth-service/tests/api/signup.rs index b0c6a0538..2cb9ba0c8 100644 --- a/auth-service/tests/api/signup.rs +++ b/auth-service/tests/api/signup.rs @@ -1,5 +1,4 @@ use crate::helpers::TestApp; -use axum::body; mod tests { @@ -15,8 +14,6 @@ mod tests { async fn should_return_422_if_malformed_input() { let app = TestApp::run().await; - let email = get_random_email(); - let test_cases = [ json!({ "password": "password", diff --git a/auth-service/tests/api/verify_2fa.rs b/auth-service/tests/api/verify_2fa.rs index 161efeab0..099de666d 100644 --- a/auth-service/tests/api/verify_2fa.rs +++ b/auth-service/tests/api/verify_2fa.rs @@ -1,5 +1,4 @@ use crate::helpers::TestApp; -use axum::body; mod tests { diff --git a/auth-service/tests/api/verify_token.rs b/auth-service/tests/api/verify_token.rs index f79d62232..3ae52a5d9 100644 --- a/auth-service/tests/api/verify_token.rs +++ b/auth-service/tests/api/verify_token.rs @@ -1,5 +1,4 @@ use crate::helpers::TestApp; -use axum::body; mod tests { From 1f7e79ce9bdf384f32af16eaff90b0fbc6251591 Mon Sep 17 00:00:00 2001 From: FedericoGambassi Date: Sun, 25 Jan 2026 11:14:25 +0100 Subject: [PATCH 09/17] refactor:switched to interior mutability for UserStore concrete implementations --- auth-service/src/app_state.rs | 7 +++---- auth-service/src/routes/signup.rs | 2 +- auth-service/src/services/data_store.rs | 2 +- .../src/services/hashmap_user_store.rs | 18 ++++++++++-------- 4 files changed, 15 insertions(+), 14 deletions(-) diff --git a/auth-service/src/app_state.rs b/auth-service/src/app_state.rs index c19ec2d72..1d1460cb5 100644 --- a/auth-service/src/app_state.rs +++ b/auth-service/src/app_state.rs @@ -1,13 +1,12 @@ use std::{ops::Deref, sync::Arc}; -use tokio::sync::RwLock; use crate::services::{data_store::UserStore, hashmap_user_store::HashmapUserStore}; #[derive(Clone)] -pub struct UserStoreType(pub Arc>>); +pub struct UserStoreType(pub Arc>); impl Deref for UserStoreType { - type Target = Arc>>; + type Target = Arc>; fn deref(&self) -> &Self::Target { &self.0 @@ -17,7 +16,7 @@ impl Deref for UserStoreType { impl Default for UserStoreType { fn default() -> Self { let store: Box = Box::new(HashmapUserStore::default()); - Self(Arc::new(RwLock::new(store))) + Self(Arc::new(store)) } } diff --git a/auth-service/src/routes/signup.rs b/auth-service/src/routes/signup.rs index 39f450356..b3744b2b8 100644 --- a/auth-service/src/routes/signup.rs +++ b/auth-service/src/routes/signup.rs @@ -17,7 +17,7 @@ pub async fn signup( let user = User::new(email, password, request.requires_2fa); - let mut user_store = _state.user_store.write().await; + let user_store = _state.user_store; if user_store.get_user(&user.email).await.is_ok() { return Err(AuthAPIError::UserAlreadyExists); } diff --git a/auth-service/src/services/data_store.rs b/auth-service/src/services/data_store.rs index 4930debf4..c3cd442df 100644 --- a/auth-service/src/services/data_store.rs +++ b/auth-service/src/services/data_store.rs @@ -12,7 +12,7 @@ pub enum UserStoreError { #[async_trait::async_trait] pub trait UserStore: Send + Sync { - async fn add_user(&mut self, user: User) -> Result<(), UserStoreError>; + async fn add_user(&self, user: User) -> Result<(), UserStoreError>; async fn get_user(&self, email: &str) -> Result; async fn validate_user(&self, email: &str, password: &str) -> Result<(), UserStoreError>; } diff --git a/auth-service/src/services/hashmap_user_store.rs b/auth-service/src/services/hashmap_user_store.rs index c8c9afc8f..0b72e3671 100644 --- a/auth-service/src/services/hashmap_user_store.rs +++ b/auth-service/src/services/hashmap_user_store.rs @@ -1,25 +1,27 @@ use std::collections::HashMap; +use tokio::sync::RwLock; + use crate::domain::user::User; use super::data_store::{UserStore, UserStoreError}; #[derive(Default)] pub struct HashmapUserStore { - users: HashMap, + users: RwLock>, } #[async_trait::async_trait] impl UserStore for HashmapUserStore { - async fn add_user(&mut self, user: User) -> Result<(), UserStoreError> { - if self.users.contains_key(&user.email) { + async fn add_user(&self, user: User) -> Result<(), UserStoreError> { + if self.users.read().await.contains_key(&user.email) { return Err(UserStoreError::UserAlreadyExists); } - self.users.insert(user.email.clone(), user); + self.users.write().await.insert(user.email.clone(), user); Ok(()) } async fn get_user(&self, email: &str) -> Result { - self.users.get(email).cloned().ok_or(UserStoreError::UserNotFound) + self.users.read().await.get(email).cloned().ok_or(UserStoreError::UserNotFound) } async fn validate_user(&self, email: &str, password: &str) -> Result<(), UserStoreError> { @@ -38,14 +40,14 @@ mod tests { #[tokio::test] async fn test_add_user() { - let mut store = HashmapUserStore::default(); + let store = HashmapUserStore::default(); let user = User::new("test@example.com".to_string(), "password".to_string(), true); assert!(store.add_user(user).await.is_ok()); } #[tokio::test] async fn test_get_user() { - let mut store = HashmapUserStore::default(); + let store = HashmapUserStore::default(); let user = User::new("test@example.com".to_string(), "password".to_string(), true); store.add_user(user).await.unwrap(); assert!(store.get_user("test@example.com").await.is_ok()); @@ -53,7 +55,7 @@ mod tests { #[tokio::test] async fn test_validate_user() { - let mut store = HashmapUserStore::default(); + let store = HashmapUserStore::default(); let user = User::new("test@example.com".to_string(), "password".to_string(), true); store.add_user(user).await.unwrap(); assert!(store.validate_user("test@example.com", "password").await.is_ok()); From b73411b22d407422f5449057ff9a0b72ff6ad36e Mon Sep 17 00:00:00 2001 From: FedericoGambassi Date: Sun, 25 Jan 2026 11:58:00 +0100 Subject: [PATCH 10/17] [Sprint 2][Task 4] implement type-driven design --- auth-service/src/domain/email.rs | 39 +++++++++++++++++++ auth-service/src/domain/mod.rs | 2 + auth-service/src/domain/password.rs | 36 +++++++++++++++++ auth-service/src/domain/user.rs | 8 ++-- auth-service/src/routes/signup.rs | 9 ++--- auth-service/src/services/data_store.rs | 6 +-- .../src/services/hashmap_user_store.rs | 28 +++++++------ 7 files changed, 106 insertions(+), 22 deletions(-) create mode 100644 auth-service/src/domain/email.rs create mode 100644 auth-service/src/domain/password.rs diff --git a/auth-service/src/domain/email.rs b/auth-service/src/domain/email.rs new file mode 100644 index 000000000..de0c33f02 --- /dev/null +++ b/auth-service/src/domain/email.rs @@ -0,0 +1,39 @@ +#[derive(Clone)] +pub struct Email(String); + +impl Email { + pub fn parse(s: String) -> Result { + if !s.is_empty() && s.contains('@') { + Ok(Email(s)) + } else { + Err(format!("'{}' is not a valid email address.", s)) + } + } +} + +impl AsRef for Email { + fn as_ref(&self) -> &str { + &self.0 + } +} + + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_email_parse() { + let email = Email::parse("test@example.com".to_string()).unwrap(); + assert_eq!(email.as_ref(), "test@example.com"); + } + + #[test] + fn test_email_parse_invalid() { + let result = Email::parse("invalid-email".to_string()); + assert!(result.is_err()); + + let result = Email::parse("".to_string()); + assert!(result.is_err()); + } +} diff --git a/auth-service/src/domain/mod.rs b/auth-service/src/domain/mod.rs index 66748a85a..76ec1692f 100644 --- a/auth-service/src/domain/mod.rs +++ b/auth-service/src/domain/mod.rs @@ -1,2 +1,4 @@ pub mod user; pub mod error; +pub mod email; +pub mod password; diff --git a/auth-service/src/domain/password.rs b/auth-service/src/domain/password.rs new file mode 100644 index 000000000..79a023783 --- /dev/null +++ b/auth-service/src/domain/password.rs @@ -0,0 +1,36 @@ +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Password(String); + +impl Password { + pub fn parse(s: String) -> Result { + if s.len() < 8 { + Err("Password must be at least 8 characters long".to_string()) + } else { + Ok(Password(s)) + } + } +} + +impl AsRef for Password { + fn as_ref(&self) -> &str { + &self.0 + } +} + + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_password_parse() { + let password = Password::parse("strongpassword".to_string()).unwrap(); + assert_eq!(password.as_ref(), "strongpassword"); + } + + #[test] + fn test_password_parse_invalid() { + let result = Password::parse("short".to_string()); + assert!(result.is_err()); + } +} diff --git a/auth-service/src/domain/user.rs b/auth-service/src/domain/user.rs index 8f97489c9..223ff50ba 100644 --- a/auth-service/src/domain/user.rs +++ b/auth-service/src/domain/user.rs @@ -1,12 +1,14 @@ +use crate::domain::{email::Email, password::Password}; + #[derive(Clone)] pub struct User { pub requires_2fa: bool, - pub password: String, - pub email: String, + pub password: Password, + pub email: Email, } impl User { - pub fn new(email: String, password: String, requires_2fa: bool) -> Self { + pub fn new(email: Email, password: Password, requires_2fa: bool) -> Self { Self { email, password, diff --git a/auth-service/src/routes/signup.rs b/auth-service/src/routes/signup.rs index b3744b2b8..9a5e67755 100644 --- a/auth-service/src/routes/signup.rs +++ b/auth-service/src/routes/signup.rs @@ -1,6 +1,6 @@ use axum::{Json, extract::State, http::StatusCode, response::IntoResponse}; use serde::{Deserialize, Serialize}; -use crate::{app_state::AppState, domain::{error::AuthAPIError, user::User}}; +use crate::{app_state::AppState, domain::{email::Email, error::AuthAPIError, password::Password, user::User}}; pub async fn signup( @@ -11,14 +11,13 @@ pub async fn signup( let password = request.password; // early return AuthAPIError::InvalidCredentials if email is empty or does not contain "@" symbol or password is less than 8 characters long - if email.is_empty() || !email.contains('@') || password.len() < 8 { - return Err(AuthAPIError::InvalidCredentials); - } + let email = Email::parse(email).map_err(|_| AuthAPIError::InvalidCredentials)?; + let password = Password::parse(password).map_err(|_| AuthAPIError::InvalidCredentials)?; let user = User::new(email, password, request.requires_2fa); let user_store = _state.user_store; - if user_store.get_user(&user.email).await.is_ok() { + if user_store.get_user(user.email.clone()).await.is_ok() { return Err(AuthAPIError::UserAlreadyExists); } user_store.add_user(user).await.map_err(|_| AuthAPIError::UnexpectedError)?; diff --git a/auth-service/src/services/data_store.rs b/auth-service/src/services/data_store.rs index c3cd442df..aaf84f289 100644 --- a/auth-service/src/services/data_store.rs +++ b/auth-service/src/services/data_store.rs @@ -1,4 +1,4 @@ -use crate::domain::user::User; +use crate::domain::{email::Email, password::Password, user::User}; #[derive(Debug, PartialEq,)] @@ -13,6 +13,6 @@ pub enum UserStoreError { #[async_trait::async_trait] pub trait UserStore: Send + Sync { async fn add_user(&self, user: User) -> Result<(), UserStoreError>; - async fn get_user(&self, email: &str) -> Result; - async fn validate_user(&self, email: &str, password: &str) -> Result<(), UserStoreError>; + async fn get_user(&self, email: Email) -> Result; + async fn validate_user(&self, email: Email, password: Password) -> Result<(), UserStoreError>; } diff --git a/auth-service/src/services/hashmap_user_store.rs b/auth-service/src/services/hashmap_user_store.rs index 0b72e3671..47a21fbd2 100644 --- a/auth-service/src/services/hashmap_user_store.rs +++ b/auth-service/src/services/hashmap_user_store.rs @@ -1,7 +1,7 @@ use std::collections::HashMap; use tokio::sync::RwLock; -use crate::domain::user::User; +use crate::domain::{email::Email, password::Password, user::User}; use super::data_store::{UserStore, UserStoreError}; @@ -13,18 +13,18 @@ pub struct HashmapUserStore { #[async_trait::async_trait] impl UserStore for HashmapUserStore { async fn add_user(&self, user: User) -> Result<(), UserStoreError> { - if self.users.read().await.contains_key(&user.email) { + if self.users.read().await.contains_key(user.email.as_ref()) { return Err(UserStoreError::UserAlreadyExists); } - self.users.write().await.insert(user.email.clone(), user); + self.users.write().await.insert(user.email.as_ref().to_string(), user); Ok(()) } - async fn get_user(&self, email: &str) -> Result { - self.users.read().await.get(email).cloned().ok_or(UserStoreError::UserNotFound) + async fn get_user(&self, email: Email) -> Result { + self.users.read().await.get(email.as_ref()).cloned().ok_or(UserStoreError::UserNotFound) } - async fn validate_user(&self, email: &str, password: &str) -> Result<(), UserStoreError> { + async fn validate_user(&self, email: Email, password: Password) -> Result<(), UserStoreError> { let user = self.get_user(email).await?; if user.password != password { return Err(UserStoreError::InvalidCredentials); @@ -41,23 +41,29 @@ mod tests { #[tokio::test] async fn test_add_user() { let store = HashmapUserStore::default(); - let user = User::new("test@example.com".to_string(), "password".to_string(), true); + let email = Email::parse("test@example.com".to_string()).unwrap(); + let password = Password::parse("password".to_string()).unwrap(); + let user = User::new(email, password, true); assert!(store.add_user(user).await.is_ok()); } #[tokio::test] async fn test_get_user() { let store = HashmapUserStore::default(); - let user = User::new("test@example.com".to_string(), "password".to_string(), true); + let email = Email::parse("test@example.com".to_string()).unwrap(); + let password = Password::parse("password".to_string()).unwrap(); + let user = User::new(email.clone(), password, true); store.add_user(user).await.unwrap(); - assert!(store.get_user("test@example.com").await.is_ok()); + assert!(store.get_user(email).await.is_ok()); } #[tokio::test] async fn test_validate_user() { let store = HashmapUserStore::default(); - let user = User::new("test@example.com".to_string(), "password".to_string(), true); + let email = Email::parse("test@example.com".to_string()).unwrap(); + let password = Password::parse("password".to_string()).unwrap(); + let user = User::new(email.clone(), password.clone(), true); store.add_user(user).await.unwrap(); - assert!(store.validate_user("test@example.com", "password").await.is_ok()); + assert!(store.validate_user(email, password).await.is_ok()); } } From ade73699cafefb166e48368cba08abc43bbecd09 Mon Sep 17 00:00:00 2001 From: FedericoGambassi Date: Sun, 25 Jan 2026 17:23:44 +0100 Subject: [PATCH 11/17] [Sprint 3][Task 1] implement login route error cases --- auth-service/src/domain/error.rs | 2 + auth-service/src/lib.rs | 2 + auth-service/src/routes/login.rs | 43 +++++++++++++-- auth-service/tests/api/helpers.rs | 4 +- auth-service/tests/api/login.rs | 90 +++++++++++++++++++++++++++++-- 5 files changed, 132 insertions(+), 9 deletions(-) diff --git a/auth-service/src/domain/error.rs b/auth-service/src/domain/error.rs index 1d7e49a9b..98d1b134a 100644 --- a/auth-service/src/domain/error.rs +++ b/auth-service/src/domain/error.rs @@ -1,5 +1,7 @@ pub enum AuthAPIError { + MalformedRequest, InvalidCredentials, + IncorrectCredentials, UserAlreadyExists, UnexpectedError, } diff --git a/auth-service/src/lib.rs b/auth-service/src/lib.rs index 428720f76..aff215073 100644 --- a/auth-service/src/lib.rs +++ b/auth-service/src/lib.rs @@ -24,7 +24,9 @@ pub struct ErrorResponse { impl IntoResponse for AuthAPIError { fn into_response(self) -> axum::response::Response { let (status, error_message) = match self { + AuthAPIError::MalformedRequest => (StatusCode::UNPROCESSABLE_ENTITY, "Malformed request"), AuthAPIError::InvalidCredentials => (StatusCode::BAD_REQUEST, "Invalid credentials"), + AuthAPIError::IncorrectCredentials => (StatusCode::UNAUTHORIZED, "Incorrect credentials"), AuthAPIError::UserAlreadyExists => (StatusCode::CONFLICT, "User already exists"), AuthAPIError::UnexpectedError => (StatusCode::INTERNAL_SERVER_ERROR, "Unexpected error"), }; diff --git a/auth-service/src/routes/login.rs b/auth-service/src/routes/login.rs index 0dbb10060..f5358bfce 100644 --- a/auth-service/src/routes/login.rs +++ b/auth-service/src/routes/login.rs @@ -1,6 +1,43 @@ -use axum::{response::IntoResponse, http::StatusCode}; +use axum::{Json, extract::State, http::StatusCode, response::IntoResponse}; +use serde::{Deserialize, Serialize}; +use crate::{app_state::AppState, domain::{email::Email, error::AuthAPIError, password::Password}}; -pub async fn login() -> impl IntoResponse { - StatusCode::OK.into_response() +pub async fn login( + State(_state): State, + Json(request): Json, +) -> Result { + let email = request.email; + let password = request.password; + + // early return AuthAPIError::InvalidCredentials if email is empty or does not contain "@" symbol or password is less than 8 characters long + let email = Email::parse(email).map_err(|_| AuthAPIError::InvalidCredentials)?; + let password = Password::parse(password).map_err(|_| AuthAPIError::InvalidCredentials)?; + + let user_store = &_state.user_store; + match user_store.get_user(email).await { + Ok(user) => { + if user.password != password { + return Err(AuthAPIError::IncorrectCredentials); + } + } + Err(_) => { + return Err(AuthAPIError::IncorrectCredentials); + } + } + + Ok(StatusCode::OK.into_response()) +} + + +#[derive(Deserialize)] +pub struct LoginRequest { + email: String, + password: String, +} + + +#[derive(Serialize, PartialEq, Debug, Deserialize)] +pub struct LoginResponse { + pub message: String, } diff --git a/auth-service/tests/api/helpers.rs b/auth-service/tests/api/helpers.rs index f04473bea..f332b39c1 100644 --- a/auth-service/tests/api/helpers.rs +++ b/auth-service/tests/api/helpers.rs @@ -39,7 +39,9 @@ impl TestApp { .expect("Failed to execute request.") } - pub async fn post_login(&self, body: &serde_json::Value) -> reqwest::Response { + pub async fn post_login(&self, body: &Body) -> reqwest::Response + where Body: serde::Serialize + { self.client .post(format!("{}/login", &self.address)) .json(body) diff --git a/auth-service/tests/api/login.rs b/auth-service/tests/api/login.rs index 15329dbeb..ce70a186b 100644 --- a/auth-service/tests/api/login.rs +++ b/auth-service/tests/api/login.rs @@ -5,13 +5,93 @@ mod tests { use super::*; #[tokio::test] - async fn test_login() { + async fn should_return_422_if_malformed_credentials() { let app = TestApp::run().await; - let body = serde_json::json!({ + + let test_cases = vec![ + serde_json::json!({ + "mail": "user@example.com", + "password": "password123", + }), + serde_json::json!({ + "email": "user@example.com", + "passgword": "password123", + }), + serde_json::json!({ + "email": "user@example.com", + }), + serde_json::json!({ + "password": "password123", + }), + serde_json::json!({}), + ]; + + for case in test_cases { + let response = app.post_login(&case).await; + + assert_eq!(response.status().as_u16(), 422); + } + } + + #[tokio::test] + async fn should_return_400_if_invalid_input() { + let app = TestApp::run().await; + + let test_cases = vec![ + serde_json::json!({ + "email": "invalid-email", + "password": "password123", + }), + serde_json::json!({ + "email": "user@example.com", + "password": "pass", + }), + serde_json::json!({ + "email": "", + "password": "", + }), + ]; + + for case in test_cases { + let response = app.post_login(&case).await; + + assert_eq!(response.status().as_u16(), 400); + } + } + + #[tokio::test] + async fn should_return_401_if_incorrect_credentials() { + let app = TestApp::run().await; + + // Create a user in the test database + let request_body = serde_json::json!({ + "email": "user@example.com", + "password": "password123", + "requires2FA": false, + }); + + let response = app.post_signup(&request_body).await; + + assert_eq!(response.status().as_u16(), 201); + + // Attempt to login with incorrect password + let wrong_password_body = serde_json::json!({ "email": "user@example.com", - "password": "password" + "password": "wrongpassword", }); - let response = app.post_login(&body).await; - assert_eq!(response.status().as_u16(), 200); + + let response = app.post_login(&wrong_password_body).await; + + assert_eq!(response.status().as_u16(), 401); + + // Attempt to login with non-existent email + let non_existent_email_body = serde_json::json!({ + "email": "foo@example.com", + "password": "password123", + }); + + let response = app.post_login(&non_existent_email_body).await; + + assert_eq!(response.status().as_u16(), 401); } } From 326c3e6c973a63896b53c94495c3edfe29e34fd7 Mon Sep 17 00:00:00 2001 From: FedericoGambassi Date: Tue, 27 Jan 2026 19:53:03 +0100 Subject: [PATCH 12/17] [Sprint 3][Task 2] implement login route succes case --- README.md | 5 +- auth-service/Cargo.lock | 905 +++++++++++++++++++++++++++- auth-service/Cargo.toml | 7 +- auth-service/src/lib.rs | 1 + auth-service/src/routes/login.rs | 14 +- auth-service/src/utils/auth.rs | 141 +++++ auth-service/src/utils/constants.rs | 25 + auth-service/src/utils/mod.rs | 2 + auth-service/tests/api/login.rs | 37 ++ compose.yml | 2 + docker.sh | 19 + 11 files changed, 1147 insertions(+), 11 deletions(-) create mode 100644 auth-service/src/utils/auth.rs create mode 100644 auth-service/src/utils/constants.rs create mode 100644 auth-service/src/utils/mod.rs create mode 100755 docker.sh diff --git a/README.md b/README.md index 6d390a25b..07872c616 100644 --- a/README.md +++ b/README.md @@ -28,8 +28,7 @@ visit http://localhost:3000 ## Run servers locally (Docker) ```bash -docker compose build -docker compose up +./docker.sh ``` -visit http://localhost:8000 and http://localhost:3000 \ No newline at end of file +visit http://localhost:8000 and http://localhost:3000 diff --git a/auth-service/Cargo.lock b/auth-service/Cargo.lock index d85a56334..c71dd58c1 100644 --- a/auth-service/Cargo.lock +++ b/auth-service/Cargo.lock @@ -2,6 +2,15 @@ # It is not intended for manual editing. version = 4 +[[package]] +name = "android_system_properties" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" +dependencies = [ + "libc", +] + [[package]] name = "async-trait" version = "0.1.89" @@ -25,6 +34,11 @@ version = "0.1.0" dependencies = [ "async-trait", "axum", + "axum-extra", + "chrono", + "dotenvy", + "jsonwebtoken", + "lazy_static", "reqwest", "serde", "serde_json", @@ -33,11 +47,17 @@ dependencies = [ "uuid", ] +[[package]] +name = "autocfg" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8" + [[package]] name = "axum" -version = "0.8.6" +version = "0.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8a18ed336352031311f4e0b4dd2ff392d4fbb370777c9d18d7fc9d7359f73871" +checksum = "8b52af3cb4058c895d37317bb27508dccc8e5f2d39454016b297bf4a400597b8" dependencies = [ "axum-core", "bytes", @@ -85,36 +105,239 @@ dependencies = [ "tracing", ] +[[package]] +name = "axum-extra" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fef252edff26ddba56bbcdf2ee3307b8129acb86f5749b68990c168a6fcc9c76" +dependencies = [ + "axum", + "axum-core", + "bytes", + "cookie", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "tower-layer", + "tower-service", + "tracing", +] + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + [[package]] name = "base64" version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64ct" +version = "1.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55248b47b0caf0546f7988906588779981c43bb1bc9d0c44087278f80cdb44ba" + [[package]] name = "bitflags" version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" +[[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 = "bumpalo" version = "3.19.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510" +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + [[package]] name = "bytes" version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d71b6127be86fdcfddb610f7182ac57211d4b18a3e9c82eb2d17662f2227ad6a" +[[package]] +name = "cc" +version = "1.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6354c81bbfd62d9cfa9cb3c773c2b7b2a3a482d569de977fd0e961f6e7c00583" +dependencies = [ + "find-msvc-tools", + "shlex", +] + [[package]] name = "cfg-if" version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +[[package]] +name = "chrono" +version = "0.4.43" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fac4744fb15ae8337dc853fee7fb3f4e48c0fbaa23d0afe49c447b4fab126118" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "cookie" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ddef33a339a91ea89fb53151bd0a4689cfce27055c291dfa69945475d22c747" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.22.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3fc4bff745c9b4c7fb1e97b25d13153da2bc7796260141df62378998d070207f" +dependencies = [ + "cookie", + "document-features", + "idna", + "log", + "publicsuffix", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", + "zeroize", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "der" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7c1832837b905bbfb5101e07cc24c8deddf52f93225eee6ead5f4d63d53ddcb" +dependencies = [ + "const-oid", + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "deranged" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ececcb659e7ba858fb4f10388c250a7252eb0a27373f1a72b8748afdd248e587" +dependencies = [ + "powerfmt", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + [[package]] name = "displaydoc" version = "0.2.5" @@ -126,6 +349,102 @@ dependencies = [ "syn", ] +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "dotenvy" +version = "0.15.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b" + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", + "spki", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "pkcs8", + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "70e796c081cee67dc755e1a36a0a172b897fab85fc3f6bc48307991f64e4eca9" +dependencies = [ + "curve25519-dalek", + "ed25519", + "serde", + "sha2", + "subtle", + "zeroize", +] + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "hkdf", + "pem-rfc7468", + "pkcs8", + "rand_core", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "ff" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" +dependencies = [ + "rand_core", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "28dea519a9695b9977216879a3ebfddf92f1c08c05d984f8996aecd6ecdc811d" + +[[package]] +name = "find-msvc-tools" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db" + [[package]] name = "fnv" version = "1.0.7" @@ -181,6 +500,28 @@ dependencies = [ "slab", ] +[[package]] +name = "generic-array" +version = "0.14.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4bb6743198531e02858aeaea5398fcc883e71851fcbcb5a2f773e2fb6cb1edf2" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + [[package]] name = "getrandom" version = "0.3.4" @@ -193,6 +534,35 @@ dependencies = [ "wasip2", ] +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core", + "subtle", +] + +[[package]] +name = "hkdf" +version = "0.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7" +dependencies = [ + "hmac", +] + +[[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.3.1" @@ -291,6 +661,30 @@ dependencies = [ "tracing", ] +[[package]] +name = "iana-time-zone" +version = "0.1.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33e57f83510bb73707521ebaffa789ec8caf86f9657cad665b092b581d40e9fb" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + [[package]] name = "icu_collections" version = "2.1.1" @@ -425,18 +819,62 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "jsonwebtoken" +version = "10.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c76e1c7d7df3e34443b3621b459b066a7b79644f059fc8b2db7070c825fd417e" +dependencies = [ + "base64", + "ed25519-dalek", + "getrandom 0.2.17", + "hmac", + "js-sys", + "p256", + "p384", + "pem", + "rand", + "rsa", + "serde", + "serde_json", + "sha2", + "signature", + "simple_asn1", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" +dependencies = [ + "spin", +] + [[package]] name = "libc" version = "0.2.177" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2874a2af47a2325c2001a6e6fad9b16a53b802102b528163885171cf92b15976" +[[package]] +name = "libm" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" + [[package]] name = "litemap" version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77" +[[package]] +name = "litrs" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11d3d7f243d5c5a8b9bb5d6dd2b1602c0cb0b9db1621bafc7ed66e35ff9fe092" + [[package]] name = "lock_api" version = "0.4.14" @@ -491,12 +929,99 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-bigint-dig" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc84195820f291c7697304f3cbdadd1cb7199c0efc917ff5eafd71225c136151" +dependencies = [ + "byteorder", + "lazy_static", + "libm", + "num-integer", + "num-iter", + "num-traits", + "rand", + "smallvec", + "zeroize", +] + +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-iter" +version = "0.1.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" +dependencies = [ + "autocfg", + "num-integer", + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + [[package]] name = "once_cell" version = "1.21.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d" +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "p384" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe42f1670a52a47d448f14b6a5c61dd78fce51856e68edaa38f7ae3a46b8d6b6" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + [[package]] name = "parking_lot" version = "0.12.5" @@ -520,6 +1045,25 @@ dependencies = [ "windows-link", ] +[[package]] +name = "pem" +version = "3.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d30c53c26bc5b31a98cd02d20f25a7c8567146caf63ed593a9d87b2775291be" +dependencies = [ + "base64", + "serde_core", +] + +[[package]] +name = "pem-rfc7468" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88b39c9bfcfc231068454382784bb460aae594343fb030d46e9f50a645418412" +dependencies = [ + "base64ct", +] + [[package]] name = "percent-encoding" version = "2.3.2" @@ -538,6 +1082,27 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" +[[package]] +name = "pkcs1" +version = "0.7.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8ffb9f10fa047879315e6625af03c164b16962a5368d724ed16323b68ace47f" +dependencies = [ + "der", + "pkcs8", + "spki", +] + +[[package]] +name = "pkcs8" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f950b2377845cebe5cf8b5165cb3cc1a5e0fa5cfa3e1f7f55707d8fd82e0a7b7" +dependencies = [ + "der", + "spki", +] + [[package]] name = "potential_utf" version = "0.1.4" @@ -547,6 +1112,30 @@ dependencies = [ "zerovec", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + [[package]] name = "proc-macro2" version = "1.0.103" @@ -556,6 +1145,22 @@ dependencies = [ "unicode-ident", ] +[[package]] +name = "psl-types" +version = "2.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac" + +[[package]] +name = "publicsuffix" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f42ea446cab60335f76979ec15e12619a2165b5ae2c12166bef27d283a9fadf" +dependencies = [ + "idna", + "psl-types", +] + [[package]] name = "quote" version = "1.0.41" @@ -571,6 +1176,36 @@ version = "5.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" +[[package]] +name = "rand" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -588,6 +1223,8 @@ checksum = "04e9018c9d814e5f30cc16a0f03271aeab3571e609612d9fe78c1aa8d11c2f62" dependencies = [ "base64", "bytes", + "cookie", + "cookie_store", "futures-core", "http", "http-body", @@ -611,6 +1248,45 @@ dependencies = [ "web-sys", ] +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[package]] +name = "rsa" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78928ac1ed176a5ca1d17e578a1825f3d81ca54cf41053a592584b020cfd691b" +dependencies = [ + "const-oid", + "digest", + "num-bigint-dig", + "num-integer", + "num-traits", + "pkcs1", + "pkcs8", + "rand_core", + "signature", + "spki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + [[package]] name = "rustversion" version = "1.0.22" @@ -629,6 +1305,26 @@ version = "1.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "pkcs8", + "subtle", + "zeroize", +] + +[[package]] +name = "semver" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2" + [[package]] name = "serde" version = "1.0.228" @@ -695,6 +1391,23 @@ dependencies = [ "serde", ] +[[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 = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + [[package]] name = "signal-hook-registry" version = "1.4.6" @@ -704,6 +1417,28 @@ dependencies = [ "libc", ] +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core", +] + +[[package]] +name = "simple_asn1" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb" +dependencies = [ + "num-bigint", + "num-traits", + "thiserror", + "time", +] + [[package]] name = "slab" version = "0.4.11" @@ -726,12 +1461,34 @@ dependencies = [ "windows-sys 0.60.2", ] +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" + +[[package]] +name = "spki" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d91ed6c858b01f942cd56b37a94b3e0a1798290327d1236e4d9cf4eaca44d29d" +dependencies = [ + "base64ct", + "der", +] + [[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.108" @@ -763,6 +1520,57 @@ dependencies = [ "syn", ] +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "time" +version = "0.3.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e7d9e3bb61134e77bde20dd4825b97c010155709965fedf0f49bb138e52a9d" +dependencies = [ + "deranged", + "itoa", + "num-conv", + "powerfmt", + "serde", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40868e7c1d2f0b8d73e4a8c7f0ff63af4f6d19be117e90bd73eb1d62cf831c6b" + +[[package]] +name = "time-macros" +version = "0.2.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30cfb0125f12d9c277f35663a0a33f8c30190f4e4574868a330595412d34ebf3" +dependencies = [ + "num-conv", + "time-core", +] + [[package]] name = "tinystr" version = "0.8.2" @@ -896,6 +1704,12 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" +[[package]] +name = "typenum" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "562d481066bde0658276a35467c4af00bdc6ee726305698a55b86e61d7ad82bb" + [[package]] name = "unicase" version = "2.8.1" @@ -932,10 +1746,16 @@ version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2e054861b4bd027cd373e18e8d8d8e6548085000e41290d95ce0c373a654b4a" dependencies = [ - "getrandom", + "getrandom 0.3.4", "serde_core", ] +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + [[package]] name = "want" version = "0.3.1" @@ -1029,12 +1849,65 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "windows-link" version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + [[package]] name = "windows-sys" version = "0.60.2" @@ -1153,6 +2026,26 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zerocopy" +version = "0.8.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "668f5168d10b9ee831de31933dc111a459c97ec93225beb307aed970d1372dfd" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c7962b26b0a8685668b671ee4b54d007a67d4eaf05fda79ac0ecf41e32270f1" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "zerofrom" version = "0.1.6" @@ -1174,6 +2067,12 @@ dependencies = [ "synstructure", ] +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + [[package]] name = "zerotrie" version = "0.2.3" diff --git a/auth-service/Cargo.toml b/auth-service/Cargo.toml index 49b6d70aa..68393fca3 100644 --- a/auth-service/Cargo.toml +++ b/auth-service/Cargo.toml @@ -7,13 +7,18 @@ edition = "2021" [dependencies] axum = "0.8.6" +axum-extra = { version = "0.12.5", features = ["cookie"] } serde = { version = "1.0.228", features = ["derive"] } serde_json = "1.0.145" uuid = { version = "1.18.1", default-features = false, features = ["v4", "serde"] } tokio = { version = "1.48.0", features = ["full"] } tower-http = { version = "0.6.6", features = ["fs"] } async-trait = "0.1.89" +jsonwebtoken = { version = "10.2.0", features = ["rust_crypto"] } +chrono = "0.4.43" +dotenvy = "0.15.7" +lazy_static = "1.5.0" [dev-dependencies] -reqwest = { version = "0.13.1", default-features = false, features = ["json"] } +reqwest = { version = "0.13.1", default-features = false, features = ["json", "cookies"] } diff --git a/auth-service/src/lib.rs b/auth-service/src/lib.rs index aff215073..e8fd91393 100644 --- a/auth-service/src/lib.rs +++ b/auth-service/src/lib.rs @@ -6,6 +6,7 @@ pub mod routes; pub mod domain; pub mod services; pub mod app_state; +pub mod utils; use routes::*; use domain::{error::AuthAPIError}; diff --git a/auth-service/src/routes/login.rs b/auth-service/src/routes/login.rs index f5358bfce..4d5afe0d0 100644 --- a/auth-service/src/routes/login.rs +++ b/auth-service/src/routes/login.rs @@ -1,12 +1,14 @@ use axum::{Json, extract::State, http::StatusCode, response::IntoResponse}; +use axum_extra::extract::cookie::CookieJar; use serde::{Deserialize, Serialize}; -use crate::{app_state::AppState, domain::{email::Email, error::AuthAPIError, password::Password}}; +use crate::{app_state::AppState, domain::{email::Email, error::AuthAPIError, password::Password}, utils::auth::generate_auth_cookie}; pub async fn login( State(_state): State, + jar: CookieJar, Json(request): Json, -) -> Result { +) -> Result<(CookieJar, impl IntoResponse), AuthAPIError> { let email = request.email; let password = request.password; @@ -15,7 +17,7 @@ pub async fn login( let password = Password::parse(password).map_err(|_| AuthAPIError::InvalidCredentials)?; let user_store = &_state.user_store; - match user_store.get_user(email).await { + match user_store.get_user(email.clone()).await { Ok(user) => { if user.password != password { return Err(AuthAPIError::IncorrectCredentials); @@ -26,7 +28,11 @@ pub async fn login( } } - Ok(StatusCode::OK.into_response()) + let auth_cookie = generate_auth_cookie(&email).map_err(|_| AuthAPIError::UnexpectedError)?; + + let updated_jar = jar.add(auth_cookie); + + return Ok((updated_jar, StatusCode::OK.into_response())); } diff --git a/auth-service/src/utils/auth.rs b/auth-service/src/utils/auth.rs new file mode 100644 index 000000000..89388928b --- /dev/null +++ b/auth-service/src/utils/auth.rs @@ -0,0 +1,141 @@ +use axum_extra::extract::cookie::{Cookie, SameSite}; +use chrono::Utc; +use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Validation}; +use serde::{Deserialize, Serialize}; + +use crate::domain::email::Email; + +use super::constants::{JWT_COOKIE_NAME, JWT_SECRET}; + +// // This is definitely NOT a good secret. We will update it soon! +// const JWT_SECRET: &str = "secret"; + +// Create cookie with a new JWT auth token +pub fn generate_auth_cookie(email: &Email) -> Result, GenerateTokenError> { + let token = generate_auth_token(email)?; + Ok(create_auth_cookie(token)) +} + +// Create cookie and set the value to the passed-in token string +fn create_auth_cookie(token: String) -> Cookie<'static> { + let cookie = Cookie::build((JWT_COOKIE_NAME, token)) + .path("/") // apply cookie to all URLs on the server + .http_only(true) // prevent JavaScript from accessing the cookie + .same_site(SameSite::Lax) // send cookie with "same-site" requests, and with "cross-site" top-level navigations. + .build(); + + cookie +} + +#[derive(Debug)] +pub enum GenerateTokenError { + TokenError(jsonwebtoken::errors::Error), + UnexpectedError, +} + +// This value determines how long the JWT auth token is valid for +pub const TOKEN_TTL_SECONDS: i64 = 600; // 10 minutes + +// Create JWT auth token +fn generate_auth_token(email: &Email) -> Result { + let delta = chrono::Duration::try_seconds(TOKEN_TTL_SECONDS) + .ok_or(GenerateTokenError::UnexpectedError)?; + + // Create JWT expiration time + let exp = Utc::now() + .checked_add_signed(delta) + .ok_or(GenerateTokenError::UnexpectedError)? + .timestamp(); + + // Cast exp to a usize, which is what Claims expects + let exp: usize = exp + .try_into() + .map_err(|_| GenerateTokenError::UnexpectedError)?; + + let sub = email.as_ref().to_owned(); + + let claims = Claims { sub, exp }; + + create_token(&claims).map_err(GenerateTokenError::TokenError) +} + +// Check if JWT auth token is valid by decoding it using the JWT secret +pub async fn validate_token(token: &str) -> Result { + decode::( + token, + &DecodingKey::from_secret(JWT_SECRET.as_bytes()), + &Validation::default(), + ) + .map(|data| data.claims) +} + +// Create JWT auth token by encoding claims using the JWT secret +fn create_token(claims: &Claims) -> Result { + encode( + &jsonwebtoken::Header::default(), + &claims, + &EncodingKey::from_secret(JWT_SECRET.as_bytes()), + ) +} + +#[derive(Debug, Serialize, Deserialize)] +pub struct Claims { + pub sub: String, + pub exp: usize, +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn test_generate_auth_cookie() { + let email = Email::parse("test@example.com".to_owned()).unwrap(); + let cookie = generate_auth_cookie(&email).unwrap(); + assert_eq!(cookie.name(), JWT_COOKIE_NAME); + assert_eq!(cookie.value().split('.').count(), 3); + assert_eq!(cookie.path(), Some("/")); + assert_eq!(cookie.http_only(), Some(true)); + assert_eq!(cookie.same_site(), Some(SameSite::Lax)); + } + + #[tokio::test] + async fn test_create_auth_cookie() { + let token = "test_token".to_owned(); + let cookie = create_auth_cookie(token.clone()); + assert_eq!(cookie.name(), JWT_COOKIE_NAME); + assert_eq!(cookie.value(), token); + assert_eq!(cookie.path(), Some("/")); + assert_eq!(cookie.http_only(), Some(true)); + assert_eq!(cookie.same_site(), Some(SameSite::Lax)); + } + + #[tokio::test] + async fn test_generate_auth_token() { + let email = Email::parse("test@example.com".to_owned()).unwrap(); + let result = generate_auth_token(&email).unwrap(); + assert_eq!(result.split('.').count(), 3); + } + + #[tokio::test] + async fn test_validate_token_with_valid_token() { + let email = Email::parse("test@example.com".to_owned()).unwrap(); + let token = generate_auth_token(&email).unwrap(); + let result = validate_token(&token).await.unwrap(); + assert_eq!(result.sub, "test@example.com"); + + let exp = Utc::now() + .checked_add_signed(chrono::Duration::try_minutes(9).expect("valid duration")) + .expect("valid timestamp") + .timestamp(); + + assert!(result.exp > exp as usize); + } + + #[tokio::test] + async fn test_validate_token_with_invalid_token() { + let token = "invalid_token".to_owned(); + let result = validate_token(&token).await; + assert!(result.is_err()); + } +} diff --git a/auth-service/src/utils/constants.rs b/auth-service/src/utils/constants.rs new file mode 100644 index 000000000..539ac424a --- /dev/null +++ b/auth-service/src/utils/constants.rs @@ -0,0 +1,25 @@ +use dotenvy::dotenv; +use lazy_static::lazy_static; +use std::env as std_env; + +// Define a lazily evaluated static. lazy_static is needed because std_env::var is not a const function. +lazy_static! { + pub static ref JWT_SECRET: String = set_token(); +} + + +fn set_token() -> String { + dotenv().ok(); // Load environment variables + let secret = std_env::var(env::JWT_SECRET_ENV_VAR).expect("JWT_SECRET must be set."); + if secret.is_empty() { + panic!("JWT_SECRET must not be empty."); + } + + secret +} + +pub mod env { + pub const JWT_SECRET_ENV_VAR: &str = "JWT_SECRET"; +} + +pub const JWT_COOKIE_NAME: &str = "jwt"; diff --git a/auth-service/src/utils/mod.rs b/auth-service/src/utils/mod.rs new file mode 100644 index 000000000..552b98718 --- /dev/null +++ b/auth-service/src/utils/mod.rs @@ -0,0 +1,2 @@ +pub mod constants; +pub mod auth; diff --git a/auth-service/tests/api/login.rs b/auth-service/tests/api/login.rs index ce70a186b..0dbdfe2f2 100644 --- a/auth-service/tests/api/login.rs +++ b/auth-service/tests/api/login.rs @@ -2,6 +2,10 @@ use crate::helpers::TestApp; mod tests { + use auth_service::utils::constants::JWT_COOKIE_NAME; + + use crate::helpers::get_random_email; + use super::*; #[tokio::test] @@ -94,4 +98,37 @@ mod tests { assert_eq!(response.status().as_u16(), 401); } + + #[tokio::test] + async fn should_return_200_if_valid_credentials_and_2fa_disabled() { + let app = TestApp::run().await; + + let email = get_random_email(); + + // Create a user in the test database + let signup_body = serde_json::json!({ + "email": email, + "password": "password123", + "requires2FA": false, + }); + + let response = app.post_signup(&signup_body).await; + + assert_eq!(response.status().as_u16(), 201); + + // Attempt to login with valid credentials + let login_body = serde_json::json!({ + "email": email, + "password": "password123", + }); + + let response = app.post_login(&login_body).await; + + assert_eq!(response.status().as_u16(), 200); + + let auth_cookie = response + .cookies() + .find(|c| c.name() == JWT_COOKIE_NAME) + .expect("no auth cookie found"); + } } diff --git a/compose.yml b/compose.yml index 9742a1ca0..499553c0a 100644 --- a/compose.yml +++ b/compose.yml @@ -14,5 +14,7 @@ services: # TODO: change "letsgetrusty" to your Docker Hub username image: fedecomprido/auth-service restart: "always" # automatically restart container when server crashes + environment: + JWT_SECRET: ${JWT_SECRET} ports: - "3000:3000" # expose port 3000 so that applications outside the container can connect to it \ No newline at end of file diff --git a/docker.sh b/docker.sh new file mode 100755 index 000000000..a97b3f33c --- /dev/null +++ b/docker.sh @@ -0,0 +1,19 @@ +#!/bin/bash + +ENV_FILE="./auth-service/.env" + +if ! [[ -f "$ENV_FILE" ]]; then + echo "Error: missing auth-service/.env file!" + exit 1 +fi + +while IFS= read -r line; do + if [[ -n "$line" ]] && [[ "$line" != "\#*" ]]; then + key=$(echo "$line" | cut -d "=" -f1) + value=$(echo "$line" | cut -d "=" -f2-) + export "$key=$value" + fi +done < <(grep -v "^#" "$ENV_FILE") + +docker-compose build +docker-compose up From 01fc2c69590a062f6f8e5f51cb37f8cd4bac6618 Mon Sep 17 00:00:00 2001 From: FedericoGambassi Date: Tue, 27 Jan 2026 23:14:59 +0100 Subject: [PATCH 13/17] [Sprint 3][Task 5] implement banned token store --- auth-service/Cargo.toml | 2 +- auth-service/src/app_state.rs | 26 +++- auth-service/src/domain/error.rs | 3 + auth-service/src/lib.rs | 18 ++- auth-service/src/main.rs | 7 +- auth-service/src/routes/logout.rs | 27 +++- auth-service/src/routes/verify_token.rs | 20 ++- auth-service/src/services/data_store.rs | 14 ++ .../services/hashset_banned_token_store.rs | 64 +++++++++ auth-service/src/services/mod.rs | 3 +- auth-service/src/utils/auth.rs | 28 +++- auth-service/src/utils/constants.rs | 11 ++ auth-service/tests/api/helpers.rs | 25 +++- auth-service/tests/api/logout.rs | 115 ++++++++++++++++- auth-service/tests/api/verify_token.rs | 122 +++++++++++++++++- 15 files changed, 452 insertions(+), 33 deletions(-) create mode 100644 auth-service/src/services/hashset_banned_token_store.rs diff --git a/auth-service/Cargo.toml b/auth-service/Cargo.toml index 68393fca3..da6cd2025 100644 --- a/auth-service/Cargo.toml +++ b/auth-service/Cargo.toml @@ -12,7 +12,7 @@ serde = { version = "1.0.228", features = ["derive"] } serde_json = "1.0.145" uuid = { version = "1.18.1", default-features = false, features = ["v4", "serde"] } tokio = { version = "1.48.0", features = ["full"] } -tower-http = { version = "0.6.6", features = ["fs"] } +tower-http = { version = "0.6.6", features = ["fs", "cors",] } async-trait = "0.1.89" jsonwebtoken = { version = "10.2.0", features = ["rust_crypto"] } chrono = "0.4.43" diff --git a/auth-service/src/app_state.rs b/auth-service/src/app_state.rs index 1d1460cb5..5b8f16cb9 100644 --- a/auth-service/src/app_state.rs +++ b/auth-service/src/app_state.rs @@ -1,5 +1,5 @@ use std::{ops::Deref, sync::Arc}; -use crate::services::{data_store::UserStore, hashmap_user_store::HashmapUserStore}; +use crate::services::{data_store::{BannedTokenStore, UserStore}, hashmap_user_store::HashmapUserStore, hashset_banned_token_store::HashsetBannedTokenStore}; #[derive(Clone)] @@ -21,14 +21,34 @@ impl Default for UserStoreType { } +#[derive(Clone)] +pub struct BannedTokenStoreType(pub Arc>); + +impl Deref for BannedTokenStoreType { + type Target = Arc>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Default for BannedTokenStoreType { + fn default() -> Self { + let store: Box = Box::new(HashsetBannedTokenStore::default()); + Self(Arc::new(store)) + } +} + + #[derive(Clone)] pub struct AppState { pub user_store: UserStoreType, + pub banned_token_store: BannedTokenStoreType, } impl AppState { - pub fn new(user_store: UserStoreType) -> Self { - Self { user_store } + pub fn new(user_store: UserStoreType, banned_token_store: BannedTokenStoreType) -> Self { + Self { user_store, banned_token_store } } // // Optional ergonomic constructor (useful for DI/tests) diff --git a/auth-service/src/domain/error.rs b/auth-service/src/domain/error.rs index 98d1b134a..da97a90e1 100644 --- a/auth-service/src/domain/error.rs +++ b/auth-service/src/domain/error.rs @@ -1,7 +1,10 @@ +#[derive(Debug)] pub enum AuthAPIError { MalformedRequest, InvalidCredentials, IncorrectCredentials, UserAlreadyExists, UnexpectedError, + MissingToken, + InvalidToken, } diff --git a/auth-service/src/lib.rs b/auth-service/src/lib.rs index e8fd91393..c8627ba86 100644 --- a/auth-service/src/lib.rs +++ b/auth-service/src/lib.rs @@ -1,6 +1,6 @@ use tokio::net::TcpListener; -use axum::{Json, Router, http::StatusCode, response::IntoResponse, routing::post, serve::Serve}; -use tower_http::{services::{ServeDir, ServeFile}}; +use axum::{Json, Router, http::{Method, StatusCode}, response::{IntoResponse, Response}, routing::post, serve::Serve}; +use tower_http::{cors::CorsLayer, services::{ServeDir, ServeFile}}; pub mod routes; pub mod domain; @@ -30,6 +30,8 @@ impl IntoResponse for AuthAPIError { AuthAPIError::IncorrectCredentials => (StatusCode::UNAUTHORIZED, "Incorrect credentials"), AuthAPIError::UserAlreadyExists => (StatusCode::CONFLICT, "User already exists"), AuthAPIError::UnexpectedError => (StatusCode::INTERNAL_SERVER_ERROR, "Unexpected error"), + AuthAPIError::MissingToken => (StatusCode::BAD_REQUEST, "Missing token"), + AuthAPIError::InvalidToken => (StatusCode::UNAUTHORIZED, "Invalid token") }; let body = Json(ErrorResponse { @@ -48,6 +50,15 @@ pub struct Application { impl Application { pub async fn build(app_state: AppState, address: &str) -> Result { + let allowed_origins = [ + "http://localhost:8000".parse()?, + ]; + + let cors = CorsLayer::new() + .allow_methods([Method::GET, Method::POST]) + .allow_credentials(true) + .allow_origin(allowed_origins); + let assets_dir = ServeDir::new("assets") .not_found_service(ServeFile::new("assets/index.html")); @@ -58,7 +69,8 @@ impl Application { .route("/verify-2fa", post(verify_2fa)) .route("/logout", post(logout)) .route("/verify-token", post(verify_token)) - .with_state(app_state); + .with_state(app_state) + .layer(cors); let listener = TcpListener::bind(address).await?; let address = listener.local_addr()?.to_string(); let server = axum::serve(listener, router); diff --git a/auth-service/src/main.rs b/auth-service/src/main.rs index 7754ce998..c52702f35 100644 --- a/auth-service/src/main.rs +++ b/auth-service/src/main.rs @@ -1,11 +1,12 @@ -use auth_service::{Application, app_state::{AppState, UserStoreType}}; +use auth_service::{Application, app_state::{AppState, BannedTokenStoreType, UserStoreType}, utils::constants::prod}; #[tokio::main] async fn main() { let user_store = UserStoreType::default(); - let app_state = AppState::new(user_store); // optionally, if builder pattern enabled: AppState::with_store(hashmap_store).build(); + let banned_token_store = BannedTokenStoreType::default(); + let app_state = AppState::new(user_store, banned_token_store); // optionally, if builder pattern enabled: AppState::with_store(hashmap_store).build(); - let app = Application::build(app_state, "0.0.0.0:3000").await.expect("Failed to build app"); + let app = Application::build(app_state, prod::APP_ADDRESS).await.expect("Failed to build app"); app.run().await.expect("Failed to run app"); } diff --git a/auth-service/src/routes/logout.rs b/auth-service/src/routes/logout.rs index 200e65d2b..29aa0ad67 100644 --- a/auth-service/src/routes/logout.rs +++ b/auth-service/src/routes/logout.rs @@ -1,6 +1,27 @@ -use axum::{response::IntoResponse, http::StatusCode}; +use axum::{extract::State, http::StatusCode, response::IntoResponse}; +use axum_extra::extract::CookieJar; +use crate::{app_state::AppState, domain::error::AuthAPIError, utils::{auth::validate_token, constants::JWT_COOKIE_NAME}}; -pub async fn logout() -> impl IntoResponse { - StatusCode::OK.into_response() + +pub async fn logout( + State(_state): State, + jar: CookieJar, +) -> Result<(CookieJar, impl IntoResponse), AuthAPIError> { + let cookie = jar.get(JWT_COOKIE_NAME).ok_or(AuthAPIError::MissingToken)?; + + let token = cookie.value().to_owned(); + + validate_token(&token, _state.banned_token_store.clone()).await.map_err(|_| AuthAPIError::InvalidToken)?; + + let jar = jar.remove(JWT_COOKIE_NAME); + + _state.banned_token_store.store_token(&token).await.map_err(|e| { + match e { + crate::services::data_store::BannedTokenStoreError::TokenAlreadyBanned => AuthAPIError::InvalidToken, + crate::services::data_store::BannedTokenStoreError::UnexpectedError => AuthAPIError::UnexpectedError, + } + } )?; + + Ok((jar, StatusCode::OK)) } diff --git a/auth-service/src/routes/verify_token.rs b/auth-service/src/routes/verify_token.rs index 8c7ee5a3e..2117930d2 100644 --- a/auth-service/src/routes/verify_token.rs +++ b/auth-service/src/routes/verify_token.rs @@ -1,6 +1,20 @@ -use axum::{response::IntoResponse, http::StatusCode}; +use axum::{Json, extract::State, http::StatusCode, response::IntoResponse}; +use serde::Deserialize; +use crate::{app_state::AppState, domain::error::AuthAPIError, utils::auth::validate_token}; -pub async fn verify_token() -> impl IntoResponse { - StatusCode::OK.into_response() + +pub async fn verify_token( + State(_state): State, + Json(request): Json, +) -> Result { + validate_token(&request.token, _state.banned_token_store.clone()).await.map_err(|_| AuthAPIError::InvalidToken)?; + + Ok(StatusCode::OK.into_response()) +} + + +#[derive(Deserialize)] +pub struct VerifyTokenRequest { + token: String, } diff --git a/auth-service/src/services/data_store.rs b/auth-service/src/services/data_store.rs index aaf84f289..2ca22cf64 100644 --- a/auth-service/src/services/data_store.rs +++ b/auth-service/src/services/data_store.rs @@ -16,3 +16,17 @@ pub trait UserStore: Send + Sync { async fn get_user(&self, email: Email) -> Result; async fn validate_user(&self, email: Email, password: Password) -> Result<(), UserStoreError>; } + + +#[derive(Debug, PartialEq)] +pub enum BannedTokenStoreError { + TokenAlreadyBanned, + UnexpectedError, +} + + +#[async_trait::async_trait] +pub trait BannedTokenStore: Send + Sync { + async fn store_token(&self, token: &str) -> Result<(), BannedTokenStoreError>; + async fn check_token(&self, token: &str) -> Result; +} diff --git a/auth-service/src/services/hashset_banned_token_store.rs b/auth-service/src/services/hashset_banned_token_store.rs new file mode 100644 index 000000000..fe926e751 --- /dev/null +++ b/auth-service/src/services/hashset_banned_token_store.rs @@ -0,0 +1,64 @@ +use std::collections::HashSet; + +use tokio::sync::RwLock; + +use crate::services::data_store::{BannedTokenStore, BannedTokenStoreError}; + +#[derive(Default)] +pub struct HashsetBannedTokenStore { + tokens: RwLock>, +} + +#[async_trait::async_trait] +impl BannedTokenStore for HashsetBannedTokenStore { + async fn store_token(&self, token: &str) -> Result<(), super::data_store::BannedTokenStoreError> { + let mut guard = self.tokens.write().await; + if guard.contains(token) { + println!("Guard already contains token"); + return Err(BannedTokenStoreError::TokenAlreadyBanned); + } + guard.insert(token.to_string()); + Ok(()) + } + + async fn check_token(&self, token: &str) -> Result { + let res = self.tokens.read().await.contains(token); + Ok(res) + } +} + + +#[cfg(test)] +mod tests { + use super::*; + use tokio::task::{self, futures}; + + #[tokio::test] + async fn store_token_new_token_ok() { + let store = HashsetBannedTokenStore::default(); + + let res = store.store_token("abc").await; + assert_eq!(res, Ok(())); + } + + #[tokio::test] + async fn store_token_same_token_twice_returns_token_already_banned() { + let store = HashsetBannedTokenStore::default(); + + assert_eq!(store.store_token("abc").await, Ok(())); + assert_eq!( + store.store_token("abc").await, + Err(BannedTokenStoreError::TokenAlreadyBanned) + ); + } + + #[tokio::test] + async fn check_token_false_before_store_true_after_store() { + let store = HashsetBannedTokenStore::default(); + + assert_eq!(store.check_token("abc").await, Ok(false)); + assert_eq!(store.store_token("abc").await, Ok(())); + assert_eq!(store.check_token("abc").await, Ok(true)); + } +} + diff --git a/auth-service/src/services/mod.rs b/auth-service/src/services/mod.rs index 3545381c9..e1def7e00 100644 --- a/auth-service/src/services/mod.rs +++ b/auth-service/src/services/mod.rs @@ -1,2 +1,3 @@ -pub mod hashmap_user_store; pub mod data_store; +pub mod hashmap_user_store; +pub mod hashset_banned_token_store; diff --git a/auth-service/src/utils/auth.rs b/auth-service/src/utils/auth.rs index 89388928b..b97b7810a 100644 --- a/auth-service/src/utils/auth.rs +++ b/auth-service/src/utils/auth.rs @@ -1,9 +1,9 @@ use axum_extra::extract::cookie::{Cookie, SameSite}; use chrono::Utc; -use jsonwebtoken::{decode, encode, DecodingKey, EncodingKey, Validation}; +use jsonwebtoken::{DecodingKey, EncodingKey, Validation, decode, encode, errors::Error}; use serde::{Deserialize, Serialize}; -use crate::domain::email::Email; +use crate::{app_state::BannedTokenStoreType, domain::{email::Email, error::AuthAPIError}}; use super::constants::{JWT_COOKIE_NAME, JWT_SECRET}; @@ -60,15 +60,29 @@ fn generate_auth_token(email: &Email) -> Result { } // Check if JWT auth token is valid by decoding it using the JWT secret -pub async fn validate_token(token: &str) -> Result { +pub async fn validate_token( + token: &str, + banned_token_store: BannedTokenStoreType, +) -> Result { + let is_banned = banned_token_store + .check_token(token) + .await + .map_err(|_| AuthAPIError::InvalidToken)?; + + if is_banned { + return Err(AuthAPIError::InvalidToken); + } + decode::( token, &DecodingKey::from_secret(JWT_SECRET.as_bytes()), &Validation::default(), ) .map(|data| data.claims) + .map_err(|_| AuthAPIError::InvalidToken) } + // Create JWT auth token by encoding claims using the JWT secret fn create_token(claims: &Claims) -> Result { encode( @@ -86,6 +100,8 @@ pub struct Claims { #[cfg(test)] mod tests { + use crate::services::hashset_banned_token_store::HashsetBannedTokenStore; + use super::*; #[tokio::test] @@ -119,9 +135,10 @@ mod tests { #[tokio::test] async fn test_validate_token_with_valid_token() { + let banned_token_store = BannedTokenStoreType::default(); let email = Email::parse("test@example.com".to_owned()).unwrap(); let token = generate_auth_token(&email).unwrap(); - let result = validate_token(&token).await.unwrap(); + let result = validate_token(&token, banned_token_store).await.unwrap(); assert_eq!(result.sub, "test@example.com"); let exp = Utc::now() @@ -134,8 +151,9 @@ mod tests { #[tokio::test] async fn test_validate_token_with_invalid_token() { + let banned_token_store = BannedTokenStoreType::default(); let token = "invalid_token".to_owned(); - let result = validate_token(&token).await; + let result = validate_token(&token, banned_token_store).await; assert!(result.is_err()); } } diff --git a/auth-service/src/utils/constants.rs b/auth-service/src/utils/constants.rs index 539ac424a..cd7ddf688 100644 --- a/auth-service/src/utils/constants.rs +++ b/auth-service/src/utils/constants.rs @@ -2,6 +2,17 @@ use dotenvy::dotenv; use lazy_static::lazy_static; use std::env as std_env; + +pub mod prod { + pub const APP_ADDRESS: &str = "0.0.0.0:3000"; +} + + +pub mod test { + pub const APP_ADDRESS: &str = "127.0.0.1:0"; +} + + // Define a lazily evaluated static. lazy_static is needed because std_env::var is not a const function. lazy_static! { pub static ref JWT_SECRET: String = set_token(); diff --git a/auth-service/tests/api/helpers.rs b/auth-service/tests/api/helpers.rs index f332b39c1..8d70674ca 100644 --- a/auth-service/tests/api/helpers.rs +++ b/auth-service/tests/api/helpers.rs @@ -1,23 +1,35 @@ -use auth_service::{Application, app_state::{AppState, UserStoreType}}; -use reqwest; +use std::sync::Arc; + +use auth_service::{Application, app_state::{AppState, BannedTokenStoreType, UserStoreType}, utils::constants::test}; +use reqwest::{self, Client, cookie::Jar}; pub struct TestApp { pub address: String, + pub cookie_jar: Arc, pub client: reqwest::Client, + pub banned_token_store: BannedTokenStoreType, } impl TestApp { pub async fn run() -> Self { let user_store = UserStoreType::default(); - let app_state = AppState::new(user_store); + let banned_token_store = BannedTokenStoreType::default(); + let app_state = AppState::new(user_store, banned_token_store.clone()); - let app = Application::build(app_state, "127.0.0.1:0").await.expect("Failed to build application"); + let app = Application::build(app_state, test::APP_ADDRESS).await.expect("Failed to build application"); let address = format!("http://{}", app.address.clone()); #[allow(clippy::let_underscore_future)] let _ = tokio::spawn(app.run()); - Self { address, client: reqwest::Client::new() } + + let cookie_jar = Arc::new(Jar::default()); + let http_client = Client::builder() + .cookie_provider(cookie_jar.clone()) + .build() + .unwrap(); + + Self { address, cookie_jar, client: http_client, banned_token_store } } pub async fn get_root(&self) -> reqwest::Response { @@ -68,7 +80,8 @@ impl TestApp { .expect("Failed to execute request.") } - pub async fn verify_token(&self, body: &serde_json::Value) -> reqwest::Response { + pub async fn post_verify_token(&self, body: &Body) -> reqwest::Response + where Body: serde::Serialize { self.client .post(format!("{}/verify-token", &self.address)) .json(body) diff --git a/auth-service/tests/api/logout.rs b/auth-service/tests/api/logout.rs index c3fe103cb..5563fcb3b 100644 --- a/auth-service/tests/api/logout.rs +++ b/auth-service/tests/api/logout.rs @@ -2,12 +2,125 @@ use crate::helpers::TestApp; mod tests { + use auth_service::utils::constants::JWT_COOKIE_NAME; + use axum_extra::extract::cookie; + use reqwest::Url; + + use crate::helpers::get_random_email; + use super::*; #[tokio::test] - async fn test_logout() { + async fn should_return_400_if_jwt_cookie_missing() { + let app = TestApp::run().await; + + let email = get_random_email(); + + // Create a user in the test database + let signup_body = serde_json::json!({ + "email": email, + "password": "password123", + "requires2FA": false, + }); + + let response = app.post_signup(&signup_body).await; + + assert_eq!(response.status().as_u16(), 201); + + let response = app.post_logout().await; + + assert_eq!(response.status().as_u16(), 400); + } + + #[tokio::test] + async fn should_return_401_if_invalid_token() { + let app = TestApp::run().await; + + app.cookie_jar.add_cookie_str( + &format!( + "{}=invalid; HttpOnly; SameSite=Lax; Secure; Path=/", + JWT_COOKIE_NAME, + ), + &Url::parse("http://127.0.0.1").expect("Failed to parse URL"), + ); + + let response = app.post_logout().await; + + assert_eq!(response.status().as_u16(), 401); + } + + #[tokio::test] + async fn should_return_200_if_valid_jwt_cookie() { + let app = TestApp::run().await; + + let email = get_random_email(); + + // Create a user in the test database + let signup_body = serde_json::json!({ + "email": email, + "password": "password123", + "requires2FA": false, + }); + + let response = app.post_signup(&signup_body).await; + + assert_eq!(response.status().as_u16(), 201); + + // Attempt to login with valid credentials + let login_body = serde_json::json!({ + "email": email, + "password": "password123", + }); + + let response = app.post_login(&login_body).await; + + assert_eq!(response.status().as_u16(), 200); + + let auth_cookie = response + .cookies() + .find(|c| c.name() == JWT_COOKIE_NAME) + .expect("no auth cookie found"); + + let response = app.post_logout().await; + + assert_eq!(response.status().as_u16(), 200); + + assert_eq!(app.banned_token_store.check_token(&auth_cookie.value()).await.unwrap(), true); + } + + #[tokio::test] + async fn should_return_400_if_logout_called_twice_in_a_row() { let app = TestApp::run().await; + + let email = get_random_email(); + + // Create a user in the test database + let signup_body = serde_json::json!({ + "email": email, + "password": "password123", + "requires2FA": false, + }); + + let response = app.post_signup(&signup_body).await; + + assert_eq!(response.status().as_u16(), 201); + + // Attempt to login with valid credentials + let login_body = serde_json::json!({ + "email": email, + "password": "password123", + }); + + let response = app.post_login(&login_body).await; + + assert_eq!(response.status().as_u16(), 200); + let response = app.post_logout().await; + assert_eq!(response.status().as_u16(), 200); + + let response = app.post_logout().await; + + assert_eq!(response.status().as_u16(), 400); } } diff --git a/auth-service/tests/api/verify_token.rs b/auth-service/tests/api/verify_token.rs index 3ae52a5d9..c10ecbd2a 100644 --- a/auth-service/tests/api/verify_token.rs +++ b/auth-service/tests/api/verify_token.rs @@ -2,15 +2,129 @@ use crate::helpers::TestApp; mod tests { + use auth_service::utils::constants::JWT_COOKIE_NAME; + use reqwest::{Url, cookie::CookieStore}; + + use crate::helpers::get_random_email; + use super::*; #[tokio::test] - async fn test_verify_token() { + async fn should_return_422_if_malformed_input() { + let app = TestApp::run().await; + + let test_cases = vec![ + serde_json::json!({ + "toghen": "mytoken", + }), + serde_json::json!({}), + ]; + + for case in test_cases { + let response = app.post_login(&case).await; + + assert_eq!(response.status().as_u16(), 422); + } + } + + #[tokio::test] + async fn should_return_200_if_valid_token() { let app = TestApp::run().await; - let body = serde_json::json!({ - "token": "some_valid_token" + + let email = get_random_email(); + + // Create a user in the test database + let signup_body = serde_json::json!({ + "email": email, + "password": "password123", + "requires2FA": false, }); - let response = app.verify_token(&body).await; + + let response = app.post_signup(&signup_body).await; + + assert_eq!(response.status().as_u16(), 201); + + // Attempt to login with valid credentials + let login_body = serde_json::json!({ + "email": email, + "password": "password123", + }); + + let response = app.post_login(&login_body).await; + assert_eq!(response.status().as_u16(), 200); + + let auth_cookie = response + .cookies() + .find(|c| c.name() == JWT_COOKIE_NAME) + .expect("no auth cookie found"); + + let token = auth_cookie.value(); + + let verify_token_body = serde_json::json!({ + "token": token + }); + + let response = app.post_verify_token(&verify_token_body).await; + + assert_eq!(response.status().as_u16(), 200); + } + + #[tokio::test] + async fn should_return_401_if_invalid_token() { + let app = TestApp::run().await; + + let verify_token_body = serde_json::json!({ + "token": "invalid" + }); + + let response = app.post_verify_token(&verify_token_body).await; + + assert_eq!(response.status().as_u16(), 401); + } + + #[tokio::test] + async fn should_return_401_if_banned_token() { + let app = TestApp::run().await; + + let email = get_random_email(); + + // Create a user in the test database + let signup_body = serde_json::json!({ + "email": email, + "password": "password123", + "requires2FA": false, + }); + + let response = app.post_signup(&signup_body).await; + + assert_eq!(response.status().as_u16(), 201); + + // Attempt to login with valid credentials + let login_body = serde_json::json!({ + "email": email, + "password": "password123", + }); + + let response = app.post_login(&login_body).await; + + assert_eq!(response.status().as_u16(), 200); + + let auth_cookie = response + .cookies() + .find(|c| c.name() == JWT_COOKIE_NAME) + .expect("no auth cookie found"); + + let token = auth_cookie.value(); + + app.banned_token_store.store_token(&token).await.unwrap(); + + let verify_token_body = serde_json::json!({ + "token": token + }); + + let response = app.post_verify_token(&verify_token_body).await; + + assert_eq!(response.status().as_u16(), 401); } } From 705f516054d4bf93510a4e3bc5f166065947a5e4 Mon Sep 17 00:00:00 2001 From: FedericoGambassi Date: Fri, 30 Jan 2026 15:52:11 +0100 Subject: [PATCH 14/17] wip --- auth-service/Cargo.lock | 52 +++++-- auth-service/Cargo.toml | 1 + auth-service/src/app_state.rs | 37 ++++- auth-service/src/domain/email.rs | 6 +- auth-service/src/main.rs | 9 +- auth-service/src/routes/login.rs | 86 ++++++++++- auth-service/src/services/data_store.rs | 79 ++++++++++ .../src/services/hashmap_two_fa_code_store.rs | 138 ++++++++++++++++++ .../src/services/hashmap_user_store.rs | 7 +- auth-service/src/services/mod.rs | 1 + auth-service/tests/api/helpers.rs | 13 +- auth-service/tests/api/login.rs | 42 +++++- 12 files changed, 442 insertions(+), 29 deletions(-) create mode 100644 auth-service/src/services/hashmap_two_fa_code_store.rs diff --git a/auth-service/Cargo.lock b/auth-service/Cargo.lock index c71dd58c1..2691607c9 100644 --- a/auth-service/Cargo.lock +++ b/auth-service/Cargo.lock @@ -39,6 +39,7 @@ dependencies = [ "dotenvy", "jsonwebtoken", "lazy_static", + "rand 0.9.2", "reqwest", "serde", "serde_json", @@ -264,7 +265,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" dependencies = [ "generic-array", - "rand_core", + "rand_core 0.6.4", "subtle", "zeroize", ] @@ -417,7 +418,7 @@ dependencies = [ "hkdf", "pem-rfc7468", "pkcs8", - "rand_core", + "rand_core 0.6.4", "sec1", "subtle", "zeroize", @@ -429,7 +430,7 @@ version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0b50bfb653653f9ca9095b427bed08ab8d75a137839d9ad64eb11810d5b6393" dependencies = [ - "rand_core", + "rand_core 0.6.4", "subtle", ] @@ -541,7 +542,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" dependencies = [ "ff", - "rand_core", + "rand_core 0.6.4", "subtle", ] @@ -833,7 +834,7 @@ dependencies = [ "p256", "p384", "pem", - "rand", + "rand 0.8.5", "rsa", "serde", "serde_json", @@ -951,7 +952,7 @@ dependencies = [ "num-integer", "num-iter", "num-traits", - "rand", + "rand 0.8.5", "smallvec", "zeroize", ] @@ -1183,8 +1184,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ "libc", - "rand_chacha", - "rand_core", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", ] [[package]] @@ -1194,7 +1205,17 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", - "rand_core", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", ] [[package]] @@ -1206,6 +1227,15 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "redox_syscall" version = "0.5.18" @@ -1271,7 +1301,7 @@ dependencies = [ "num-traits", "pkcs1", "pkcs8", - "rand_core", + "rand_core 0.6.4", "signature", "spki", "subtle", @@ -1424,7 +1454,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ "digest", - "rand_core", + "rand_core 0.6.4", ] [[package]] diff --git a/auth-service/Cargo.toml b/auth-service/Cargo.toml index da6cd2025..0f0a248bd 100644 --- a/auth-service/Cargo.toml +++ b/auth-service/Cargo.toml @@ -18,6 +18,7 @@ jsonwebtoken = { version = "10.2.0", features = ["rust_crypto"] } chrono = "0.4.43" dotenvy = "0.15.7" lazy_static = "1.5.0" +rand = "0.9.2" [dev-dependencies] diff --git a/auth-service/src/app_state.rs b/auth-service/src/app_state.rs index 5b8f16cb9..6bbcaed20 100644 --- a/auth-service/src/app_state.rs +++ b/auth-service/src/app_state.rs @@ -1,5 +1,7 @@ use std::{ops::Deref, sync::Arc}; -use crate::services::{data_store::{BannedTokenStore, UserStore}, hashmap_user_store::HashmapUserStore, hashset_banned_token_store::HashsetBannedTokenStore}; +use tokio::sync::Mutex; + +use crate::services::{data_store::{BannedTokenStore, TwoFACodeStore, UserStore}, hashmap_two_fa_code_store::HashmapTwoFACodeStore, hashmap_user_store::HashmapUserStore, hashset_banned_token_store::HashsetBannedTokenStore}; #[derive(Clone)] @@ -40,15 +42,44 @@ impl Default for BannedTokenStoreType { } +#[derive(Clone)] +pub struct TwoFACodeStoreType(pub Arc>>); + +impl Deref for TwoFACodeStoreType { + type Target = Arc>>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Default for TwoFACodeStoreType { + fn default() -> Self { + let store: Mutex> = Mutex::new(Box::new(HashmapTwoFACodeStore::default())); + Self(Arc::new(store)) + } +} + + + #[derive(Clone)] pub struct AppState { pub user_store: UserStoreType, pub banned_token_store: BannedTokenStoreType, + pub two_fa_code_store: TwoFACodeStoreType, // New! } impl AppState { - pub fn new(user_store: UserStoreType, banned_token_store: BannedTokenStoreType) -> Self { - Self { user_store, banned_token_store } + pub fn new( + user_store: UserStoreType, + banned_token_store: BannedTokenStoreType, + two_fa_code_store: TwoFACodeStoreType, // New! + ) -> Self { + Self { + user_store, + banned_token_store, + two_fa_code_store, // New! + } } // // Optional ergonomic constructor (useful for DI/tests) diff --git a/auth-service/src/domain/email.rs b/auth-service/src/domain/email.rs index de0c33f02..946b49e8d 100644 --- a/auth-service/src/domain/email.rs +++ b/auth-service/src/domain/email.rs @@ -1,7 +1,11 @@ -#[derive(Clone)] +#[derive(Clone, Debug, PartialEq, Eq, Hash)] pub struct Email(String); impl Email { + pub fn new(s: &str) -> Self { + Self(s.to_string()) + } + pub fn parse(s: String) -> Result { if !s.is_empty() && s.contains('@') { Ok(Email(s)) diff --git a/auth-service/src/main.rs b/auth-service/src/main.rs index c52702f35..ad873c624 100644 --- a/auth-service/src/main.rs +++ b/auth-service/src/main.rs @@ -1,11 +1,16 @@ -use auth_service::{Application, app_state::{AppState, BannedTokenStoreType, UserStoreType}, utils::constants::prod}; +use auth_service::{Application, app_state::{AppState, BannedTokenStoreType, TwoFACodeStoreType, UserStoreType}, utils::constants::prod}; #[tokio::main] async fn main() { let user_store = UserStoreType::default(); let banned_token_store = BannedTokenStoreType::default(); - let app_state = AppState::new(user_store, banned_token_store); // optionally, if builder pattern enabled: AppState::with_store(hashmap_store).build(); + let two_fa_code_store = TwoFACodeStoreType::default(); + let app_state = AppState::new( + user_store, + banned_token_store, + two_fa_code_store, + ); // optionally, if builder pattern enabled: AppState::with_store(hashmap_store).build(); let app = Application::build(app_state, prod::APP_ADDRESS).await.expect("Failed to build app"); app.run().await.expect("Failed to run app"); diff --git a/auth-service/src/routes/login.rs b/auth-service/src/routes/login.rs index 4d5afe0d0..02d3b96fa 100644 --- a/auth-service/src/routes/login.rs +++ b/auth-service/src/routes/login.rs @@ -1,7 +1,7 @@ use axum::{Json, extract::State, http::StatusCode, response::IntoResponse}; use axum_extra::extract::cookie::CookieJar; use serde::{Deserialize, Serialize}; -use crate::{app_state::AppState, domain::{email::Email, error::AuthAPIError, password::Password}, utils::auth::generate_auth_cookie}; +use crate::{app_state::AppState, domain::{email::Email, error::AuthAPIError, password::Password}, services::data_store::{LoginAttemptId, TwoFACode}, utils::auth::generate_auth_cookie}; pub async fn login( @@ -16,23 +16,81 @@ pub async fn login( let email = Email::parse(email).map_err(|_| AuthAPIError::InvalidCredentials)?; let password = Password::parse(password).map_err(|_| AuthAPIError::InvalidCredentials)?; + // let user_store = &_state.user_store; + // match user_store.get_user(email.clone()).await { + // Ok(user) => { + // if user.password != password { + // return Err(AuthAPIError::IncorrectCredentials); + // } + // } + // Err(_) => { + // return Err(AuthAPIError::IncorrectCredentials); + // } + // } + + // let auth_cookie = generate_auth_cookie(&email).map_err(|_| AuthAPIError::UnexpectedError)?; + + // let updated_jar = jar.add(auth_cookie); + + // return Ok((updated_jar, StatusCode::OK.into_response())); + + // let user = &_state.user_store.get_user(email.clone()).await.map_err(|_| AuthAPIError::IncorrectCredentials)?; let user_store = &_state.user_store; - match user_store.get_user(email.clone()).await { + let user = match user_store.get_user(email.clone()).await { Ok(user) => { if user.password != password { return Err(AuthAPIError::IncorrectCredentials); } + else { user } } Err(_) => { return Err(AuthAPIError::IncorrectCredentials); } + }; + + match user.requires_2fa { + // We are now passing `&user.email` and `&state` to `handle_2fa` + true => handle_2fa(&user.email, &_state, jar).await, + false => handle_no_2fa(&user.email, jar).await, } +} + + +async fn handle_2fa( + email: &Email, // New! + state: &AppState, // New! + jar: CookieJar, +) -> Result<(CookieJar, (StatusCode, Json)), AuthAPIError> { + // First, we must generate a new random login attempt ID and 2FA code + let login_attempt_id = LoginAttemptId::default(); + let code = TwoFACode::default(); + + state.two_fa_code_store.lock().await.add_code(email.to_owned(), login_attempt_id.clone(), code).await.map_err(|_| AuthAPIError::UnexpectedError)?; + + // Finally, we need to return the login attempt ID to the client + let response = Json(LoginResponse::TwoFactorAuth(TwoFactorAuthResponse { + message: "2FA required".to_owned(), + login_attempt_id: login_attempt_id.as_ref().to_string(), // Add the generated login attempt ID + })); + Ok(( + jar, + ( + StatusCode::PARTIAL_CONTENT, + response + ) + )) +} + + +async fn handle_no_2fa( + email: &Email, + jar: CookieJar, +) -> Result<(CookieJar, (StatusCode, Json)), AuthAPIError> { let auth_cookie = generate_auth_cookie(&email).map_err(|_| AuthAPIError::UnexpectedError)?; let updated_jar = jar.add(auth_cookie); - - return Ok((updated_jar, StatusCode::OK.into_response())); + Ok((updated_jar, (StatusCode::OK, Json(LoginResponse::RegularAuth)))) } @@ -43,7 +101,23 @@ pub struct LoginRequest { } -#[derive(Serialize, PartialEq, Debug, Deserialize)] -pub struct LoginResponse { +// #[derive(Serialize, PartialEq, Debug, Deserialize)] +// pub struct LoginResponse { +// pub message: String, +// } + + +#[derive(Debug, Serialize)] +#[serde(untagged)] +pub enum LoginResponse { + RegularAuth, + TwoFactorAuth(TwoFactorAuthResponse) +} + + +#[derive(Debug, Serialize, Deserialize)] +pub struct TwoFactorAuthResponse { pub message: String, + #[serde(rename = "loginAttemptId")] + pub login_attempt_id: String, } diff --git a/auth-service/src/services/data_store.rs b/auth-service/src/services/data_store.rs index 2ca22cf64..181c3feb6 100644 --- a/auth-service/src/services/data_store.rs +++ b/auth-service/src/services/data_store.rs @@ -1,3 +1,4 @@ +use rand::Rng; use crate::domain::{email::Email, password::Password, user::User}; @@ -30,3 +31,81 @@ pub trait BannedTokenStore: Send + Sync { async fn store_token(&self, token: &str) -> Result<(), BannedTokenStoreError>; async fn check_token(&self, token: &str) -> Result; } + + +#[async_trait::async_trait] +pub trait TwoFACodeStore: Send + Sync { + async fn add_code( + &mut self, + email: Email, + login_attempt_id: LoginAttemptId, + code: TwoFACode, + ) -> Result<(), TwoFACodeStoreError>; + async fn remove_code(&mut self, email: &Email) -> Result<(), TwoFACodeStoreError>; + async fn get_code( + &self, + email: &Email, + ) -> Result<(LoginAttemptId, TwoFACode), TwoFACodeStoreError>; +} + + +#[derive(Debug, PartialEq)] +pub enum TwoFACodeStoreError { + LoginAttemptIdNotFound, + UnexpectedError, +} + + +#[derive(Debug, Clone, PartialEq)] +pub struct LoginAttemptId(String); + +impl LoginAttemptId { + pub fn parse(id: String) -> Result { + match uuid::Uuid::parse_str(&id) { + Ok(_) => Ok(LoginAttemptId(id)), + Err(e) => Err(e.to_string()), + } + } +} + +impl Default for LoginAttemptId { + fn default() -> Self { + LoginAttemptId(uuid::Uuid::new_v4().to_string()) + } +} + +// TODO: Implement AsRef for LoginAttemptId +impl AsRef for LoginAttemptId { + fn as_ref(&self) -> &str { + &self.0 + } +} + + +#[derive(Clone, Debug, PartialEq)] +pub struct TwoFACode(String); + +impl TwoFACode { + pub fn parse(code: String) -> Result { + if code.len() == 6 && code.chars().all(|c| c.is_ascii_digit()) { + Ok(Self(code)) + } else { + Err("Invalid 2FA code".to_string()) + } + } +} + +impl Default for TwoFACode { + fn default() -> Self { + let mut rng = rand::rng(); + let value: u32 = rng.random_range(0..1_000_000); + Self(format!("{:06}", value)) + } +} + +impl AsRef for TwoFACode { + fn as_ref(&self) -> &str { + &self.0 + } +} + diff --git a/auth-service/src/services/hashmap_two_fa_code_store.rs b/auth-service/src/services/hashmap_two_fa_code_store.rs new file mode 100644 index 000000000..a77baf459 --- /dev/null +++ b/auth-service/src/services/hashmap_two_fa_code_store.rs @@ -0,0 +1,138 @@ +use std::collections::HashMap; +use tokio::sync::RwLock; +use crate::{domain::email::Email, services::data_store::{TwoFACodeStore, TwoFACodeStoreError}}; +use super::data_store::{LoginAttemptId, TwoFACode}; + + +#[derive(Default)] +pub struct HashmapTwoFACodeStore { + codes: RwLock>, +} + +#[async_trait::async_trait] +impl TwoFACodeStore for HashmapTwoFACodeStore { + async fn add_code( + &mut self, + email: Email, + login_attempt_id: LoginAttemptId, + code: TwoFACode, + ) -> Result<(), TwoFACodeStoreError> { + let mut guard = self.codes.write().await; + + if guard.contains_key(&email) { + return Err(TwoFACodeStoreError::UnexpectedError); + } + guard.insert(email, (login_attempt_id, code)); + + Ok(()) + } + + async fn remove_code(&mut self, email: &Email) -> Result<(), TwoFACodeStoreError> { + let mut guard = self.codes.write().await; + + guard.remove(email).ok_or(TwoFACodeStoreError::UnexpectedError)?; + + Ok(()) + } + + async fn get_code( + &self, + email: &Email, + ) -> Result<(LoginAttemptId, TwoFACode), TwoFACodeStoreError> { + let guard = self.codes.read().await; + + let res = guard.get(email).cloned().ok_or(TwoFACodeStoreError::UnexpectedError)?; + Ok(res) + } +} + + +#[cfg(test)] +mod tests { + use super::*; + use crate::domain::email::Email; + use crate::services::data_store::TwoFACodeStoreError; + + + #[tokio::test] + async fn add_code_then_get_code_returns_inserted_values() { + let mut store = HashmapTwoFACodeStore::default(); + + let email = Email::parse("test@example.com".to_string()).unwrap(); + let login_attempt_id = LoginAttemptId::default(); + let code = TwoFACode::parse("123456".to_string()).unwrap(); + + store + .add_code(email.clone(), login_attempt_id.clone(), code.clone()) + .await + .unwrap(); + + let (got_login_attempt_id, got_code) = store.get_code(&email).await.unwrap(); + assert_eq!(got_login_attempt_id, login_attempt_id); + assert_eq!(got_code, code); + } + + #[tokio::test] + async fn add_code_twice_for_same_email_returns_error() { + let mut store = HashmapTwoFACodeStore::default(); + + let email = Email::parse("test@example.com".to_string()).unwrap(); + let login_attempt_id1 = LoginAttemptId::default(); + let code1 = TwoFACode::parse("123456".to_string()).unwrap(); + + store + .add_code(email.clone(), login_attempt_id1, code1) + .await + .unwrap(); + + let login_attempt_id2 = LoginAttemptId::default(); + let code2 = TwoFACode::parse("654321".to_string()).unwrap(); + + let err = store + .add_code(email.clone(), login_attempt_id2, code2) + .await + .unwrap_err(); + + assert_eq!(err, TwoFACodeStoreError::UnexpectedError); + } + + #[tokio::test] + async fn remove_code_then_get_code_returns_error() { + let mut store = HashmapTwoFACodeStore::default(); + + let email = Email::parse("test@example.com".to_string()).unwrap(); + let login_attempt_id = LoginAttemptId::default(); + let code = TwoFACode::parse("123456".to_string()).unwrap(); + + store + .add_code(email.clone(), login_attempt_id, code) + .await + .unwrap(); + + store.remove_code(&email).await.unwrap(); + + let err = store.get_code(&email).await.unwrap_err(); + assert_eq!(err, TwoFACodeStoreError::UnexpectedError); + } + + #[tokio::test] + async fn remove_code_for_missing_email_returns_error() { + let mut store = HashmapTwoFACodeStore::default(); + + let email = Email::parse("missing@example.com".to_string()).unwrap(); + let err = store.remove_code(&email).await.unwrap_err(); + + assert_eq!(err, TwoFACodeStoreError::UnexpectedError); + } + + #[tokio::test] + async fn get_code_for_missing_email_returns_error() { + let store = HashmapTwoFACodeStore::default(); + + let email = Email::parse("missing@example.com".to_string()).unwrap(); + let err = store.get_code(&email).await.unwrap_err(); + + assert_eq!(err, TwoFACodeStoreError::UnexpectedError); + } +} + diff --git a/auth-service/src/services/hashmap_user_store.rs b/auth-service/src/services/hashmap_user_store.rs index 47a21fbd2..7889aa4eb 100644 --- a/auth-service/src/services/hashmap_user_store.rs +++ b/auth-service/src/services/hashmap_user_store.rs @@ -13,10 +13,13 @@ pub struct HashmapUserStore { #[async_trait::async_trait] impl UserStore for HashmapUserStore { async fn add_user(&self, user: User) -> Result<(), UserStoreError> { - if self.users.read().await.contains_key(user.email.as_ref()) { + let mut guard = self.users.write().await; + + if guard.contains_key(user.email.as_ref()) { return Err(UserStoreError::UserAlreadyExists); } - self.users.write().await.insert(user.email.as_ref().to_string(), user); + guard.insert(user.email.as_ref().to_string(), user); + Ok(()) } diff --git a/auth-service/src/services/mod.rs b/auth-service/src/services/mod.rs index e1def7e00..62f734096 100644 --- a/auth-service/src/services/mod.rs +++ b/auth-service/src/services/mod.rs @@ -1,3 +1,4 @@ pub mod data_store; pub mod hashmap_user_store; pub mod hashset_banned_token_store; +pub mod hashmap_two_fa_code_store; diff --git a/auth-service/tests/api/helpers.rs b/auth-service/tests/api/helpers.rs index 8d70674ca..95e26f7ca 100644 --- a/auth-service/tests/api/helpers.rs +++ b/auth-service/tests/api/helpers.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use auth_service::{Application, app_state::{AppState, BannedTokenStoreType, UserStoreType}, utils::constants::test}; +use auth_service::{Application, app_state::{AppState, BannedTokenStoreType, TwoFACodeStoreType, UserStoreType}, utils::constants::test}; use reqwest::{self, Client, cookie::Jar}; @@ -9,13 +9,20 @@ pub struct TestApp { pub cookie_jar: Arc, pub client: reqwest::Client, pub banned_token_store: BannedTokenStoreType, + pub two_fa_code_store: TwoFACodeStoreType, } impl TestApp { pub async fn run() -> Self { let user_store = UserStoreType::default(); let banned_token_store = BannedTokenStoreType::default(); - let app_state = AppState::new(user_store, banned_token_store.clone()); + let two_fa_code_store = TwoFACodeStoreType::default(); + + let app_state = AppState::new( + user_store, + banned_token_store.clone(), + two_fa_code_store.clone(), + ); let app = Application::build(app_state, test::APP_ADDRESS).await.expect("Failed to build application"); let address = format!("http://{}", app.address.clone()); @@ -29,7 +36,7 @@ impl TestApp { .build() .unwrap(); - Self { address, cookie_jar, client: http_client, banned_token_store } + Self { address, cookie_jar, client: http_client, banned_token_store, two_fa_code_store } } pub async fn get_root(&self) -> reqwest::Response { diff --git a/auth-service/tests/api/login.rs b/auth-service/tests/api/login.rs index 0dbdfe2f2..11abca056 100644 --- a/auth-service/tests/api/login.rs +++ b/auth-service/tests/api/login.rs @@ -2,7 +2,7 @@ use crate::helpers::TestApp; mod tests { - use auth_service::utils::constants::JWT_COOKIE_NAME; + use auth_service::{domain::email::Email, routes::TwoFactorAuthResponse, utils::constants::JWT_COOKIE_NAME}; use crate::helpers::get_random_email; @@ -131,4 +131,44 @@ mod tests { .find(|c| c.name() == JWT_COOKIE_NAME) .expect("no auth cookie found"); } + + #[tokio::test] + async fn should_return_206_if_valid_credentials_and_2fa_enabled() { + let app = TestApp::run().await; + + let email = get_random_email(); + + // Create a user in the test database + let signup_body = serde_json::json!({ + "email": email, + "password": "password123", + "requires2FA": true, + }); + + let response = app.post_signup(&signup_body).await; + + assert_eq!(response.status().as_u16(), 201); + + // Attempt to login with valid credentials + let login_body = serde_json::json!({ + "email": email, + "password": "password123", + "require_2fa": true, + }); + + let response = app.post_login(&login_body).await; + + assert_eq!(response.status().as_u16(), 206); + + let json_body = response + .json::() + .await + .expect("Could not deserialize response body to TwoFactorAuthResponse"); + + assert_eq!(json_body.message, "2FA required".to_owned()); + + // TODO: assert that `json_body.login_attempt_id` is stored inside `app.two_fa_code_store` + let login_attempt_id = json_body.login_attempt_id; + assert_eq!(app.two_fa_code_store.lock().await.get_code(&Email::new(&email)).await.unwrap().0.as_ref(), login_attempt_id); + } } From dfbbbb1f2953d5e53c414559bbe2cbf2fd59cdc9 Mon Sep 17 00:00:00 2001 From: comprido96 Date: Sat, 31 Jan 2026 20:53:25 +0100 Subject: [PATCH 15/17] [Sprint 4][Task 1-2] implement 2FA login --- auth-service/src/app_state.rs | 30 ++++++++++++++++--- auth-service/src/main.rs | 4 ++- auth-service/src/routes/login.rs | 4 ++- auth-service/src/services/email_client.rs | 13 ++++++++ .../src/services/mock_email_client.rs | 27 +++++++++++++++++ auth-service/src/services/mod.rs | 2 ++ auth-service/tests/api/helpers.rs | 4 ++- docker.sh | 4 +-- 8 files changed, 79 insertions(+), 9 deletions(-) create mode 100644 auth-service/src/services/email_client.rs create mode 100644 auth-service/src/services/mock_email_client.rs diff --git a/auth-service/src/app_state.rs b/auth-service/src/app_state.rs index 6bbcaed20..c063e7e2f 100644 --- a/auth-service/src/app_state.rs +++ b/auth-service/src/app_state.rs @@ -1,7 +1,7 @@ use std::{ops::Deref, sync::Arc}; use tokio::sync::Mutex; -use crate::services::{data_store::{BannedTokenStore, TwoFACodeStore, UserStore}, hashmap_two_fa_code_store::HashmapTwoFACodeStore, hashmap_user_store::HashmapUserStore, hashset_banned_token_store::HashsetBannedTokenStore}; +use crate::{services::{data_store::{BannedTokenStore, TwoFACodeStore, UserStore}, email_client::EmailClient, hashmap_two_fa_code_store::HashmapTwoFACodeStore, hashmap_user_store::HashmapUserStore, hashset_banned_token_store::HashsetBannedTokenStore, mock_email_client::MockEmailClient}}; #[derive(Clone)] @@ -61,24 +61,46 @@ impl Default for TwoFACodeStoreType { } +#[derive(Clone)] +pub struct EmailClientType(pub Arc>); + +impl Deref for EmailClientType { + type Target = Arc>; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl Default for EmailClientType { + fn default() -> Self { + let store: Box = Box::new(MockEmailClient::default()); + Self(Arc::new(store)) + } +} + + #[derive(Clone)] pub struct AppState { pub user_store: UserStoreType, pub banned_token_store: BannedTokenStoreType, - pub two_fa_code_store: TwoFACodeStoreType, // New! + pub two_fa_code_store: TwoFACodeStoreType, + pub email_client: EmailClientType, } impl AppState { pub fn new( user_store: UserStoreType, banned_token_store: BannedTokenStoreType, - two_fa_code_store: TwoFACodeStoreType, // New! + two_fa_code_store: TwoFACodeStoreType, + email_client: EmailClientType, ) -> Self { Self { user_store, banned_token_store, - two_fa_code_store, // New! + two_fa_code_store, + email_client, } } diff --git a/auth-service/src/main.rs b/auth-service/src/main.rs index ad873c624..f986a65b5 100644 --- a/auth-service/src/main.rs +++ b/auth-service/src/main.rs @@ -1,4 +1,4 @@ -use auth_service::{Application, app_state::{AppState, BannedTokenStoreType, TwoFACodeStoreType, UserStoreType}, utils::constants::prod}; +use auth_service::{Application, app_state::{AppState, BannedTokenStoreType, EmailClientType, TwoFACodeStoreType, UserStoreType}, services::email_client::EmailClient, utils::constants::prod}; #[tokio::main] @@ -6,10 +6,12 @@ async fn main() { let user_store = UserStoreType::default(); let banned_token_store = BannedTokenStoreType::default(); let two_fa_code_store = TwoFACodeStoreType::default(); + let email_client = EmailClientType::default(); let app_state = AppState::new( user_store, banned_token_store, two_fa_code_store, + email_client, ); // optionally, if builder pattern enabled: AppState::with_store(hashmap_store).build(); let app = Application::build(app_state, prod::APP_ADDRESS).await.expect("Failed to build app"); diff --git a/auth-service/src/routes/login.rs b/auth-service/src/routes/login.rs index 02d3b96fa..3c34b8548 100644 --- a/auth-service/src/routes/login.rs +++ b/auth-service/src/routes/login.rs @@ -65,7 +65,9 @@ async fn handle_2fa( let login_attempt_id = LoginAttemptId::default(); let code = TwoFACode::default(); - state.two_fa_code_store.lock().await.add_code(email.to_owned(), login_attempt_id.clone(), code).await.map_err(|_| AuthAPIError::UnexpectedError)?; + state.two_fa_code_store.lock().await.add_code(email.to_owned(), login_attempt_id.clone(), code.clone()).await.map_err(|_| AuthAPIError::UnexpectedError)?; + + state.email_client.send_email(email, "2FA Access Token", &format!("{}", code.as_ref())).await.map_err(|_| AuthAPIError::UnexpectedError)?; // Finally, we need to return the login attempt ID to the client let response = Json(LoginResponse::TwoFactorAuth(TwoFactorAuthResponse { diff --git a/auth-service/src/services/email_client.rs b/auth-service/src/services/email_client.rs new file mode 100644 index 000000000..ebd9c7468 --- /dev/null +++ b/auth-service/src/services/email_client.rs @@ -0,0 +1,13 @@ +use async_trait::async_trait; +use crate::domain::email::Email; + + +#[async_trait] +pub trait EmailClient: Send + Sync { + async fn send_email( + &self, + recipient: &Email, + subject: &str, + content: &str, + ) -> Result<(), String>; +} diff --git a/auth-service/src/services/mock_email_client.rs b/auth-service/src/services/mock_email_client.rs new file mode 100644 index 000000000..349597137 --- /dev/null +++ b/auth-service/src/services/mock_email_client.rs @@ -0,0 +1,27 @@ +use crate::domain::{email::Email}; +use super::email_client::EmailClient; + + +#[derive(Default)] +pub struct MockEmailClient; + + +#[async_trait::async_trait] +impl EmailClient for MockEmailClient { + async fn send_email( + &self, + recipient: &Email, + subject: &str, + content: &str, + ) -> Result<(), String> { + // Our mock email client will simply log the recipient, subject, and content to standard output + println!( + "Sending email to {} with subject: {} and content: {}", + recipient.as_ref(), + subject, + content + ); + + Ok(()) + } +} diff --git a/auth-service/src/services/mod.rs b/auth-service/src/services/mod.rs index 62f734096..4735bac8c 100644 --- a/auth-service/src/services/mod.rs +++ b/auth-service/src/services/mod.rs @@ -2,3 +2,5 @@ pub mod data_store; pub mod hashmap_user_store; pub mod hashset_banned_token_store; pub mod hashmap_two_fa_code_store; +pub mod email_client; +pub mod mock_email_client; diff --git a/auth-service/tests/api/helpers.rs b/auth-service/tests/api/helpers.rs index 95e26f7ca..8412a2459 100644 --- a/auth-service/tests/api/helpers.rs +++ b/auth-service/tests/api/helpers.rs @@ -1,6 +1,6 @@ use std::sync::Arc; -use auth_service::{Application, app_state::{AppState, BannedTokenStoreType, TwoFACodeStoreType, UserStoreType}, utils::constants::test}; +use auth_service::{Application, app_state::{AppState, BannedTokenStoreType, EmailClientType, TwoFACodeStoreType, UserStoreType}, utils::constants::test}; use reqwest::{self, Client, cookie::Jar}; @@ -17,11 +17,13 @@ impl TestApp { let user_store = UserStoreType::default(); let banned_token_store = BannedTokenStoreType::default(); let two_fa_code_store = TwoFACodeStoreType::default(); + let email_client = EmailClientType::default(); let app_state = AppState::new( user_store, banned_token_store.clone(), two_fa_code_store.clone(), + email_client, ); let app = Application::build(app_state, test::APP_ADDRESS).await.expect("Failed to build application"); diff --git a/docker.sh b/docker.sh index a97b3f33c..4e7717bdb 100755 --- a/docker.sh +++ b/docker.sh @@ -15,5 +15,5 @@ while IFS= read -r line; do fi done < <(grep -v "^#" "$ENV_FILE") -docker-compose build -docker-compose up +docker compose build +docker compose up From d16a27166a473a8c0078e75dac30c3db0d4812b1 Mon Sep 17 00:00:00 2001 From: comprido96 Date: Sat, 31 Jan 2026 22:41:16 +0100 Subject: [PATCH 16/17] [Sprint 4][Task 3] implement verify-2fa route --- auth-service/src/routes/verify_2fa.rs | 52 ++++- auth-service/tests/api/helpers.rs | 5 +- auth-service/tests/api/verify_2fa.rs | 291 +++++++++++++++++++++++++- 3 files changed, 338 insertions(+), 10 deletions(-) diff --git a/auth-service/src/routes/verify_2fa.rs b/auth-service/src/routes/verify_2fa.rs index 2acd21c60..fee21f7ce 100644 --- a/auth-service/src/routes/verify_2fa.rs +++ b/auth-service/src/routes/verify_2fa.rs @@ -1,6 +1,52 @@ -use axum::{response::IntoResponse, http::StatusCode}; +use axum::{Json, extract::State, http::StatusCode}; +use axum_extra::extract::CookieJar; +use serde::{Deserialize, Serialize}; +use crate::{app_state::AppState, domain::{email::Email, error::AuthAPIError}, services::data_store::{LoginAttemptId, TwoFACode}, utils::auth::generate_auth_cookie}; -pub async fn verify_2fa() -> impl IntoResponse { - StatusCode::OK.into_response() +pub async fn verify_2fa( + State(state): State, + jar: CookieJar, + Json(request): Json, +) -> Result<(CookieJar, (StatusCode, Json)), AuthAPIError> { + let email = Email::parse(request.email).map_err(|_| AuthAPIError::InvalidCredentials)?; + let login_attempt_id = + LoginAttemptId::parse(request.login_attempt_id).map_err(|_| AuthAPIError::InvalidCredentials)?; + let two_fa_code = + TwoFACode::parse(request.two_fa_code).map_err(|_| AuthAPIError::InvalidCredentials)?; + + // avoid moving out of state unless that's what you want + let two_fa_code_store = state.two_fa_code_store.clone(); + + let code_tuple = two_fa_code_store + .lock().await + .get_code(&email).await + .map_err(|_| AuthAPIError::IncorrectCredentials)?; + + if code_tuple.0 != login_attempt_id || code_tuple.1 != two_fa_code { + return Err(AuthAPIError::IncorrectCredentials); + } + + let auth_cookie = generate_auth_cookie(&email).map_err(|_| AuthAPIError::UnexpectedError)?; + let updated_jar = jar.add(auth_cookie); + + let res = two_fa_code_store.lock().await.remove_code(&email).await.map_err(|_| AuthAPIError::UnexpectedError)?; + + Ok((updated_jar, (StatusCode::OK, Json(Verify2FAResponse { message: "Ok".to_string() })))) +} + + +#[derive(Deserialize)] +pub struct Verify2FARequest { + pub email: String, + #[serde(rename = "loginAttemptId")] + pub login_attempt_id: String, + #[serde(rename = "2FACode")] + pub two_fa_code: String, +} + + +#[derive(Debug, Serialize, Deserialize)] +pub struct Verify2FAResponse { + pub message: String, } diff --git a/auth-service/tests/api/helpers.rs b/auth-service/tests/api/helpers.rs index 8412a2459..6340884f0 100644 --- a/auth-service/tests/api/helpers.rs +++ b/auth-service/tests/api/helpers.rs @@ -80,7 +80,10 @@ impl TestApp { .expect("Failed to execute request.") } - pub async fn verify_2fa(&self, body: &serde_json::Value) -> reqwest::Response { + pub async fn post_verify_2fa(&self, body: &Body) -> reqwest::Response + where + Body: serde::Serialize, + { self.client .post(format!("{}/verify-2fa", &self.address)) .json(body) diff --git a/auth-service/tests/api/verify_2fa.rs b/auth-service/tests/api/verify_2fa.rs index 099de666d..a73526406 100644 --- a/auth-service/tests/api/verify_2fa.rs +++ b/auth-service/tests/api/verify_2fa.rs @@ -2,17 +2,296 @@ use crate::helpers::TestApp; mod tests { + use auth_service::{domain::email::Email, routes::TwoFactorAuthResponse, services::data_store::LoginAttemptId, utils::constants::JWT_COOKIE_NAME}; + + use crate::helpers::get_random_email; + use super::*; #[tokio::test] - async fn test_verify_2fa() { + async fn should_return_422_if_malformed_input() { + let app = TestApp::run().await; + + let test_cases = vec![ + serde_json::json!({ + "mail": "user@example.com", + "loginAttemptId": "string", + "2FACode": "string" + }), + serde_json::json!({ + "email": "user@example.com", + "loghinAttemptId": "string", + "2FACode": "string" + }), + serde_json::json!({ + "email": "user@example.com", + "loghinAttemptId": "string", + "2FAKCode": "string" + }), + serde_json::json!({ + "email": "user@example.com", + "2FACode": "string" + }), + serde_json::json!({ + "loginAttemptId": "string", + "2FACode": "string" + }), + serde_json::json!({ + "email": "user@example.com", + "loginAttemptId": "string", + }), + serde_json::json!({}), + ]; + + for case in test_cases { + let response = app.post_verify_2fa(&case).await; + + assert_eq!(response.status().as_u16(), 422); + } + } + + + #[tokio::test] + async fn should_return_400_if_invalid_input() { + let app = TestApp::run().await; + + let test_cases = vec![ + serde_json::json!({ + "email": "userexample.com", + "loginAttemptId": "string", + "2FACode": "string" + }), + serde_json::json!({ + "email": "user@example.com", + "loginAttemptId": "", + "2FACode": "string" + }), + serde_json::json!({ + "email": "user@example.com", + "loginAttemptId": "string", + "2FACode": "" + }), + ]; + + for case in test_cases { + let response = app.post_verify_2fa(&case).await; + + assert_eq!(response.status().as_u16(), 400); + } + } + + + + #[tokio::test] + async fn should_return_401_if_incorrect_credentials() { + let app = TestApp::run().await; + + let email = get_random_email(); + + // Create a user in the test database + let signup_body = serde_json::json!({ + "email": email, + "password": "password123", + "requires2FA": true, + }); + + let response = app.post_signup(&signup_body).await; + + assert_eq!(response.status().as_u16(), 201); + + // Attempt to login with valid credentials + let login_body = serde_json::json!({ + "email": email, + "password": "password123", + }); + + let response = app.post_login(&login_body).await; + + assert_eq!(response.status().as_u16(), 206); + + let (login_attempt_id, code) = app.two_fa_code_store.lock().await.get_code(&Email::new(&email)).await.unwrap(); + let verify_2fa_body = serde_json::json!({ + "email": email, + "loginAttemptId": LoginAttemptId::default().as_ref(), + "2FACode": code.as_ref(), + }); + + let response = app.post_verify_2fa(&verify_2fa_body).await; + + assert_eq!(response.status().as_u16(), 401); + } + + + // #[tokio::test] + // async fn should_return_401_if_old_code() { + // let app = TestApp::run().await; + + // let email = get_random_email(); + + // let signup_body = serde_json::json!({ + // "email": email, + // "password": "password123", + // "requires2FA": true + // }); + + // let response = app.post_signup(&signup_body).await; + + // assert_eq!(response.status().as_u16(), 201); + + // // First login call + + // let login_body = serde_json::json!({ + // "email": email, + // "password": "password123" + // }); + + // let response = app.post_login(&login_body).await; + + // assert_eq!(response.status().as_u16(), 206); + + // let response_body = response + // .json::() + // .await + // .expect("Could not deserialize response body to TwoFactorAuthResponse"); + + // assert_eq!(response_body.message, "2FA required".to_owned()); + // assert!(!response_body.login_attempt_id.is_empty()); + + // let login_attempt_id = response_body.login_attempt_id; + + // let (login_attempt_id, code) = app.two_fa_code_store.lock().await.get_code(&Email::new(&email)).await.unwrap(); + + // // Second login call + + // let response = app.post_login(&login_body).await; + + // assert_eq!(response.status().as_u16(), 206); + + // // 2FA attempt with old login_attempt_id and code + + // let request_body = serde_json::json!({ + // "email": email, + // "loginAttemptId": login_attempt_id.as_ref(), + // "2FACode": code.as_ref() + // }); + + // let response = app.post_verify_2fa(&request_body).await; + + // assert_eq!(response.status().as_u16(), 401); + // } + + #[tokio::test] + async fn should_return_200_if_correct_code() { let app = TestApp::run().await; - let body = serde_json::json!({ - "email": "user@example.com", - "loginAttemptId": "1", - "2FACode": "123456" + + let random_email = get_random_email(); + + let signup_body = serde_json::json!({ + "email": random_email, + "password": "password123", + "requires2FA": true + }); + + let response = app.post_signup(&signup_body).await; + + assert_eq!(response.status().as_u16(), 201); + + let login_body = serde_json::json!({ + "email": random_email, + "password": "password123" + }); + + let response = app.post_login(&login_body).await; + + assert_eq!(response.status().as_u16(), 206); + + let response_body = response + .json::() + .await + .expect("Could not deserialize response body to TwoFactorAuthResponse"); + + assert_eq!(response_body.message, "2FA required".to_owned()); + assert!(!response_body.login_attempt_id.is_empty()); + + let login_attempt_id = response_body.login_attempt_id; + + let (login_attempt_id, code) = app.two_fa_code_store.lock().await.get_code(&Email::new(&random_email)).await.unwrap(); + + let request_body = serde_json::json!({ + "email": random_email, + "loginAttemptId": login_attempt_id.as_ref(), + "2FACode": code.as_ref() }); - let response = app.verify_2fa(&body).await; + + let response = app.post_verify_2fa(&request_body).await; + assert_eq!(response.status().as_u16(), 200); + + let auth_cookie = response + .cookies() + .find(|cookie| cookie.name() == JWT_COOKIE_NAME) + .expect("No auth cookie found"); + + assert!(!auth_cookie.value().is_empty()); + } + + + #[tokio::test] + async fn should_return_401_if_same_code_twice() { + let app = TestApp::run().await; + + let random_email = get_random_email(); + + let signup_body = serde_json::json!({ + "email": random_email, + "password": "password123", + "requires2FA": true + }); + + let response = app.post_signup(&signup_body).await; + + assert_eq!(response.status().as_u16(), 201); + + let login_body = serde_json::json!({ + "email": random_email, + "password": "password123" + }); + + let response = app.post_login(&login_body).await; + + assert_eq!(response.status().as_u16(), 206); + + let response_body = response + .json::() + .await + .expect("Could not deserialize response body to TwoFactorAuthResponse"); + + assert_eq!(response_body.message, "2FA required".to_owned()); + assert!(!response_body.login_attempt_id.is_empty()); + + let login_attempt_id = response_body.login_attempt_id; + + let (login_attempt_id, code) = app.two_fa_code_store.lock().await.get_code(&Email::new(&random_email)).await.unwrap(); + + let request_body = serde_json::json!({ + "email": random_email, + "loginAttemptId": login_attempt_id.as_ref(), + "2FACode": code.as_ref() + }); + + let response = app.post_verify_2fa(&request_body).await; + + assert_eq!(response.status().as_u16(), 200); + + let auth_cookie = response + .cookies() + .find(|cookie| cookie.name() == JWT_COOKIE_NAME) + .expect("No auth cookie found"); + + assert!(!auth_cookie.value().is_empty()); + + let response = app.post_verify_2fa(&request_body).await; + + assert_eq!(response.status().as_u16(), 401); } } From 39fe78208213cc375b815936fb64bb584e53dd66 Mon Sep 17 00:00:00 2001 From: comprido96 Date: Sun, 1 Feb 2026 00:31:47 +0100 Subject: [PATCH 17/17] [Sprint 5][Task 1] setup postgresql --- auth-service/Cargo.lock | 783 +++++++++++++++++- auth-service/Cargo.toml | 2 +- auth-service/build.rs | 5 + ...20260131231959_create_users_table.down.sql | 2 + .../20260131231959_create_users_table.up.sql | 6 + auth-service/src/lib.rs | 8 + auth-service/src/main.rs | 20 +- auth-service/src/utils/constants.rs | 8 + compose.yml | 38 +- 9 files changed, 850 insertions(+), 22 deletions(-) create mode 100644 auth-service/build.rs create mode 100644 auth-service/migrations/20260131231959_create_users_table.down.sql create mode 100644 auth-service/migrations/20260131231959_create_users_table.up.sql diff --git a/auth-service/Cargo.lock b/auth-service/Cargo.lock index 2691607c9..6471a7377 100644 --- a/auth-service/Cargo.lock +++ b/auth-service/Cargo.lock @@ -2,6 +2,12 @@ # 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 = "android_system_properties" version = "0.1.5" @@ -22,6 +28,15 @@ dependencies = [ "syn", ] +[[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" @@ -43,6 +58,7 @@ dependencies = [ "reqwest", "serde", "serde_json", + "sqlx", "tokio", "tower-http", "uuid", @@ -151,6 +167,9 @@ name = "bitflags" version = "2.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3" +dependencies = [ + "serde_core", +] [[package]] name = "block-buffer" @@ -208,6 +227,15 @@ dependencies = [ "windows-link", ] +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "const-oid" version = "0.9.6" @@ -258,6 +286,36 @@ 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.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d374276b40fb8bbdee95aef7c7fa6b5316ec764510eb64b8dd0e2ed0d7e7f5" + +[[package]] +name = "crossbeam-queue" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" + [[package]] name = "crypto-bigint" version = "0.5.5" @@ -403,6 +461,15 @@ dependencies = [ "zeroize", ] +[[package]] +name = "either" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719" +dependencies = [ + "serde", +] + [[package]] name = "elliptic-curve" version = "0.13.8" @@ -424,6 +491,34 @@ dependencies = [ "zeroize", ] +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "etcetera" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943" +dependencies = [ + "cfg-if", + "home", + "windows-sys 0.48.0", +] + +[[package]] +name = "event-listener" +version = "5.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite", +] + [[package]] name = "ff" version = "0.13.1" @@ -446,12 +541,29 @@ version = "0.1.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8591b0bcc8a98a64310a2fae1bb3e9b8564dd10e381e6e28010fde8e8e8568db" +[[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 = "fnv" version = "1.0.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" +[[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" @@ -468,6 +580,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2dff15bf788c671c1934e366d07e30c1814a8ef514e1af724a602e8a2fbe1b10" dependencies = [ "futures-core", + "futures-sink", ] [[package]] @@ -476,6 +589,34 @@ version = "0.3.31" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e" +[[package]] +name = "futures-executor" +version = "0.3.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e28d1d997f585e54aebc3f97d39e72338912123a67330d723fdbb564d646c9f" +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.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e5c1b78ca4aae1ac06c48a526a655760685149f0d465d21f37abfe57ce075c6" + [[package]] name = "futures-sink" version = "0.3.31" @@ -495,7 +636,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81" dependencies = [ "futures-core", + "futures-io", + "futures-sink", "futures-task", + "memchr", "pin-project-lite", "pin-utils", "slab", @@ -546,6 +690,44 @@ dependencies = [ "subtle", ] +[[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.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" + +[[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 = "hkdf" version = "0.12.4" @@ -564,6 +746,15 @@ dependencies = [ "digest", ] +[[package]] +name = "home" +version = "0.5.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d" +dependencies = [ + "windows-sys 0.61.2", +] + [[package]] name = "http" version = "1.3.1" @@ -788,6 +979,16 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "indexmap" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017" +dependencies = [ + "equivalent", + "hashbrown 0.16.1", +] + [[package]] name = "ipnet" version = "2.11.0" @@ -864,6 +1065,27 @@ version = "0.2.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de" +[[package]] +name = "libredox" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d0b95e02c851351f877147b7deea7b1afb1df71b63aa5f8270716e0c5720616" +dependencies = [ + "bitflags", + "libc", + "redox_syscall 0.7.0", +] + +[[package]] +name = "libsqlite3-sys" +version = "0.30.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e99fb7a497b1e3339bc746195567ed8d3e24945ecd636e3619d20b9de9e9149" +dependencies = [ + "pkg-config", + "vcpkg", +] + [[package]] name = "litemap" version = "0.8.1" @@ -897,6 +1119,16 @@ version = "0.8.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" +[[package]] +name = "md-5" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" +dependencies = [ + "cfg-if", + "digest", +] + [[package]] name = "memchr" version = "2.7.6" @@ -1023,6 +1255,12 @@ dependencies = [ "sha2", ] +[[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" @@ -1041,7 +1279,7 @@ checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" dependencies = [ "cfg-if", "libc", - "redox_syscall", + "redox_syscall 0.5.18", "smallvec", "windows-link", ] @@ -1104,6 +1342,12 @@ dependencies = [ "spki", ] +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + [[package]] name = "potential_utf" version = "0.1.4" @@ -1245,6 +1489,15 @@ dependencies = [ "bitflags", ] +[[package]] +name = "redox_syscall" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49f3fe0889e69e2ae9e41f4d6c4c0181701d00e4697b356fb1f74173a5e0ee27" +dependencies = [ + "bitflags", +] + [[package]] name = "reqwest" version = "0.13.1" @@ -1288,6 +1541,20 @@ dependencies = [ "subtle", ] +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + [[package]] name = "rsa" version = "0.9.8" @@ -1317,6 +1584,40 @@ dependencies = [ "semver", ] +[[package]] +name = "rustls" +version = "0.23.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c665f33d38cea657d9614f766881e4d510e0eda4239891eea56b4cadcf01801b" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be040f8b0a225e40375822a563fa9524378b9d63112f53e19ffff34df5d33fdd" +dependencies = [ + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7df23109aa6c1567d1c575b9952556388da57401e4ace1d15f79eedad0d8f53" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + [[package]] name = "rustversion" version = "1.0.22" @@ -1421,6 +1722,17 @@ dependencies = [ "serde", ] +[[package]] +name = "sha1" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3bf829a2d51ab4a5ddf1352d8470c140cadc8301b2ae1789db023f01cedd6ba" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "sha2" version = "0.10.9" @@ -1480,6 +1792,9 @@ name = "smallvec" version = "1.15.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03" +dependencies = [ + "serde", +] [[package]] name = "socket2" @@ -1496,6 +1811,9 @@ name = "spin" version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +dependencies = [ + "lock_api", +] [[package]] name = "spki" @@ -1507,12 +1825,213 @@ dependencies = [ "der", ] +[[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-mysql", + "sqlx-postgres", + "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", + "rustls", + "serde", + "serde_json", + "sha2", + "smallvec", + "thiserror", + "tokio", + "tokio-stream", + "tracing", + "url", + "webpki-roots 0.26.11", +] + +[[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", +] + +[[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-mysql", + "sqlx-postgres", + "sqlx-sqlite", + "syn", + "tokio", + "url", +] + +[[package]] +name = "sqlx-mysql" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa003f0038df784eb8fecbbac13affe3da23b45194bd57dba231c8f48199c526" +dependencies = [ + "atoi", + "base64", + "bitflags", + "byteorder", + "bytes", + "crc", + "digest", + "dotenvy", + "either", + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "generic-array", + "hex", + "hkdf", + "hmac", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "percent-encoding", + "rand 0.8.5", + "rsa", + "serde", + "sha1", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "whoami", +] + +[[package]] +name = "sqlx-postgres" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46" +dependencies = [ + "atoi", + "base64", + "bitflags", + "byteorder", + "crc", + "dotenvy", + "etcetera", + "futures-channel", + "futures-core", + "futures-util", + "hex", + "hkdf", + "hmac", + "home", + "itoa", + "log", + "md-5", + "memchr", + "once_cell", + "rand 0.8.5", + "serde", + "serde_json", + "sha2", + "smallvec", + "sqlx-core", + "stringprep", + "thiserror", + "tracing", + "whoami", +] + +[[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 = "stringprep" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1" +dependencies = [ + "unicode-bidi", + "unicode-normalization", + "unicode-properties", +] + [[package]] name = "subtle" version = "2.6.1" @@ -1611,6 +2130,21 @@ dependencies = [ "zerovec", ] +[[package]] +name = "tinyvec" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa5fdc3bce6191a1dbc8c02d5c8bffcf557bafa17c124c5264a458f1b0613fa" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + [[package]] name = "tokio" version = "1.48.0" @@ -1639,6 +2173,17 @@ dependencies = [ "syn", ] +[[package]] +name = "tokio-stream" +version = "0.1.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70" +dependencies = [ + "futures-core", + "pin-project-lite", + "tokio", +] + [[package]] name = "tokio-util" version = "0.7.17" @@ -1716,9 +2261,21 @@ checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0" 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", +] + [[package]] name = "tracing-core" version = "0.1.34" @@ -1746,12 +2303,39 @@ version = "2.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "75b844d17643ee918803943289730bec8aac480150456169e647ed0b576ba539" +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + [[package]] name = "unicode-ident" version = "1.0.22" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9312f7c4f6ff9069b165498234ce8be658059c6728633667c526e27dc2cf1df5" +[[package]] +name = "unicode-normalization" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8" +dependencies = [ + "tinyvec", +] + +[[package]] +name = "unicode-properties" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + [[package]] name = "url" version = "2.5.8" @@ -1780,6 +2364,12 @@ dependencies = [ "serde_core", ] +[[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" @@ -1810,6 +2400,12 @@ dependencies = [ "wit-bindgen", ] +[[package]] +name = "wasite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b" + [[package]] name = "wasm-bindgen" version = "0.2.108" @@ -1879,6 +2475,34 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "webpki-roots" +version = "0.26.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9" +dependencies = [ + "webpki-roots 1.0.5", +] + +[[package]] +name = "webpki-roots" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12bed680863276c63889429bfd6cab3b99943659923822de1c8a39c49e4d722c" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "whoami" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d" +dependencies = [ + "libredox", + "wasite", +] + [[package]] name = "windows-core" version = "0.62.2" @@ -1938,13 +2562,31 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + [[package]] name = "windows-sys" version = "0.60.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" dependencies = [ - "windows-targets", + "windows-targets 0.53.5", ] [[package]] @@ -1956,6 +2598,37 @@ dependencies = [ "windows-link", ] +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + [[package]] name = "windows-targets" version = "0.53.5" @@ -1963,58 +2636,148 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" dependencies = [ "windows-link", - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", - "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + [[package]] name = "windows_aarch64_gnullvm" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + [[package]] name = "windows_aarch64_msvc" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + [[package]] name = "windows_i686_gnu" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + [[package]] name = "windows_i686_gnullvm" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + [[package]] name = "windows_i686_msvc" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + [[package]] name = "windows_x86_64_gnu" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + [[package]] name = "windows_x86_64_gnullvm" version = "0.53.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + [[package]] name = "windows_x86_64_msvc" version = "0.53.1" diff --git a/auth-service/Cargo.toml b/auth-service/Cargo.toml index 0f0a248bd..0fa896bb1 100644 --- a/auth-service/Cargo.toml +++ b/auth-service/Cargo.toml @@ -19,7 +19,7 @@ chrono = "0.4.43" dotenvy = "0.15.7" lazy_static = "1.5.0" rand = "0.9.2" - +sqlx = { version = "0.8.6", features = [ "runtime-tokio-rustls", "postgres", "migrate"] } [dev-dependencies] reqwest = { version = "0.13.1", default-features = false, features = ["json", "cookies"] } diff --git a/auth-service/build.rs b/auth-service/build.rs new file mode 100644 index 000000000..d5068697c --- /dev/null +++ b/auth-service/build.rs @@ -0,0 +1,5 @@ +// generated by `sqlx migrate build-script` +fn main() { + // trigger recompilation when a new migration is added + println!("cargo:rerun-if-changed=migrations"); +} diff --git a/auth-service/migrations/20260131231959_create_users_table.down.sql b/auth-service/migrations/20260131231959_create_users_table.down.sql new file mode 100644 index 000000000..329be0477 --- /dev/null +++ b/auth-service/migrations/20260131231959_create_users_table.down.sql @@ -0,0 +1,2 @@ +-- Add down migration script here +DROP TABLE IF EXISTS users; \ No newline at end of file diff --git a/auth-service/migrations/20260131231959_create_users_table.up.sql b/auth-service/migrations/20260131231959_create_users_table.up.sql new file mode 100644 index 000000000..52ff3e247 --- /dev/null +++ b/auth-service/migrations/20260131231959_create_users_table.up.sql @@ -0,0 +1,6 @@ +-- Add up migration script here +CREATE TABLE IF NOT EXISTS users( + email TEXT NOT NULL PRIMARY KEY, + password_hash TEXT NOT NULL, + requires_2fa BOOLEAN NOT NULL DEFAULT FALSE +); \ No newline at end of file diff --git a/auth-service/src/lib.rs b/auth-service/src/lib.rs index c8627ba86..f53b3842b 100644 --- a/auth-service/src/lib.rs +++ b/auth-service/src/lib.rs @@ -1,6 +1,7 @@ use tokio::net::TcpListener; use axum::{Json, Router, http::{Method, StatusCode}, response::{IntoResponse, Response}, routing::post, serve::Serve}; use tower_http::{cors::CorsLayer, services::{ServeDir, ServeFile}}; +use sqlx::{postgres::PgPoolOptions, PgPool}; pub mod routes; pub mod domain; @@ -84,3 +85,10 @@ impl Application { Ok(()) } } + + + +pub async fn get_postgres_pool(url: &str) -> std::result::Result { + // Create a new PostgreSQL connection pool + PgPoolOptions::new().max_connections(5).connect(url).await +} diff --git a/auth-service/src/main.rs b/auth-service/src/main.rs index f986a65b5..ae2baf2ef 100644 --- a/auth-service/src/main.rs +++ b/auth-service/src/main.rs @@ -1,8 +1,10 @@ -use auth_service::{Application, app_state::{AppState, BannedTokenStoreType, EmailClientType, TwoFACodeStoreType, UserStoreType}, services::email_client::EmailClient, utils::constants::prod}; +use auth_service::{Application, app_state::{AppState, BannedTokenStoreType, EmailClientType, TwoFACodeStoreType, UserStoreType}, get_postgres_pool, services::email_client::EmailClient, utils::constants::{DATABASE_URL, prod}}; +use sqlx::PgPool; #[tokio::main] async fn main() { + let pg_pool = configure_postgresql().await; let user_store = UserStoreType::default(); let banned_token_store = BannedTokenStoreType::default(); let two_fa_code_store = TwoFACodeStoreType::default(); @@ -17,3 +19,19 @@ async fn main() { let app = Application::build(app_state, prod::APP_ADDRESS).await.expect("Failed to build app"); app.run().await.expect("Failed to run app"); } + + +async fn configure_postgresql() -> PgPool { + // Create a new database connection pool + let pg_pool = get_postgres_pool(&DATABASE_URL) + .await + .expect("Failed to create Postgres connection pool!"); + + // Run database migrations against our test database! + sqlx::migrate!() + .run(&pg_pool) + .await + .expect("Failed to run migrations"); + + pg_pool +} diff --git a/auth-service/src/utils/constants.rs b/auth-service/src/utils/constants.rs index cd7ddf688..5746846ab 100644 --- a/auth-service/src/utils/constants.rs +++ b/auth-service/src/utils/constants.rs @@ -16,6 +16,13 @@ pub mod test { // Define a lazily evaluated static. lazy_static is needed because std_env::var is not a const function. lazy_static! { pub static ref JWT_SECRET: String = set_token(); + pub static ref DATABASE_URL: String = set_db_url(); +} + + +fn set_db_url() -> String { + dotenv().ok(); + std_env::var(env::DATABASE_URL_ENV_VAR).expect("DATABASE_URL must be set.") } @@ -30,6 +37,7 @@ fn set_token() -> String { } pub mod env { + pub const DATABASE_URL_ENV_VAR: &str = "DATABASE_URL"; pub const JWT_SECRET_ENV_VAR: &str = "JWT_SECRET"; } diff --git a/compose.yml b/compose.yml index 499553c0a..4a5017fd7 100644 --- a/compose.yml +++ b/compose.yml @@ -1,20 +1,38 @@ services: app-service: - # TODO: change "letsgetrusty" to your Docker Hub username - image: fedecomprido/app-service # specify name of image on Docker Hub - restart: "always" # automatically restart container when server crashes - environment: # set up environment variables - AUTH_SERVICE_IP: ${AUTH_SERVICE_IP:-localhost} # Use localhost as the default value + image: fedecomprido/app-service + restart: "always" + environment: + AUTH_SERVICE_IP: ${AUTH_SERVICE_IP:-localhost} ports: - - "8000:8000" # expose port 8000 so that applications outside the container can connect to it - depends_on: # only run app-service after auth-service has started + - "8000:8000" + depends_on: auth-service: condition: service_started auth-service: - # TODO: change "letsgetrusty" to your Docker Hub username image: fedecomprido/auth-service - restart: "always" # automatically restart container when server crashes + restart: "always" environment: JWT_SECRET: ${JWT_SECRET} + # New! + DATABASE_URL: "postgres://postgres:${POSTGRES_PASSWORD}@db:5432" + ports: + - "3000:3000" + # New! + depends_on: + - db + # New! + db: + image: postgres:15.2-alpine + restart: always + environment: + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD} ports: - - "3000:3000" # expose port 3000 so that applications outside the container can connect to it \ No newline at end of file + - "5432:5432" + volumes: + - db:/var/lib/postgresql/data + +# New! +volumes: + db: + driver: local \ No newline at end of file