manta_server/server/mod.rs
1//! Axum HTTP/HTTPS server setup.
2//!
3//! - [`ServerState`] — shared application state passed through every
4//! handler via Axum's `State<Arc<ServerState>>` extractor. Holds one
5//! [`SiteBackend`] per configured site so a single server can fan
6//! out to multiple CSM/OpenCHAMI clusters.
7//! - [`start_server`] — binary entry point. Builds the router (see
8//! [`routes::build_router`]), installs the request-logging
9//! middleware, optionally wraps the listener in TLS, and installs a
10//! SIGTERM/Ctrl+C handler for graceful shutdown.
11//! - Submodules:
12//! - [`handlers`] — per-resource Axum handlers; converts HTTP
13//! requests into service-layer calls.
14//! - [`routes`] — router registration (one entry per `/v2`
15//! path).
16//! - [`audit`] — audit trail of every mutating request (middleware,
17//! event schema, Kafka + log sinks).
18//! - [`common`] — server-only helpers (per-request `InfraContext`,
19//! JWT claim extractors, Vault client).
20//! - [`api_doc`] — utoipa OpenAPI document served at
21//! `GET /openapi.json` + `GET /docs`.
22
23pub mod api_doc;
24pub mod audit;
25pub mod common;
26pub mod handlers;
27pub mod routes;
28
29use std::collections::HashMap;
30use std::net::SocketAddr;
31use std::sync::Arc;
32
33use axum_server::tls_rustls::RustlsConfig;
34use manta_backend_dispatcher::error::Error;
35use std::time::Duration;
36
37use crate::dispatcher::StaticBackendDispatcher;
38use crate::server::audit::AuditLog;
39use crate::server::common::app_context::InfraContext;
40
41/// All per-site connection data the server needs to talk to backend APIs.
42///
43/// Built once at startup from a `[sites.X]` block in `server.toml`,
44/// then owned by [`ServerState::sites`] inside a `HashMap` keyed by
45/// the site name. The matching `[sites.X]` block is selected per
46/// request from the `X-Manta-Site` header.
47///
48/// Borrowed per request as an [`common::app_context::InfraContext`]
49/// via [`ServerState::infra_context`] so the service layer can pass
50/// the per-site bundle around without taking ownership.
51pub struct SiteBackend {
52 /// Dispatches API calls to the configured CSM or OpenCHAMI backend.
53 pub backend: StaticBackendDispatcher,
54 /// Base URL for the CSM/OpenCHAMI API (e.g. `https://api.cluster/apis`).
55 pub shasta_base_url: String,
56 /// PEM-encoded root CA certificate for the backend; empty vec skips verification.
57 pub shasta_root_cert: Vec<u8>,
58 /// HashiCorp Vault base URL; `None` means features requiring vault return 501.
59 pub vault_base_url: Option<String>,
60 /// Gitea VCS base URL derived from the site base URL.
61 pub gitea_base_url: String,
62 /// Kubernetes API URL; `None` means console and log-streaming endpoints return 501.
63 pub k8s_api_url: Option<String>,
64}
65
66/// Shared state for all HTTP handlers.
67///
68/// Holds one [`SiteBackend`] per configured site so a single server
69/// can serve multiple clusters. Each request supplies the target site
70/// via the `X-Manta-Site` header; handlers call
71/// [`ServerState::infra_context`] (or, via the
72/// [`handlers::RequestCtx`] extractor, the cached
73/// `RequestCtx::infra()` shortcut) to retrieve the per-site data.
74///
75/// Plumbed through Axum's `State<Arc<ServerState>>` extractor. Owned
76/// by [`start_server`] and cloned (cheaply, since it's an `Arc`) into
77/// every spawned task.
78pub struct ServerState {
79 /// Per-site connection data, keyed by site name.
80 pub sites: HashMap<String, SiteBackend>,
81 /// How long a WebSocket console session may be idle before the server
82 /// closes it. Protects against leaked Kubernetes pod attachments.
83 pub console_inactivity_timeout: Duration,
84 /// Audit trail every mutating request is recorded to (always the
85 /// log; Kafka too when `[auditor.kafka]` is configured).
86 pub audit: AuditLog,
87 /// Global request timeout applied to every HTTP route (router-level
88 /// `TimeoutLayer`). All long-running work (power transitions, SAT
89 /// dispatch) runs CLI-side, so this is the only request-timeout
90 /// knob the server has.
91 pub request_timeout: Duration,
92 /// Drain window for `axum_server::Handle::graceful_shutdown` on
93 /// SIGTERM / Ctrl+C. Sourced from
94 /// `server.toml`'s `[server] shutdown_grace_period_secs`.
95 pub shutdown_grace_period: Duration,
96 /// Filesystem root that confines `POST /migrate/{backup,restore}`
97 /// file access. `None` disables both endpoints — even admin callers
98 /// must wait for an operator to opt in via `[server]
99 /// migrate_backup_root`. The path is stored already-canonicalised
100 /// so per-request validation is a single `starts_with` against this.
101 pub migrate_backup_root: Option<std::path::PathBuf>,
102}
103
104impl ServerState {
105 /// Build a borrowed [`InfraContext`] for the named site.
106 ///
107 /// Called per-request so the service layer can work with its
108 /// existing `&InfraContext<'_>` API without taking ownership of the
109 /// underlying [`SiteBackend`].
110 ///
111 /// # Errors
112 ///
113 /// Returns [`Error::NotFound`] when `site_name` is not in
114 /// [`Self::sites`].
115 pub fn infra_context<'a>(
116 &'a self,
117 site_name: &'a str,
118 ) -> Result<InfraContext<'a>, Error> {
119 let site = self.sites.get(site_name).ok_or_else(|| {
120 Error::NotFound(format!("site '{site_name}' not found"))
121 })?;
122 Ok(InfraContext {
123 backend: &site.backend,
124 site_name,
125 shasta_base_url: &site.shasta_base_url,
126 shasta_root_cert: &site.shasta_root_cert,
127 vault_base_url: site.vault_base_url.as_deref(),
128 gitea_base_url: &site.gitea_base_url,
129 k8s_api_url: site.k8s_api_url.as_deref(),
130 })
131 }
132}
133
134/// Request-logging middleware. Logs `method uri → status` at INFO
135/// after the inner handler returns, including handler-internal
136/// error responses. Composed once by [`start_server`] around the
137/// router built by [`routes::build_router`].
138async fn log_requests(
139 request: axum::extract::Request,
140 next: axum::middleware::Next,
141) -> axum::response::Response {
142 let method = request.method().clone();
143 let uri = request.uri().clone();
144 let response = next.run(request).await;
145 tracing::info!("{} {} → {}", method, uri, response.status());
146 response
147}
148
149/// How long shutdown waits for queued audit events to reach Kafka.
150pub const AUDIT_FLUSH_TIMEOUT: Duration = Duration::from_secs(5);
151
152/// Start the HTTP or HTTPS server.
153///
154/// Builds the router via [`routes::build_router`], wraps it with the
155/// request-logging middleware, binds the listener at
156/// `<listen_addr>:<port>`, and serves until a SIGTERM or Ctrl+C is
157/// received — at which point the in-process shutdown handler
158/// triggers `axum_server`'s graceful drain with the
159/// [`ServerState::shutdown_grace_period`] window.
160///
161/// When `cert_path` and `key_path` are both `Some`, the server
162/// listens with TLS (`https://`). When both are `None`, it listens
163/// as plain HTTP. Mixing one of the two is rejected.
164///
165/// After the drain, audit events still queued for Kafka get up to
166/// [`AUDIT_FLUSH_TIMEOUT`] to be delivered.
167///
168/// # Errors
169///
170/// - [`Error::BadRequest`] when `listen_addr:port` does not parse as
171/// a `SocketAddr`, or when exactly one of `cert_path` / `key_path`
172/// is supplied (they must be set together).
173/// - Any I/O / TLS load error from `RustlsConfig::from_pem_file` or
174/// the underlying `axum_server::bind*` call surfaces via the
175/// `From<io::Error>` impl on [`Error`].
176pub async fn start_server(
177 state: Arc<ServerState>,
178 listen_addr: &str,
179 port: u16,
180 cert_path: Option<&str>,
181 key_path: Option<&str>,
182) -> Result<(), Error> {
183 // Read shutdown-grace before `state` is moved into the router.
184 let shutdown_grace_period = state.shutdown_grace_period;
185 let audit = state.audit.clone();
186
187 // Both `request_timeout` and `power_timeout` are now applied **inside**
188 // `build_router` so the per-route `/power` override actually wins —
189 // see the comment on `build_router` for why a global outer layer
190 // would silently defeat the override.
191 let app =
192 routes::build_router(state).layer(axum::middleware::from_fn(log_requests));
193
194 let addr: SocketAddr = format!("{listen_addr}:{port}")
195 .parse()
196 .map_err(|e| Error::BadRequest(format!("Invalid listen address: {e}")))?;
197
198 match (cert_path, key_path) {
199 (Some(cert), Some(key)) => {
200 let tls_config = RustlsConfig::from_pem_file(cert, key).await?;
201 let handle = axum_server::Handle::new();
202 let ready_handle = handle.clone();
203 tokio::spawn(async move {
204 ready_handle.listening().await;
205 tracing::info!(
206 "HTTPS server ready, accepting requests on https://{}",
207 addr
208 );
209 eprintln!("HTTPS server ready, accepting requests on https://{addr}");
210 });
211 install_shutdown_handler(handle.clone(), shutdown_grace_period);
212 axum_server::bind_rustls(addr, tls_config)
213 .handle(handle)
214 .serve(app.into_make_service_with_connect_info::<SocketAddr>())
215 .await?;
216 }
217 (None, None) => {
218 let handle = axum_server::Handle::new();
219 let ready_handle = handle.clone();
220 tokio::spawn(async move {
221 ready_handle.listening().await;
222 tracing::info!(
223 "HTTP server ready, accepting requests on http://{}",
224 addr
225 );
226 eprintln!("HTTP server ready, accepting requests on http://{addr}");
227 });
228 install_shutdown_handler(handle.clone(), shutdown_grace_period);
229 axum_server::bind(addr)
230 .handle(handle)
231 .serve(app.into_make_service_with_connect_info::<SocketAddr>())
232 .await?;
233 }
234 _ => {
235 return Err(Error::BadRequest(
236 "--cert and --key must be provided together".to_string(),
237 ));
238 }
239 }
240
241 // The drain is over: deliver audit events still queued for Kafka.
242 // `flush` blocks, so keep it off the async workers.
243 if let Err(e) = tokio::task::spawn_blocking(move || {
244 audit.flush(AUDIT_FLUSH_TIMEOUT);
245 })
246 .await
247 {
248 tracing::warn!("audit flush at shutdown did not complete: {e}");
249 }
250
251 Ok(())
252}
253
254/// Spawn a task that waits for SIGTERM or Ctrl+C and triggers
255/// `axum_server`'s graceful shutdown with a bounded drain window.
256/// Without this, the runtime drops in-flight requests when Tokio is
257/// shut down by the OS — `docker stop` / k8s pod termination would
258/// abandon clients mid-call.
259///
260/// The grace-period comes from `ServerState::shutdown_grace_period`
261/// (sourced from `server.toml`); pods that hit this without
262/// finishing get SIGKILL'd by the kubelet.
263fn install_shutdown_handler(
264 handle: axum_server::Handle<SocketAddr>,
265 grace_period: Duration,
266) {
267 tokio::spawn(async move {
268 let mut sigterm = match tokio::signal::unix::signal(
269 tokio::signal::unix::SignalKind::terminate(),
270 ) {
271 Ok(s) => s,
272 Err(e) => {
273 tracing::warn!(
274 "failed to install SIGTERM handler; falling back to Ctrl+C only: {e}"
275 );
276 let _ = tokio::signal::ctrl_c().await;
277 handle.graceful_shutdown(Some(grace_period));
278 return;
279 }
280 };
281 let grace_secs = grace_period.as_secs();
282 tokio::select! {
283 _ = sigterm.recv() => {
284 tracing::info!("SIGTERM received; draining for up to {grace_secs}s");
285 }
286 _ = tokio::signal::ctrl_c() => {
287 tracing::info!("Ctrl+C received; draining for up to {grace_secs}s");
288 }
289 }
290 handle.graceful_shutdown(Some(grace_period));
291 });
292}
293
294#[cfg(test)]
295mod timeout_layer_tests {
296 //! Behavioural tests for the global + per-route TimeoutLayer
297 //! composition used by `start_server` and
298 //! `routes::build_router::power_router`. These prove the *pattern*
299 //! (outer layer applies to all routes; an inner layer overrides for
300 //! the specific routes it wraps) — the production router relies on
301 //! exactly this composition to give `/power` more headroom than the
302 //! global default without affecting other endpoints.
303 //!
304 //! Pure tower/axum unit tests — no `ServerState`, no real handlers,
305 //! no TCP listener. `tower::ServiceExt::oneshot` drives the router
306 //! in-process.
307 use std::time::Duration;
308
309 use axum::{
310 Router,
311 body::Body,
312 http::{Request, StatusCode},
313 routing::get,
314 };
315 use tower::ServiceExt as _;
316 use tower_http::timeout::TimeoutLayer;
317
318 fn get_req(uri: &str) -> Request<Body> {
319 Request::builder()
320 .method("GET")
321 .uri(uri)
322 .body(Body::empty())
323 .unwrap()
324 }
325
326 /// Handler that sleeps `delay` then returns 200 — used to drive
327 /// the timeout layer past its limit on purpose.
328 async fn sleep_handler(delay: Duration) -> &'static str {
329 tokio::time::sleep(delay).await;
330 "ok"
331 }
332
333 #[tokio::test]
334 async fn global_timeout_returns_408_when_handler_exceeds_limit() {
335 let router = Router::new()
336 .route(
337 "/slow",
338 get(|| async { sleep_handler(Duration::from_millis(400)).await }),
339 )
340 .layer(TimeoutLayer::with_status_code(
341 StatusCode::REQUEST_TIMEOUT,
342 Duration::from_millis(50),
343 ));
344
345 let resp = router.oneshot(get_req("/slow")).await.unwrap();
346 assert_eq!(resp.status(), StatusCode::REQUEST_TIMEOUT);
347 }
348
349 #[tokio::test]
350 async fn fast_handler_finishes_before_timeout_fires() {
351 let router = Router::new()
352 .route(
353 "/fast",
354 get(|| async { sleep_handler(Duration::from_millis(10)).await }),
355 )
356 .layer(TimeoutLayer::with_status_code(
357 StatusCode::REQUEST_TIMEOUT,
358 Duration::from_secs(5),
359 ));
360
361 let resp = router.oneshot(get_req("/fast")).await.unwrap();
362 assert_eq!(resp.status(), StatusCode::OK);
363 }
364}