Router assembly, OpenAPI/Swagger, CORS, and bootstrap
Browse files at this commitc4d0a2381cc266d9fbc332f6de02450cb5db51ebParent: 3c4822c- feat
- router assembly, OpenAPI/Swagger, CORS, and bootstrap
3 changed files +210 -0
- src/lib.rs +139 -0
- src/main.rs +57 -0
- src/state.rs +14 -0
src/lib.rsadded+139 -0
| @@ -0,0 +1,139 @@ | |||
| 1 | +pub mod config; | ||
| 2 | +pub mod constant; | ||
| 3 | +pub mod database; | ||
| 4 | +pub mod domain; | ||
| 5 | +pub mod error; | ||
| 6 | +pub mod rate_limit; | ||
| 7 | +pub mod state; | ||
| 8 | +pub mod validate; | ||
| 9 | +pub mod web; | ||
| 10 | + | ||
| 11 | +use axum::extract::Request; | ||
| 12 | +use axum::http::{HeaderValue, Method, header}; | ||
| 13 | +use axum::middleware::{self, Next}; | ||
| 14 | +use axum::routing::get; | ||
| 15 | +use axum::{Json, Router}; | ||
| 16 | +use serde_json::json; | ||
| 17 | +use tower_http::cors::{AllowOrigin, CorsLayer}; | ||
| 18 | +use tower_http::trace::TraceLayer; | ||
| 19 | +use utoipa::openapi::security::{ApiKey, ApiKeyValue, SecurityScheme}; | ||
| 20 | +use utoipa::{Modify, OpenApi}; | ||
| 21 | +use utoipa_axum::router::OpenApiRouter; | ||
| 22 | +use utoipa_axum::routes; | ||
| 23 | +use utoipa_swagger_ui::SwaggerUi; | ||
| 24 | + | ||
| 25 | +use crate::rate_limit::RateLimiter; | ||
| 26 | +use crate::state::AppState; | ||
| 27 | + | ||
| 28 | +/// Top-level OpenAPI document. Per-path operations and schemas are collected | ||
| 29 | +/// automatically from the `#[utoipa::path]`-annotated handlers via `utoipa-axum`. | ||
| 30 | +#[derive(OpenApi)] | ||
| 31 | +#[openapi( | ||
| 32 | + info( | ||
| 33 | + title = "Hezarfen Backend API", | ||
| 34 | + version = env!("CARGO_PKG_VERSION"), | ||
| 35 | + description = "Notes, events, attendance, and exams behind cookie-session auth.", | ||
| 36 | + ), | ||
| 37 | + modifiers(&SecurityAddon), | ||
| 38 | + tags( | ||
| 39 | + (name = "meta", description = "Liveness and service metadata"), | ||
| 40 | + (name = "auth", description = "Registration, login, session lifecycle"), | ||
| 41 | + (name = "users", description = "User listing and role administration (admin only)"), | ||
| 42 | + (name = "notes", description = "Per-user notes CRUD"), | ||
| 43 | + (name = "events", description = "Events and attendance"), | ||
| 44 | + (name = "exams", description = "Exams (homework/quiz) and student results"), | ||
| 45 | + ), | ||
| 46 | +)] | ||
| 47 | +struct ApiDoc; | ||
| 48 | + | ||
| 49 | +/// Registers the `session` cookie as an API-key security scheme so protected | ||
| 50 | +/// operations render an auth requirement in the docs. | ||
| 51 | +struct SecurityAddon; | ||
| 52 | + | ||
| 53 | +impl Modify for SecurityAddon { | ||
| 54 | + fn modify(&self, openapi: &mut utoipa::openapi::OpenApi) { | ||
| 55 | + if let Some(components) = openapi.components.as_mut() { | ||
| 56 | + components.add_security_scheme( | ||
| 57 | + "session_cookie", | ||
| 58 | + SecurityScheme::ApiKey(ApiKey::Cookie(ApiKeyValue::new("session"))), | ||
| 59 | + ); | ||
| 60 | + } | ||
| 61 | + } | ||
| 62 | +} | ||
| 63 | + | ||
| 64 | +/// Assemble the full application router. Shared by `main` and the test suites. | ||
| 65 | +/// | ||
| 66 | +/// Also serves interactive docs: Swagger UI at `/swagger`, raw spec at | ||
| 67 | +/// `/api-docs/openapi.json`. Root `/` mirrors the health probe. | ||
| 68 | +pub fn build_router(state: AppState) -> Router { | ||
| 69 | + let (router, api) = OpenApiRouter::with_openapi(ApiDoc::openapi()) | ||
| 70 | + .route("/", get(health)) | ||
| 71 | + .routes(routes!(health)) | ||
| 72 | + .nest("/auth", web::auth::routes(&state.rate_limit)) | ||
| 73 | + .nest("/users", web::users::routes()) | ||
| 74 | + .nest("/notes", web::notes::routes()) | ||
| 75 | + .nest("/events", web::events::routes()) | ||
| 76 | + .nest("/exams", web::exams::routes()) | ||
| 77 | + .split_for_parts(); | ||
| 78 | + | ||
| 79 | + // Catch-all per-IP limit over every route (Swagger included). Kept inside | ||
| 80 | + // the CORS layer so a 429 still carries the CORS headers a browser needs | ||
| 81 | + // to surface the error to frontend code. | ||
| 82 | + let api_limiter = RateLimiter::per_minute( | ||
| 83 | + state.rate_limit.api_per_minute, | ||
| 84 | + state.rate_limit.trust_proxy, | ||
| 85 | + ); | ||
| 86 | + | ||
| 87 | + router | ||
| 88 | + .merge(SwaggerUi::new("/swagger").url("/api-docs/openapi.json", api)) | ||
| 89 | + .with_state(state) | ||
| 90 | + .layer(middleware::from_fn(move |req: Request, next: Next| { | ||
| 91 | + let limiter = api_limiter.clone(); | ||
| 92 | + async move { limiter.enforce(req, next).await } | ||
| 93 | + })) | ||
| 94 | + .layer(cors_layer()) | ||
| 95 | + .layer(TraceLayer::new_for_http()) | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +/// CORS for a cookie-authenticated API. `CorsLayer::permissive()` would send | ||
| 99 | +/// `Access-Control-Allow-Origin: *`, which browsers refuse to combine with | ||
| 100 | +/// credentialed (cookie) requests — so instead reflect the caller's origin, or a | ||
| 101 | +/// `CORS_ALLOWED_ORIGINS` (comma-separated) allowlist when set, and advertise | ||
| 102 | +/// `Access-Control-Allow-Credentials: true`. | ||
| 103 | +fn cors_layer() -> CorsLayer { | ||
| 104 | + let layer = CorsLayer::new() | ||
| 105 | + .allow_methods([ | ||
| 106 | + Method::GET, | ||
| 107 | + Method::POST, | ||
| 108 | + Method::PATCH, | ||
| 109 | + Method::DELETE, | ||
| 110 | + Method::OPTIONS, | ||
| 111 | + ]) | ||
| 112 | + .allow_headers([header::CONTENT_TYPE]) | ||
| 113 | + .allow_credentials(true); | ||
| 114 | + | ||
| 115 | + let allowlist: Vec<HeaderValue> = std::env::var("CORS_ALLOWED_ORIGINS") | ||
| 116 | + .unwrap_or_default() | ||
| 117 | + .split(',') | ||
| 118 | + .map(str::trim) | ||
| 119 | + .filter(|origin| !origin.is_empty()) | ||
| 120 | + .filter_map(|origin| origin.parse().ok()) | ||
| 121 | + .collect(); | ||
| 122 | + | ||
| 123 | + if allowlist.is_empty() { | ||
| 124 | + layer.allow_origin(AllowOrigin::mirror_request()) | ||
| 125 | + } else { | ||
| 126 | + layer.allow_origin(AllowOrigin::list(allowlist)) | ||
| 127 | + } | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +/// Liveness probe. | ||
| 131 | +#[utoipa::path( | ||
| 132 | + get, | ||
| 133 | + path = "/health", | ||
| 134 | + tag = "meta", | ||
| 135 | + responses((status = 200, description = "Service is up")), | ||
| 136 | +)] | ||
| 137 | +async fn health() -> Json<serde_json::Value> { | ||
| 138 | + Json(json!({ "status": "ok" })) | ||
| 139 | +} | ||
src/main.rsadded+57 -0
| @@ -0,0 +1,57 @@ | |||
| 1 | +use hezarfen_backend::config::Config; | ||
| 2 | +use hezarfen_backend::state::AppState; | ||
| 3 | +use hezarfen_backend::{build_router, database}; | ||
| 4 | + | ||
| 5 | +#[tokio::main] | ||
| 6 | +async fn main() -> anyhow::Result<()> { | ||
| 7 | + dotenvy::dotenv().ok(); | ||
| 8 | + tracing_subscriber::fmt() | ||
| 9 | + .with_env_filter( | ||
| 10 | + tracing_subscriber::EnvFilter::try_from_default_env() | ||
| 11 | + .unwrap_or_else(|_| "info,hezarfen_backend=debug".into()), | ||
| 12 | + ) | ||
| 13 | + .init(); | ||
| 14 | + | ||
| 15 | + let cfg = Config::from_env(); | ||
| 16 | + let db = database::init(&cfg).await?; | ||
| 17 | + let app = build_router(AppState { | ||
| 18 | + db, | ||
| 19 | + cookie_secure: cfg.cookie_secure, | ||
| 20 | + rate_limit: cfg.rate_limit.clone(), | ||
| 21 | + }); | ||
| 22 | + | ||
| 23 | + let addr = format!("{}:{}", cfg.host, cfg.port); | ||
| 24 | + let listener = tokio::net::TcpListener::bind(addr.as_str()).await?; | ||
| 25 | + tracing::info!("hezarfen_backend listening on http://{addr}"); | ||
| 26 | + // `with_connect_info` records each connection's peer address, which the | ||
| 27 | + // rate limiter uses as its per-client key (unless TRUST_PROXY is set). | ||
| 28 | + axum::serve( | ||
| 29 | + listener, | ||
| 30 | + app.into_make_service_with_connect_info::<std::net::SocketAddr>(), | ||
| 31 | + ) | ||
| 32 | + .with_graceful_shutdown(shutdown_signal()) | ||
| 33 | + .await?; | ||
| 34 | + tracing::info!("shutting down"); | ||
| 35 | + Ok(()) | ||
| 36 | +} | ||
| 37 | + | ||
| 38 | +/// Resolve on SIGINT (Ctrl-C) or SIGTERM. As PID 1 in a container the process | ||
| 39 | +/// gets no default signal handling, so without this a `podman stop` waits out | ||
| 40 | +/// its grace period and SIGKILLs us — skipping the embedded store's clean close. | ||
| 41 | +async fn shutdown_signal() { | ||
| 42 | + let ctrl_c = async { | ||
| 43 | + tokio::signal::ctrl_c() | ||
| 44 | + .await | ||
| 45 | + .expect("failed to install SIGINT handler"); | ||
| 46 | + }; | ||
| 47 | + let terminate = async { | ||
| 48 | + tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) | ||
| 49 | + .expect("failed to install SIGTERM handler") | ||
| 50 | + .recv() | ||
| 51 | + .await; | ||
| 52 | + }; | ||
| 53 | + tokio::select! { | ||
| 54 | + _ = ctrl_c => {}, | ||
| 55 | + _ = terminate => {}, | ||
| 56 | + } | ||
| 57 | +} | ||
src/state.rsadded+14 -0
| @@ -0,0 +1,14 @@ | |||
| 1 | +use crate::database::Database; | ||
| 2 | +use crate::rate_limit::RateLimitConfig; | ||
| 3 | + | ||
| 4 | +/// Shared application state handed to every handler. | ||
| 5 | +#[derive(Clone)] | ||
| 6 | +pub struct AppState { | ||
| 7 | + pub db: Database, | ||
| 8 | + /// Whether the session cookie carries the `Secure` attribute | ||
| 9 | + /// (from [`crate::config::Config::cookie_secure`]). | ||
| 10 | + pub cookie_secure: bool, | ||
| 11 | + /// Per-IP request limits (from [`crate::config::Config::rate_limit`]). | ||
| 12 | + /// Read once by [`crate::build_router`] when the limiters are built. | ||
| 13 | + pub rate_limit: RateLimitConfig, | ||
| 14 | +} | ||