From c4d0a2381cc266d9fbc332f6de02450cb5db51eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sat, 11 Jul 2026 21:39:14 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(app):=20router=20assembly,=20O?= =?UTF-8?q?penAPI/Swagger,=20CORS,=20and=20bootstrap?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit state.rs defines AppState — the db handle, cookie_secure flag, and rate-limit config shared by every handler. lib.rs build_router assembles the whole app (shared by main and the test suites): it mounts each feature router, serves /health and root, and layers the catch-all per-IP rate limiter inside CORS so a 429 still carries the headers a browser needs. CORS is credential-aware — it reflects the request Origin, or a CORS_ALLOWED_ORIGINS allowlist when set, never a wildcard. utoipa collects the OpenAPI spec from the handlers and serves Swagger UI at /swagger with the session cookie as a documented security scheme. main.rs is the bootstrap: load .env, init tracing, read Config, open the database, serve with per-connection peer info (the limiter's key), and shut down cleanly on SIGINT/SIGTERM so the embedded store closes — important as PID 1 in a container. --- src/lib.rs | 139 +++++++++++++++++++++++++++++++++++++++++++++++++++ src/main.rs | 57 +++++++++++++++++++++ src/state.rs | 14 ++++++ 3 files changed, 210 insertions(+) create mode 100644 src/lib.rs create mode 100644 src/main.rs create mode 100644 src/state.rs diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..685e510 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,139 @@ +pub mod config; +pub mod constant; +pub mod database; +pub mod domain; +pub mod error; +pub mod rate_limit; +pub mod state; +pub mod validate; +pub mod web; + +use axum::extract::Request; +use axum::http::{HeaderValue, Method, header}; +use axum::middleware::{self, Next}; +use axum::routing::get; +use axum::{Json, Router}; +use serde_json::json; +use tower_http::cors::{AllowOrigin, CorsLayer}; +use tower_http::trace::TraceLayer; +use utoipa::openapi::security::{ApiKey, ApiKeyValue, SecurityScheme}; +use utoipa::{Modify, OpenApi}; +use utoipa_axum::router::OpenApiRouter; +use utoipa_axum::routes; +use utoipa_swagger_ui::SwaggerUi; + +use crate::rate_limit::RateLimiter; +use crate::state::AppState; + +/// Top-level OpenAPI document. Per-path operations and schemas are collected +/// automatically from the `#[utoipa::path]`-annotated handlers via `utoipa-axum`. +#[derive(OpenApi)] +#[openapi( + info( + title = "Hezarfen Backend API", + version = env!("CARGO_PKG_VERSION"), + description = "Notes, events, attendance, and exams behind cookie-session auth.", + ), + modifiers(&SecurityAddon), + tags( + (name = "meta", description = "Liveness and service metadata"), + (name = "auth", description = "Registration, login, session lifecycle"), + (name = "users", description = "User listing and role administration (admin only)"), + (name = "notes", description = "Per-user notes CRUD"), + (name = "events", description = "Events and attendance"), + (name = "exams", description = "Exams (homework/quiz) and student results"), + ), +)] +struct ApiDoc; + +/// Registers the `session` cookie as an API-key security scheme so protected +/// operations render an auth requirement in the docs. +struct SecurityAddon; + +impl Modify for SecurityAddon { + fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) { + if let Some(components) = openapi.components.as_mut() { + components.add_security_scheme( + "session_cookie", + SecurityScheme::ApiKey(ApiKey::Cookie(ApiKeyValue::new("session"))), + ); + } + } +} + +/// Assemble the full application router. Shared by `main` and the test suites. +/// +/// Also serves interactive docs: Swagger UI at `/swagger`, raw spec at +/// `/api-docs/openapi.json`. Root `/` mirrors the health probe. +pub fn build_router(state: AppState) -> Router { + let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi()) + .route("/", get(health)) + .routes(routes!(health)) + .nest("/auth", web::auth::routes(&state.rate_limit)) + .nest("/users", web::users::routes()) + .nest("/notes", web::notes::routes()) + .nest("/events", web::events::routes()) + .nest("/exams", web::exams::routes()) + .split_for_parts(); + + // Catch-all per-IP limit over every route (Swagger included). Kept inside + // the CORS layer so a 429 still carries the CORS headers a browser needs + // to surface the error to frontend code. + let api_limiter = RateLimiter::per_minute( + state.rate_limit.api_per_minute, + state.rate_limit.trust_proxy, + ); + + router + .merge(SwaggerUi::new("/swagger").url("/api-docs/openapi.json", api)) + .with_state(state) + .layer(middleware::from_fn(move |req: Request, next: Next| { + let limiter = api_limiter.clone(); + async move { limiter.enforce(req, next).await } + })) + .layer(cors_layer()) + .layer(TraceLayer::new_for_http()) +} + +/// CORS for a cookie-authenticated API. `CorsLayer::permissive()` would send +/// `Access-Control-Allow-Origin: *`, which browsers refuse to combine with +/// credentialed (cookie) requests — so instead reflect the caller's origin, or a +/// `CORS_ALLOWED_ORIGINS` (comma-separated) allowlist when set, and advertise +/// `Access-Control-Allow-Credentials: true`. +fn cors_layer() -> CorsLayer { + let layer = CorsLayer::new() + .allow_methods([ + Method::GET, + Method::POST, + Method::PATCH, + Method::DELETE, + Method::OPTIONS, + ]) + .allow_headers([header::CONTENT_TYPE]) + .allow_credentials(true); + + let allowlist: Vec = std::env::var("CORS_ALLOWED_ORIGINS") + .unwrap_or_default() + .split(',') + .map(str::trim) + .filter(|origin| !origin.is_empty()) + .filter_map(|origin| origin.parse().ok()) + .collect(); + + if allowlist.is_empty() { + layer.allow_origin(AllowOrigin::mirror_request()) + } else { + layer.allow_origin(AllowOrigin::list(allowlist)) + } +} + +/// Liveness probe. +#[utoipa::path( + get, + path = "/health", + tag = "meta", + responses((status = 200, description = "Service is up")), +)] +async fn health() -> Json { + Json(json!({ "status": "ok" })) +} diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..90b1c25 --- /dev/null +++ b/src/main.rs @@ -0,0 +1,57 @@ +use hezarfen_backend::config::Config; +use hezarfen_backend::state::AppState; +use hezarfen_backend::{build_router, database}; + +#[tokio::main] +async fn main() -> anyhow::Result<()> { + dotenvy::dotenv().ok(); + tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::try_from_default_env() + .unwrap_or_else(|_| "info,hezarfen_backend=debug".into()), + ) + .init(); + + let cfg = Config::from_env(); + let db = database::init(&cfg).await?; + let app = build_router(AppState { + db, + cookie_secure: cfg.cookie_secure, + rate_limit: cfg.rate_limit.clone(), + }); + + let addr = format!("{}:{}", cfg.host, cfg.port); + let listener = tokio::net::TcpListener::bind(addr.as_str()).await?; + tracing::info!("hezarfen_backend listening on http://{addr}"); + // `with_connect_info` records each connection's peer address, which the + // rate limiter uses as its per-client key (unless TRUST_PROXY is set). + axum::serve( + listener, + app.into_make_service_with_connect_info::(), + ) + .with_graceful_shutdown(shutdown_signal()) + .await?; + tracing::info!("shutting down"); + Ok(()) +} + +/// Resolve on SIGINT (Ctrl-C) or SIGTERM. As PID 1 in a container the process +/// gets no default signal handling, so without this a `podman stop` waits out +/// its grace period and SIGKILLs us — skipping the embedded store's clean close. +async fn shutdown_signal() { + let ctrl_c = async { + tokio::signal::ctrl_c() + .await + .expect("failed to install SIGINT handler"); + }; + let terminate = async { + tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) + .expect("failed to install SIGTERM handler") + .recv() + .await; + }; + tokio::select! { + _ = ctrl_c => {}, + _ = terminate => {}, + } +} diff --git a/src/state.rs b/src/state.rs new file mode 100644 index 0000000..f1c7de6 --- /dev/null +++ b/src/state.rs @@ -0,0 +1,14 @@ +use crate::database::Database; +use crate::rate_limit::RateLimitConfig; + +/// Shared application state handed to every handler. +#[derive(Clone)] +pub struct AppState { + pub db: Database, + /// Whether the session cookie carries the `Secure` attribute + /// (from [`crate::config::Config::cookie_secure`]). + pub cookie_secure: bool, + /// Per-IP request limits (from [`crate::config::Config::rate_limit`]). + /// Read once by [`crate::build_router`] when the limiters are built. + pub rate_limit: RateLimitConfig, +}