//! Read-only `axum` HTTP server, SSE stream, and embedded SPA assets. use crate::cache::{CacheError, DirectorySort, HilbertColorBy}; use crate::domain::{RelPath, SizeMetric}; use crate::engine::{Engine, EngineEvent}; use axum::Json; use axum::Router; use axum::body::Body; use axum::extract::{Query, Request, State}; use axum::http::header::{CACHE_CONTROL, CONTENT_TYPE, HOST, ORIGIN}; use axum::http::uri::{Authority, Uri}; use axum::http::{HeaderName, HeaderValue, Method, StatusCode, Version}; use axum::middleware::{self, Next}; use axum::response::sse::{Event, KeepAlive, Sse}; use axum::response::{IntoResponse, Response}; use axum::routing::get; use futures_util::stream::Stream; use rust_embed::Embed; use serde::{Deserialize, Serialize}; use std::convert::Infallible; use std::net::SocketAddr; use std::sync::Arc; use std::time::Duration; use time::OffsetDateTime; use time::format_description::well_known::Rfc3339; use tokio::net::TcpListener; use tokio_stream::StreamExt; use tokio_stream::wrappers::BroadcastStream; use tower_http::compression::CompressionLayer; use tower_http::trace::TraceLayer; const API_SCHEMA_VERSION: u32 = 1; /// Embedded production build of `web/dist/`. #[derive(Debug, Embed)] #[folder = "web/dist"] pub struct WebAssets; /// Standard JSON envelope for API responses. #[derive(Debug, Serialize)] struct ApiEnvelope { schema_version: u32, generated_at: String, #[serde(flatten)] payload: T, } impl ApiEnvelope { fn new(payload: T) -> Self { Self { schema_version: API_SCHEMA_VERSION, generated_at: now_rfc3339(), payload, } } } /// Consistent JSON error envelope (`CONTEXT.md` / `PHASE-3.md`). #[derive(Debug, Serialize)] struct ApiErrorBody { error: String, code: &'static str, } struct ApiError { status: StatusCode, code: &'static str, message: String, } impl ApiError { fn bad_request(message: impl Into) -> Self { Self { status: StatusCode::BAD_REQUEST, code: "bad_request", message: message.into(), } } fn not_found(message: impl Into) -> Self { Self { status: StatusCode::NOT_FOUND, code: "not_found", message: message.into(), } } fn internal(message: impl Into) -> Self { Self { status: StatusCode::INTERNAL_SERVER_ERROR, code: "internal_error", message: message.into(), } } } impl IntoResponse for ApiError { fn into_response(self) -> Response { ( self.status, Json(ApiErrorBody { error: self.message, code: self.code, }), ) .into_response() } } impl From for ApiError { fn from(err: CacheError) -> Self { match err { CacheError::Domain(d) => Self::bad_request(d.to_string()), other => Self::internal(other.to_string()), } } } /// Build the complete read-only `axum` [`Router`] for `engine`. pub fn build_router(engine: Arc) -> Router { let api_json = Router::new() .route("/api/health", get(handle_health)) .route("/api/volume", get(handle_volume)) .route("/api/snapshots", get(handle_snapshots)) .route("/api/tree", get(handle_tree)) .route("/api/directory", get(handle_directory)) .route("/api/analytics/scatter", get(handle_scatter)) .route("/api/analytics/hilbert", get(handle_hilbert)) .route("/api/analytics/sankey", get(handle_sankey)) .route("/api/search", get(handle_search)) .fallback(get(handle_static)) .layer(CompressionLayer::new()); let sse_routes = Router::new().route("/api/events", get(handle_events)); Router::new() .merge(sse_routes) .merge(api_json) .with_state(engine) .layer(middleware::from_fn(security_headers_middleware)) .layer(middleware::from_fn(origin_guard_middleware)) .layer(middleware::from_fn(host_guard_middleware)) .layer(middleware::from_fn(read_only_method_middleware)) .layer(TraceLayer::new_for_http()) } /// Bind strictly to `host:port` (must be loopback) and serve until shutdown signal. pub async fn serve(engine: Arc, addr: SocketAddr) -> anyhow::Result<()> { let listener = TcpListener::bind(addr).await?; serve_listener(engine, listener).await } /// Serve on an already-bound [`TcpListener`] until shutdown signal. pub async fn serve_listener(engine: Arc, listener: TcpListener) -> anyhow::Result<()> { let router = build_router(engine); axum::serve(listener, router) .with_graceful_shutdown(shutdown_signal()) .await?; Ok(()) } async fn shutdown_signal() { let ctrl_c = async { let _ = tokio::signal::ctrl_c().await; }; #[cfg(unix)] let terminate = async { if let Ok(mut sig) = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) { sig.recv().await; } }; #[cfg(not(unix))] let terminate = std::future::pending::<()>(); tokio::select! { () = ctrl_c => {}, () = terminate => {}, } } async fn read_only_method_middleware(req: Request, next: Next) -> Response { if req.method() != Method::GET && req.method() != Method::HEAD { return ( StatusCode::METHOD_NOT_ALLOWED, Json(ApiErrorBody { error: format!( "method {} is not allowed; Getǣl is strictly read-only", req.method() ), code: "method_not_allowed", }), ) .into_response(); } next.run(req).await } async fn host_guard_middleware(req: Request, next: Next) -> Response { match req.headers().get(HOST) { Some(host_hdr) => { let Ok(host_str) = host_hdr.to_str() else { return forbidden_host(); }; if !is_loopback_host(host_str) { return forbidden_host(); } } None if req.version() >= Version::HTTP_11 => { return forbidden_host(); } None => {} } next.run(req).await } async fn origin_guard_middleware(req: Request, next: Next) -> Response { if req.uri().path().starts_with("/api/") { if let Some(sec_fetch_site) = req.headers().get("sec-fetch-site") && sec_fetch_site .to_str() .is_ok_and(|v| v.eq_ignore_ascii_case("cross-site")) { return forbidden_origin(); } if let Some(origin_hdr) = req.headers().get(ORIGIN) { let Ok(origin_str) = origin_hdr.to_str() else { return forbidden_origin(); }; if !is_loopback_origin(origin_str) { return forbidden_origin(); } } } next.run(req).await } async fn security_headers_middleware(req: Request, next: Next) -> Response { let mut res = next.run(req).await; let headers = res.headers_mut(); headers.insert( HeaderName::from_static("content-security-policy"), HeaderValue::from_static( "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; connect-src 'self'; object-src 'none'; frame-ancestors 'none'", ), ); headers.insert( HeaderName::from_static("x-content-type-options"), HeaderValue::from_static("nosniff"), ); headers.insert( HeaderName::from_static("x-frame-options"), HeaderValue::from_static("DENY"), ); headers.insert( HeaderName::from_static("referrer-policy"), HeaderValue::from_static("no-referrer"), ); res } fn forbidden_host() -> Response { ( StatusCode::FORBIDDEN, Json(ApiErrorBody { error: "non-loopback Host header rejected".to_string(), code: "forbidden_host", }), ) .into_response() } fn forbidden_origin() -> Response { ( StatusCode::FORBIDDEN, Json(ApiErrorBody { error: "cross-origin API request rejected".to_string(), code: "forbidden_origin", }), ) .into_response() } fn is_loopback_host(raw: &str) -> bool { let Ok(authority) = raw.parse::() else { return false; }; if !authority.as_str().eq_ignore_ascii_case(raw) || raw.contains('@') { return false; } let host = authority.host(); let after_host = &authority.as_str()[host.len()..]; if !after_host.is_empty() { let Some(port_str) = after_host.strip_prefix(':') else { return false; }; if port_str.is_empty() || port_str.parse::().is_err() { return false; } } host.eq_ignore_ascii_case("localhost") || host == "127.0.0.1" || host == "[::1]" } fn is_loopback_origin(raw: &str) -> bool { let Ok(uri) = raw.parse::() else { return false; }; let Some(scheme) = uri.scheme_str() else { return false; }; if !scheme.eq_ignore_ascii_case("http") && !scheme.eq_ignore_ascii_case("https") { return false; } let Some(authority) = uri.authority() else { return false; }; is_loopback_host(authority.as_str()) } #[derive(Debug, Serialize)] struct HealthPayload { status: &'static str, platform: &'static str, snapshots_supported: bool, home_display: String, uptime_secs: u64, scan_state: crate::engine::ScanState, scanned_dirs: u64, scanned_files: u64, scanned_physical_bytes: u64, scanned_logical_bytes: u64, inaccessible_dirs: u64, fsevents_active: bool, last_full_scan_completed_ns: i64, cache_populated: bool, } async fn handle_health(State(engine): State>) -> Result { let st = engine.status(); let eng = Arc::clone(&engine); let cache_populated = tokio::task::spawn_blocking(move || eng.cache.has_root()) .await .map_err(|e| ApiError::internal(e.to_string()))??; Ok(Json(ApiEnvelope::new(HealthPayload { status: "ok", platform: crate::macos::current_platform(), snapshots_supported: crate::macos::snapshots_supported(), home_display: engine.config.home_display(), uptime_secs: engine.uptime_secs(), scan_state: st.scan_state, scanned_dirs: st.progress.scanned_dirs, scanned_files: st.progress.scanned_files, scanned_physical_bytes: st.progress.scanned_physical_bytes, scanned_logical_bytes: st.progress.scanned_logical_bytes, inaccessible_dirs: st.progress.inaccessible_dirs, fsevents_active: st.fsevents_active, last_full_scan_completed_ns: st.last_full_scan_completed_ns, cache_populated, }))) } #[derive(Debug, Serialize)] struct VolumePayload { volume: crate::macos::VolumeStats, home_scanned_physical_bytes: u64, home_scanned_logical_bytes: u64, } async fn handle_volume(State(engine): State>) -> Result { let cached_vol = engine.volume_stats(); let eng = Arc::clone(&engine); let (vol, root_rec) = tokio::task::spawn_blocking(move || { let vol = cached_vol.or_else(|| eng.refresh_volume_sync()); let root_rec = eng.cache.get_directory_record(&RelPath::root()); (vol, root_rec) }) .await .map_err(|e| ApiError::internal(e.to_string()))?; let volume = vol.ok_or_else(|| ApiError::internal("volume telemetry unavailable"))?; let root = root_rec?; let (home_phys, home_log) = root.map_or((0, 0), |r| { (r.subtree_physical_bytes, r.subtree_logical_bytes) }); Ok(Json(ApiEnvelope::new(VolumePayload { volume, home_scanned_physical_bytes: home_phys, home_scanned_logical_bytes: home_log, }))) } #[derive(Debug, Serialize)] struct SnapshotsPayload { supported: bool, inventory: crate::macos::SnapshotInventory, purgeable_pool_bytes: u64, } async fn handle_snapshots( State(engine): State>, ) -> Result { let cached_snaps = engine.snapshot_inventory(); let purgeable_pool_bytes = engine.volume_stats().map_or(0, |v| v.purgeable_bytes); let eng = Arc::clone(&engine); let inv = tokio::task::spawn_blocking(move || cached_snaps.or_else(|| eng.refresh_snapshots_sync())) .await .map_err(|e| ApiError::internal(e.to_string()))? .unwrap_or_default(); Ok(Json(ApiEnvelope::new(SnapshotsPayload { supported: crate::macos::snapshots_supported(), inventory: inv, purgeable_pool_bytes, }))) } #[derive(Debug, Deserialize)] struct TreeQuery { #[serde(default)] path: String, #[serde(default = "default_tree_depth")] depth: u32, #[serde(default)] metric: SizeMetric, #[serde(default = "default_true")] include_hidden: bool, } const fn default_tree_depth() -> u32 { 3 } const fn default_true() -> bool { true } #[derive(Debug, Serialize)] struct TreePayload { tree: crate::cache::TreeNode, } async fn handle_tree( State(engine): State>, Query(q): Query, ) -> Result { let rel = RelPath::parse(&q.path).map_err(|e| ApiError::bad_request(e.to_string()))?; let eng = Arc::clone(&engine); let tree = tokio::task::spawn_blocking(move || { eng.cache .get_tree(&rel, q.depth, q.metric, q.include_hidden) }) .await .map_err(|e| ApiError::internal(e.to_string()))?? .ok_or_else(|| ApiError::not_found(format!("directory '{}' not found in cache", q.path)))?; Ok(Json(ApiEnvelope::new(TreePayload { tree }))) } #[derive(Debug, Deserialize)] struct DirectoryQuery { #[serde(default)] path: String, #[serde(default)] sort: DirectorySort, #[serde(default)] metric: SizeMetric, } async fn handle_directory( State(engine): State>, Query(q): Query, ) -> Result { let rel = RelPath::parse(&q.path).map_err(|e| ApiError::bad_request(e.to_string()))?; let eng = Arc::clone(&engine); let view = tokio::task::spawn_blocking(move || { let mut dir_view = eng.cache.get_directory(&rel, q.sort, q.metric)?; if let Some(ref mut v) = dir_view && let Ok(mut live_files) = crate::scanner::read_direct_files_live(&eng.config.home_root, &rel, 200) { match q.sort { DirectorySort::Size => live_files.sort_unstable_by(|a, b| { b.bytes(q.metric) .cmp(&a.bytes(q.metric)) .then_with(|| a.name.cmp(&b.name)) }), DirectorySort::Name => live_files.sort_unstable_by(|a, b| a.name.cmp(&b.name)), DirectorySort::Mtime => live_files.sort_unstable_by(|a, b| { b.mtime_ns .cmp(&a.mtime_ns) .then_with(|| a.name.cmp(&b.name)) }), DirectorySort::Count => {} } v.top_files = live_files; } Ok::<_, CacheError>(dir_view) }) .await .map_err(|e| ApiError::internal(e.to_string()))?? .ok_or_else(|| ApiError::not_found(format!("directory '{}' not found in cache", q.path)))?; Ok(Json(ApiEnvelope::new(view))) } #[derive(Debug, Deserialize)] struct ScatterQuery { #[serde(default)] path: String, #[serde(default)] metric: SizeMetric, #[serde(default = "default_scatter_limit")] limit: usize, } const fn default_scatter_limit() -> usize { 600 } async fn handle_scatter( State(engine): State>, Query(q): Query, ) -> Result { let rel = RelPath::parse(&q.path).map_err(|e| ApiError::bad_request(e.to_string()))?; let eng = Arc::clone(&engine); let scatter = tokio::task::spawn_blocking(move || eng.cache.get_scatter(&rel, q.metric, q.limit)) .await .map_err(|e| ApiError::internal(e.to_string()))?? .ok_or_else(|| { ApiError::not_found(format!("directory '{}' not found in cache", q.path)) })?; Ok(Json(ApiEnvelope::new(scatter))) } #[derive(Debug, Deserialize)] struct HilbertQuery { #[serde(default)] path: String, #[serde(default = "default_hilbert_order")] order: u32, #[serde(default)] color_by: HilbertColorBy, #[serde(default)] metric: SizeMetric, } const fn default_hilbert_order() -> u32 { 6 } async fn handle_hilbert( State(engine): State>, Query(q): Query, ) -> Result { let rel = RelPath::parse(&q.path).map_err(|e| ApiError::bad_request(e.to_string()))?; let eng = Arc::clone(&engine); let hilbert = tokio::task::spawn_blocking(move || { eng.cache.get_hilbert(&rel, q.order, q.color_by, q.metric) }) .await .map_err(|e| ApiError::internal(e.to_string()))?? .ok_or_else(|| ApiError::not_found(format!("directory '{}' not found in cache", q.path)))?; Ok(Json(ApiEnvelope::new(hilbert))) } #[derive(Debug, Deserialize)] struct SankeyQuery { #[serde(default)] path: String, #[serde(default)] metric: SizeMetric, } async fn handle_sankey( State(engine): State>, Query(q): Query, ) -> Result { let rel = RelPath::parse(&q.path).map_err(|e| ApiError::bad_request(e.to_string()))?; let eng = Arc::clone(&engine); let sankey = tokio::task::spawn_blocking(move || eng.cache.get_sankey(&rel, q.metric)) .await .map_err(|e| ApiError::internal(e.to_string()))?? .ok_or_else(|| ApiError::not_found(format!("directory '{}' not found in cache", q.path)))?; Ok(Json(ApiEnvelope::new(sankey))) } #[derive(Debug, Deserialize)] struct SearchQuery { #[serde(default)] q: String, #[serde(default)] path: String, #[serde(default = "default_search_limit")] limit: usize, } const fn default_search_limit() -> usize { 50 } #[derive(Debug, Serialize)] struct SearchPayload { query: String, hits: Vec, } async fn handle_search( State(engine): State>, Query(q): Query, ) -> Result { let rel = RelPath::parse(&q.path).map_err(|e| ApiError::bad_request(e.to_string()))?; let query_str = q.q.clone(); let eng = Arc::clone(&engine); let hits = tokio::task::spawn_blocking(move || eng.cache.search(&query_str, &rel, q.limit)) .await .map_err(|e| ApiError::internal(e.to_string()))??; Ok(Json(ApiEnvelope::new(SearchPayload { query: q.q, hits }))) } async fn handle_events( State(engine): State>, ) -> Sse>> { let rx = engine.subscribe(); let stream = BroadcastStream::new(rx).map(|msg| match msg { Ok(ev) => { let event_name = match &ev { EngineEvent::ScanProgress { .. } => "scan_progress", EngineEvent::DirUpdated { .. } => "dir_updated", EngineEvent::VolumeUpdated(_) => "volume_updated", EngineEvent::SnapshotsUpdated(_) => "snapshots_updated", }; let data = serde_json::to_string(&ev).unwrap_or_else(|_| "{}".to_string()); Ok(Event::default().event(event_name).data(data)) } Err(_) => Ok(Event::default() .event("resync_required") .data(r#"{"type":"resync_required"}"#)), }); Sse::new(stream).keep_alive( KeepAlive::new() .interval(Duration::from_secs(15)) .text("heartbeat"), ) } async fn handle_static(req: Request) -> Response { let raw_path = req.uri().path().trim_start_matches('/'); let asset_path = if raw_path.is_empty() { "index.html" } else { raw_path }; if let Some(content) = WebAssets::get(asset_path) { let mime = mime_guess::from_path(asset_path).first_or_octet_stream(); let cache_header = if asset_path.starts_with("assets/") { "public, max-age=31536000, immutable" } else { "no-cache" }; return ( StatusCode::OK, [(CONTENT_TYPE, mime.as_ref()), (CACHE_CONTROL, cache_header)], content.data.into_owned(), ) .into_response(); } // SPA fallback for client-side routes (non-API) if !raw_path.starts_with("api/") && let Some(index) = WebAssets::get("index.html") { return ( StatusCode::OK, [ (CONTENT_TYPE, "text/html; charset=utf-8"), (CACHE_CONTROL, "no-cache"), ], index.data.into_owned(), ) .into_response(); } ( StatusCode::NOT_FOUND, Json(ApiErrorBody { error: "not found".to_string(), code: "not_found", }), ) .into_response() } fn now_rfc3339() -> String { OffsetDateTime::now_utc() .format(&Rfc3339) .unwrap_or_else(|_| "1970-01-01T00:00:00Z".to_string()) } #[cfg(test)] #[allow(clippy::unwrap_used, clippy::expect_used)] mod tests { use super::*; use crate::cache::CacheStore; use crate::config::Config; use crate::macos::{FakeSnapshotProvider, FakeVolumeTelemetry, SnapshotInventory, VolumeStats}; use crate::scanner::{ApfsScanner, Scanner}; use crate::watcher::FakeWatcher; use std::fs; use tempfile::TempDir; use tower::ServiceExt; fn test_engine() -> (TempDir, Arc) { let tmp = TempDir::new().unwrap(); let home = tmp.path().to_path_buf(); fs::create_dir_all(home.join("Projects/app")).unwrap(); fs::write(home.join("Projects/app/main.rs"), vec![b'a'; 8192]).unwrap(); fs::write(home.join(".zshrc"), vec![b'b'; 1024]).unwrap(); let cfg = Arc::new(Config::load_from(&home, None, None).unwrap()); let cache = Arc::new(CacheStore::open_in_memory().unwrap()); let scanner = Arc::new(ApfsScanner::new()); let scan = scanner.scan_full(&home, &|_| {}).unwrap(); cache.replace_full_scan(&scan, &home, 1, 2).unwrap(); let vol = Arc::new(FakeVolumeTelemetry::new(VolumeStats { volume_name: "Data".to_string(), mount_point: "/System/Volumes/Data".to_string(), device_identifier: "disk3s5".to_string(), container_ref: Some("disk3".to_string()), filesystem_type: Some("apfs".to_string()), total_bytes: 500_000_000_000, strictly_free_bytes: 150_000_000_000, purgeable_bytes: 25_000_000_000, important_available_bytes: 175_000_000_000, opportunistic_available_bytes: 160_000_000_000, sibling_volumes: Vec::new(), })); let snaps = Arc::new(FakeSnapshotProvider::new(SnapshotInventory::default())); let watcher = Arc::new(FakeWatcher::new()); let engine = Arc::new(Engine::new(cfg, cache, scanner, vol, snaps, watcher)); engine.refresh_volume_sync(); engine.refresh_snapshots_sync(); (tmp, engine) } #[test] fn embedded_web_bundle_contains_index_html() { assert!(WebAssets::get("index.html").is_some()); } #[tokio::test] async fn all_read_only_api_endpoints_and_security_guards_work() { let (_tmp, engine) = test_engine(); let app = build_router(engine); for uri in [ "/api/health", "/api/volume", "/api/snapshots", "/api/tree?path=&depth=2", "/api/directory?path=Projects", "/api/analytics/scatter?path=", "/api/analytics/hilbert?path=&order=5", "/api/analytics/sankey?path=", "/api/search?q=main", "/", ] { let res = app .clone() .oneshot( Request::builder() .uri(uri) .header(HOST, "127.0.0.1:6174") .body(Body::empty()) .unwrap(), ) .await .unwrap(); assert_eq!(res.status(), StatusCode::OK, "uri={uri}"); } // Security: non-GET returns 405 for method in [Method::POST, Method::DELETE, Method::PUT] { let res = app .clone() .oneshot( Request::builder() .method(method) .uri("/api/health") .header(HOST, "127.0.0.1:6174") .body(Body::empty()) .unwrap(), ) .await .unwrap(); assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED); } // Security: path traversal returns 400 let bad_path = app .clone() .oneshot( Request::builder() .uri("/api/directory?path=../etc/passwd") .header(HOST, "127.0.0.1:6174") .body(Body::empty()) .unwrap(), ) .await .unwrap(); assert_eq!(bad_path.status(), StatusCode::BAD_REQUEST); // Health payload includes platform-appropriate home_display let health_res = app .oneshot( Request::builder() .uri("/api/health") .header(HOST, "127.0.0.1:6174") .body(Body::empty()) .unwrap(), ) .await .unwrap(); assert_eq!(health_res.status(), StatusCode::OK); let body = axum::body::to_bytes(health_res.into_body(), usize::MAX) .await .unwrap(); let json: serde_json::Value = serde_json::from_slice(&body).unwrap(); let expected_home_display = if cfg!(target_os = "windows") { std::env::var("HOMEPATH") .ok() .filter(|s| !s.trim().is_empty()) .unwrap_or_default() } else { "~".to_string() }; if expected_home_display.is_empty() { assert!( json.get("home_display") .and_then(|v| v.as_str()) .is_some_and(|s| !s.is_empty()) ); } else { assert_eq!( json.get("home_display").and_then(|v| v.as_str()), Some(expected_home_display.as_str()) ); } } #[tokio::test] async fn security_headers_origin_and_host_edge_cases() { let (_tmp, engine) = test_engine(); let app = build_router(engine); for bad in [ "evil.example:6174", "[::1]evil.com", "localhost:evil", "127.0.0.1.evil.com", "user@localhost:6174", ] { let bad_host = app .clone() .oneshot( Request::builder() .uri("/api/health") .header(HOST, bad) .body(Body::empty()) .unwrap(), ) .await .unwrap(); assert_eq!(bad_host.status(), StatusCode::FORBIDDEN, "host={bad}"); } let missing_host = app .clone() .oneshot( Request::builder() .uri("/api/health") .body(Body::empty()) .unwrap(), ) .await .unwrap(); assert_eq!(missing_host.status(), StatusCode::FORBIDDEN); let bad_origin = app .clone() .oneshot( Request::builder() .uri("/api/health") .header(HOST, "127.0.0.1:6174") .header(ORIGIN, "https://evil.example") .body(Body::empty()) .unwrap(), ) .await .unwrap(); assert_eq!(bad_origin.status(), StatusCode::FORBIDDEN); let ok_res = app .oneshot( Request::builder() .uri("/api/health") .header(HOST, "127.0.0.1:6174") .body(Body::empty()) .unwrap(), ) .await .unwrap(); assert!(ok_res.headers().contains_key("content-security-policy")); assert_eq!( ok_res .headers() .get("x-content-type-options") .and_then(|v| v.to_str().ok()), Some("nosniff") ); assert_eq!( ok_res .headers() .get("x-frame-options") .and_then(|v| v.to_str().ok()), Some("DENY") ); } #[tokio::test] async fn sse_events_stream_delivers_dir_and_volume_updates() { let (_tmp, engine) = test_engine(); let app = build_router(Arc::clone(&engine)); let res = app .oneshot( Request::builder() .uri("/api/events") .header(HOST, "127.0.0.1:6174") .body(Body::empty()) .unwrap(), ) .await .unwrap(); assert_eq!(res.status(), StatusCode::OK); let _ = engine.events_tx.send(EngineEvent::DirUpdated { path: "Projects".to_string(), delta_physical_bytes: 4096, delta_logical_bytes: 4096, }); engine.refresh_volume_sync(); let mut stream = res.into_body().into_data_stream(); let chunk = tokio::time::timeout( Duration::from_secs(1), futures_util::StreamExt::next(&mut stream), ) .await .unwrap() .unwrap() .unwrap(); let text1 = String::from_utf8_lossy(&chunk); assert!(text1.contains("dir_updated")); } }