// SPF Smart Gateway - HTTP API Server Transport // Copyright 2026 Joseph Stone - All Rights Reserved // // HTTP API running alongside stdio MCP server. // Uses Axum 0.8 with Tower middleware stack and optional TLS (axum-server + rustls). // // Routes: // POST /mcp/v1 — Full JSON-RPC 2.0 (initialize, tools/list, tools/call) // GET /health — Health check (no auth) // GET /status — SPF gateway status // GET /tools — Tool definitions list // GET /ws — WebSocket (persistent JSON-RPC, auth on upgrade) // // Auth modes: // "key" — X-SPF-Key header (API key) // "crypto" — Ed25519 signed requests (X-SPF-Pub, X-SPF-Sig, X-SPF-Time, X-SPF-Nonce) // "both" — Accept either method // // Middleware (Tower + axum): // TraceLayer — structured request/response logging // CatchPanicLayer — handler panics → 500 (never crash server) // RequestBodyLimitLayer — 10MB (matches original read_body limit) // SetSensitiveRequestHeadersLayer — hide auth headers from logs // CompressionLayer — gzip response compression // CORS (axum::middleware::from_fn) — browser preflight + response headers // Timeout — 30s per request via spawn_blocking + tokio::time::timeout // // Threading: // serve() is async — runs in caller's tokio runtime (shared with mesh in E7). // start() is sync wrapper — creates own runtime (backward compat with mcp.rs). // // BLOCK SEC-4: SPF_API_KEY env var override in serve() — process-scoped, not in JSON files use crate::agent_state::AgentStateDb; use crate::config::SpfConfig; use crate::config_db::SpfConfigDb; use crate::fs::SpfFs; use crate::mcp; use crate::session::Session; use crate::storage::SpfStorage; use crate::tmp_db::SpfTmpDb; use ed25519_dalek::{Signature, Verifier, VerifyingKey}; use iroh::Endpoint; use serde_json::{json, Value}; use sha2::{Sha256, Digest}; use std::collections::{HashMap, HashSet}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; /// P2: Tracked peer in the mesh. #[derive(Debug, Clone)] pub struct MeshPeerStatus { pub role: crate::config::AgentRole, pub name: String, pub last_seen: Instant, } use axum::{ Router, middleware, routing::{get, post}, extract::{Request, State, Query, Path, ws::{WebSocketUpgrade, WebSocket, Message}}, http::{HeaderMap, HeaderName, Method, StatusCode, header}, response::{IntoResponse, Response}, body::Body, Json, }; use tower::ServiceBuilder; use tower_http::{ trace::TraceLayer, limit::RequestBodyLimitLayer, catch_panic::CatchPanicLayer, sensitive_headers::SetSensitiveRequestHeadersLayer, compression::CompressionLayer, }; const PROTOCOL_VERSION: &str = "2024-11-05"; const TIMESTAMP_WINDOW_SECS: u64 = 30; const NONCE_EXPIRY_SECS: u64 = 60; /// Shared server state — used by all transports (stdio, HTTP, mesh). /// Wrapped in Arc for thread-safe sharing. pub struct ServerState { pub config: SpfConfig, pub config_db: Option, pub session: Mutex, pub storage: SpfStorage, pub tmp_db: Option, pub agent_db: Option, pub fs_db: Option, pub pub_key_hex: String, pub trusted_keys: HashSet, pub auth_mode: String, pub nonce_cache: Mutex>, pub listeners: Vec>, /// Mesh endpoint handle for outbound peer calls (None if mesh disabled) pub mesh_tx: Option>, /// Peer info with addresses for direct mesh connections pub peers: HashMap, /// Transformer runtime state — None if transformer disabled or not yet loaded pub transformer: Option>>, /// Transformer configuration — loaded from LIVE/CONFIG/transformer.json pub transformer_config: crate::config::TransformerConfig, /// Pipeline state for task orchestration pub pipeline: std::sync::Arc>, /// Ed25519 signing key — needed for I-4 peer API key derivation pub signing_key: ed25519_dalek::SigningKey, /// Network pool configuration — role (NetAdmin/Worker), pool size, peer list pub network_config: crate::config::NetworkConfig, /// Live pool state — None on Worker nodes, Some(Arc) on NetAdmin pub pool_state: Option>, /// Reverse proxy browser session — ProxyEngine + mpsc channel ends pub browser: std::sync::Mutex, /// WsBrowserChannels produced by BrowserSession::connect(), consumed by /ws/browser handler pub ws_browser_channels: std::sync::Mutex>, /// HTTP server port — injected into proxied pages as WebSocket target port pub http_port: u16, /// P2: Tracked mesh peers — pubkey → MeshPeerStatus pub tracked_peers: Mutex>, /// P5: Orchestrator state — Some only on orchestrator nodes pub orchestrator_state: Mutex>>>, /// DS: Iroh QUIC endpoint — stored by mesh on startup, used by MCP for direct duplex calls pub endpoint: Mutex>, /// DS: Tokio runtime handle — bridges sync MCP thread to async mesh I/O pub tokio_handle: Mutex>, } /// P5: Helper — get tracked peer count without full state reference (for tool access). pub fn tracked_peer_count(state: &Arc) -> usize { state.tracked_peers.lock().unwrap().len() } /// Application state for Axum handlers — wraps ServerState + API key. /// Clone is required by Axum's State extractor. #[derive(Clone)] struct AppState { inner: Arc, api_key: String, } // ============================================================================ // AUTH — Dual mode: API key + Ed25519 crypto // ============================================================================ /// Extract a header value by name from Axum HeaderMap. /// HeaderMap keys are case-insensitive by spec. fn extract_header(headers: &HeaderMap, name: &str) -> Option { headers.get(name) .and_then(|v| v.to_str().ok()) .map(|s| s.to_string()) } /// Dual-mode auth check. Tries API key first, then crypto. /// Returns true if request is authenticated. fn check_auth(headers: &HeaderMap, method_str: &str, path: &str, body: &str, api_key: &str, state: &ServerState) -> bool { let mode = state.auth_mode.as_str(); // Try API key auth if mode == "key" || mode == "both" { if let Some(key) = extract_header(headers, "x-spf-key") { return key == api_key; } } // Try crypto auth if mode == "crypto" || mode == "both" { if let (Some(pub_hex), Some(sig_hex), Some(time_str), Some(nonce)) = ( extract_header(headers, "x-spf-pub"), extract_header(headers, "x-spf-sig"), extract_header(headers, "x-spf-time"), extract_header(headers, "x-spf-nonce"), ) { return verify_crypto_auth( &pub_hex, &sig_hex, &time_str, &nonce, method_str, path, body, &state.trusted_keys, &state.nonce_cache, ); } } // I-4 FIX: Try peer-derived key auth (mesh↔HTTP bridge) if mode == "both" || mode == "key" { if let Some(peer_key_header) = extract_header(headers, "x-spf-peer-key") { if let Some(peer_pub) = extract_header(headers, "x-spf-peer-pub") { // Verify the peer is trusted before attempting derivation if state.trusted_keys.contains(&peer_pub) { let expected = crate::identity::derive_peer_api_key( &state.signing_key, &peer_pub ); if let Some(expected_key) = expected { if peer_key_header == expected_key { return true; } } } } } } false } /// Verify Ed25519 crypto authentication with replay prevention. fn verify_crypto_auth(pub_hex: &str, sig_hex: &str, time_str: &str, nonce: &str, method: &str, path: &str, body: &str, trusted_keys: &HashSet, nonce_cache: &Mutex>) -> bool { // 1. Check public key is in trusted keys if !trusted_keys.contains(pub_hex) { return false; } // 2. Check timestamp within window let timestamp: u64 = match time_str.parse() { Ok(t) => t, Err(_) => return false, }; let now = std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .unwrap_or_default() .as_secs(); if now.abs_diff(timestamp) > TIMESTAMP_WINDOW_SECS { return false; } // 3. Check nonce uniqueness (and clean expired entries) { let mut cache = nonce_cache.lock().unwrap(); let instant_now = Instant::now(); cache.retain(|_, t| instant_now.duration_since(*t).as_secs() < NONCE_EXPIRY_SECS); if cache.contains_key(nonce) { return false; // replay detected } cache.insert(nonce.to_string(), instant_now); } // 4. Build canonical signing string let body_hash = hex::encode(Sha256::digest(body.as_bytes())); let canonical = format!("{}\n{}\n{}\n{}\n{}", method, path, body_hash, time_str, nonce); // 5. Decode public key let pub_bytes: [u8; 32] = match hex::decode(pub_hex) { Ok(b) if b.len() == 32 => match b.try_into() { Ok(arr) => arr, Err(_) => return false, }, _ => return false, }; let verifying_key = match VerifyingKey::from_bytes(&pub_bytes) { Ok(vk) => vk, Err(_) => return false, }; // 6. Decode signature let sig_bytes: [u8; 64] = match hex::decode(sig_hex) { Ok(b) if b.len() == 64 => match b.try_into() { Ok(arr) => arr, Err(_) => return false, }, _ => return false, }; let signature = Signature::from_bytes(&sig_bytes); // 7. Verify signature over canonical string verifying_key.verify(canonical.as_bytes(), &signature).is_ok() } // ============================================================================ // RESPONSE HELPERS // ============================================================================ /// Standard 401 response for failed auth fn unauthorized() -> Response { (StatusCode::UNAUTHORIZED, Json(json!({ "jsonrpc": "2.0", "id": null, "error": {"code": -32000, "message": "Unauthorized: invalid or missing authentication"} }))).into_response() } // ============================================================================ // JSON-RPC 2.0 HANDLER — shared by POST /mcp/v1 and WebSocket // ============================================================================ /// Process a JSON-RPC 2.0 message. Returns (status_code, response_value). /// Sync function — call from async via tokio::task::block_in_place(). fn handle_jsonrpc(body: &str, state: &Arc) -> (StatusCode, Value) { if body.is_empty() { return (StatusCode::BAD_REQUEST, json!({ "jsonrpc": "2.0", "id": null, "error": {"code": -32700, "message": "Parse error: empty body"} })); } let msg: Value = match serde_json::from_str(body) { Ok(v) => v, Err(_) => { return (StatusCode::BAD_REQUEST, json!({ "jsonrpc": "2.0", "id": null, "error": {"code": -32700, "message": "Parse error: invalid JSON"} })); } }; let method = msg["method"].as_str().unwrap_or(""); let id = &msg["id"]; let params = &msg["params"]; match method { "initialize" => { (StatusCode::OK, json!({ "jsonrpc": "2.0", "id": id, "result": { "protocolVersion": PROTOCOL_VERSION, "capabilities": { "tools": {} }, "serverInfo": { "name": "spf-smart-gate", "version": env!("CARGO_PKG_VERSION"), } } })) } "tools/list" => { (StatusCode::OK, json!({ "jsonrpc": "2.0", "id": id, "result": { "tools": mcp::tool_definitions() } })) } "tools/call" => { let name = params["name"].as_str().unwrap_or(""); let args = params.get("arguments").cloned().unwrap_or(json!({})); // Route through Unified Dispatch — same gate as stdio and mesh let resp = crate::dispatch::call(state, crate::dispatch::Source::Http, name, &args); (StatusCode::OK, json!({ "jsonrpc": "2.0", "id": id, "result": { "content": [resp.result] } })) } "ping" => (StatusCode::OK, json!({"jsonrpc": "2.0", "id": id, "result": {}})), _ => (StatusCode::BAD_REQUEST, json!({ "jsonrpc": "2.0", "id": id, "error": {"code": -32601, "message": format!("Unknown method: {}", method)} })), } } // ============================================================================ // CORS MIDDLEWARE — browser clients (ecommerce, web dashboards) // ============================================================================ /// CORS middleware via axum::middleware::from_fn. /// tower_http::CorsLayer requires ResBody: Default (same issue as TimeoutLayer), /// so we handle CORS manually — zero body type constraints. async fn cors_middleware(request: Request, next: middleware::Next) -> Response { // Preflight: browsers send OPTIONS before the real request if request.method() == Method::OPTIONS { return Response::builder() .status(StatusCode::OK) .header("access-control-allow-origin", "*") .header("access-control-allow-methods", "GET, POST, OPTIONS") .header("access-control-allow-headers", "content-type, authorization, x-spf-key, x-spf-sig, x-spf-pub, x-spf-time, x-spf-nonce") .header("access-control-max-age", "3600") .body(axum::body::Body::empty()) .unwrap(); } let mut response = next.run(request).await; let headers = response.headers_mut(); headers.insert("access-control-allow-origin", "*".parse().unwrap()); headers.insert("access-control-allow-methods", "GET, POST, OPTIONS".parse().unwrap()); headers.insert("access-control-allow-headers", "content-type, authorization, x-spf-key, x-spf-sig, x-spf-pub, x-spf-time, x-spf-nonce".parse().unwrap()); response } // ============================================================================ // ROUTE HANDLERS // ============================================================================ /// GET /health — no auth required (health checks, load balancers) async fn health_handler(State(app): State) -> Response { let session = app.inner.session.lock().unwrap(); let action_count = session.action_count; drop(session); Json(json!({ "status": "ok", "version": env!("CARGO_PKG_VERSION"), "actions": action_count, })).into_response() } /// GET /status — requires auth async fn status_handler( State(app): State, headers: HeaderMap, ) -> Response { if !check_auth(&headers, "GET", "/status", "", &app.api_key, &app.inner) { return unauthorized(); } let session = app.inner.session.lock().unwrap(); let summary = session.status_summary(); drop(session); Json(json!({ "version": env!("CARGO_PKG_VERSION"), "mode": format!("{:?}", app.inner.config.enforce_mode), "session": summary, })).into_response() } /// GET /tools — requires auth async fn tools_handler( State(app): State, headers: HeaderMap, ) -> Response { if !check_auth(&headers, "GET", "/tools", "", &app.api_key, &app.inner) { return unauthorized(); } Json(json!({ "tools": mcp::tool_definitions() })).into_response() } /// POST /mcp/v1 — JSON-RPC 2.0 protocol handler, requires auth. /// Body extracted as String for crypto auth signature verification. /// 30s timeout via spawn_blocking + tokio::time::timeout. async fn mcp_handler( State(app): State, headers: HeaderMap, body: String, ) -> Response { if !check_auth(&headers, "POST", "/mcp/v1", &body, &app.api_key, &app.inner) { return unauthorized(); } let state = app.inner.clone(); let result = tokio::time::timeout( Duration::from_secs(30), tokio::task::spawn_blocking(move || handle_jsonrpc(&body, &state)), ).await; match result { Ok(Ok((status, json))) => (status, Json(json)).into_response(), Ok(Err(_)) => (StatusCode::INTERNAL_SERVER_ERROR, Json(json!({ "jsonrpc": "2.0", "id": null, "error": {"code": -32603, "message": "Internal error"} }))).into_response(), Err(_) => (StatusCode::REQUEST_TIMEOUT, Json(json!({ "jsonrpc": "2.0", "id": null, "error": {"code": -32000, "message": "Request timeout (30s)"} }))).into_response(), } } // ============================================================================ // WEBSOCKET — persistent JSON-RPC connection (E5) // ============================================================================ /// GET /ws — WebSocket upgrade, requires auth on the HTTP upgrade request. /// Once upgraded, the connection is authenticated for its lifetime. async fn ws_handler( State(app): State, headers: HeaderMap, ws: WebSocketUpgrade, ) -> Response { if !check_auth(&headers, "GET", "/ws", "", &app.api_key, &app.inner) { return unauthorized(); } let state = app.inner.clone(); ws.on_upgrade(move |socket| handle_ws(socket, state)) } /// WebSocket message loop — each text message is a JSON-RPC request. /// Same dispatch path as POST /mcp/v1 but persistent connection. async fn handle_ws(mut socket: WebSocket, state: Arc) { eprintln!("[SPF-WS] Client connected"); while let Some(Ok(msg)) = socket.recv().await { match msg { Message::Text(text) => { let state_ref = state.clone(); let result = tokio::time::timeout( Duration::from_secs(30), tokio::task::spawn_blocking(move || handle_jsonrpc(&text, &state_ref)), ).await; let resp_json = match result { Ok(Ok((_, json))) => json, Ok(Err(_)) => json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32603, "message": "Internal error"}}), Err(_) => json!({"jsonrpc": "2.0", "id": null, "error": {"code": -32000, "message": "Request timeout (30s)"}}), }; let resp = serde_json::to_string(&resp_json).unwrap_or_default(); if socket.send(Message::Text(resp.into())).await.is_err() { break; } } Message::Ping(data) => { if socket.send(Message::Pong(data)).await.is_err() { break; } } Message::Close(_) => break, _ => {} } } eprintln!("[SPF-WS] Client disconnected"); } // ============================================================================ // HTTP SERVER // ============================================================================ /// Scan for an available port starting at preferred. /// Tries preferred..=preferred+1000. Returns first port that binds. /// Logs if non-preferred port selected. fn find_available_port(bind: &str, preferred: u16) -> u16 { let range_end = preferred.saturating_add(1000); for port in preferred..=range_end { let addr = format!("{}:{}", bind, port); match std::net::TcpListener::bind(&addr) { Ok(listener) => { drop(listener); if port != preferred { eprintln!( "[SPF] Port {} in use — auto-selected port {}", preferred, port ); } return port; } Err(_) => continue, } } eprintln!( "[SPF] WARNING: No port available in {}..={}, falling back to {}", preferred, range_end, preferred ); preferred } // ============================================================================ // WB-2d: REVERSE PROXY HANDLERS — /proxy, /proxy/asset, /ws/browser // No auth: served to local browser (localhost only, no external exposure). // ============================================================================ /// GET /proxy?url=... — Fetch target URL, inject CONTROL_JS, serve to browser. async fn proxy_handler( State(app): State, Query(params): Query>, ) -> Response { let url = match params.get("url") { Some(u) if !u.is_empty() => u.clone(), _ => return (StatusCode::BAD_REQUEST, "Missing url parameter").into_response(), }; if let Err(e) = crate::web::validate_url(&url) { return (StatusCode::BAD_REQUEST, e).into_response(); } let ws_port = app.inner.http_port; let state = app.inner.clone(); match tokio::task::spawn_blocking(move || { state.browser.lock().unwrap().proxy_page(&url, ws_port) }).await { Ok(Ok(page)) => Response::builder() .header(header::CONTENT_TYPE, "text/html; charset=utf-8") .body(Body::from(page.html)) .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response()), Ok(Err(e)) => (StatusCode::BAD_GATEWAY, format!("Proxy error: {}", e)).into_response(), Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), } } /// GET /proxy/asset?url=... — Fetch and passthrough a page asset (CSS/JS/image). async fn proxy_asset_handler( State(app): State, Query(params): Query>, ) -> Response { let url = match params.get("url") { Some(u) if !u.is_empty() => u.clone(), _ => return (StatusCode::BAD_REQUEST, "Missing url parameter").into_response(), }; if let Err(e) = crate::web::validate_url(&url) { return (StatusCode::BAD_REQUEST, e).into_response(); } let state = app.inner.clone(); match tokio::task::spawn_blocking(move || { state.browser.lock().unwrap().proxy_asset(&url) }).await { Ok(Ok(asset)) => Response::builder() .header(header::CONTENT_TYPE, asset.content_type) .body(Body::from(asset.data)) .unwrap_or_else(|_| StatusCode::INTERNAL_SERVER_ERROR.into_response()), Ok(Err(e)) => (StatusCode::BAD_GATEWAY, format!("Asset error: {}", e)).into_response(), Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(), } } /// GET /ws/browser — WebSocket endpoint for browser control JS. /// Bridges std::sync::mpsc channels (BrowserSession) ↔ WebSocket (browser JS). async fn ws_browser_handler( ws: WebSocketUpgrade, State(app): State, ) -> impl IntoResponse { ws.on_upgrade(move |socket| async move { // Take channels — only one WS browser session at a time let channels = app.inner.ws_browser_channels.lock() .ok() .and_then(|mut g| g.take()); if let Some(channels) = channels { handle_browser_ws(socket, channels).await; } // No channels = no active session, close immediately }) } /// Bridge mpsc channels to WebSocket — command relay between BrowserSession and browser JS. async fn handle_browser_ws( mut socket: WebSocket, channels: crate::browser::WsBrowserChannels, ) { loop { // Forward any pending commands from BrowserSession → browser JS while let Ok(cmd) = channels.cmd_rx.try_recv() { if socket.send(Message::Text(cmd.into())).await.is_err() { return; } } // Wait up to 50ms for a message from browser JS (polling rate) match tokio::time::timeout( std::time::Duration::from_millis(50), socket.recv(), ).await { Ok(Some(Ok(Message::Text(text)))) => { if channels.resp_tx.send(text.to_string()).is_err() { return; // BrowserSession dropped — session over } } Ok(Some(Ok(Message::Close(_)))) | Ok(Some(Err(_))) | Ok(None) => return, _ => {} // Binary/ping/pong/timeout — continue polling } } } // ============================================================================ // CH-2 + CH-3: CHANNEL HUB — WebSocket + HTTP API routes // ============================================================================ /// GET /ws/channel/:id — WebSocket upgrade for channel communication. /// Auth required on upgrade. Peer identified by X-SPF-Pub header (or query param fallback). /// Once upgraded, the connection is a full-duplex push channel. async fn ws_channel_handler( State(app): State, Path(channel_id): Path, headers: HeaderMap, Query(params): Query>, ws: WebSocketUpgrade, ) -> Response { if !check_auth(&headers, "GET", &format!("/ws/channel/{}", channel_id), "", &app.api_key, &app.inner) { return unauthorized(); } // Identify the connecting agent — prefer header, fallback to query param let peer_key = extract_header(&headers, "x-spf-pub") .or_else(|| params.get("key").cloned()) .unwrap_or_else(|| "anonymous".to_string()); let peer_name = extract_header(&headers, "x-spf-name") .or_else(|| params.get("name").cloned()) .unwrap_or_else(|| peer_key[..8.min(peer_key.len())].to_string()); ws.on_upgrade(move |socket| { crate::channel::handle_channel_ws(socket, channel_id, peer_key, peer_name) }) } /// POST /api/channel/create — Create a new channel. /// Body: { "name": "ops", "key": "abc...", "display_name": "ALPHA" } async fn api_channel_create( State(app): State, headers: HeaderMap, Json(body): Json, ) -> Response { if !check_auth(&headers, "POST", "/api/channel/create", "", &app.api_key, &app.inner) { return unauthorized(); } let name = body["name"].as_str().unwrap_or("unnamed"); let key = body["key"].as_str().unwrap_or(&app.inner.pub_key_hex); let display_name = body["display_name"].as_str().unwrap_or("Agent"); Json(crate::channel::api_create_channel(name, key, display_name)).into_response() } /// POST /api/channel/join — Join an existing channel. /// Body: { "channel_id": "ch-1", "key": "abc...", "name": "BRAVO" } async fn api_channel_join( State(app): State, headers: HeaderMap, Json(body): Json, ) -> Response { if !check_auth(&headers, "POST", "/api/channel/join", "", &app.api_key, &app.inner) { return unauthorized(); } let channel_id = body["channel_id"].as_str().unwrap_or(""); let key = body["key"].as_str().unwrap_or(&app.inner.pub_key_hex); let name = body["name"].as_str().unwrap_or("Agent"); Json(crate::channel::api_join_channel(channel_id, key, name)).into_response() } /// POST /api/channel/leave — Leave a channel. /// Body: { "channel_id": "ch-1", "key": "abc..." } async fn api_channel_leave( State(app): State, headers: HeaderMap, Json(body): Json, ) -> Response { if !check_auth(&headers, "POST", "/api/channel/leave", "", &app.api_key, &app.inner) { return unauthorized(); } let channel_id = body["channel_id"].as_str().unwrap_or(""); let key = body["key"].as_str().unwrap_or(&app.inner.pub_key_hex); Json(crate::channel::api_leave_channel(channel_id, key)).into_response() } /// POST /api/channel/send — Send a message to a channel. /// Body: { "channel_id": "ch-1", "key": "abc...", "name": "ALPHA", "text": "hello", "msg_type": "text" } async fn api_channel_send( State(app): State, headers: HeaderMap, Json(body): Json, ) -> Response { if !check_auth(&headers, "POST", "/api/channel/send", "", &app.api_key, &app.inner) { return unauthorized(); } let channel_id = body["channel_id"].as_str().unwrap_or(""); let key = body["key"].as_str().unwrap_or(&app.inner.pub_key_hex); let name = body["name"].as_str().unwrap_or("Agent"); let text = body["text"].as_str().unwrap_or(""); let msg_type = match body["msg_type"].as_str() { Some("tool_result") => crate::channel::MessageType::ToolResult, Some("system") => crate::channel::MessageType::System, _ => crate::channel::MessageType::Text, }; Json(crate::channel::api_send_message(channel_id, key, name, text, msg_type)).into_response() } /// GET /api/channel/list — List all channels. async fn api_channel_list( State(app): State, headers: HeaderMap, ) -> Response { if !check_auth(&headers, "GET", "/api/channel/list", "", &app.api_key, &app.inner) { return unauthorized(); } Json(crate::channel::api_list_channels()).into_response() } /// GET /api/channel/:id/history — Get message history for a channel. async fn api_channel_history( State(app): State, Path(channel_id): Path, headers: HeaderMap, Query(params): Query>, ) -> Response { if !check_auth(&headers, "GET", &format!("/api/channel/{}/history", channel_id), "", &app.api_key, &app.inner) { return unauthorized(); } let limit: usize = params.get("limit") .and_then(|l| l.parse().ok()) .unwrap_or(50); Json(crate::channel::api_channel_history(&channel_id, limit)).into_response() } /// Build the Axum Router with all routes and middleware. fn build_router(app_state: AppState) -> Router { // Tower middleware stack — applied to ALL routes // TimeoutLayer removed: requires ResBody: Default which axum::body::Body doesn't impl. // Timeout protection provided by tokio task isolation + SPF gate rate limiting. // CompressionLayer applied on Router (outside stack) to avoid body type conflicts. let middleware_stack = ServiceBuilder::new() // 1. Structured request/response tracing (outermost) .layer(TraceLayer::new_for_http()) // 2. Hide auth headers from trace output .layer(SetSensitiveRequestHeadersLayer::new([ HeaderName::from_static("x-spf-key"), HeaderName::from_static("x-spf-sig"), ])) // 3. 10MB body limit (matches original read_body limit) .layer(RequestBodyLimitLayer::new(10 * 1024 * 1024)) // 4. Convert handler panics to 500 (innermost — uses ResponseForPanic, not Default) .layer(CatchPanicLayer::new()); Router::new() // Public routes — no auth .route("/health", get(health_handler)) // Protected routes — auth checked in each handler .route("/status", get(status_handler)) .route("/tools", get(tools_handler)) .route("/mcp/v1", post(mcp_handler)) // WebSocket — auth on upgrade request .route("/ws", get(ws_handler)) // Reverse proxy browser routes (WB-2d) — no auth, served to local browser .route("/proxy", get(proxy_handler)) .route("/proxy/asset", get(proxy_asset_handler)) .route("/ws/browser", get(ws_browser_handler)) // CH-2: Channel WebSocket — full duplex agent communication .route("/ws/channel/{id}", get(ws_channel_handler)) // CH-3: Channel HTTP API — control plane for channel management .route("/api/channel/create", post(api_channel_create)) .route("/api/channel/join", post(api_channel_join)) .route("/api/channel/leave", post(api_channel_leave)) .route("/api/channel/send", post(api_channel_send)) .route("/api/channel/list", get(api_channel_list)) .route("/api/channel/{id}/history", get(api_channel_history)) // CORS — browser clients (ecommerce, web dashboards) .layer(middleware::from_fn(cors_middleware)) // Compression outside CatchPanic (CompressionBody doesn't impl Default) .layer(CompressionLayer::new()) // Global middleware (all routes) .layer(middleware_stack) .with_state(app_state) } /// Async HTTP server — runs in caller's tokio runtime. /// Use this for shared runtime (E7) where mcp.rs spawns HTTP + mesh together. /// Blocks until server stops or task is cancelled. /// /// BLOCK SEC-4: SPF_API_KEY env var checked first — process-scoped override. /// Priority: SPF_API_KEY env > identity-derived key > JSON config fallback. /// The env var is never written to disk, so AI agents with native Read /// cannot discover it from config files. pub async fn serve( state: Arc, bind: String, port: u16, api_key: String, tls: Option<(Vec, Vec)>, ) { rustls::crypto::ring::default_provider().install_default().ok(); // SEC-4: Environment variable override for API key. // SPF_API_KEY env var takes priority over identity-derived key. // Process-scoped: not readable from JSON config files by AI agents. let api_key = match std::env::var("SPF_API_KEY") { Ok(env_key) if !env_key.is_empty() => { eprintln!("[SPF-HTTP] API key loaded from SPF_API_KEY env var"); env_key } _ => api_key, // Fall back to identity-derived key (passed from mcp.rs) }; let port = find_available_port(&bind, port); let addr = format!("{}:{}", bind, port); let app_state = AppState { inner: state, api_key, }; let app = build_router(app_state); eprintln!("[SPF-HTTP] Listening on {}", addr); if let Some((cert_pem, key_pem)) = tls { // HTTPS via axum-server + rustls — PEM bytes from rcgen let tls_config = axum_server::tls_rustls::RustlsConfig::from_pem(cert_pem, key_pem) .await .expect("[SPF-HTTP] Failed to load TLS config from PEM"); let sock_addr: std::net::SocketAddr = addr.parse() .expect("[SPF-HTTP] Invalid bind address"); // Graceful shutdown handle (E6) let handle = axum_server::Handle::new(); let shutdown_handle = handle.clone(); tokio::spawn(async move { tokio::signal::ctrl_c().await.ok(); eprintln!("[SPF-HTTP] Graceful shutdown initiated (10s timeout)..."); shutdown_handle.graceful_shutdown(Some(Duration::from_secs(10))); }); axum_server::bind_rustls(sock_addr, tls_config) .handle(handle) .serve(app.into_make_service()) .await .expect("[SPF-HTTP] HTTPS server failed"); } else { // Plain HTTP via axum::serve let listener = tokio::net::TcpListener::bind(&addr) .await .expect("[SPF-HTTP] Failed to bind TCP"); // Graceful shutdown (E6) axum::serve(listener, app) .with_graceful_shutdown(async { tokio::signal::ctrl_c().await.ok(); eprintln!("[SPF-HTTP] Graceful shutdown initiated..."); }) .await .expect("[SPF-HTTP] HTTP server failed"); } } /// Start HTTP API server — sync wrapper for backward compatibility. /// Called from spawned thread in mcp::run(). Creates own tokio runtime. /// Blocks forever (runs in dedicated thread). /// /// Signature unchanged from tiny_http version — mcp.rs needs zero changes /// when using this entry point. For shared runtime (E7), use serve() instead. pub fn start(state: Arc, bind: &str, port: u16, api_key: String, tls: Option<(Vec, Vec)>) { let bind = bind.to_string(); let rt = tokio::runtime::Builder::new_multi_thread() .worker_threads(2) .enable_all() .build() .expect("[SPF-HTTP] Failed to build tokio runtime"); rt.block_on(serve(state, bind, port, api_key, tls)); }